text:
Q: csvsimple longtable header issue I am trying to create a longtable from a CSV file with the help of the package csvsimple. I managed to get almost everything in order except for one extra line below the first header (it does not apply to successive headers on next pages).
I am guessing it comes from these two lines of code:
after first line=\\\midrule\endhead,
late after line=\\,

It seems that csvsimple is applying two linebreaks (\\) after the first line of the table which would be the header.
The thing is that if I remove the linebreak from the after first line argument, it seems to throw an error or do not compile at all.
And if I try to use late after first line, it removes the extra line but does not display the midrule as specified..
MWE
\documentclass[draft]{article}
\begin{filecontents*}{test.csv}
  a,b,c
  1,2,3
  4,5,6
\end{filecontents*}
\usepackage{mwe}
\usepackage{booktabs}
\usepackage{longtable}
\usepackage{csvsimple}
\begin{document}
\csvloop{
  file=test.csv,
  respect all,
  separator=comma,
  no head,
  before reading={
    \begin{longtable}{lll}
    \toprule
  },
  command={\csviffirstrow
    {\textbf{\csvcoli} & \textbf{\csvcolii} & \textbf{\csvcoliii}}
    {\csvcoli & \csvcolii & \csvcoliii}
  },
  after first line=\midrule\endhead,
  late after line=\\,
  late after last line=\\\bottomrule,
  after reading=\end{longtable}
}
\end{document}

Output

A: The following should work. late after first line has to be placed after late after line to have an effect. Otherwise, it is overwritten by late after line.
\documentclass[draft]{article}
\begin{filecontents*}{test.csv}
  a,b,c
  1,2,3
  4,5,6
\end{filecontents*}
\usepackage{mwe}
\usepackage{booktabs}
\usepackage{longtable}
\usepackage{csvsimple}
\begin{document}
\csvloop{
  file=test.csv,
  respect all,
  separator=comma,
  no head,
  before reading={
    \begin{longtable}{lll}
    \toprule
  },
  command={\csviffirstrow
    {\textbf{\csvcoli} & \textbf{\csvcolii} & \textbf{\csvcoliii}}
    {\csvcoli & \csvcolii & \csvcoliii}
  },
  late after line=\\,
  late after first line=\\\midrule\endhead,
  late after last line=\\\bottomrule,
  after reading=\end{longtable}
}
\end{document}


text:
Q: one-to-many scalability and efficiency of getting the many - parse.com I have a question about the scalability of getting the many from a one-to-many relationship in parse.com. Below is a diagram of what I am trying to do.

I have a Like object that has a userWhoLiked and a messageLiked attributes as pointers. My question is in regards to checking if a User has liked a message already when loading a feed of Message objects. I was thinking that I could write some cloud code that would return both the Message itself as well as information about if the User has already liked that object. However, I feel like this would be very inefficient. I would in essence have a query for all the Message objects (which will be n objects long), and then another query for finding if the User has already liked that Message object by going through all the Like objects n times and checking the userWhoLiked and messageLiked based on the user logged in and Message I am checking. I am going to use the pointer to build the one-to-many relationship because the number of Like objects will be arbitrarily large. Is the method that I have described (using cloud code and then checking the Like objects ) for getting if a user has liked an object is okay and scalable? Is there a better way, or any suggestions? I appreciate your time. Thanks.

A: Why not just do one query on Like objects where the userWhoLiked key is equal to the current user? This will return all of the objects which the current user has liked and you can also infer that all objects not included have not been liked.
In case you haven't checked it out yet, I'd highly recommend the Parse Anypic tutorial which has a very similar structure

redpajama_set_name: RedPajamaStackExchange


text:
Q: $\mathbb{R}/{\sim}$: A Question about the Formal Definition of a Quotient For an equivalence relation $\sim$ what is $\mathbb{R}/{\sim}$? I mean explicitly and formally...

A: Define on $\mathbb R$ an equivalence relation $\sim$ that's reflexive, symmetric and transitive and for all $x\in \mathbb R$ let
$$[x]=\{y\in\mathbb R\ |\ y\sim x\}$$
the class of $x$ i.e. the set of element in relation with $x$, hence it isn't difficult to prove that the set of classes denoted by $\mathbb R/\sim$
$$\mathbb R/\sim=\{[x]\ |\ x\in\mathbb R\}$$
 forms  a partition of $\mathbb R$.


text:
Q: Django dynamic filter based on variable (str) I am writing a function that can return table items based on a dynamically inserted model. So I need to refrain from using the model name in the function. Now I sometimes will have a many-to-many relationship with another model and want to select on that.
Say I have a projects = ManyToMany(Projects) field in my Files model. Now I can use:
filter(projects__in=[1])

to select for files related to projects with id 1, but I need the projects part of this filter to be dynamic, so I can use something like:
a_field = 'projects'
filter(a_field+'__in'=[1])

which obviously doesn't work. How should I do this?

A: You can do this by using the **kwargs in Python: you construct a dictionary that maps string (the name of the parameters), to values, and then call the function with a dictionary with two asterisks, like:
a_field = 'projects'
params = {a_field+'__in': [1]}
filter(**params)
we of course need to construct the dictionary on a separate line:
a_field = 'projects'
filter(**{a_field+'__in': [1]})
If you thus have a dictionary like {'foo': 'bar', 'qux': 14}, then calling it with foo(**{'foo': 'bar', 'qux': 14}) is equivalent to foo(foo='bar', qux=14). This technique is not specific towards Django, but to Python. Python also has a way to do this with positional parameters: foo(*[1, 'a', 4]) is equivalent to foo(1, 'a', 4).


text:
Q: jstl as Spring 3 email template I'm building an standard web application.
For generating view i'm using jstl.
Withih this application i need to send some emails.
I was looking for a email temlate, and i found Velocity.
And now i thinking, do i really need a Velocity or i can use jstl for email templates. Maybe jstl would be the best solution ?
Or maybe you have your own solutions for email templates ?
If there is an possibility to use jstl, how to use it ?
Do you have any examples or tutorials ?

A: I would recommend you to use Thymeleaf as it supports Rich HTML e-mail Template .
The detailed sample example is available here. Spring3 MVC+ Thymeleaf
Features :

*

*Expressions in Spring EL.

*Flow control: iterations, conditionals, ...

*Utility functions: date/number formatting, dealing with lists,
arrays...

*Easy i18n, integrated with our application's Spring
internationalization infrastructure.

*Natural templating: our email templates can be static prototypes,
written by UI designers.

A: I use Velocity as it is easy, light, lots of support on the web and you are not limited to what you can do with your templates.
Here is an implementation of Velocity with Spring:
velocity null point exception
For the template, just use HTML with keywords ${keyword}

Hi ${userName}, this is an email template with HTML!

        Your email address is ${emailAddress}.

You can use loops, inject beans etc.


text:
Q: Return titles from page using requests.get and BeautifulSoup I am trying to return the teaser titles of all articles on a page. No matter which page I search susing the below code, I receive
Process finished with exit code 0 and nothing more.
Could someone please tell me where I'm going wrong. I'm usin PyCharm 2016.3.2 and Anaconda3.
Thanks
import requests
from bs4 import BeautifulSoup

  if __name__ == "__main__":
    # User agent to bypass scraping security
    agent = {'User-Agent': 'Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405'}
    req = requests.get("http://www.zerohedge.com/", agent)

    #req.content = html page source and we are using the html parser
    soup = BeautifulSoup(req.content, "html.parser")

    for i in soup.find_all("title teaser-title"):
        print(i.text)

A: You'll need to specify the tag you want the search and optionally its class. Like this:
soup.find_all("h2", class_="title teaser-title")

Or use an cssselector:
soup.select("h2[class='title teaser-title']")


text:
Q: Haskell default io buffering Yesterday I wrote a little xinetd exercise for my students: make a reverse echo program.
To learn something new, I tried to implement a Haskell solution. The trivial main = forever $ interact reverse does not work. I went through this question and made a corrected version:
import Control.Monad
import System.IO

main = forever $ interact revLines

revLines = unlines . map (reverse) . lines

But this corrected version also doesn't work. I read the buffering documentation and played with the various settings.
If I set NoBuffering or LineBuffering, my program works correctly. Finally I printed out the default buffering modes for stdin and stdout.
import System.IO

main = do
  hGetBuffering stdin >>= print
  hGetBuffering stdout >>= print

I've got BlockBuffering Nothing if I run my program from xinetd(echo "test" | nc localhost 7) but from cli I've got LineBuffering

*

*What is the difference between a xinetd tcp service and a cli program, regards to buffering?

*Do I have to set manually the buffering if I want to write a working program with both running method?

Edit: Thank you all for the helpful answers.
I accept the answer which was given by blaze, he give me a hint with isatty(3). I went through again the System.IO documentation and found the hIsTerminalDevice function, with which I am able to check the connection of the handle.
For the record, here is my final program:
{-# OPTIONS_GHC -W #-}

import System.IO

main = do
  hSetBuffering stdin LineBuffering
  hSetBuffering stdout LineBuffering

  interact revLines

revLines = unlines . map (reverse) . lines

A: The GHC runtime system tries to be clever when it chooses the default buffering. If it looks like stdin and stdout are directly connected to terminal, they will be line-buffered. If it looks like they are connected to something else, they are block-buffered. This can be problematic if you want to run a program with line-by-line input that doesn't come directly from a terminal. For example, I think that cat | your-program behaves differently from just your-program.

Do i have to set manually the buffering if i want to write a working program with both running method?

Yes.

A: It's not specific to Haskell (e.g. the standard C library does the same thing).
Traditionally, if a file descriptor corresponds to the terminal, buffering is set to line mode, otherwise to block mode. File descriptor type can be checked by the isatty(3) function -- not sure if it is exported to System.IO.
And yes, you need to set buffering mode manually if you depend on it.
By the way, you can cheat the system and force block buffering in the command line by running your program as cat | ./prog | cat.


text:
Q: res.sendFile does not work I am using Express 4.13, and I met some problems when I  tried to serve the files:
function doServeFile(name, fullpath, res, download) {
    if (fullpath) {
        if (download)
            res.download(fullpath, name);
        else {
            res.sendFile(fullpath, {}, function (err) {
                console.info(err);
            });
        }
    }
    else {
        res.status(404);
    }
}

function serveFile(id, res, download) {
    Model.findById(id).then(file=> {
        var fullPath = Config.uploadDest + "/" + file.path;
        doServeFile(file.filename, fullPath, res, download)
    }).catch(Util.dbErrorHandler);
}
router.get("/:id", function (req, res, next) {
    serveFile(req.params.id, res);
});
router.get("/download/:id", function (req, res, next) {
    serveFile(req.params.id, res, true);
});

As the codes shown, once I send request /1 to the server, it will retrieve the file whose id is 1 to get the file path, and then use the res.sendFile to serve the file to client.
However when I run the application, I found that the request will hang on too long to have the response. But I can see the logs like this:
---try send file:D:/file_upload/1464578330791_user.jpg
It seems that the file has been fetched, but the res.sendFile does not complete its job.
Also, when I tried /download/1, the file can be downloaded.
What's going on ?

A: I had this same issue the other day and found that sendFile doesn't actually acknowledge absolute paths correctly and hangs. Setting the root option solved the issue. Hopefully it might work for you.
res.sendFile(fullpath, {root: '/'});

A: After dig into the source codes of express, I found the answer.
When the res.sendFile is called, express will to make sure that the root of the path is set or the path must be an absolute path, check this, it  is just the isAbsolutepath which cause this problem,codes:
exports.isAbsolute = function(path){
  if ('/' == path[0]) return true;
  if (':' == path[1] && '\\' == path[2]) return true;
  if ('\\\\' == path.substring(0, 2)) return true; // Microsoft Azure absolute path
};

So a path like
D:/a/a.txt will not be treated as an absolute path!
D:\\a\\a.txt will be. And so does linux-like path /home/a/a.txt.
And this is how I build the path(manually), which is not an absolute path from express's perspective:
var fullPath = Config.uploadDest + "/" + file.path;

So I change it to:
var fullPath = path.join(Config.uploadDest,file.path);

It worked.

A: If you are using windows operating system, use its full path such as
D:/folder1/folder2/index.html


text:
Q: Set basic auth on server side I configured resource and authorization servers in one application. I use spring-security oauth2, with Resource Owner Password Credentials. Can I set up basic auth on the server side? I don't want to do it on the front-end.
I don't know what a part of the code I need to show...
When I want to receive a token I need to enter this in postman:

Can I configure it on the server side?
Authorization Server:
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private JwtAccessTokenConverter jwtTokenEnhancer;

    @Autowired
    private UserApprovalHandler userApprovalHandler;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.jdbc(dataSource);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
        security.checkTokenAccess("isAuthenticated()");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore).tokenEnhancer(jwtTokenEnhancer).userApprovalHandler(userApprovalHandler)
                .authenticationManager(authenticationManager)
                .pathMapping("/oauth/token", "/login");
    }
}

Resource Server:
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    private static final String RESOURCE_ID = "resource_id";

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId(RESOURCE_ID).stateless(false);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .cors().and().csrf().disable()

                .authorizeRequests()
                .antMatchers("/swagger-ui.html#").permitAll()
                .antMatchers("/").authenticated()
                .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
    }
}

Security config:
@Configuration
@EnableWebSecurity(debug = true)
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private ClientDetailsService clientDetailsService;

    @Autowired
    private CustomAuthenticationProvider customAuthenticationProvider;

    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(10);
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    public void configure(final AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(customAuthenticationProvider);
    }

    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(jwtTokenEnhancer());
    }

    @Bean
    protected JwtAccessTokenConverter jwtTokenEnhancer() {
        converter.setSigningKey("Demo-Key-1");
        return converter;
    }

    @Bean
    @Autowired
    public TokenStoreUserApprovalHandler userApprovalHandler(TokenStore tokenStore) {
        TokenStoreUserApprovalHandler handler = new TokenStoreUserApprovalHandler();
        handler.setTokenStore(tokenStore);
        handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService));
        handler.setClientDetailsService(clientDetailsService);
        return handler;
    }

    @Bean
    @Autowired
    public ApprovalStore approvalStore(TokenStore tokenStore) throws Exception {
        TokenApprovalStore store = new TokenApprovalStore();
        store.setTokenStore(tokenStore);
        return store;
    }

    @Override
    @Order(Ordered.HIGHEST_PRECEDENCE)
    protected void configure(final HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/resources/**").permitAll()
                .antMatchers(HttpMethod.OPTIONS, "/oauth/token").permitAll()
                .and().cors().and().csrf().disable();
    }
}

A: This answer is accompanied by a complete and working sample.
Maybe you are biting off more than you can chew here?
For example:
.antMatchers(HttpMethod.OPTIONS, "/oauth/token").permitAll()

The /oauth/token endpoint must remain protected. This is the endpoint on the authorization server that issues tokens to authenticated clients. The system will probably fail with NullpointerException or other exceptions if you open it, however, the above configuration option indicate that maybe you're a bit confused about how OAuth2 works.
What I would recommend is to first fully understand authorization server versus resource server. You can definitely combine the two, but they would have very different endpoints.
Authorization Server - typical endpoints
/oauth/token - issues tokens
/oauth/authorize - issues authorization codes
/introspect - validates a token and returns token claims in a known format

Resource Server - These would be your application endpoints, requiring Bearer tokens, for example
/account/123/debit

and these endpoints expect a stateless request that has an authorization header
Authorization: Bearer <token value here>

A controller for a resource server would look like this:
@PreAuthorize("hasRole('your-scope-role')")
@RequestMapping(value = "/hello")
@ResponseBody
public String hello(Principal principal) {
    return "Hello to " + principal.getName();
}

Feel free to review the simple project that I have created for you.
In addition to that, I also recommend this video on OAuth2 and OpenID Connect
In my sample, I have configured the clients like this:
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        InMemoryClientDetailsService clientDetails = new InMemoryClientDetailsService();
        BaseClientDetails client = new BaseClientDetails(
            "testclient",
            null,
            "testscope,USER,ADMIN",
            "password",
            null
        );
        client.setClientSecret(passwordEncoder.encode("secret"));
        clientDetails.setClientDetailsStore(
            Collections.singletonMap(
                client.getClientId(),
                client
            )
        );
        clients.withClientDetails(clientDetails);
    }

Take a look at this simple test case, the client is using http-basic authentication:
mvc.perform(
    post("/oauth/token")
            .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE)
            .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
            .param("username", "admin")
            .param("password", "password")
            .param("grant_type", "password")
            .param("response_type", "token")
            .param("client_id", "testclient")
            .header("Authorization", "Basic " + Base64.encodeBase64String("testclient:secret".getBytes()))

This is client authentication, using the http-basic method:
.header("Authorization", "Basic " + Base64.encodeBase64String("testclient:secret".getBytes()))


text:
Q: RAILS: Calling a parent model within a nested partial form Im trying to call a variable from the 'product' model in a 'variant' partial.  I can call an existing variable from the 'variant' using:
 <%= f.object.product_id %>

But I can't get this to work:
<%= f.object.product.id %>

I can do this:
<%= f.object.product %>

But it returns #<Product:0x007fee2c9a8ec8> and I don't know what to do with it!
Here's a more detailed overview of the situation:
I have 'store' model that has_many 'products'.  Each 'product' has_many 'variants'. The variants are nested.  Here's the '/store/show.html.erb' file:
  <% @store.products.each do |product| %>

        <%= form_for(product) do |f| %>
          <%= f.fields_for :variants do |builder| %>
            <%= render 'variant_fields', f: builder %>
          <% end %>

  <% end %>

And here's the '/store/_variant_fields' partial:
<fieldset>

             <%= f.label :variant_name %><%= f.text_field :variant_name %>

</fieldset>

A: the easiest solution would be to pass the product to your partial:
<% render 'variant_fields', f: builder, product: f.object %>

in your partial:
<fieldset>

             <%= f.label :variant_name %><%= f.text_field :variant_name %><%= product.inspect %>

</fieldset>

See what product.inspect shows you.


text:
Q: why clang doesn't reuse stack space? I expected that stack memory of scope-local variables is reused once they left the scope. This is true for GCC and MSVC, at least in optimised builds. In debug builds they don't reuse stack memory, I guess to be able to poison that memory and catch bugs.
But this is not true for Clang. E.g. the following code outputs different addresses:
#include <stdio.h>

int main()
{
    {
        int j;
        printf("%p\n", &j);
    }
    {
        int j;
        printf("%p\n", &j);
    }

    /*
    for (int i = 0; i != 2; ++i)
    {
        int j;
        printf("&j = %p\n", &j);
    }
    */
}

GodBolt
The same result (no reusage) if I replace int j; by int j[1];.
Interestingly, in cases where such behaviour has higher probability of overflowing the stack, e.g. if an array contains more than one element, its stack space is reused by Clang. Same for for loops (commented part of the code above).
It seems Clang does this deliberately. Why?


text:
Q: what's the best way to do my appendix? I am a new latex user, I would be grateful if you could help me to do appendix in my thesis, in my code below I use this way to do my appendix but I need the best and easiest way to do appanix, as well as that How can I refer to (Appendix I) in (Copyright) chapter for example.
My code is :
\documentclass[12pt]{report}
\usepackage{times} %Times new roman font
%\usepackage{mathptmx}

\usepackage[top=2.5cm, bottom=2.5cm, left=3.5cm, right=2.5cm]{geometry}
\usepackage{amsfonts,amsmath,amssymb}

\usepackage[colorlinks = true,
            linkcolor = blue,
            urlcolor  = blue,
            citecolor = blue,
            anchorcolor = blue]{hyperref}

\begin{document}
\chapter*{Copyright}
\addcontentsline{toc}{chapter}{Copyright}
test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test
\newpage

\tableofcontents
\addcontentsline{toc}{chapter}{Contents}
\newpage

\chapter*{Appendixes}
\addcontentsline{toc}{chapter}{Appendixes}
\section*{Appendix I (Benchmark IEC microgrid data)}
\begin{itemize}
\item Utility: rated short-circuit MVA=1000, f=60 Hz, rated kV=120, $V_{base}$=120 kV.
\item Distributed Generations (DGs):
\begin{itemize}
\item DG1, DG3: synchronous generator with rated MVA=9, f=60Hz, rated kV=2.4, Inertia constant H=1.07 s, friction factor F=0.1 pu, Rs=0.0036 pu, $Xd$=1.56 pu, $Xd^\prime$=0.296 pu, $Xd^{\prime\prime}$=0.177 pu, $Xq$=1.06 pu, $Xq^{\prime\prime}$=0.177 pu, $Xl$=0.052 pu, $Td^\prime$=3.7 s, $Td^{\prime\prime}$=0.05 s, $Tq0^{\prime\prime}$=0.05 s.
\end{itemize}
\end{itemize}
\end{document}

A: You can start the appendices with \part*{Appendices}, then issue \appendix to change the chapter numbering scheme. If you want the appendices with roman numbering you can use
\makeatletter
\def\thechapter{\@Roman\c@chapter}
\makeatother

after \appendix. Then you start each appendix with \chapter, and add a \label to it. After than you can use \ref normally.

\documentclass[12pt]{report}
% \usepackage{times} %Times new roman font
\usepackage{newtxtext}
\usepackage{newtxmath}
%\usepackage{mathptmx}

\usepackage[top=2.5cm, bottom=2.5cm, left=3.5cm, right=2.5cm]{geometry}
\usepackage{amsfonts,amsmath,amssymb}

\usepackage[colorlinks = true,
            linkcolor = blue,
            urlcolor  = blue,
            citecolor = blue,
            anchorcolor = blue]{hyperref}

\begin{document}
\chapter*{Copyright}
\addcontentsline{toc}{chapter}{Copyright}
test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test see Appendix~\ref{app:benchmark}
\newpage

\tableofcontents
\addcontentsline{toc}{chapter}{Contents}
\newpage

\part*{Appendices}
\appendix
\makeatletter
\def\thechapter{\@Roman\c@chapter}
\makeatother

\chapter{Benchmark IEC microgrid data}
\label{app:benchmark}

\begin{itemize}
\item Utility: rated short-circuit MVA=1000, f=60 Hz, rated kV=120, $V_{base}$=120 kV.
\item Distributed Generations (DGs):
\begin{itemize}
\item DG1, DG3: synchronous generator with rated MVA=9, f=60Hz, rated kV=2.4, Inertia constant H=1.07 s, friction factor F=0.1 pu, Rs=0.0036 pu, $Xd$=1.56 pu, $Xd^\prime$=0.296 pu, $Xd^{\prime\prime}$=0.177 pu, $Xq$=1.06 pu, $Xq^{\prime\prime}$=0.177 pu, $Xl$=0.052 pu, $Td^\prime$=3.7 s, $Td^{\prime\prime}$=0.05 s, $Tq0^{\prime\prime}$=0.05 s.
\end{itemize}
\end{itemize}
\end{document}

Slightly off topic but important nonetheless: the times package has been for quite some time now. It was superseded by the mathptmx which is also obsolete and was superseded by the newtx bundle (newtxtext and newtxmath).


text:
Q: ffmpeg - different video and audio length synchronization I have a task where the sound is longer and the image should come later.
Actually, this is exactly what I want, but it's a bit different: ffmpeg : mix audio and video of different length
First of all, I leave the picture I draw below to be understood.
Click to see the image.
By doing this I am thinking of catching sync. With which ffmpeg command can I do this?
Thank you.

A: I had to use offset.
I solved it this way. I will automatically add the corresponding time interval according to the difference between video and audio. I will use the programming language for this.
ffmpeg -i  finalsound.flv -itsoffset 00:00:44 -i finalvideo.flv -c copy final.flv

Thank you.


text:
Q: convert rgb depth image to oni file I need to generate oni file from rgb and depth image. I used NiRecordSynthetic sample from openni. It works correctly for my depth image but when I add transformImageMD function for my RGB image, I will get segmentation fault in imageMap(x,y) = imagePixel.
I don't know why.
here is my code:
void transformDepthMD(Mat FrameDepth,DepthMetaData& depthMD)
{
    DepthMap& depthMap = depthMD.WritableDepthMap();
    for (XnUInt32 y = 0; y < depthMap.YRes(); y++)
    {
        for (XnUInt32 x = 0; x < depthMap.XRes(); x++)
        {
            //Punch vertical cut lines in the depth image
            if ((x % 2) == 0)
            {

                depthMap(x,y) = FrameDepth.at<XnUInt16>(y,x);
            }
        }
    }
}
void transformImageMD(Mat FrameImage,ImageMetaData& imageMD)
{
    RGB24Map& imageMap = imageMD.WritableRGB24Map();
    for (XnUInt32 y = 0; y < imageMD.YRes(); y++)
    {
     for (XnUInt32 x = 0; x <imageMD.XRes(); x++)
      {
            XnRGB24Pixel imagePixel;
            imagePixel.nBlue=FrameImage.at<Vec3b>(y,x)[0];
            imagePixel.nGreen=FrameImage.at<Vec3b>(y,x)[1];
            imagePixel.nRed=FrameImage.at<Vec3b>(y,x)[2];
            imageMap(x,y) = imagePixel;
        }
    }

}

int main(int argc, char* argv[])
{
    XnStatus nRetVal = XN_STATUS_OK;
    nRetVal = xnLogInitFromXmlFile(SAMPLE_XML_PATH);
    if (nRetVal != XN_STATUS_OK)
    {
        printf("Log couldn't be opened: %s. Running without log", xnGetStatusString(nRetVal));
    }
    if (argc < 3)
    {
        printf("usage: %s <inputFile> <outputFile>\n", argv[0]);
        return -1;
    }
    const char* strInputFile = argv[1];
    const char* strOutputFile = argv[2];
    Context context;
    nRetVal = context.Init();
    CHECK_RC(nRetVal, "Init");
    // open input file
    Player player;
    nRetVal = context.OpenFileRecording(strInputFile, player);
    CHECK_RC(nRetVal, "Open input file");
    // Get depth node from recording
    DepthGenerator depth;
    nRetVal = context.FindExistingNode(XN_NODE_TYPE_DEPTH, depth);
    CHECK_RC(nRetVal, "Find depth generator");
    // Create mock node based on depth node from recording
    MockDepthGenerator mockDepth;
    nRetVal = mockDepth.CreateBasedOn(depth);
    CHECK_RC(nRetVal, "Create mock depth node");

    ImageGenerator image;
    nRetVal = context.FindExistingNode(XN_NODE_TYPE_IMAGE, image);
    CHECK_RC(nRetVal, "Find depth generator");
    // Create mock node based on depth node from recording
    MockImageGenerator mockImage;
    nRetVal = mockImage.CreateBasedOn(image);
    CHECK_RC(nRetVal, "Create mock depth node");
    // create recorder
    Recorder recorder;
    nRetVal = recorder.Create(context);
    CHECK_RC(nRetVal, "Create recorder");
    nRetVal = recorder.SetDestination(XN_RECORD_MEDIUM_FILE, strOutputFile);
    CHECK_RC(nRetVal, "Set recorder destination file");
    // add depth node to recorder
    nRetVal = recorder.AddNodeToRecording(mockDepth);
    CHECK_RC(nRetVal, "Add node to recording");
    nRetVal = recorder.AddNodeToRecording(mockImage);
    CHECK_RC(nRetVal, "Add node to recording");

    nRetVal = player.SetRepeat(FALSE);
    XN_IS_STATUS_OK(nRetVal);
    XnUInt32 nNumFrames = 0;
    nRetVal = player.GetNumFrames(image.GetName(), nNumFrames);
    CHECK_RC(nRetVal, "Get player number of frames");
    DepthMetaData depthMD;
    ImageMetaData imageMD;
    int frameNum = 0;
    String path = "myData";
    while ((nRetVal = depth.WaitAndUpdateData()) != XN_STATUS_EOF)
    {
        ++frameNum;
        CHECK_RC(nRetVal, "Read next frame");
        // Get depth meta data
        depth.GetMetaData(depthMD);
        image.GetMetaData(imageMD);

        nRetVal = depthMD.MakeDataWritable();
        CHECK_RC(nRetVal, "Make depth data writable");

        nRetVal = imageMD.MakeDataWritable();
        CHECK_RC(nRetVal, "Make depth data writable");

        String ficheroActualRGB;
        ficheroActualRGB = path  +"RGB_" + boost::to_string(frameNum) + ".png";
        String ficheroActualDepth = path +"Depth_"+ boost::to_string(frameNum) + ".png";

        Mat matFrameImage = imread(ficheroActualRGB, 1);
        resize(matFrameImage, matFrameImage, Size(640, 480), 0, 0, INTER_CUBIC);
        Mat matFrameDepth = imread(ficheroActualDepth,1);
        resize(matFrameDepth, matFrameDepth, Size(640, 480), 0, 0, INTER_CUBIC);

        transformDepthMD(matFrameDepth,depthMD);
        transformImageMD(matFrameImage,imageMD);
//         Pass the transformed data to the mock depth generator
        nRetVal = mockDepth.SetData(depthMD);
        CHECK_RC(nRetVal, "Set mock node new data");

        nRetVal = mockImage.SetData(imageMD);
        CHECK_RC(nRetVal, "Set mock node new data");

        /* We need to call recorder.Record explicitly because we're not using WaitAndUpdateAll(). */
        nRetVal = recorder.Record();
        CHECK_RC(nRetVal, "Record");
        printf("Recorded: frame %u out of %u\r", depthMD.FrameID(), nNumFrames);
    }
    printf("\n");
    return 0;
}

Thanks,

A: Since strange reason I also cannot get any data from imageMD. But you can use yourself style to convert RGB-D image to .oni file.
I have used OpenCV and OpenNI to achieve this.
Here is sample code.
string color_dir="your_color_dir/", depth_dir="your_depth_dir/";
int frame_num = 100;

XnStatus nRetVal = XN_STATUS_OK;
Context context;
nRetVal = context.Init();
CHECK_RC(nRetVal, "Init");

Player player;
nRetVal = context.OpenFileRecording("input.oni", player);  // we use existence .oni file to simulate a oni context environment.
CHECK_RC(nRetVal, "Open input file");

DepthGenerator depth;
ImageGenerator color;
nRetVal = context.FindExistingNode(XN_NODE_TYPE_IMAGE, color);
CHECK_RC(nRetVal, "Find color generator");

nRetVal = context.FindExistingNode(XN_NODE_TYPE_DEPTH, depth);
CHECK_RC(nRetVal, "Find depth generator");

MockDepthGenerator mockDepth;
nRetVal = mockDepth.CreateBasedOn(depth);
CHECK_RC(nRetVal, "Create mock depth node");
MockImageGenerator mockColor;
mockColor.CreateBasedOn(color);
CHECK_RC(nRetVal, "Create mock color node");

Recorder recorder;
nRetVal = recorder.Create(context);
CHECK_RC(nRetVal, "Create recorder");

nRetVal = recorder.SetDestination(XN_RECORD_MEDIUM_FILE, "dst.oni");
CHECK_RC(nRetVal, "Set recorder destination file");

nRetVal = recorder.AddNodeToRecording(mockDepth);
CHECK_RC(nRetVal, "Add node to recording");
nRetVal = recorder.AddNodeToRecording(mockColor);
CHECK_RC(nRetVal, "Add node to recording");

for (int i = 0; i < frame_num;++i)
{
    std::stringstream ss;
    ss << depth_dir << i << ".png";
    std::string filepath_depth = ss.str();

    std::stringstream sss;
    sss << color_dir << i << ".png";
    std::string filepath_color = sss.str();

    cv::Mat depth_img = cv::imread(filepath_depth, CV_LOAD_IMAGE_ANYCOLOR | CV_LOAD_IMAGE_ANYDEPTH);
    depth_img.convertTo(depth_img, CV_16U);

    cv::Mat color_img = cv::imread(filepath_color, CV_LOAD_IMAGE_ANYCOLOR | CV_LOAD_IMAGE_ANYDEPTH);
    color_img.convertTo(color_img, CV_8UC3);

    //depth
    DepthMetaData depthMD;
    XnUInt32& di = depthMD.FrameID();
    di = i;                     // set frame id.
    XnUInt64& dt = depthMD.Timestamp();
    dt = i*30000+1;             // set a proper timestamp.

    depthMD.AllocateData(depth_img.cols, depth_img.rows);
    DepthMap& depthMap = depthMD.WritableDepthMap();
    for (XnUInt32 y = 0; y < depthMap.YRes(); y++)
    {
        for (XnUInt32 x = 0; x < depthMap.XRes(); x++)
        {
            depthMap(x, y) = depth_img.at<ushort>(y, x);
        }
    }
    nRetVal = mockDepth.SetData(depthMD);
    CHECK_RC(nRetVal, "Set mock node new data");

    //color
    ImageMetaData colorMD;
    XnUInt32& ci = colorMD.FrameID();
    ci = i;
    XnUInt64& ct = colorMD.Timestamp();
    ct = i*30000+1;

    colorMD.AllocateData(color_img.cols, color_img.rows, XN_PIXEL_FORMAT_RGB24);
    RGB24Map& imageMap = colorMD.WritableRGB24Map();
    for (XnUInt32 y = 0; y < imageMap.YRes(); y++)
    {
        for (XnUInt32 x = 0; x < imageMap.XRes(); x++)
        {
            cv::Vec3b intensity = color_img.at<cv::Vec3b>(y, x);
            imageMap(x, y).nBlue = (XnUInt8)intensity.val[0];
            imageMap(x, y).nGreen = (XnUInt8)intensity.val[1];
            imageMap(x, y).nRed = (XnUInt8)intensity.val[2];
        }
    }
    nRetVal = mockColor.SetData(colorMD);
    CHECK_RC(nRetVal, "Set mock node new data");

    recorder.Record();
    printf("Recorded: frame %u out of %u\r", depthMD.FrameID(), frame_num);
}


text:
Q: Allow value to be a function so we have the same API as useState I started analyzing useLocalStorage hook from https://usehooks-ts.com/ and I am wondering why they are actually allowing value to be a function in setValue ? There is a comment "Allow value to be a function so we have the same API as useState" but I don't really understand it. In what case value would be a function? Could anyone explain it for me?
 try {
      // Allow value to be a function so we have the same API as useState
      const newValue = value instanceof Function ? value(storedValue) : value

      // Save to local storage
      window.localStorage.setItem(key, JSON.stringify(newValue))

      // Save state
      setStoredValue(newValue)

A: This is a "functional update":

If the new state is computed using the previous state, you can pass a function to setState. The function will receive the previous value, and return an updated value.

It is especially interesting if you update the state value asynchronously, while the current value may have changed in the meantime, and your final update must account for this new change.


text:
Q: Google Container Engine stdout Logs Not Showing Up My stdout logs are not showing up in Google Logs Viewer, or when using kubectl logs <pod>. The cluster has Cloud Logging enabled and fluentd containers are running on each node.
Example Python code:
logger = logging.getLogger()
logger.setLevel(logging.INFO)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.INFO)
logger.addHandler(handler)
logger.info("test log")

The "counter-pod" example from their docs does work on my cluster, so the fluentd containers are picking up stdout and sending it to Logs Viewer.
Any suggestions for things I should try? Thanks in advance.

A: The logs are definitely going to stdout, they just aren't showing up when running kubectl logs <pod_name>. Nor are they showing up in Google Logs Viewer.
This is because logs sent to stdout will only be captured if they're coming from the process that's the entry point of the Docker container. Things that are done in the shell or via a cron job don't show up.
In my case I had a cron job that was invoking a script. By running the script as the container's entry point, the logs showed up fine.

A: If the logs aren't showing up when you run kubectl logs pod, then the problem is almost certainly that the logs from your application aren't going to stdout or stderr, so that's what you should focus on.
What happens if you docker run your application locally? Does docker logs then show the logs you expect? That should at least get you a faster iteration cycle to play around with different approaches to fixing it.


text:
Q: Reset state without Effects using key I came across exercise from beta.react docs concerning issue: Reset state without Effects.
You may find it in the bottom : Challenge 3 of 4: Reset state without Effects.
There's a component that receives object of person data to present it in editable form.
As for start it tells you that useEffect is redundant.
import React, { useState } from "react";
//ExportContact.jsx

export default function EditContact({ savedContact, onSave }) {
  const [name, setName] = useState(savedContact.name);
  const [email, setEmail] = useState(savedContact.email);

  // useEffect(() => {
  //   setName(savedContact.name);
  //   setEmail(savedContact.email);
  // }, [savedContact]);

  return (
    <section>
      <label>
        Name:{" "}
        <input
          type="text"
          value={name}
          onChange={(e) => setName(e.target.value)}
        />
      </label>
      <label>
        Email:{" "}
        <input
          type="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
        />
      </label>
      <button
        onClick={() => {
          const updatedData = {
            id: savedContact.id,
            name: name,
            email: email
          };
          onSave(updatedData);
        }}
      >
        Save
      </button>
      <button
        onClick={() => {
          setName(savedContact.name);
          setEmail(savedContact.email);
        }}
      >
        Reset
      </button>
    </section>
  );
}

Suggested solution is to split into another component that will receive key of contact id.
Like that where EditForm contains everything EditContact had so far.
export default function EditContact(props) {
  return (
    <EditForm
      {...props}
      key={props.savedContact.id}
    />
  );
}

I'm just wondering how would it be different to add key prop with contact id value right into the parent component like this:

      <EditContact
        key={selectedContact.id}
        savedContact={selectedContact}
        onSave={handleSave}
      />

Instead of splitting EditContact into artificial subcomponent only to receive a key prop.

A: The difference is explained in the official link about spread attributes.
Below is the official summary:

Spread attributes can be useful but they also make it easy to pass unnecessary props to components that don't care about them or to pass invalid HTML attributes to the DOM. We recommend using this syntax sparingly.


text:
Q: Randomly "502 bad gateway" on production, but it's ok on dev machine (express js) I've got a node js script (Express js framework). I have a problem with this server only on production - on developer machine everything is good.
On developer machine an on production this server is running in Docker container. Container if from the same image of course.
The problematic scenario:

*

*Start server

*Make a request:
2.1. upload file to server and save in on hard disc drive
2.2. send a POST request via curl to microservice. This request is send to micorservice the file from 2.1 point. It's POST request. We use node-libcurl library
2.3. After long time (few minutes) microservice returns a response.
2.4. This response is saved on server.
2.5. Print a template.
On developer machine this request works totally correctly: from point 2.1 to 2.5.
But on production machine this request works correctly do all points except 2.5. I know it works good on 2.1-2.4 because server logs this information.
Production is on https://www.linode.com/.
Have you any idea what's wrong?
EDIT:
I forgot to mention, but server on production returns "502 bad gateway" error randomly for the same file and microservice response. Sometimes this requests is ok

A: I dont know how you start the application within the container, but I would suggest you'll use forever (https://www.npmjs.com/package/forever) to make sure it does not go inactive.
I've had 502 errors because of that in other systems when there were no activity for a few minutes.
Hope this helps a little


text:
Q: App Down after being forced onto paid plan Many years ago I created an app and deployed it to Heroku and utilized heroku-postgresql as the database where content generated by the app was stored. A few months ago I received a notification stating that I had to upgrade to a paid plan and add a paid dyno. I've barely touched it for the last 2 years, only having to upgrade once when a key module was deprecated, so I barely even remember how to use Heroku.
After I upgraded to a paid plan (postgresql-spherical-36581) and added basic dynos (which appear to be active), when attempting to open the app I received a 500 error and the browser displayed *'We're sorry, but something went wrong.' *
Herolu's support team have been little help and they either don't have access to my account details or chose not to take the time to read it. In my past life as a developer this forum was unbelievably helpful so I'm hoping the error messages I'm getting makes sense to someone. I tried to add all logs but when trying to post the question I got an error saying "this looks liek spam"
I've searched the forum for answers but can't find anything that answers my question.
Thank you
App logs when trying to open the app url in browser:
dyno=web.1 connect=0ms service=20ms status=500 bytes=1753 protocol=https
2023-01-28T17:50:46.560796+00:00 app[web.1]: 10.1.84.246 - - [28/Jan/2023:17:50:46 UTC] "GET /users/sign_in HTTP/1.1" 500 1477


text:
Q: unable to remove div inserted by jquery am trying to remove a div inserted by jquery onclick. for some reason its just not working i tried remove(); hide(); css(); empty(); they all are just not working.. so here's my js function
function callme()
{
var content = '
'
'sdfsdfsdfsdfsfsddsfsfsdfsdfsdfsfsdfsdfsdfsfsdfsd'
'
';
jQuery('body.floating_box').empty();
jQuery('body').append(content);
}

and here is my html code

23

A: use jQuery('#floating_box')
You are using an id, but are not referencing it as one ..
You need to use the .remove() method, because with the .empty() you are creating multiple elements with the same id which is invalid
Have a look at this demo

Update
After the comment, i see that you want the 1st time you click to create the element, and subsequent clicks to just show/hide it ..
use this code
$('#notify').click(
function (){
    if ($('#floating_box').length > 0) // it exists
    {
        jQuery('#floating_box').toggle(); // show/hide\
    }
    else //does not exist 1st time only..
    {
        var content = '
popup
';
        jQuery('body').append(content);
    }
});

and remove the onclick="callme" from the element..

A: demo
function callme()
{
    var content = '
' +
    'sdfsdfsdfsdfsfsddsfsfsdfsdfsdfsfsdfsdfsdfsfsdfsd' +
    '
';
    jQuery('#floating_box').toggle();
    if (!$('#floating_box').length)
      jQuery('body').append(content);
}

A: var content = '
' +
'sdfsdfsdfsdfsfsddsfsfsdfsdfsdfsfsdfsdfsdfsfsdfsd' +
'
';

See the +  ??
jQuery('body.floating_box').remove(); // edit: sorry my mistake
jQuery('body #floating_box').remove(); // better? should remove all elements within  with the id "floating_box"

Should be just fine.

A: You are not seeing the floating_box being removed because a new version of the floating_box div is added whenever you call the callme function.
 function callme() {
     var $floatingbox = jQuery("#floating_box");
     if ( $floatingbox.length ) {
         $floatingbox.remove();
     }
     else {
        var content = '
' +
            'sdfsdfsdfsdfsfsddsfsfsdfsdfsdfsfsdfsdfsdfsfsdfsd' +
            '
';
        jQuery('body').append(content);
     }
 }

This will check whether the floating_box div exists, and remove it otherwise add it.


text:
Q: Formdata in expo app is being recieved in _parts but in object form when send from web app I am sending form to backend by using FormData and using multer on backend to recieve the data, it works fine on my web app but on doing the same axios call to submit data in react-native shows that data fields are being received on backend in following form
{ _parts: [ [ 'firstname', 'fahad' ], [ 'firstname', 'RAO' ] ] }

i am doing following call in my web app (which works there) and in my expo app
const testFOrmData = ()=>{

        var data = new FormData()
        data.append("firstname","fahad")
        data.append("firstnae","RAO")
        const adata  = {
            firsn:"rew"
        }
axios.post("http://x.x.x.x:xxxx/api/testform",data)
.then((res)=>{
    console.log(res)
})
alert("SANS")
    }

How to receive it in object form such that i dont have to make changes in my existing code in backend as i have so many forms and i have submitted them using form data in my web app and have to do same in mobile app but i dont want to submit without FormData(by sending object in axios)
my backend
router.post("/testform",upload.none(),(req,res)=>{
    console.log(req.body)
    res.json({resp:req.body})
})


text:
Q: Transforming $x^2-x-1=0$ into $(x^2-1)^2-1=x$ introduces roots that don't solve the original equation. What's wrong with the logic? The equation
$$x^2-x-1=0$$
has two solutions (the golden ratio being one). However, since
$$x^2-x-1=0 \quad\implies\quad x^2-1=x$$
we have an equation for $x$ in terms of itself. If we take the left hand side which is equal to $x$ and plug it back into the $x^2$ term we get the quartic
$$(x^2-1)^2-1=x$$
This has four solutions (the old solutions with the addition of $0$ and $1$) but these new solutions do not solve the original equation.

Why is there a logical error in using the equation in $x$ recursively in the way shown?

A: The problem is, I think, clearer if you take a simpler example.  $$x^2=1\implies 1\times x^2=1\implies x^2\times x^2=1\implies x^4=1$$
but, of course, there are solutions of $x^4=1$ that are not solutions of $x^2=1$.
The problem, of course, is that some of the implications really are one way only.  It is simply not true that $x^2\times x^2=1\implies x^2=1$, all we can say is that $x^2\times x^2=1\implies x^2=\pm 1$. In this way, solutions of the final equation need not be solutions of the original.
As suggested by @IzaakvanDongen in the comments, one can achieve the same sort of example without falling back on complex solutions.  Indeed one could write $$x=1\implies 1\times x=1\implies x\times x=1 \implies x^2=1$$
and, of course, $x=-1$ solves the final equation but not the original.

A: Let's set $f(x)=x^2-1$. Your original equation is $f(x)=x$, and it's got, as you said, two solutions. Your new equation is $f(f(x))=x$, and it's got four solutions.
As already highlighted in lulu's answer: your new equation is just implied by the original one: if $f(x)=x$, then $f(f(x))=f(x)=x$. Your new equation is, however, not equivalent to the original one, because the opposite implication is not valid.
Namely, if $f(f(x))=x$, it may be that actually you have $f(x)=y$ for some $y\ne x$, and also $f(y)=x$. In other words, function $f$ doesn't have $x$ as its "fixed point". instead it swaps it with some other value $y$. Then, obviously, $f(f(x))=f(y)=x$, and $f(f(y))=f(x)=y$, so $x$ and $y$ are two additional solutions. In our case, $f(x)=x^2-1$ "swaps" $0$ and $-1$, so those two numbers pop up as additional solutions.
A bigger point is that not every transformation of an equation to a different one transforms it to an equivalent equation. If implication is valid only in one direction, you may end up with more solutions than the original equation has. (I have most often seen people do this when they square both sides of the equation.) One way to cope with that is to proceed nevertheless, but to check (at the end) whether the obtained solutions satisfy the original equation, or are those some additional solutions that popped up like in your example.

A: Note that there is no logical error in saying that  $x^2-x-1=0$ implies $(x^2-1)^2-1=x$ but as in the answer by @lulu there are now other solutions as well.

A: I likewise got flabbergasted by reinjecting a recursive definition of $x$ into the golden ratio equation and realizing
I had introduced a new root. (In my case, the recursion was $x = 1 + \frac 1 x$.)
The reasons of my surprise was the following fallacy:

I reused the recursion I started from to derive the equation; so I hadn't added any information. So how come I ended up smuggling in a new root?

It is a fallacy insofar as introducing a new root does not come as a result of adding, but losing information.
For example, when you reuse the recursive definition $x = x^2 - 1$ inside this very definition, you obtain
a new recursive definition of $x$ from which you cannot retrieve the one you started from. So you have lost this
information:
$$x = (x^2 - 1)^2 - 1$$
$$\phantom{x} = x^4 - 2\,x^2$$
$$\phantom{x} = x^2\,(x^2-2)$$
Yet, you don't have a contradiction; you have not introduced any new information, just derived a weaker statement.
$${x} = x^2\,(x^2-2)$$
$$x^4 - 2\,x^2 - x = 0$$
$$(x^2 - x - 1)\,(x^2+x) = 0 \iff \left[ x^2 + x = 0 \ \lor\  x = x^2 - 1 \right]$$
And, indeed, if you assume that $x^2 + x \neq 0$ and divide both sides by this expression, you retrieve your original equation.
$$\frac x {x^2 + x} = \frac {x^4 - 2\,x^2}{x^2 + x} = x^2 - x - 1 + \frac x { x^2 + x }$$
As an aside, notice that you would have obtained some intriguing extraneous roots if you had substituted $x^2 - 1$ for both occurrences of $x$ in the equation.
$$(x^2 - 1)^2 - (x^2 - 1) - 1 = 0$$
$$x^4 - 3\,x^2 + 1 = 0$$
$$(x^2 - x - 1)\ (x^2 + x - 1) = 0$$
The extraneous roots are $\frac {-1 + \sqrt 5}2$ and $\frac {-1 - \sqrt 5}2$.


text:
Q: Mathematica - Problem with creating symbolic XML In a mathematica application I have an OO-System object which represents a cuboid as follows:
 In[27]:= oscg@getItem[11]@getObject[]

 Out[27]= {"GE", {"CB", {{3., 0., 3.}, 0.9}}, {0.3}}

I transfer this object to Xml with the following method:
 In[28]:= oscg@getItem[11]@toXml[]

 Out[28]= XMLElement["cuboid", {"point" -> "{3., 0., 3.}",
  "diameter" -> "9
  --
  10", "hue" -> "0.3"}, {}]

I would have expected here:
 XMLElement["cuboid", {"point" -> "{3., 0., 3.}", "diameter" -> "0.9", "hue" -> "0.3"}, {}]

The method code is as follows:
 toXml[]:= Module[
{ret,
p=getPoint[] + getColref[]@absPoint[getMe[]],
d=getDiameter[],
h=getHue[]},
ret=XMLElement["cuboid",{"point"->ToString[p], "diameter"->ToString[d],
    "hue"->ToString[h]}, {}];
ret
];

The problem is that 0.9 becomes 9 -- 10.
I thought about a format issue but hue is nicely output as 0.3. ( The problem becomes critical in the stage where the Xml is read and parsed back to object creation code. )
Question:
Could it nevertheless be a format, display issue? ( A topic I am not very familiar with in Mathematica. ) Any ideas, on how to attack this?

A: Your diameter is likely stored as a rational:
 In[1]:= ToString[9/10]
Out[1]:= 9
         --
         10

Notice that two end-of-line codes are needed to print that fraction as a string.
Try ToString[N@d], ToString[N@h], etc. in toXml[]. You could also use ToString[d,InputForm] to get 9/10.


text:
Q: How to use the TypeScript version of the project not the .yarn/sdks/typescript/lib for VS Code I am using Yarn v3 and PnP.
Following the Editor Setup#vscode guide, but the VSCode will use the TypeScript version generated by below command:
yarn dlx @yarnpkg/sdks vscode

It will generate a new directory called .yarn/sdks, and there will be a generated TypeScript package there. The package information:
{
  "name": "typescript",
  "version": "4.9.5-sdk",
  "main": "./lib/typescript.js",
  "type": "commonjs"
}

There is a .vscode/settings.json:
{
  "typescript.tsdk": ".yarn/sdks/typescript/lib",
  "search.exclude": {
    "**/.yarn": true,
    "**/.pnp.*": true
  },
  "prettier.prettierPath": ".yarn/sdks/prettier/index.js",
  "typescript.enablePromptUseWorkspaceTsdk": true
}

As you can see, I can select the generated typescript.
But before I migrate to Yarn v3 and PnP, I use npm as my package manager. I can select the TypeScript version which is the project's devDependency.
package.json:
"typescript": "^4.1.2"

This makes the VSCode typescript version and the project's typescript inconsistent.
My project use "typescript": "^4.1.2", but VSCode use 4.9.5-sdk.
How can I select the typescript used in my project rather than the typescript generated by yarn dlx @yarnpkg/sdks vscode command?
Since I use PnP, there is no more node_modules directory. VSCode can't select the TypeScript version from node_modules anymore.


text:
Q: How is an executor termination recursion in java? This is a program that reads information site for previous format it uses recursion and executor.It works fine,my problem is to test whether the program is completed and success notification.
public class NewClass {

    static String levels[] = { "div.col-md-9 li a", "div#sidebar ul li a" };
    static String links = "";

    private void getRecursive(String href, int level, final ExecutorService executor) {

        if (level > levels.length - 1) {
            return;
        }

        Document doc;
        try {
            doc = Jsoup.connect(href).get();
            Elements elements = doc.select(levels[level]);
            final int flevel = ++level;
            for (final Element element : elements) {
                executor.execute(new Runnable() {
                    @Override
                    public void run() {
                        if (!element.attr("href").isEmpty()) {
                            links += element.attr("abs:href") + "\n";
                            System.out.println(links);
                            getRecursive(element.attr("abs:href"), flevel, executor);
                        }
                    }
                });
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

If levels.length = 1, the rule enforcer works well,but If levels.length>1 will appear error : Exception in thread "pool-1-thread-138" java.util.concurrent.RejectedExecutionException
    public static void main(String[] args) {
    try {
        ExecutorService executor = Executors.newFixedThreadPool(5);
        new NewClass().getRecursive("http://www.java2s.com/", 0, executor);
        executor.shutdown();
        executor.awaitTermination(1, TimeUnit.HOURS);
        if (executor.isTerminated()) {
            JOptionPane.showMessageDialog(null, "Success");
        }
    } catch (Exception ex) {
        Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
    }
}
}

A: The issue is that you're calling executor.execute after calling executor.shutdown(). The awaitTermination method only waits for tasks that were submitted before shutdown was called.
Here's why this is happening:

*

*Let's say the program starts on thread main.

*The first call to executor.execute is on main.

*Suppose the executor now runs on thread-pool-1, it also calls executor.execute.

*But before those new tasks execute, we jump back onto main and call executor.shutdown.

*The executor might start executing tasks again, maybe on thread-pool-2 this time, and it tries to call executor.execute. However, executor.shutdown() has already been called, so a java.util.concurrent.RejectedExecutionException is thrown.

There are a few ways to solve this:

*

*Using an executor might be overkill in this instance; just doing it single threaded will probably be sufficient.

*It may be possible to refactor the code so that the last executor.execute can call executor.shutdown. However, if there isn't a distinct last call, this won't be possible.

*If you absolutely need to do this off the main thread, you could perform the entire recursive call in its own thread:
public static void main(String[] args) {
    try {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.execute(new Runnable() {
            @Override
            public void run() {
                NewClass.getRecursive("http://www.java2s.com/", 0);
            }
        });
        executor.shutdown();
        executor.awaitTermination(1, TimeUnit.HOURS);
        if (executor.isTerminated()) {
            JOptionPane.showMessageDialog(null, "Success");
        }
    }
    catch (Exception ex)
    {
        Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
    }
}

and
private static class NewClass {

    static String levels[] = { "div.col-md-9 li a", "div#sidebar ul li a" };
    static String links = "";

    private static void getRecursive(String href, int level) {

        if (level > levels.length - 1) {
            return;
        }

        Document doc;
        try {
            doc = Jsoup.connect(href).get();
            Elements elements = doc.select(levels[level]);
            final int flevel = ++level;
            for (final Element element : elements) {
                if (!element.attr("href").isEmpty()) {
                    links += element.attr("abs:href") + "\n";
                    System.out.println(links);
                    getRecursive(element.attr("abs:href"), flevel);
                }
            }
        }
        catch (IOException e1) {
            e1.printStackTrace();
        }
    }
}

A: You can't submit any new tasks after you shutdown the ExecutorService, the recursion seems to stop after you've processed all the levels (you don't submit any new tasks after that), you can do something like this:
if (level > levels.length - 1) {
    executor.shutdown();
    return;
}


text:
Q: Quais as linguagens atuais utilizadas para desenvolvimento de aplicações para Windows? Quais as linguagens atuais utilizadas para desenvolvimento de aplicações para Windows?
Gostaria de saber as que possuem dependências, como o Java que precisa instalar o JRE ou algumas .NET que precisam que instale o .NET Framework previamente, assim como as que rodam sem nenhum instalação anterior.
Especificamente gostaria de saber linguagens que são utilizadas nas aplicações com interface gráfica (GUI).

Essa pergunta pode servir como um guia para programadores que querem começar a desenvolver para Desktop Windows.

Encorajada por essa pergunta: Qual a linguagem de programação para criar aplicações Android?

A: Essencialmente todas podem ser usadas de JavaScript à C, passando pelas citadas na pergunta, e obviamente C++, Delphi, Python e outras, não faz sentido listar todas.
Aí caímos no tipo de aplicação que usará, o Windows é muito libertário e permite todo tipo, para cada tipo haverá uma linguagem mais adequada. Vou concentrar em GUI.
Web GUI
Se for usar JavaScript pode fazer para rodar na web mesmo, em um browser, PWA, Webview em outra aplicação ou algo que suporte tecnologias web, como o Electron. Alguns dirão que isso é fazer para web e não para Windows, mas se ele roda no Windows é para o Windows e está fazendo GUI.
Scripts e dependentes
Diversas linguagens de script podem ser usadas para fazer diversas tarefas, mas se for criar uma aplicação desktop com GUI complica um pouco. Não é que elas não permitem, mas raramente é tão adequado.Algumas deixam bem a desejar, como o JS se for GUI nativa, o PHP que tem como mas o resultado é bem ruim, e outras porque tem o problema de ter que mandar todos os scripts em vez de mandar um executável para que parece ser uma preocupação (algumas até possuem alguma forma como Python faz).
Para GUI Java nunca se deu muito bem porque parece um pato (anda, nada e voa, nenhum bem), roda em todas plataformas mas em todas não roda bem, mas é uma opção razoável.
Sem instalação
Se realmente quer só o executável tem que pensar em linguagens como C, C++, Rust, Go, Delphi, e até Lua ou Harbour (eu sei que quase ninguém usa, mas é usada e gosto de citar) dependendo de como faça.
Claro que faz pouco sentido usar C pra muita coisa GUI complexa. Go ou mesmo Rust não tem histórico de uso com GUI. Delphi é proprietária e hoje em dia isso é um problema, mas tem GUI boa. C++ não é para qualquer um trabalhar. Cada uma tem um problema.
A Qt é uma biblioteca muita usada e veja os bindings disponíveis para ela que portanto fazem dessas linguagens candidatas à tarefa descrita na pergunta. A Qt é das mais interessantes, embora eu acho que ela andou tomando um rumo complicado, melhorou em vários pontos, mas estagnou em outro e piorou em vários alguns.
Outro framework usado é o WxWidgets, veja a lista de bindings.
Não vou listar todos os frameworks até porque alguns são pouco usados, muitos são usáveis de forma muito ruim apesar da linguagem suportá-lo em um binding, teria que fazer uma análise profunda em cada um. Se quiser tem uma lista de vários toolkits (não inclui frameworks que rodam em cima deles).
O .NET se encaixa bem porque a Microsoft faz dele o flagship para GUI, mas mesmo aí tem dificuldade de escolha porque temos 3 opções oficiais (Windows Forms, WPF e WinUI) e outras extras (algumas funcionam fora do Windows ou funcionam em cima da GUI nativa da plataforma que está rodando).
Existem alguns produtos que rodam em várias plataformas, entre elas o Windows, um exemplo da próprio Microsoft é o Xamarin e MAUI.
Entre essas é possível usar a API Win32 pura para GUI mas literalmente ninguém faz isso, não é algo palatável e nem é considerado uma opção real.
E o .NET não precisa mais estar instalado na máquina para funcionar. Na verdade essa forma de deploy já pode ser considerada legada. Então C# é das mais usadas e VB.NET era considerada, mas ela não tem futuro. F# ou outras linguagens que rodem no .NET podem ser usadas, mas na prática não são.
Conclusão
Mas não posso deixar de dizer que a linguagem não importa mas sim o ecossistema em volta delas, isso é o que definirá o que é interessante para essa tarefa ou não, você escolhe o framework que usará e aí vê qual é a melhor linguagem para a tarefa.
Veja Critérios para escolher linguagem para uso específico considerando o desempenho e Há algum problema em usar Java para aplicação de automação comercial no dektop? Ou é melhor fazer para web usando PHP?.

A: Oficialmente são mantidas quatro tecnologias pela Microsoft:

*

*Windows Universal - cujo é a última tecnologia da Microsoft feita essencialmente para dispositivos que funcionam no Windows 10. Estes aplicativos podem ser nativos na plataforma ou infundidos em aplicações .NET Core.
Inclui desenvolvimento em c#, f#, vb.net, c++ e javascript.

*Windows Forms e XAML - é uma tecnologia legado, mas ainda utilizado, onde suas aplicações dependem do .NET Framework para serem executadas. O XAML utiliza uma linguagem de design parecida com o XML para prototipação de interfaces.
Inclui desenvolvimento em c#, f# e vb.net.

*Windows API - também conhecido como Win32 API - são os aplicativos nativos, feitos para rodar em qualquer ambiente no Windows. São feitos essencialmente para aplicativos que requerem uma comunicação direta com algum driver ou hardware ou necessita de uma performance não-gerenciada.
Inclui desenvolvimento em c e c++.
Existem outras tecnologias de terceiros, mas não vou citar elas aqui. Acima estou descrevendo qual o escopo de cada uma. O Windows Universal pode abranger todos dispositivos que rodem o Windows 10, incluindo Xbox, computadores ou televisões. Os outros são para escopos um pouco mais limitados.
Levaram o Windows Forms para o .NET Core. A teoria é que as interfaces funcionem em multi-plataforma.


text:
Q: How can I get rid of this invisible file? Background
I have a folder named akorg✽. That Unicode character causes headaches for me when software makes incorrect assumptions about the text encoding of my file paths, so I'd like to remove it from the name.
The problem
You'd think this would be easy:
$ mv akorg✽ akorg
mv: cannot move 'akorg✽' to a subdirectory of itself, 'akorg/akorg✽'

but—that's strange—it thinks a folder called akorg already exists. I'm pretty sure there isn't one:
$ ls -la
total 699K
drwxr-xr-x 15 ak ak   15 Jun 12 17:34 .
drwxr-xr-x 57 ak ak 4.0K Jun 12 17:35 ..
drwxr-xr-x 11 ak ak   21 Jun 12 16:58 akorg✽
drwxr-xr-x  2 ak ak    2 May 28 20:47 Desktop
...

Still, stat says otherwise:
$ stat akorg
  File: 'akorg'
  Size: 21          Blocks: 33         IO Block: 1536   directory
Device: 15h/21d Inode: 292128      Links: 11
...

So apparently there is an invisible folder in the way. Whatever, I'll just remove it:
$ rmdir akorg
rmdir: failed to remove 'akorg': No such file or directory

Right, then. What in the world is this thing?
What I know so far

*

*I'm using the stable release of ZFS on Linux. Here's the zpool status and zfs properties.

*stat returns the same inode for both akorg and akorg✽. Searching by that inode returns only akorg✽:
$ find . -maxdepth 1 -inum 292128
./akorg✽

*More things that don't work on the "invisible" folder:
$ rm akorg
rm: cannot remove 'akorg': Is a directory
$ unlink akorg
unlink: cannot unlink 'akorg': Is a directory
$ mv akorg akorg_temp
mv: cannot move 'akorg' to 'akorg_temp': No such file or directory

*I get the same results in both Bash 4.2.45 and zsh 5.0.0. In both, tab-completion of ak returns only akorg✽/.

*The strace of my initial renaming attempt confirms that I'm typing the names correctly and that the attempt is thwarted by the preexistence of a folder named akorg.

*This response to a more explicit renaming attempt is puzzling and scary:
$ mv --verbose --no-target-directory --no-clobber akorg✽ akorg
removed 'akorg✽'

I don't understand why it claims to have removed akorg✽, or why it would try. Fortunately, ls and stat akorg akorg✽ reveal that nothing is actually gone. Here's the strace.

*To rule out encoding quirks as the cause of this, I've temporarily given akorg✽ an intermediate name:
$ mv --verbose --no-target-directory --no-clobber akorg✽ bananas
'akorg✽' -> 'bananas'

That worked as expected,
$ ls -la
total 715K
drwxr-xr-x 16 ak ak   16 Jun 13 15:11 .
drwxr-xr-x 57 ak ak 4.0K Jun 13 14:03 ..
drwxr-xr-x 11 ak ak   21 Jun 12 16:58 bananas
drwxr-xr-x  2 ak ak    2 May 28 20:47 Desktop
...

but the "invisible" folder is still present:
$ stat bananas akorg
  File: 'bananas'
  Size: 21          Blocks: 33         IO Block: 1536   directory
Device: 15h/21d Inode: 292128      Links: 11
...
  File: 'akorg'
  Size: 21          Blocks: 33         IO Block: 1536   directory
Device: 15h/21d Inode: 292128      Links: 11
...

and mv still behaves strangely when I try to use the name akorg:
$ mv --verbose --no-target-directory --no-clobber bananas akorg
removed 'bananas'

A: As you're using zsh, I recommend tab completion or shell globbing (always echo/ls before removing). If those doesn't work, you have a few options:
Check your filename through a hex dump and use $'...' to input it
% touch akorg✽
% ls | grep akorg | hexdump -C
00000000  61 6b 6f 72 67 e2 9c bd  0a                       |akorg....|
00000009
% ls $'akorg\xe2\x9c\xbd'
akorg✽
% rm $'akorg\xe2\x9c\xbd'
% ls
%

Note that the final 0a above is the newline at the end of the input, so we don't want it in our name.
Use ls -i to get the inode number and use find to delete it
% touch akorg✽
% ls -i
6128574 akorg✽
% find . -inum 6128574
akorg✽
% find . -inum 6128574 -delete
% ls
%

You could also find it by name (either way, print first!)
Use ls -b to get the escaped name and enter it with $'...' (This works with nonprinting characters but doesn't seem to affect your unicode one, so this is for others' reference).
% ls
foo?bar
% ls -b
foo\rbar
% rm foo$'\r'bar
% ls
%

A: This is weird. (And this "answer" started as a comment ;), became a bit long for it.)
Looking at the strace it looks like there are no hidden characters or the like, else I suspect you would have seen it in e.g. (which should have resulted in -1 ENOENT and not 0 if everything was OK):
stat("akorg", {st_mode=S_IFDIR|0755, st_size=21, ...}) = 0

as you do in:
lstat("akorg\342\234\275", {st_mode=S_IFDIR|0755, st_size=21, ...}) = 0

Came across a mail exchange where one person has the opposite problem. ls list the files, but stat give ENOENT – though that was on FreeBSD.
I do not know much about zfs, but could it be that some sync, snapshot or the like has failed and left a corrupted file table? Did you create/have a directory named akorg that you deleted before you tried the mv?
Do not know if you can get some error descriptions by:
# zpool status -v

One thing to try is check the reverse inode lookup (optionally add yet another d) and check path:
# zdb -dddd <pool-name> <inode>

On a folder named baz:
# zdb -dddd qqq 31
Object  lvl   iblk   dblk  dsize  lsize   %full  type
    31    1    16K    512     1K    512  100.00  ZFS directory
                                    264   bonus  ZFS znode
dnode flags: USED_BYTES USERUSED_ACCOUNTED
dnode maxblkid: 0
path    /baz
uid     1000
gid     1000
atime   Fri Jun 14 12:39:46 2013
mtime   Fri Jun 14 11:55:33 2013
ctime   Fri Jun 14 11:55:33 2013
crtime  Fri Jun 14 11:55:33 2013
gen 1510
mode    40775
size    2
parent  3
links   2
xattr   0
rdev    0x0000000000000000
microzap: 512 bytes, 0 entries

On a directory named foo holding several subdirectories including one named akorg✽:
Object  lvl   iblk   dblk  dsize  lsize   %full  type
    16    1    16K    512     1K    512  100.00  ZFS directory
                                    264   bonus  ZFS znode
dnode flags: USED_BYTES USERUSED_ACCOUNTED
dnode maxblkid: 0
path    /foo
uid     1000
gid     1000
atime   Fri Jun 14 13:10:38 2013
mtime   Fri Jun 14 12:13:18 2013
ctime   Fri Jun 14 12:13:18 2013
crtime  Fri Jun 14 11:41:53 2013
gen 1482
mode    40775
size    6
parent  3
links   6
xattr   0
rdev    0x0000000000000000
microzap: 512 bytes, 4 entries

    foo1 = 15 (type: Directory)
    foo2 = 18 (type: Directory)
    foo = 19 (type: Directory)
    akorg✽ = 30 (type: Directory)

The settings you have on zfs get all storage/home-ak-annex for various name mod also looks sane (as far as I can tell) as well as the other properties by reading ZFS Properties:
storage/home-ak-annex  utf8only              off                    -
storage/home-ak-annex  normalization         none                   -
storage/home-ak-annex  casesensitivity       sensitive              -

If you build zfs yourself you can enable debug by ./configure --enable-debug and play with the above including -vvvv, -bbbb etc.
Lastly you could open a new Issue on the git.

A: I'm guessing that you don't have an invisible directory, but rather that stat misprints the unicode characters so that the file name looks like akorg when on-screen.
Two possible solutions:

*

*Use a shell with tab completion (zsh or bash).  At the prompt do: rm -rf akorg<tab>.  Zsh at least will complete the file name, escaping shell-special characters as necessary.

*A one liner, a bit risky: rm -rf akorg?
You could do #2 by hand, something like: ls -1 > filenames. Use some text editor on the file named "filenames" to delete all lines except the offending directory.  Add a prefix of rm -rf to that line.  Exit editor.  Execute as a shell script: sh filenames


text:
Q: Tensorflow Type Error invalid type , must be a string or Tensor I'm trying to get a simple boosted decision tree up and running with test data. I have something like this working on another machine, but when porting the code over I get this error:
TypeError: Fetch argument 0 has invalid type <class 'numpy.int64'>, must be a string or Tensor. (Can not convert a int64 into a Tensor or Operation.) based on reading, this error generally results in reassigning a critical variable, but I'm having a hard time figuring out what it might be.
This is my code (sorry if it's a bit messy, I condensed it down as much as I could)
import pandas as pd
import tensorflow as tf
tf.random.set_seed(123)
from sklearn.datasets import make_blobs

#creates an input function for a tf model
def make_input_fn(X, Y, n_epochs=None, shuffle=True):
    batch_len = len(Y)
    def input_fn():
        dataset = tf.data.Dataset.from_tensor_slices((dict(X), Y))
        if shuffle:
            dataset = dataset.shuffle(batch_len)
        # For training, cycle thru dataset as many times as need (n_epochs=None).
        dataset = dataset.repeat(n_epochs)
        #dividing data into batches
        dataset = dataset.batch(batch_len)
        return dataset
    return input_fn

def fullTest():
    print('_______Defining Test Data Blobs_______')
    xVals, yVals = make_blobs(n_samples=10, centers=2, n_features=3, random_state=0)

    #xVals
    xVals = pd.DataFrame(xVals)
    xVals.columns = ['feature {}'.format(num) for num in xVals.columns]
    print('xVals:')
    print(xVals)

    #yVals
    yVals = pd.DataFrame(yVals)
    yVals.columns = ['flag']
    print('yVals:')
    print(yVals['flag'].value_counts())

    # Defining input function
    train_input_fn = make_input_fn(xVals, yVals)

    trainX=xVals
    trainY=yVals

    #defining tf feature columns
    feature_columns=[]
    for feature_name in list(trainX.columns):
        feature_columns.append(tf.feature_column.numeric_column(feature_name,dtype=tf.float32))

    #creating the estimator
    n_batches = 1
    est = tf.estimator.BoostedTreesClassifier(feature_columns, n_batches_per_layer=n_batches)

    est.train(train_input_fn, max_steps=250)

if __name__ == '__main__':
    fullTest()

There's a lot of error printout. This is the more pertinant stuff:
...\site-packages\tensorflow\python\framework\ops.py", line 3759, in _as_graph_element_locked
    (type(obj).__name__, types_str))
TypeError: Can not convert a int64 into a Tensor or Operation.

During handling of the above exception, another exception occurred:

line 309, in __init__
    (fetch, type(fetch), str(e)))
TypeError: Fetch argument 0 has invalid type <class 'numpy.int64'>, must be a string or Tensor. (Can not convert a int64 into a Tensor or Operation.)

full traceback:
Traceback (most recent call last):
  File "D:\Documents\Contracting\Yang\Ok2StandUp\Environments\ok2suGen\lib\site-packages\tensorflow\python\client\session.py", line 305, in __init__
    fetch, allow_tensor=True, allow_operation=True))
  File "D:\Documents\Contracting\Yang\Ok2StandUp\Environments\ok2suGen\lib\site-packages\tensorflow\python\framework\ops.py", line 3667, in as_graph_element
    return self._as_graph_element_locked(obj, allow_tensor, allow_operation)
  File "D:\Documents\Contracting\Yang\Ok2StandUp\Environments\ok2suGen\lib\site-packages\tensorflow\python\framework\ops.py", line 3759, in _as_graph_element_locked
    (type(obj).__name__, types_str))
TypeError: Can not convert a int64 into a Tensor or Operation.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Daniel Warfield\AppData\Local\Programs\Python\Python35\Lib\site-packages\Ok2StandLibrary\ok2stand_library\modeling\modeling_tools.py", line 127, in <module>
    fullTest()
  File "C:\Users\Daniel Warfield\AppData\Local\Programs\Python\Python35\Lib\site-packages\Ok2StandLibrary\ok2stand_library\modeling\modeling_tools.py", line 105, in fullTest
    est.train(train_input_fn, max_steps=250)
  File "D:\Documents\Contracting\Yang\Ok2StandUp\Environments\ok2suGen\lib\site-packages\tensorflow_estimator\python\estimator\estimator.py", line 349, in train
    loss = self._train_model(input_fn, hooks, saving_listeners)
  File "D:\Documents\Contracting\Yang\Ok2StandUp\Environments\ok2suGen\lib\site-packages\tensorflow_estimator\python\estimator\estimator.py", line 1175, in _train_model
    return self._train_model_default(input_fn, hooks, saving_listeners)
  File "D:\Documents\Contracting\Yang\Ok2StandUp\Environments\ok2suGen\lib\site-packages\tensorflow_estimator\python\estimator\estimator.py", line 1208, in _train_model_default
    saving_listeners)
  File "D:\Documents\Contracting\Yang\Ok2StandUp\Environments\ok2suGen\lib\site-packages\tensorflow_estimator\python\estimator\estimator.py", line 1507, in _train_with_estimator_spec
    log_step_count_steps=log_step_count_steps) as mon_sess:
  File "D:\Documents\Contracting\Yang\Ok2StandUp\Environments\ok2suGen\lib\site-packages\tensorflow\python\training\monitored_session.py", line 604, in MonitoredTrainingSession
    stop_grace_period_secs=stop_grace_period_secs)
  File "D:\Documents\Contracting\Yang\Ok2StandUp\Environments\ok2suGen\lib\site-packages\tensorflow\python\training\monitored_session.py", line 1038, in __init__
    stop_grace_period_secs=stop_grace_period_secs)
  File "D:\Documents\Contracting\Yang\Ok2StandUp\Environments\ok2suGen\lib\site-packages\tensorflow\python\training\monitored_session.py", line 749, in __init__
    self._sess = _RecoverableSession(self._coordinated_creator)
  File "D:\Documents\Contracting\Yang\Ok2StandUp\Environments\ok2suGen\lib\site-packages\tensorflow\python\training\monitored_session.py", line 1231, in __init__
    _WrappedSession.__init__(self, self._create_session())
  File "D:\Documents\Contracting\Yang\Ok2StandUp\Environments\ok2suGen\lib\site-packages\tensorflow\python\training\monitored_session.py", line 1236, in _create_session
    return self._sess_creator.create_session()
  File "D:\Documents\Contracting\Yang\Ok2StandUp\Environments\ok2suGen\lib\site-packages\tensorflow\python\training\monitored_session.py", line 909, in create_session
    hook.after_create_session(self.tf_sess, self.coord)
  File "D:\Documents\Contracting\Yang\Ok2StandUp\Environments\ok2suGen\lib\site-packages\tensorflow\python\training\basic_session_run_hooks.py", line 587, in after_create_session
    self._save(session, global_step)
  File "D:\Documents\Contracting\Yang\Ok2StandUp\Environments\ok2suGen\lib\site-packages\tensorflow\python\training\basic_session_run_hooks.py", line 620, in _save
    write_meta_graph=self._save_graph_def)
  File "D:\Documents\Contracting\Yang\Ok2StandUp\Environments\ok2suGen\lib\site-packages\tensorflow\python\training\saver.py", line 1158, in save
    global_step = training_util.global_step(sess, global_step)
  File "D:\Documents\Contracting\Yang\Ok2StandUp\Environments\ok2suGen\lib\site-packages\tensorflow\python\training\training_util.py", line 68, in global_step
    return int(sess.run(global_step_tensor))
  File "D:\Documents\Contracting\Yang\Ok2StandUp\Environments\ok2suGen\lib\site-packages\tensorflow\python\client\session.py", line 958, in run
    run_metadata_ptr)
  File "D:\Documents\Contracting\Yang\Ok2StandUp\Environments\ok2suGen\lib\site-packages\tensorflow\python\client\session.py", line 1166, in _run
    self._graph, fetches, feed_dict_tensor, feed_handles=feed_handles)
  File "D:\Documents\Contracting\Yang\Ok2StandUp\Environments\ok2suGen\lib\site-packages\tensorflow\python\client\session.py", line 477, in __init__
    self._fetch_mapper = _FetchMapper.for_fetch(fetches)
  File "D:\Documents\Contracting\Yang\Ok2StandUp\Environments\ok2suGen\lib\site-packages\tensorflow\python\client\session.py", line 276, in for_fetch
    return _ElementFetchMapper(fetches, contraction_fn)
  File "D:\Documents\Contracting\Yang\Ok2StandUp\Environments\ok2suGen\lib\site-packages\tensorflow\python\client\session.py", line 309, in __init__
    (fetch, type(fetch), str(e)))
TypeError: Fetch argument 0 has invalid type <class 'numpy.int64'>, must be a string or Tensor. (Can not convert a int64 into a Tensor or Operation.)

version info (also GPU acceleration isn't working but as long as that isn't the source of the problem it's not a concern):
2020-08-31 20:29:14.209013: W tensorflow/stream_executor/platform/default/dso_loader.cc:59] Could not load dynamic library 'cudart64_101.dll'; dlerror: cudart64_101.dll not found
2020-08-31 20:29:14.209649: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
Python Version: 3.5.6 |Anaconda, Inc.| (default, Aug 26 2018, 16:05:27) [MSC v.1900 64 bit (AMD64)]
tf version: 2.3.0


text:
Q: What are the low level programming waveforms for the Atmel ATF16V8B? I want to program some ATF16V8B chips for a project. Naturally I don't have a programmer. No problem, I'll homebrew it with a Raspberry Pi.  It will be fun.
I only need one thing - I need the programming waveforms. Specific sequence enter programming mode, what voltage to apply and for what duration for each byte to be programmed, etc. All the stuff that they used to put in the datasheets before they replaced that whole section with "Program PLDs using a programmer".
Can anyone provide?

A: The programming algorithm for standard GALs, including the 16V8, is documented on this web page. It's too long to reproduce in its entirety here, but there are a couple of "quirks" that will make it difficult to perform using a Raspberry Pi:

*

*The GAL is a 5V part. The Raspberry Pi uses 3.3V I/O.

*To program the GAL, you have to supply 12V to the EDIT pin, and an even higher programming voltage (14 to 16V, depending on the part) on another pin.
My advice? Get a prebuilt programmer to handle it for you. I use a TL866 USB programmer, which can handle GALs as well as many other programmable parts (parallel EEPROMs, serial flash, AVRs and other microcontrollers...). It's a handy thing to have around.


text:
Q: 'require' is not defined in console tab of node-inspector's repl I tried to
require('fs').writeFileSync('o.json', JSON.stringify(anObject));

for debugging, and I got RefrenceError: require is not defined.
This is bizarre. What kind of an environment is it that doesn't have require?

A: In Node.js, the require function is not defined globally. When you require a module, its source code is wrapped by a function that takes several arguments and require is one of them:
(function (exports, require, module, __filename, __dirname) {/* your code */
});

You can see that wrapper in Node Inspector when you look at the content of any source file.
Now there are two different scenarios for evaluating code from Node Inspector's console:

*

*The debugged process is running. Expressions are evaluated in the global context, i.e. you have access only to globally defined symbols. require is not among them.

*The debugged process is paused on a break point. The expression is evaluated in the context of the select stack frame and have access too all variables in the current scope (which include variables captured by closures from by outer functions). However: most functions don't call require, therefore this variable is not captured in any closure and you can't access it.
I had a short chat with one of the Node core developers about exposing require as a global symbol, because it would simplify injecting code from Node Inspector, but my arguments were not convincing enough.

A: It is possible to use require in node-inspector, by hitting a breakpoint where 'require' is in scope (Tested with NodeJS v0.10.25, node-inspector@0.7.0-2):
An example (a super simple 2-byte 'REPL' for Node): create a file (for example r.js) containing just:
0;

then use
$ node --debug-brk r.js

and start node-inspector and the browser in the usual way,
-or- (using node-debug module from NPM) use:
$ node-debug r.js

Now switch to the node-inspector console in the browser and verify that require is indeed defined, then do something with it, like:
> typeof require;
"function"
> fs = require('fs');
undefined
> fs.writeFileSync('bla.txt', 'blup');
undefined

and verify that this file gets written in the directory where you started node.
Note: the browser part of node-inspector can be quite glitchy: when debuggong different scripts one after the other, I often need to refresh (causing a debugger disconnect), then restart Node until the script shows up correctly in the browser.
P.S. This method has an uncanny similarity to creating a Perl 'REPL' by running it as perl -de '0;'... Coincidence?

A: FWIW, just by starting with node-debug _mocha, stopping at a breakpoint and selecting the lowest frame on the call stack in the right-side panel, I got to a context where require() was available: require('fs') worked OK, but require('q') and other installed modules didn't, even if I specified an absolute path. Will get back if I come across the solution.

A: require() is implemented in all CommonJS environments, which include Node.js, but not in the browser's console, which is what node-inspector is based on (to be specific, the Blink Developer Tools):
> require
ReferenceError: require is not defined


text:
Q: Control not going inside jquery function @model DynamicRowAdd.Models.Test

@{
    ViewBag.Title = "Index";
}

Index

            @Html.TextBoxFor(Model => Model.Id, new { @Value = "1" })

            @Html.TextBoxFor(Model => Model.Name, new { @Value = "Abcd" })

<button id="myButton">Add New Row</button>

The above code when i try to run, I get the hi as alert. The following code is when the button is clicked which is not firing. the control is not going inside the function. Why.? I am doing something wrong.

A: $(document).ready(function(){

//Write your code here

});

JS Fiddle

A: use append method no need to specify any tr.. if u want to insert tr at beggining use prepend()
$('#myTable').append(newRow);


text:
Q: Laravel redirect to specific route when user is not logged If i go to http://www.yourdomain.com/admin/login i see my login page.
If i go to http://www.yourdomain.com/admin/example i have the redirect to http://www.yourdomain.com/login without the admin.
My web routes:
Auth::routes();

Route::prefix('admin')->group(function() {
    Route::get('/login','Auth\AdminLoginController@showLoginForm')->name('admin.login');
    Route::post('/login','Auth\AdminLoginController@login')->name('admin.login.submit');
    Route::get('/manifiesto','AdminController@getIndex')->name('admin.dashboard');
    Route::get('/logout','Auth\AdminLoginController@logout')->name('admin.logout');
    Route::get('/trabajadores','AdminController@showTrabajadores')->name('admin.trabajadores');
    Route::get('/clientes','AdminController@showClientes')->name('admin.clientes');
    Route::get('/proyectos','AdminController@showProyectos')->name('admin.proyectos');
    Route::get('/administradores','AdminController@showAdmins')->name('admin.administradores');
});

When i put some url with the /admin before and user isn't logged, i want to redirect to /admin/login.
Thanks.
More info:
App/http/Controllers/Auth/AdminLoginController.php
<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Auth;
class AdminLoginController extends Controller
{

    protected $loginPath = 'admin/login';

    public function __construct()
    {
        $this->middleware('guest:admin', ['except' => ['logout']]);
    }
    public function showLoginForm()
    {
        return view('backend.public.pages.login');
    }
    public function login(Request $request)
   {
       //validate the form data
       $this->validate($request, [
           'email' => 'required|email',
           'password' => 'required|min:6'
       ]);
       //attempt to log the user in
       if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)){
            //if successful, then redirect to their intended location
            return redirect()->intended(route('admin.dashboard'));
       }
       return redirect()->back()->withInput($request->only('email','remember'));
   }

   public function logout()
   {
       Auth::guard('admin')->logout();

       return redirect('/');
   }
}

App\Http\Middleware\AdminAuthenticate.php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class AdminAuthenticate
{
/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @param  string|null  $guard
 * @return mixed
 */
 public function handle($request, Closure $next)
 {
    if ($this->auth->guest())
    {
        if ($request->ajax())
        {
            return response('Unauthorized.', 401);
        }
        else
        {
            return redirect()->guest('admin/login'); // <--- here
        }
    }

    return $next($request);
 }
}

A: *

*Create an middleware

php artisan make:middleware AuthAdmin

*Check for guest in the handle method of the middleware

public function handle($request, Closure $next)
{
    if (Auth::guest()) {
        if ($request->ajax() || $request->wantsJson()) {
            return response('Unauthorized.', 401);
        } else {
            return redirect()->guest('admin/login');
        }
    }

    return $next($request);
}

*Add a key to the middleware in app/Http/Kernel.php in $routeMiddleware array

'auth_admin' => \App\Http\Middleware\AuthAdmin::class

*Attach the auth_admin middleware to the group

Route::group(['prefix' => 'admin',  'middleware' => 'auth_admin'], function() {
    // Your admin routes except login
});

A: write bellow code in your route.php file
Route::group(array('prefix' => 'admin'), function() {
        Route::controller('login', 'AdminloginController');
    });
    Route::group(array('before' => 'admin_ajax', 'prefix' => 'admin'), function()
    {
        //route for pages which are render after login
    });
    Route::get('/admin', function() {
        return View::make('admin.loginform');
    });

And Write bellow code in your filter.php file
Route::filter('admin_ajax', function() {
    if (!Auth::admin()->check()) {
        return Redirect::to('admin/login');
    } else {
    }
});

And if you are using laravel 5.4
Route::get('/manage', function () {
    return redirect('manage/login');
});
Route::group(['prefix' => 'manage'], function() {
    //login bypass for the below listed controllers
    Route::resource('login', 'AdminLoginController@showLoginForm');
    Route::post('dologin', 'AdminLoginController@login');
});

A: All you can do is add the auth middleware like this :
Route::group(['prefix' => 'admin',  'middleware' => 'auth'], function() {
    Route::get('/login','Auth\AdminLoginController@showLoginForm')->name('admin.login');
    Route::post('/login','Auth\AdminLoginController@login')->name('admin.login.submit');
    Route::get('/manifiesto','AdminController@getIndex')->name('admin.dashboard');
    Route::get('/logout','Auth\AdminLoginController@logout')->name('admin.logout');
    Route::get('/trabajadores','AdminController@showTrabajadores')->name('admin.trabajadores');
    Route::get('/clientes','AdminController@showClientes')->name('admin.clientes');
    Route::get('/proyectos','AdminController@showProyectos')->name('admin.proyectos');
    Route::get('/administradores','AdminController@showAdmins')->name('admin.administradores');
});

But by default this will redirect to /login, if you want to override this you have two chocies depending on if you have other type of users that uses the /login route or not !!

*

*If NO ONE uses /login route
1- You need to modify App\Http\Middleware\Authenticate::handle() method and change /login to admin/login.
2- Then you need to add $loginPath property to your \App\Http\Controllers\Auth\AuthController class.
Authenticate
namespace App\Http\Middleware;
class Authenticate {
        /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($this->auth->guest())
        {
            if ($request->ajax())
            {
                return response('Unauthorized.', 401);
            }
            else
            {
                return redirect()->guest('admin/login'); // <--- here
            }
        }

        return $next($request);
    }
}

AuthController
namespace App\Http\Controllers\Auth;
class AuthController extends Controller
{
    protected $loginPath = 'admin/login'; // <--- here

    // ... other properties, constructor, traits, etc
}

*

*If there is someone using /login route
You must create you own middleware and do what it takes for auth checking in the handle method with redirecting to your admin/liging route :)
In this case :

*

*Add the following line in $routeMiddleware property at app/Http/Kernel.php file
'adminAuth' => \App\Http\Middleware\YourNewMiddleware::class,

*Don't forget to add your new middleware in route group as follow
 Route::group(['prefix' => 'admin',  'middleware' => 'adminAuth'], function()
 {
    // your admin routes
 });

A: Make an another middleware for admin. follow the step

*

*Make a file named AdminAuthenticate in app/Http/Middleware location and copy the content of Authenticate in New file
change the Class name as AdminAuthenticate

*Change the content of handle function as show below
public function handle($request, Closure $next, $guard = null)
{
    if (Auth::guard($guard)->guest()) {
        if ($request->ajax()) {
            return response('Unauthorized.', 401);
        } else {
            return redirect()->guest('/admin/login');
        }
    }

    return $next($request);
}

*Add the following line in $routeMiddleware array at app/Http/Kernel.php file
'AdminAuth' => \App\Http\Middleware\AdminAuthenticate::class,

*Now everything is okay. just add your new middleware in route group as follow
Route::group(['prefix' => 'admin',  'middleware' => 'AdminAuth'], function()
{
   // all admin routes
});

Or you can add new middleware to constructor function of every admin controller as like below
$this->middleware('AdminAuth');


text:
Q: JFrame - reading two keystrokes (ESC and F2) and executing different actions I'm looking to recognise two keystrokes from the ESC and F2 key. Below is how I recognise when the escape key is pressed:
// Enable escape to close the window by first returning the rootPane object for this frame, then the InputMap that is usedduring condition i.e. JComponent.WHEN_IN_FOCUSED_WINDOW
    // and then use function put to add a binding for keyStroke to actionMapKey
    frame.getRootPane().getInputMap(JComponent. WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "Cancel");

    // Kill the AuotIt script when closing the window by first returning the rootPane object for this frame then the ActionMap used to determine what Action
    // to fire for particular KeyStroke binding. The returned ActionMap, unless otherwise set, will have the ActionMap from the UI set as the parent.
    frame.getRootPane().getActionMap().put("Cancel", new AbstractAction(){
        public void actionPerformed(ActionEvent x) {
            // Undertake some action here
        }
    });

I attempted the exact same thing but changing the keyevent to F2 but nothing happens when I press the F2 button. Below is how I attempted recognising the F2:
frame.getRootPane().getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0), "pressed");

    //
    frame.getRootPane().getActionMap().put("pressed", new AbstractAction(){
        public void actionPerformed(ActionEvent x) {

            // Change the hasusersetcomport flag in hasusersetcomport.txt to 0
            notifyScriptThatUserNeedsCOMPorts("0");

            // Notify Script That User Pressed Allow Pairing (which is the default setting for wasallowpairingpressed.txt)
            notifyScriptThatUserPressedAllowPairing("1");

            // Write menu Item Event Control ID
            RFC95.writeMenuItemEventControlID("8");

            // Write empty string into config file
            writeUserSelectedCOMportIntoConfigFile("");

            // Notify user that current pairing has been deleted
            notifMssgLabel.setText("
CURRENT PAIRING SETTING DELETED. WINDOW CLOSING
");
            notifMssgLabel.setForeground(officialSuccessFontColour);
            notifMssgLabel.setFont(officialFontBold);

            // Change the hasusersetcomport flag in hasusersetcomport.txt to 0
            notifyScriptThatUserNeedsCOMPorts("0");

            panelTimer.start();
        }
    });

Any ideas as to why I'm encountering the problem.
Thanks.