text:
Q: How do I move the background image to the back and the login container to the front I am trying to move antoine-barres.jpg background image all the way to the back, then the clouds.png, then the login container all the way to the front. How do I do it, I have tried z-index but not sure how it works, I have tried but ran out of ideas, please help.

Welcome

                            <form class="register-form">
                                Email
                                <input type="text" class="form-control" placeholder="Email">
                                Password
                                <input type="password" class="form-control" placeholder="Password">
                                <button class="btn btn-danger btn-block btn-round">Register</button>
                            </form>

                                Forgot password?

© , made with  by Creative Tim

A: Try this:
.page-header {
    background: url(../assets/img/clouds.png);
}

or

.wrapper {
    background: url(../assets/img/clouds.png);
}

A: I'm not really understand your problem, can you explain it more?

.wrapper {
  background: url('https://upload.wikimedia.org/wikipedia/commons/4/46/WP_SOPA_asset_Radial_Gradient.jpg'); // i change url
}

.row {
  z-index: 999;
}

.moving-clouds {
  background: url('http://eskipaper.com/images/simple-cloud-wallpaper-1.jpg');
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Welcome

            <form class="register-form">
              Email
              <input type="text" class="form-control" placeholder="Email">

              Password
              <input type="password" class="form-control" placeholder="Password">
              <button class="btn btn-danger btn-block btn-round">Register</button>
            </form>

              Forgot password?

© , made with  by Creative Tim

JSFiddle Demo

A: You have to use the moving cloud image before the container

Welcome

                        <form class="register-form">
                            Email
                            <input type="text" class="form-control" placeholder="Email">

                            Password
                            <input type="password" class="form-control" placeholder="Password">
                            <button class="btn btn-danger btn-block btn-round">Register</button>
                        </form>

                            Forgot password?

© 2018, made with  by Creative Tim


text:
Q: dynamic content after fn.readfile for an email I'm sending an email for user confirmation with AWS SES from a custom file.
Is there any way to include custom params after fs.readFile()?
(For example, a variable with a dynamic URL for an activation code.)
fs.readFile('./mypath', function (err, email) {
  if (err) { return console.log(err); }
  // some modifications to email response
  ses.sendEmail(params, function (err, data) {
    if (err) { return console.log(err); }
    return; // all ok
)}

I'm looking for another option instead of reading the entire file and replacing the desired content. In PHP, for example, defining variables before file_get_contents() does the trick if the variable is defined inside the document. So I was looking for something like that.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to create spinning wheel like view with cards I want to create something like this view:
I want the view to let the blue border cycle trough the cards and stop at a random integer value and highlight the current card that has the border by making it a little bigger. I'm new to animating with swift and don't know where to start.
This is my current code for the view:
struct Card: Identifiable, Hashable {

    func hash(into hasher: inout Hasher) {
            hasher.combine(id)
            hasher.combine(name)
        }

    let id: String = UUID().uuidString
    var cardBackGroundColor: Color
    var image: Image
    var name: String
}

struct PriceRollView: View {
    @State var cards = [Card(cardBackGroundColor: ColorConstants.turquoise, image: Image("vacation"), name: "Hawaii vacation"),
                        Card(cardBackGroundColor: ColorConstants.lightPink, image: Image("suit"), name: "Tailored suit"), Card(cardBackGroundColor: ColorConstants.lightYellow, image: Image("shoes"), name: "Sneaker"), Card(cardBackGroundColor: ColorConstants.darkPink, image: Image("watch"), name: "Classic Chronometer"), Card(cardBackGroundColor: ColorConstants.purple, image: Image("car"), name: "Sports car"), Card(cardBackGroundColor: ColorConstants.turquoise, image: Image("airplane"), name: "Private jet flight"), Card(cardBackGroundColor: ColorConstants.darkPink, image: Image("smartWatch"), name: "Smart watch"), Card(cardBackGroundColor: ColorConstants.lightYellow, image: Image("coliseum"), name: "Italy vacation")]
    let columns = [
        GridItem(.flexible()),
        GridItem(.flexible()),
        GridItem(.flexible())
    ]
    var body: some View {
        VStack {
            Text("Rolling for your price...").foregroundColor(ColorConstants.darkBlue)
            LazyVGrid(columns: columns, spacing: 12) {
                    ForEach(cards, id: \.self) { card in
                        VStack(alignment: .center) {
                            card.image
                                .resizable()
                                .scaledToFit()
                            Text(card.name)
                                .foregroundColor(ColorConstants.darkBlue)
                                .lineLimit(1)
                                .minimumScaleFactor(0.5)
                        }
                        .padding(12)
                        .frame(width: (ScreenConstants.width - 48) / 3, height: (ScreenConstants.width - 48) / 3)
                        .background(card.cardBackGroundColor)
                        .cornerRadius(4)
                    }
                }.padding(.leading, 12)
                    .padding(.trailing, 12)
                    .padding(.top, ScreenConstants.hasNotch ? 12 : 20)
            Spacer()
        }.statusBar(hidden: true)
    }
}

A: You can do so using a Timer:
struct TestView: View {
    @State var index = 0
    let timer = Timer.publish(every: 0.5, on: .main, in: .common).autoconnect()
    var body: some View {
        LazyVGrid(columns: [.init(), .init(), .init()]) {
            ForEach(0..<10) { index in
                Text("Hiii\(index)")
                    .background(index == self.index ? Color.blue: .red)
                    .cornerRadius(4)
            }
        }.onReceive(timer) { _ in
            withAnimation(.default) {
                if index == 9 {
                    index = 0
                }else {
                    index += 1
                }
            }
        }
    }
}

In the onReceive closure, you set the next item to be highlighted to a State variable, and in the ForEach you check if the value matches the current one & modify the content as you want.


text:
Q: is there a UIKit equivalent to SwiftUI's zstack? I'm trying to create something like this. I've been working with SwiftUI recently so I know I could create that by adding an image, text and button (the I'm flexible text is the label for a button/NavigationLink) to a zstack. but I'm looking around trying to see if there's anyway to do that in UIKit. preferably without using storyboards. I'm open to a cocoapods library or whatever if that's what it takes. I've looked around and explored using SwiftUI to create the desired ZStack and then use it in my UIKit with a UIHostingController but because it involves a button/navigationlink. seeing as how the NavigationLink would require the destination to conform to a View, I wanted to ask around before converting even more of my project to swiftui. I was more hoping this project would be for giving me more experience building views in UIKit without storyboards so I'd prefer to do that instead of using SwiftUI. if that's possible I guess.
I've tried searching around but all my google searches involving UIButtons and images just link to posts about setting the image in a UIButton.

A: since you wanted to get more experience in creating views using UIKit, I've created a view that inherits from UIView that you can reuse. There's quite a lot of code to get the same result in UIKit. The code and output are provided below.
NOTE: Read the comments provided
Code
class ImageCardWithButton: UIView {

    lazy var cardImage: UIImageView = {
        let image = UIImageView()
        image.translatesAutoresizingMaskIntoConstraints = false // To flag that we are using Constraints to set the layout
        image.image = UIImage(named: "dog")
        image.contentMode = .scaleAspectFill
        return image
    }()

    lazy var gradientView: UIView = {
        let view = UIView()
        view.translatesAutoresizingMaskIntoConstraints = false // IMPORTANT IF YOU ARE USING CONSTRAINTS INSTEAD OF FRAMES
        return view
    }()

    // VStack equivalent in UIKit
    lazy var contentStack: UIStackView = {
        let stack = UIStackView()
        stack.translatesAutoresizingMaskIntoConstraints = false
        stack.axis = .vertical
        stack.distribution = .fillProportionally // Setting the distribution to fill based on the content
        return stack
    }()

    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.textAlignment = .center
        label.numberOfLines = 0 // Setting line number to 0 to allow sentence breaks
        label.text = "Let your curiosity do the booking"
        label.font = UIFont(name: "Raleway-Semibold", size: 20) // Custom font defined for the project
        label.textColor = .white
        return label
    }()

    lazy var cardButton: UIButton = {
        let button = UIButton()
        button.translatesAutoresizingMaskIntoConstraints = false
        button.backgroundColor = .white
        button.setTitle("I'm flexible", for: .normal)
        button.setTitleColor(.blue, for: .normal)
//        button.addTarget(self, action: #selector(someObjcMethod), for: .touchUpInside) <- Adding a touch event and function to invoke
        return button
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }

    private func commonInit() {
        self.addSubview(cardImage) // Adding the subview to the current view. i.e., self

        // Setting the corner radius of the view
        self.layer.cornerRadius = 10
        self.layer.masksToBounds = true

        NSLayoutConstraint.activate([
            cardImage.leadingAnchor.constraint(equalTo: self.leadingAnchor),
            cardImage.trailingAnchor.constraint(equalTo: self.trailingAnchor),
            cardImage.topAnchor.constraint(equalTo: self.topAnchor),
            cardImage.bottomAnchor.constraint(equalTo: self.bottomAnchor),
        ])

        setupGradientView()
        addTextAndButton()
    }

    private func setupGradientView() {
        let height = self.frame.height * 0.9 // Height of the translucent gradient view

        self.addSubview(gradientView)
        NSLayoutConstraint.activate([
            gradientView.leadingAnchor.constraint(equalTo: self.leadingAnchor),
            gradientView.trailingAnchor.constraint(equalTo: self.trailingAnchor),
            gradientView.bottomAnchor.constraint(equalTo: self.bottomAnchor),
            gradientView.heightAnchor.constraint(equalToConstant: height)
        ])

        // Adding the gradient
        let colorTop =  UIColor.clear
        let colorBottom = UIColor.black

        let gradientLayer = CAGradientLayer()
        gradientLayer.colors = [colorTop.cgColor, colorBottom.cgColor]
        gradientLayer.locations = [0.0, 1.0]
        gradientLayer.frame = CGRect(
            x: 0,
            y: self.frame.height - height,
            width: self.frame.width,
            height: height)
        gradientView.layer.insertSublayer(gradientLayer, at:0)
        print(self.frame)
    }

    private func addTextAndButton() {

        // Adding the views to the stackview
        contentStack.addArrangedSubview(titleLabel)
        contentStack.addArrangedSubview(cardButton)

        gradientView.addSubview(contentStack)
        NSLayoutConstraint.activate([
            contentStack.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 20),
            contentStack.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -20),    // Negative for leading and bottom constraints
            contentStack.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -20),        // Negative for leading and bottom constraints

            cardButton.heightAnchor.constraint(equalToConstant: 60)
        ])

        cardButton.layer.cornerRadius = 30 // Half of the height of the button
    }

}

Output

Important pointers

*

*You can create the layout using constraints or frames. In case you are using constraints, it is important to set a views .translatesAutoresizingMaskIntoConstraints to false (You can read the documentation for it).

*NSLayoutConstraint.activate([...]) Is used to apply an array of constraints at once. Alternatively, you can use:
cardImage.leadingAnchor.constraint(...)isActivated = true

for individual constraints

*Manual layout of the views will sometimes require padding. So for this you will have to use negative or positive values for the padding based on the edge (side) of the view you are in. It's easy to remember to set the value of the padding in the direction of the centre of the view.

E.x., From the leading/left edge, you will need to add a padding of 10 towards the centre of the view or -10 from the right/trailing side towards the centre.


text:
Q: pdflatex removes highlights in the included PDF I have a figure in the PDF format and there are some texts in the figure (pdf) are highlighted. However, when I include this PDF file into latex document, the highlights are automatically removed. Do you know to to preserve the highlights? I am using PdfLaTeX to compile the TeX documents. The minimal working example provide below:
\documentclass{article}
\usepackage{graphicx}
\begin{document}

\begin{figure}
\includegraphics[width=\linewidth]{figure}
\end{figure}

\end{document}

The figure in PDF format can be downloaded here.
However, you can use any pdf file that contains highlights to see the problem.

A: If you highlight and annotate inside a PDF figure  with tools such as Acrobat, Preview, or Evince, these elements do not become part of the PDF figure – they are stored as PDF annotations.
Basically, annotations are distinct objects that are put on top of the PDF figure, can be edited, moved around and so on by viewers that support this. They also may look differently in every viewer, as the PDF specifications only defines the annotation types and properties, but not how they are to be rendered on screen.
To have annotations become part of the figure, the PDF need to be "flattened", for instance, by printing it (including annotations) into another PDF file. However, this is not supported by many PDF viewers.

A: I had a similar problem and I experimented with the other solutions posted here. I sketch a brief summary for future reference in case someone incurs the same issue.
Basically the solution is to annotate the pdf with a custom editor and then print it to pdf. For this I tried two options:

*

*print through the pdf editor --> I used Okular in ubuntu and it works, however the resulting document is a bit blurred

*open the annotated pdf with Chrome and print it --> this worked for me with a nice and scalable output*

*However, I have to say that controlling the extent of the highlighted text is a nightmare, at least in the case of text within a table. In my case I highlighted just few words in a cell, but when I printed it the result was all the cell highlighted...I didn't fully understand why, but I suspect it happens when you highlight a space before/after the first/last word of each highlighted group of words.


text:
Q: Swift AVPlayerViewController Done button to close app i have a question about the "Done"-Button in iOS Player, is it possible to use the Done-Button as a Exit or Close Button for Apps coded with Swift?
App that i want to build is a Standalone App with only one video, when i click the App Button on the Homescreen, it have to open and play the video, if i click on "Done" in the Top-Left Corner it have to be closed.
My Code is:
import UIKit
import AVKit
import AVFoundation

class ViewController: UIViewController {

    var playerViewController = AVPlayerViewController()
    var playerView = AVPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func viewDidAppear(animated: Bool) {

        let fileURL = NSBundle.mainBundle().pathForResource("Befeuchtungsstrecke", ofType: "mp4")
        playerView = AVPlayer(URL: NSURL(fileURLWithPath: fileURL!))

        playerViewController.player = playerView
        self.presentViewController(playerViewController, animated: true){

            self.playerViewController.player?.play()

        }

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

EDIT: sorry i don't know that apple don't want to close a App manuell.
Ok then, i want to solve the problem in another way.
I have two ViewController in the first one (ViewConrtoller1) there is a Button where you can go to the second view (ViewConrtoller2). In the Second there is a video with all Controller (Play, Pause, Back, Forward etc.) and also have the "Done" Button on Top-Left Corner.
How can i get back (ViewController2 --> ViewController1) to the first by using "Done" Button? Is that possible?
Thanks :)

A: Kumar's comment is right - you shouldn't quit your app programatically. It violates the Apple guidelines for an iOS app.


text:
Q: Copy and Paste Files with Similar Extension using Batch File with recursive function I'm trying to use the CMD Prompt to copy all my Excel files from all my subfolders into one aggregate folder. I've tried to use the following code:
 @echo off
    if exist aggregatexlsx (echo "it exists") else md aggregatexlsx
    for /R %%f in (*.xlsx) Do COPY %%f C:\Users\Username\Documents\Excel Test\aggregatexlsx
    exit /b

However, I receive the following response:

When I type in the for statement (with 1 %f) into the Command Prompt by itself, it returns me the following:

So my question is: if it calls the Excel documents (this is a small test case I have put together for a clean example), why is it struggling to copy and paste them in the new directory, aggregatexlsx?

A: The syntax of your copy command is incorrect. It's copy [file] [destination].
for /r "C:\Users\Username\Documents\Excel" %%f in (*.xlsx) do copy "%%~f" "Test\aggregatexlsx"

This is assuming you want to loop through C:\Users\Username\Documents\Excel


text:
Q: Javascript fetch and @RequestAttribute in springboot I have an authenticate API on springboot server. When I call the API from POSTMAN, the userDetails object is not null and I get success on client side. However when I do from reactJS userDetails object is null and server returns 500 with msg Response for preflight does not have HTTP ok status.
Could someone help me explain why its successful in POSTMAN and not in javascript?
Code in ReactJS
var data = {
        "password":"password",
        "username":"uname"
 }

fetch("https://ipaddress:port/module/authenticate", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify(data)
 }).then(response => {
...
    })
    .catch((e) => {
...
    })

Code in springboot
@PostMapping(value = "/module/authenticate ")
@ResponseBody
public ResponseEntity<String> authenticate(@RequestAttribute UserDetails userDetails) throws Exception {
...
}

public class UserDetails {
// The username for the logging in user.
private String username;
// The password for the user.
private String password;

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

}
Found Reason for POST man not failing
Post man doesn't do an OPTIONS call before the POST API hence, it'll not fail. However the fetch call does OPTIONS check first for cors access, and it needs to be handled by spring security.   Reference: Why is an OPTIONS request sent and can I disable it?
A work around could be to set content type as plain/text

A: There is no need for workaround to handle pre-flight request
configure it correctly in your spring security
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class AppSecurityAdapter extends WebSecurityConfigurerAdapter {

//... other configuration here

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring()
            .antMatchers(HttpMethod.OPTIONS, "/**")


text:
Q: SQLite экспорт выборки в JSON Очеедной глупый вопрос, ответ на который не смог найти в "ГУГЛ":

SELECT docs.date, docs.typeId, rows.docId, docTypes.removed, docs.removed
FROM docs, docTypes, products, rows
WHERE docTypes.removed <> 1 and docs.removed <> 1
ORDER BY docs.date;

вот такая у меня выборка из базы данных. Во-первых проблема в том, что результатов слишком много и не все выводятся в консоли. Во-вторых, мне необходимо экспортировать эти результаты в формате JSON.
И есть ли возможность получать результаты каждого запроса в виде файла?

A: Всё получилось с использованием DB Browser for SQLite


text:
Q: Is there a way to check when a series is highlighted on apache echarts line chart I'm using the Line Chart type from Apache Echarts in an Angular project and I need to know when a line has entered into the "highlight" or "emphasis" state:

This state is triggered when hovering on a line & letting the cursor there (cursor not showing on screenshot).
Using the "highlight" event from the chart instance does not work because it emits every time you move the cursor anywhere on the graph; and actually, it does not emit when you do the hover & holding.
Using the ZRender object and listening to the "mouseover" event is more accurate as it emits only when you "mouseover" a series line. However, I still don't know when the line has actually entered into the "emphasis" or "highlight" state (when the others are grayed out and the hovered line keeps its color).
this.chartInstance.getZr().on('mouseover', (event: any) => {
  console.log(event);

  // can't find anything that can tell me if a series line is highlighted or not.
  console.log((this.chartInstance as any).getModel());
  console.log((this.chartInstance as any).getModel().getSeries());
})

Is there a flag on the series data that could tell me if one series (line) is on the "highlight" state?
Thanks in advance.

A: Seems to work for me. Try not to log the event, instead log params and get the event from there (look at console).
let myChart02 = echarts.init(document.getElementById('echart02'));

myChart02.group = 'myGroup';

myChart02.on('mouseover', (params) => {
  console.log(params);
})

myChart02.setOption(option02);

Working example: https://stackblitz.com/edit/echarts-sync-zoom-only-jzkzh8?file=index.js


text:
Q: POWERSHELL: Commands output differently inside functions I am learning as I go, this is a small part in a large project but its an inconvenience  for me
I am working on a script and one of its functions is to output information about the system.
Now ideally this is the command I would like to use to generate a report of connected drives over 60GB. It lists everything I want.
$size = 60GB

Get-Volume | Where-Object {$_.Size -gt $Size} | Sort-Object {$_.DriveLetter}

I am aware of other commands. They all seem to react the same way to being in a function. So that means I just don't understand what that reason is or how to control that.
If somebody could explain to me why this command outputs differently inside of a function. I've tried Googling however I cannot seem to find anything online. I believe its 100% me not knowing what to Google.
Function ProductConfirmation {
    $processor = (Get-ComputerInfo).CsProcessors.Name
    $product = (Get-WmiObject win32_baseboard).Product
    $gpuname = (Get-WmiObject win32_videocontroller).Name
    $gpudesc = (Get-WmiObject win32_videocontroller).Description
    systeminfo | Select-String  'BIOS Version',
                                'Network Card(s)',
                                'OS Name',
                                'OS Version',
                                'System Manufacturer',
                                'System Model',
                                'System Type',
                                'Time Zone'

    Write-Host "`nCPU: $processor"
    Write-Host "`nMotherboard: $product"
    Write-Host "`nGPU Name: $gpuname"
    Write-Host "GPU Description: $gpudesc"
    Start-Sleep -s 5

    Write-Host "`n RAM INFORMATION`n"
    Get-CimInstance -Class CIM_PhysicalMemory -ErrorAction Stop | Select    'Manufacturer',
                                                                            'DeviceLocator',
                                                                            'PartNumber',
                                                                            'ConfiguredClockSpeed'
    ''
    systeminfo | Select-String  'Total Physical Memory'
    Start-Sleep -s 4
    Write-Host "`n Generating Hard Drive Report`n`n`n"
    Write-Host " Double check all drives that should be with this computer are connected." -ForegroundColor RED
    Start-Sleep -s 4
    $size = 60GB
    Get-Volume | Where-Object {$_.Size -gt $Size} | Sort-Object {$_.DriveLetter}
}
ProductConfirmation

Attached are the outputs of both commands run in a VM.
Top - Run in its function
Bottom - Run on its own
Screenshot.png


text:
Q: Should I flag as "not-an-answer" for a new user immediately? Today I commented on an answer which I later realized was from the OP attempting to give more information in response to comments.  I commented to OP that the original question should have been edited, rather than posting an "answer".
I moved that information into the original post and flag the "answer" as "not an answer", but I'm concerned that the "answer" could get deleted without OP knowing it and OP may never get to see my comment (at least not in the original context).
It seems from reading this question/answer, that it is likely that OP will never actually get to see my comment in the original context (next to the "answer") which may make my comment difficult to understand.
Is this something I should worry about?  Should I try to give OP some time before I flag it?  Is there a generally accepted protocol here?

A: New users need the most guidance as they're not familiar with how the family of Stack Exchange websites work. The more quickly we show them the correct way to do things, the more likely they are to be productive members of the community.
Sometimes I see users afraid to downvote a new post or afraid to flag something, just because it's a new user they're dealing with. The problem with this approach is:

*

*The poor content doesn't get pushed to the bottom and remains in the 0 votes section, or worse, is moved to the top due to a sympathy upvote.

*The new user comes to believe the behavior is "okay", despite any comments you might leave.

*Other new users see the content and think that the behavior is okay, using it as evidence in their own mind that they can do the same. This can make it harder for the first person that does downvote them, and it makes it harder for the first moderator that must respond to a flag on their post, as he/she will now have to deal with an indignant user who thinks he/she was doing the right thing.
In your case, flagging the post was the best action. The moderators can leave comments before deleting the post, and those comments are seen by the user. Additionally, in the "edit" message, or in the comment to the question, you could leave a comment if need be, explaining how to use the site properly. Don't let that stop you from taking action. The faster the new user learns, the easier the transition will be from forum to Q&A. Having users on the site, such as yourself, who are willing to take the time to explain the rules to new users is exactly the right approach to creating more good users. ;)

A: I think you did the right thing. You were careful enough to leave a comment explaining the situation to the OP, and even edited the question on the OP's behalf. I think (but I may be wrong here) that the OP will get a notification about that comment, regardless of the answer being deleted or not.
Moreover, every user can see their own deleted questions and answers, provided they have a link to them. In this case, the user is guaranteed to have a link to the question (since it's his own), so he will see the deleted answer there, and the comments below it.


text:
Q: How do I send a date stored in a field of a table in a Mysql database to a javascript variable to calculate the time between two date? I found the following:
// Set the date we're counting down to

    var countDownDate = new Date ("Jun 23, 2017 19:00:00"). getTime ();

// Update the count down every 1 second

    var x = setInterval (function () {})

// Get todays date and time

    var now = new Date (). getTime ();

// Find the distance between now and the count down date

    var distance = countDownDate - now;

What I cannot do is replace "Jun 23, 2017 19:00:00" with the variable where I store the value of the date in the database
I get the variable with PHP and save it @ date1
Something like this: var countDownDate = new Date ("@ date1"). GetTime ();

A: You can use it either on page load or via javascript.
On page load you can assign javascript variable like below and can consume as it is.
var date1 = <?php echo $data1?>;

On ajax, you can get the output from the server and then use it accordingly.


text:
Q: How to Ban CNAME redirection to my Website? I'm used to buy over 15 domains per week, but sometime I may buy some domains that were used for bad things in the past and their reputation is so bad that if I don't add TLS, browsers flag it as a bad one.
On 2 of those bad domains I found that other bad domains are CNAME redirected to mine. Meaning when somebody accesses that domain it gets my content.
How can I ban that domain from CNAME redirecting visitors to mine?
I tried banning Frame viewing my Website, but it doesn't work. I still see people coming from that referrer.


text:
Q: Looping over strings Having fun with strings, I found three different macros to loop over a string character by character.
However, I am not very sure how they work exactly.
Can somebody explain the mechanism of each of them?
Which is the most "correct" one?
Is there some other way to construct this macro?
I have changed the original ones so that they all look as similar as possible.
Macro based on one by Tarass:
This is the easiest one to understand for me.
Since the arguments are delimited, the first one is the first letter and the rest is reintroduced into the loop.
The looping works from within the \if statement.
Macro based on one by David Carlisle:
This one is trickier.
The looping comes from inside the \if statement, but not really.
If the \expandafter is eliminated, it does not work.
If the \xloop is placed behind the \fi it does not work either.
So what is happening exactly?
The rest is easier, every time \xloop is executed, it finds the remaining part of the string and takes the first character.
Macro based on one by Florent:
This one is still more complicated (for me, at least).
The looping works from outside the \if statement, but the characters are accessed one by one as before.
Surprisingly, here the spaces are not discarded.
This can be achieved also in the previous macros with \obeyspaces.
\documentclass{article}

\begin{document}

\subsection*{Macro based on one by Tarass:}

\def\xloop<#1#2>{%
  \ifx\relax#1
    \else
      (#1)\xloop<#2>%
  \fi}
\def\markletters#1{\xloop<#1\relax>}

\markletters{Hello World!}

\subsection*{Macro based on one by David Carlisle:}

\def\xloop#1{%
  \ifx\relax#1
    \else
      (#1)\expandafter\xloop%
  \fi}
\def\markletters#1{\xloop#1\relax}%

\markletters{Hello World!}

\subsection*{Macro based on one by Florent:}

\def\gobblechar{\let\xchar= }
\def\assignthencheck{\afterassignment\xloop\gobblechar}
\def\xloop{%
  \ifx\relax\xchar
      \let\next=\relax
    \else
      (\xchar)\let\next=\assignthencheck
  \fi
  \next}
\def\markletters#1{\assignthencheck#1\relax}

\markletters{Hello World!}

\end{document}

A: There are two differences between the first solution and the other two: The second and third solution both use tail recursion, in contrast to the first one. And, related to this, the first solution has to copy the argument from iteration to iteration, while the other two solutions pass over the argument just once, processing character by character without copying the rest.
First solution. In a conventional programming language the if-then-else-fi would be read completely and only then the code of one of the branches would be executed. In TeX, the \fi remains in the input until expanded. So the first loop produces something like
\ifx\relax H\else(H)\xloop<ello...>\fi
(H)\ifx\relax e\else(e)\xloop<llo...>\fi\fi
(H)(e)\ifx\relax l\else(l)\xloop<lo...>\fi\fi\fi

Note how the \fis pile up at the end.
Second solution. This is the most compact one. The \expandafter changes the order of expansions: \fi is expanded first, so the \ifx gets finished before continuing with the next \xloop.
\xloop Hello...\relax
\ifx\relax H\else (H)\expandafter\xloop\fi ello...\relax
(H)\expandafter\xloop\fi ello...\relax
(H)\xloop ello...\relax
(H)\ifx\relax e\else (e)\expandafter\xloop\fi llo...\relax
(H)(e)\expandafter\xloop\fi llo...\relax
(H)(e)\xloop llo...\relax

Third solution. \afterassignment first "assigns" the next character to a macro before testing it. Tail recursion is obtained by letting \next point to the code that is to be executed after the closing \fi.
\assignthencheck Hello...\relax
\xloop ello...\relax % \xchar is set to H
\ifx\relax\xchar\let\next=\relax\else(\xchar)\let\next=\assignthencheck\fi\next ello...\relax
(\xchar)\let\next=\assignthencheck\fi\next ello...\relax
(H)\next ello...\relax % \next points to the code of \assignthencheck
(H)\xloop llo...\relax % \xchar is set to e
(H)\ifx\relax\xchar\let\next=\relax\else(\xchar)\let\next=\assignthencheck\fi\next llo...\relax
(H)(\xchar)\let\next=\assignthencheck\fi\next llo...\relax
(H)(e)\next llo...\relax % \next points to the code of \assignthencheck

Edit: To illustrate what David and Enrico mean by the first two solutions being fully expandable and the third one not, try
\edef\resultexpanded{\markletters{Hello World!}}

\edef expands the second argument until it encounters non-expandable TeX primitives (or characters) and then uses the result to define \resultexpanded. For the first two versions of markletters, \resultexpanded is defined as
(H)(e)(l)(l)(o)(W)(o)(r)(l)(d)(!)

whereas in the third case it contains
\afterassignment\let\next=\relax\next\let\xchar=Hello World!\relax

which is the non-expandable rest.

A: The solutions by Tarass and David Carlisle are not that different. The latter is more efficient, because it removes the conditional before going to the next cycle, whereas the former nests them and, at each cycle, a \fi is added to the stack: a (very) long string could cause memory overflow.
The other difference, that is, the delimiters <>, is irrelevant as they play no role whatsoever.
Ignoring spaces is the price to pay for expandability of the macro: this means that the result is "computed" directly by macro expansion.
The third solution uses a different approach: instead of absorbing the next item as the argument to a macro, which is the cause for space gobbling, the control sequence is let to the next item, which is then removed, until arriving at \relax.
Note that you can't use this for storing the processed token list, because all cycles use \xchar for printing the item.
A further solution with xparse and expl3:
\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\markletters}{om}
 {
  \IfNoValueTF{#1}
   {
    \kessels_markletters:nn { #2 } { \tl_use:N \l_kessels_marked_letters_tl }
   }
   {
    \kessels_markletters:nn { #2 } { \tl_set_eq:NN #1 \l_kessels_marked_letters_tl }
   }
 }

\tl_new:N \l_kessels_unmarked_letters_tl
\tl_new:N \l_kessels_marked_letters_tl

\cs_new_protected:Nn \kessels_markletters:nn
 {
  \tl_set:Nn \l_kessels_unmarked_letters_tl { #1 }
  \tl_replace_all:Nnn \l_kessels_unmarked_letters_tl { ~ } { \textvisiblespace }
  \tl_clear:N \l_kessels_marked_letters_tl
  \tl_map_inline:Nn \l_kessels_unmarked_letters_tl
   {
    \tl_put_right:Nn \l_kessels_marked_letters_tl { (##1) }
   }
  #2
 }
\ExplSyntaxOff

\begin{document}

\markletters{Hello World!}

\markletters[\foo]{Hello World!}

\texttt{\meaning\foo}

\end{document}

Spaces are first replaced with \textvisiblespace (you can use \nonbreakingspace if you prefer).
If the optional argument is missing, the processed string is printed, otherwise it is stored in the macro given as argument (no check for it not being defined is performed, but it can be easily added).

Here's a simplified version, just for printing the result. As you see, the code is much shorter and each command does a well stated task. It does exactly the same as Florent's code.
\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\markletters}{m}
 {
  % save the input in a variable
  \tl_set:Nn \l_kessels_unmarked_letters_tl { #1 }
  % replace spaces with \textvisiblespace
  \tl_replace_all:Nnn \l_kessels_unmarked_letters_tl { ~ } { \textvisiblespace }
  % map the input surrounding each item by parentheses
  \tl_map_inline:Nn \l_kessels_unmarked_letters_tl { (##1) }
 }
\tl_new:N \l_kessels_unmarked_letters_tl
\ExplSyntaxOff

\begin{document}

\markletters{Hello World!}

\end{document}

A: If I modify your test a bit to make a shorter argument for tracing
\documentclass{article}

\def\test#1{{
\tracingonline=1
\tracingmacros=1
\markletters{#1}
}
\typeout{TYPEOUT: \markletters{#1}}
}
\begin{document}

\subsection*{Macro based on one by Tarass:}

\def\xloop<#1#2>{%
  \ifx\relax#1
    \else
      (#1)\xloop<#2>%
  \fi}
\def\markletters#1{\xloop<#1\relax>}

\test{a bc}

\subsection*{Macro based on one by David Carlisle:}

\def\xloop#1{%
  \ifx\relax#1
    \else
      (#1)\expandafter\xloop%
  \fi}
\def\markletters#1{\xloop#1\relax}%

\test{a bc}

\subsection*{Macro based on one by Florent:}

\def\gobblechar{\let\xchar= }
\def\assignthencheck{\afterassignment\xloop\gobblechar}
\def\xloop{%
  \ifx\relax\xchar
      \let\next=\relax
    \else
      (\xchar)\let\next=\assignthencheck
  \fi
  \next}
\def\markletters#1{\assignthencheck#1\relax}

\test{a bc}

\end{document}

then the first test produces
\markletters #1->\xloop <#1\relax >
#1<-a bc

\xloop <#1#2>->\ifx \relax #1 \else (#1)\xloop <#2>\fi
#1<-a
#2<- bc\relax

\@nobreakfalse ->\global \let \if@nobreak \iffalse

\xloop <#1#2>->\ifx \relax #1 \else (#1)\xloop <#2>\fi
#1<-b
#2<-c\relax

\xloop <#1#2>->\ifx \relax #1 \else (#1)\xloop <#2>\fi
#1<-c
#2<-\relax

\xloop <#1#2>->\ifx \relax #1 \else (#1)\xloop <#2>\fi
#1<-\relax
#2<-
TYPEOUT: (a)(b)(c)

Here you see that the macro uses a delimited argument so the entire list is grabbed each time (all tokens up to > ) and the first token is handled, with the remaining tokens being re-inserted in the recursive call.

*

*as #1 works as a normal non-delimited argument it always drops spaces.

*As the whole thing works by expansion it works in expansion only contexts such as \write so you get TYPEOUT: (a)(b)(c)

*At each stage there is a \fi inserted after the loop so if you have 1000 entries there will be 1000 of these, and at some point you will over-fill the input stack.

The second block produces
\markletters #1->\xloop #1\relax
#1<-a bc

\xloop #1->\ifx \relax #1 \else (#1)\expandafter \xloop \fi
#1<-a

\@nobreakfalse ->\global \let \if@nobreak \iffalse

\xloop #1->\ifx \relax #1 \else (#1)\expandafter \xloop \fi
#1<-b

\xloop #1->\ifx \relax #1 \else (#1)\expandafter \xloop \fi
#1<-c

\xloop #1->\ifx \relax #1 \else (#1)\expandafter \xloop \fi
#1<-\relax
TYPEOUT: (a)(b)(c)

Here you can see that after the first macro the inner macro does not grab the whole list, but just the first token. Doing it this way avoids reparsing teh list, and overloading the input stack, but you need to expand the \fi (to nothing) before doing the recursive call as you do not have the possibility of putting the \fi after the list as in the first version. hence the \expandafter which forces \fi to expand before \xloop.
The third version produces
\markletters #1->\assignthencheck #1\relax
#1<-a bc

\assignthencheck ->\afterassignment \xloop \gobblechar

\gobblechar ->\let \xchar =

\xloop ->\ifx \relax \xchar \let \next =\relax \else (\xchar )\let \next =\assi
gnthencheck \fi \next

\@nobreakfalse ->\global \let \if@nobreak \iffalse

\next ->\afterassignment \xloop \gobblechar

\gobblechar ->\let \xchar =

\xloop ->\ifx \relax \xchar \let \next =\relax \else (\xchar )\let \next =\assi
gnthencheck \fi \next

\next ->\afterassignment \xloop \gobblechar

\gobblechar ->\let \xchar =

\xloop ->\ifx \relax \xchar \let \next =\relax \else (\xchar )\let \next =\assi
gnthencheck \fi \next

\next ->\afterassignment \xloop \gobblechar

\gobblechar ->\let \xchar =

\xloop ->\ifx \relax \xchar \let \next =\relax \else (\xchar )\let \next =\assi
gnthencheck \fi \next

\next ->\afterassignment \xloop \gobblechar

\gobblechar ->\let \xchar =

\xloop ->\ifx \relax \xchar \let \next =\relax \else (\xchar )\let \next =\assi
gnthencheck \fi \next
! Undefined control sequence.

Here the item is grabbed by a \let assignment, this has the advantage of seeing space tokens, but as it does not work by expansion it fails in the \typeout.


text:
Q: create Class in Qt with QDialog inside for specific Dialogs I just want to make a custom Dialog, so I want to make a class around the standard QDialog. The goal is to call the constructor which creates the Dialog, and the show() function should be called to make it shown. Next step would be to make a connect between my Widget (which calls the Dialog constructor) Pushbutton and the show() function.
My header looks like this:
#include <QDialog>

class Dialog_Setting : public QDialog
{
    Q_OBJECT
  public:
    Dialog_Setting();

  public slots:
    void show(void);

  private:
    QDialog * dialog;
};

my .cpp:
   #include "Dialog_Setting.h"

Dialog_Setting::Dialog_Setting()
{
  dialog = new QDialog;
}

void Dialog_Setting::show()
{
  dialog->show();
}

I have taken out my connect and get a new error.
What is wrong with my class?

undefined reference to `vtable for Dialog_Setting'

thanks for your help, I love StackOverflow

A: Make sure that show() is implemented as a slot so you can connect() stuff to it:
#include <QDialog>

class Dialog_Setting : public QDialog
{
    Q_OBJECT
public:
    Dialog_Setting();

public slots:
    void show();
};

You also forgot to inherit from QObject or some other QObject-based class like QDialog and to declare the macro Q_OBJECT. All of these things are required to make your custom classes communicate with other classes through connect().


text:
Q: Mac Keybord touch (suppr, enter, tab ...) don't work on Android Studio I am on Mac OS Big Sur version 11.4 and i develop  flutter app using Android Studio, when i started the IDE work well, but know i can't use suppr, tab or enter on the keybord, they don't work, i can only tap text but can't suppr them or enter ...
suppr work the first time i click on it but in the second time or more it doesn't work.
thank you for your help
I use Flutter 2.5.3 • channel stable •
Tools • Dart 2.14.4
Android Studio Android Studio Arctic Fox | 2020.3.1 Patch 3
Mac M1 Apple Chip

A: How to completely uninstall Android Studio on Mac?
rm -Rf /Applications/Android\ Studio.app
rm -Rf ~/Library/Preferences/AndroidStudio*
rm -Rf ~/Library/Preferences/com.google.android.*
rm -Rf ~/Library/Preferences/com.android.*
rm -Rf ~/Library/Application\ Support/AndroidStudio*
rm -Rf ~/Library/Logs/AndroidStudio*
rm -Rf ~/Library/Caches/AndroidStudio*
rm -Rf ~/.AndroidStudio*
rm -Rf ~/.gradle
rm -Rf ~/.android
rm -Rf ~/Library/Android*
rm -Rf /usr/local/var/lib/android-sdk/
i resolve doing this after uninstall and reinstall android studio


text:
Q: Pure JavaScript: toggle links active My code is working only for first "a" child. Does not working on the rest "a" child. Why?
There are some solutions on the internet but in jQuery. I prefer pure JavaScript.

document.querySelector('a').addEventListener('click', active);

function active() {
    document.querySelector('a').classList.remove('active');
    this.classList.add('active');
}
.topnav {
  overflow: hidden;
  background-color: grey;
}

.topnav a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 10px;
  text-decoration: none;
}

.topnav a:hover {
  background-color: #ddd;
  color: black;
}

.topnav a.active {
    background-color: red;
    color: white;
}

  Home
  News
  Contact
  About

A: Add id instead of class; remove 'active' class on each click and then add 'active' class to clicked anchor tag;

document.getElementById('news').onclick = active;
document.getElementById('home').onclick = active;
document.getElementById('contact').onclick = active;
document.getElementById('about').onclick = active;

//addEventListener('click', active);

function active() {
    document.querySelector('a.active').classList.remove('active');
    this.classList.add('active');
}
.topnav {
  overflow: hidden;
  background-color: grey;
}

.topnav a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 10px;
  text-decoration: none;
}

.topnav a:hover {
  background-color: #ddd;
  color: black;
}

.topnav a.active {
    background-color: red;
    color: white;
}

  Home
  News
  Contact
  About

A: You can use event delegation with querySelectorAll to write small and neat solution like below:

document.querySelector('.topnav').addEventListener('click', active);

function active(e) {
    document.querySelectorAll('.topnav > a').forEach(function(a){
      a.classList.remove('active');
    })
    e.target.classList.add('active');
}
  .topnav {
      overflow: hidden;
      background-color: grey;
    }

    .topnav a {
      float: left;
      display: block;
      color: #f2f2f2;
      text-align: center;
      padding: 10px;
      text-decoration: none;
    }

    .topnav a:hover {
      background-color: #ddd;
      color: black;
    }

    .topnav a.active {
        background-color: red;
        color: white;
    }

      Home
      News
      Contact
      About

A: You need querySelectorAll and some looping:
const menuItems = document.querySelectorAll('a');

menuItems.forEach(el =>
  el.addEventListener('click', active)
);

function active() {
  menuItems.forEach(el =>
    el.classList.remove('active')
  );
  this.classList.add('active');
}

A: You should use document.querySelectorAll('a')


text:
Q: Deleting airflow logs in scheduler folder Currently i am using Airflow with Version : 1.10.10
After opening into airflow/logs folder there are many folder that are named based on your DAG name but there is a folder named scheduler which when opened consist folder that are named in date format ( E.g 2020/07/08 ) and it goes until the date when i first using airflow.After searching through multiple forum I'm still not sure what this folder logs are for.
Anyway the probelm is I kept wondering if it is okay to delete the contents inside scheduler folder since it takes so much space unlike the rest of the folder that are named based on the DAG name (I'm assuming thats where the log of each DAG runs is stored). Will the action of deleting the contents of scheduler cause any error or loss of DAG log?.
This might be a silly question but i want to make sure since the Airflow is in production server. I've tried creating an Airflow instance in local instance and delete the scheduler folder contents and it seems no error have occurred. Any feedback and sharing experience on handling this issue is welcomed
Thanks in Advance

A: It contains the logs of airflow scheduler afaik. I have used it only one time for a problem about SLAs.
I've been deleting old files in it for over a year, never encountered a problem. this is my command to delete old log files of scheduler:
find /etc/airflow/logs/scheduler -type f -mtime +45 -delete


text:
Q: libotify / notify-send: body text is not printed if it contains '<' or '>' I am on Linux Mint 18.1, MATE.
I am using the notify-send command to visualize the name of keys (such as <enter>), while sending them to the current window via a python script.For about two weeks, notify-send has shown a weird behavior. I know the basic syntax in bash is notify-send [OPTIONS] <summary> [body].
Basic problem
When executing notify-send -t 0 '<enter>' 'text body', everything looks fine:

However, when trying to print the key name in the message body with notify-send -t 0 'Summary' '<enter>', I get:

The same happens with notify-send -t 0 'Summary' '<',  notify-send -t 0 'Summary' '>' or notify-send -t 0 'Summary' \<
Any ideas why the body text is printed blank if it contains < or > ?

Workaround (fails)
I have tried to use a python module istead:
from gi.repository import Notify
Notify.init("App Name")
Notify.Notification.new("Summary","<enter>").show()

But the result is the same as in picture 2 above.

Additional info:
When trying zenity --info --title='Summary' --text='<enter>' in bash, I get an error message:
(zenity:4952): Gtk-WARNING **: Failed to set text '<enter>' from markup due to error parsing markup: Error on line 1 char 24: Element 'markup' was closed, but the currently open element is 'enter'
And instead of the text <enter>, the opening info dialog has the surprising text: All updates are complete.

A: The notification spec says that body can include simple markup, so any tags inside "<...>" will be removed and interpreted if possible. For example, "<b>hello</b>" will show the word in bold.
You can use the standard html entity mechanism and show a < with < and
> with > giving, for example,
notify-send 'Summary' '<enter>'

If you prefer you can just use a multiline summary, eg:
notify-send 'Summary
<enter>'


text:
Q: How to convert an unity3d game app crash log backtrace to code location ***** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
Build fingerprint: 'google/volantis/flounder:7.1.1/N9F27M/4333998:user/release-keys'
Revision: '0'
ABI: 'arm'
pid: 23136, tid: 23160, name: UnityMain  >>> com.kumora.emblem <<<
signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x0
    r0 c0d0d570  r1 00000000  r2 00000024  r3 00000038
    r4 c0d0d578  r5 00000038  r6 de77d141  r7 c837fc78
    r8 00000000  r9 ce4e7694  sl 00000024  fp df1c5c70
    ip dea4fab0  sp d0f75a18  lr de80ec47  pc de77d148  cpsr 600b0030
backtrace:
    #00 pc 00914148  /vendor/lib/libglcore.so
    #01 pc 009a5c45  /vendor/lib/libglcore.so
    #02 pc 009a5fd9  /vendor/lib/libglcore.so
    #03 pc 0079ef39  /vendor/lib/libglcore.so
    #04 pc 005130b0  /data/app/com.kumora.emblem-1/lib/arm/libunity.so
    #05 pc 00264054  /data/app/com.kumora.emblem-1/lib/arm/libunity.so
    #06 pc 002631c0  /data/app/com.kumora.emblem-1/lib/arm/libunity.so
    #07 pc 005b7eec  /data/app/com.kumora.emblem-1/lib/arm/libunity.so
    #08 pc 005b7fa8  /data/app/com.kumora.emblem-1/lib/arm/libunity.so
    #09 pc 0019ac44  /data/app/com.kumora.emblem-1/lib/arm/libunity.so
    #10 pc 0045ef4c  /data/app/com.kumora.emblem-1/lib/arm/libunity.so
    #11 pc 00199ef0  /data/app/com.kumora.emblem-1/lib/arm/libunity.so
    #12 pc 0019b6e4  /data/app/com.kumora.emblem-1/lib/arm/libunity.so
    #13 pc 0019c690  /data/app/com.kumora.emblem-1/lib/arm/libunity.so
    #14 pc 001a34c8  /data/app/com.kumora.emblem-1/lib/arm/libunity.so
    #15 pc 00125d90  /data/app/com.kumora.emblem-1/lib/arm/libunity.so
    #16 pc 00128364  /data/app/com.kumora.emblem-1/lib/arm/libunity.so
    #17 pc 00149794  /data/app/com.kumora.emblem-1/lib/arm/libunity.so
    #18 pc 002e7b34  /data/app/com.kumora.emblem-1/lib/arm/libunity.so
    #19 pc 002e941c  /data/app/com.kumora.emblem-1/lib/arm/libunity.so
    #20 pc 00540a68  /data/app/com.kumora.emblem-1/lib/arm/libunity.so
    #21 pc 00543248  /data/app/com.kumora.emblem-1/lib/arm/libunity.so
    #22 pc 0020e629  /data/app/com.kumora.emblem-1/oat/arm/base.odex (offset 0x1ec000)

I am using this method to convert the address to code location but the result seems no right. Is there any better way to find the crash code location in my file or unity native code?


text:
Q: Triangular numbers of the form $x^4+y^4$ Recall that triangular numbers are those $T(n)=n(n+1)/2$ with $n\in\mathbb N=\{0,1,2,\ldots\}$. Fermat ever proved that the equation $x^4+y^4=z^2$ has no positive integer solution. So I think it's natural to investigate triangular numbers of the form $x^4+y^4$ with $x,y\in\mathbb N$. Clearly,
$$T(0)=0^4+0^4\ \ \mbox{and}\ \ T(1)=1^4+0^4.$$
Via a computer, I find that
$$15^4+28^4=665281=T(1153).$$
Question. Is $T(1153)=665281$ the only triangular number greater than one and of the form $x^4+y^4$ with $x,y\in\mathbb N$?
My computation indicates that $\{x^4+y^4:\ x,y=0,\ldots,5100\}$ contains no other triangular numbers greater than one. I guess that the above question has a positive answer. Can one prove this?
Your comments are welcome!

A: An exhaustive search up to $10^7$ finds that the only solutions of
$x^4+y^4=T(n)$ in integers with $0 \leq x \leq y \leq 10^7$ are:
$$
0^4 + 0^4 = T(0), \quad
0^4 + 1^4 = T(1), \quad
15^4 + 28^4 = T(1153),
$$
noted by OP Zhi-Wei Sun;
$$
3300^4 + 7712^4 = T(85508608),
$$
already found by Tomita; and the new example
$$
6848279^4 + 6896460^4 = T(94462407145153).
$$
Such searches can be done efficiently using the gp function
hyperellratpoints, recently ported into gp from Stahlke and Stoll's
C program ratpoints; the search up to $10^7$ took a few hours.
Probably there are infinitely many solutions, but quite sparse,
because one expects the number of solutions with $0 \leq x,y \leq N$
to be asymptotically proportional to
$$
\sum_{x=0}^N \sum_{y=0}^N \left(8(x^4+y^4)+1\right)^{-1/2}
$$
which grows as a multiple of $\log N$.  Proving anything like that
seems intractable by present-day methods.  This is typical of Diophantine equations leading to "log-K3 surfaces" such as
$x^4 + y^4 = n(n+1)/2$.

A: New solution:     $57331396^4+ 54099540^4=T(6224076560720896)$
$x^4 + y^4 = \frac{\large{n(n+1)}}{\large{2}}$
The problem can be reduced to finding the integer points on quartic as follows.
Let $Y=2n+1$ and $t=y$, then we get $Y^2 = 8x^4 + 8t^4 + 1$ in $x$ with parameter $t$.
Searching the integer points $(x,Y)$ with $t \lt 100000$, we found the integer point $(x,y,Y)=(3300, 7712, 171017217).$
Hence we get $(x,y,n)=(3300, 7712, 85508608).$
$3300^4+7712^4=T(85508608).$


text:
Q: storing cookies in client js and reading in java I have stored a js array(key value pair) in cookie using JSON.stringify...
Ex:
var a={"aaa":"111","bbb":222};
document.cookie="mycookie="+JSON.stringify(a);

When I'm reading the cookie from js it returns the value for mycookie as a string {"aaa":"111","bbb":222} so I can parse it again using JSON.parse() and it works fine for me.
My need is to get the same cookie from java.. so I used HttpServletRequest's request.getCookie() method. It returns an array of cookies.. while iterating in to that, it does not have the cookie as "mycookie" instead of that it contains the following cookie list
cookie[0]= aaa:
cookie[1]= bbb:

why it does not return a value as
cookie[0]= mycookie:{"aaa":"111","bbb":222}

how does the getcookie method parses a single cookie in this mannar..
JS:
var dateOfVisiting=new Date().getTime().toString();
    var mycookie =  {'page':'example.com','date':dateOfVisiting};
var expiryDate = new Date();
    expiryDate.setTime(expiryDate.getTime()+(30*24*60*60*1000));
var expires = "; expires="+expiryDate.toGMTString();
    document.cookie="mycookie="+JSON.stringify(mycookie)+expires+"; path=/;"

Java
  Cookie[] cookies = request.getCookies();
  String myData = null;
  for(Cookie cookie : cookies){
  System.out.println(cookie.getName()+":"+cookie.getValue());
    if("mycookie".equals(cookie.getName())){
    myData = cookie.getValue();
    }
  }

The result is
page:
date:
And its not getting inside the if condition


text:
Q: BLoC behaved wrongly when updating the Model I am writing a similar task manager app, i have some issues when working with BLoC:

*

*First, I create a Page to show all the task that have been added by pressing the FloatingActionButton() below.

*

*Next, when the user finished the form by hitting the FlatButton on the top right which is called SAVE, it will be submitted to Firestore, by the _submit() method in the JobForm class.

*

*NOTE: I also added some validator to validate the NameForm and the RatePerHourForm so it will show an error when they are null and they worked very well.

*

*I used a StreamBuilder() to update my JobPage() ( the first screen ), everywhen the data from Firestore changed.

*

*That was a summary of what I am trying to do.

BUT, when the user press the SAVE button, the Name Field and the ratePerHour Field is always empty even when i called  onChanged: , in every TextField() to update them.
HERE IS MY flutter doctor:
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 2.2.1, on Microsoft Windows [Version 10.0.19042.985], locale en-US)
[!] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    X Android license status unknown.
      Run `flutter doctor --android-licenses` to accept the SDK licenses.
      See https://flutter.dev/docs/get-started/install/windows#android-setup for more details.
[√] Chrome - develop for the web
[√] Android Studio (version 4.1.0)
[√] Connected device (3 available)

! Doctor found issues in 1 category.

*** There is 1 issue in 1 category but it is fine because i run flutter on a real device.
HERE IS MY pbspec.yaml:
name: untitled
description: A new Flutter project.

    # The following line prevents the package from being accidentally published to
    # pub.dev using `pub publish`. This is preferred for private packages.
    publish_to: 'none' # Remove this line if you wish to publish to pub.dev

    # The following defines the version and build number for your application.
    # A version number is three numbers separated by dots, like 1.2.43
    # followed by an optional build number separated by a +.
    # Both the version and the builder number may be overridden in flutter
    # build by specifying --build-name and --build-number, respectively.
    # In Android, build-name is used as versionName while build-number used as versionCode.
    # Read more about Android versioning at https://developer.android.com/studio/publish/versioning
    # In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
    # Read more about iOS versioning at
    # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
    version: 1.0.0+1

    environment:
      sdk: ">=2.7.0 <3.0.0"

    dependencies:
      flutter:
        sdk: flutter

      # The following adds the Cupertino Icons font to your application.
      # Use with the CupertinoIcons class for iOS style icons.
      cupertino_icons: ^1.0.2
      firebase_auth: ^0.14.0+5
      google_sign_in: ^4.0.7
      flutter_facebook_login: ^2.0.1
      provider: ^5.0.0
      cloud_firestore: ^0.12.9+5

    dev_dependencies:
      flutter_test:
        sdk: flutter

    # For information on the generic Dart part of this file, see the
    # following page: https://dart.dev/tools/pub/pubspec

    # The following section is specific to Flutter.
    flutter:

      # The following line ensures that the Material Icons font is
      # included with your application, so that you can use the icons in
      # the material Icons class.
      uses-material-design: true

      # To add assets to your application, add an assets section, like this:
      assets:
        - images/

      # An image asset can refer to one or more resolution-specific "variants", see
      # https://flutter.dev/assets-and-images/#resolution-aware.

      # For details regarding adding assets from package dependencies, see
      # https://flutter.dev/assets-and-images/#from-packages

      # To add custom fonts to your application, add a fonts section here,
      # in this "flutter" section. Each entry in this list should have a
      # "family" key with the font family name, and a "fonts" key with a
      # list giving the asset and other descriptors for the font. For
      # example:
      # fonts:
      #   - family: Schyler
      #     fonts:
      #       - asset: fonts/Schyler-Regular.ttf
      #       - asset: fonts/Schyler-Italic.ttf
      #         style: italic
      #   - family: Trajan Pro
      #     fonts:
      #       - asset: fonts/TrajanPro.ttf
      #       - asset: fonts/TrajanPro_Bold.ttf
      #         weight: 700
      #
      # For details regarding fonts from package dependencies,
      # see https://flutter.dev/custom-fonts/#from-packages

HERE IS MY CODE:
*** JobPage():
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:untitled/app/home/job_form/jobs_form.dart';
import 'package:untitled/app/home/models/job.dart';
import 'package:untitled/common_widgets/platform_alert_dialog.dart';
import 'package:untitled/services/auth.dart';
import 'package:untitled/services/database.dart';

class JobsPage extends StatelessWidget {

  Future<void> _signOut(BuildContext context) async{
    try {
      final auth = Provider.of<AuthBase>(context, listen: false) ;
      await auth.signOut();
    } catch(e){
      print(e.toString());
    }
  }

  Future<void> _confirmSignOut(BuildContext context) async{
    final didRequestSignOut = await PlatformAlertDialog(
        title: 'Sign out',
        content: 'Are you sure?',
      cancelText: 'No',
    ).show(context);
    if (didRequestSignOut == true){
      _signOut(context);
    }
  }

  void _navigateToJobForm(BuildContext context){
    Navigator.of(context).push(
      MaterialPageRoute<void>(
        fullscreenDialog: true,
        builder: (_) => JobForm.create(context),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('JOB'),
        centerTitle: true,
        actions: <Widget>[
          TextButton(
            child: Text(
                'Sign out',
              style: TextStyle(
                color: Colors.white,
                fontSize: 18.0,
              ),
            ),
            onPressed: () => _confirmSignOut(context),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () => _navigateToJobForm(context),
      ),
      body:  _buildContents(context),
    );
  }

  Widget _buildContents(BuildContext context) {
    final database = Provider.of<Database>(context);

    return StreamBuilder<List<Job>>(
      stream: database.jobsStream(),
        builder: (context, snapshot) {
        if(snapshot.hasData){
          final jobs = snapshot.data;
          final children = jobs.map((job) => Text(job.name)).toList();
          return ListView(
            children: children,
          );
        }
        if(snapshot.hasError){
          return Center(child: Text('Some error occurred'));
        }
        return Center(
          child: CircularProgressIndicator(),
        );
        }
    );
  }
}

*** JobForm():
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:untitled/app/home/job_form/job_form_bloc.dart';
import 'package:untitled/app/home/job_form/job_form_model.dart';
import 'package:untitled/app/sign_in/validator.dart';
import 'package:untitled/common_widgets/platform_exception_alert_dialog.dart';
import 'package:untitled/services/database.dart';

class JobForm extends StatefulWidget {
  const JobForm({Key key,  @required this.bloc}) : super(key: key);
  final JobFormBloc bloc;

  static Widget create(BuildContext context){
    final Database database = Provider.of<Database>(context, listen: false);
    return Provider(
      create: (context) => JobFormBloc(database: database),
      child: Consumer<JobFormBloc>(
        builder: (context, bloc, _) => JobForm(bloc: bloc),
      ),
      dispose: (context, bloc) => bloc.dispose(),
    );
  }
  @override
  _JobFormState createState() => _JobFormState();
}

class _JobFormState extends State<JobForm> with EmailAndPasswordValidator {

  final TextEditingController _nameController =  TextEditingController();
  final TextEditingController _ratePerHourController =  TextEditingController();
  final FocusNode _nameFocusNode = FocusNode();
  final FocusNode _ratePerHourFocusNode = FocusNode();

  @override
  void dispose(){
    _nameController.dispose();
    _nameFocusNode.dispose();
    _ratePerHourFocusNode.dispose();
    _ratePerHourController.dispose();
    super.dispose();
  }
  void _onEditingNameComplete(JobFormModel model){
    print(model.name);
    final newNode =  model.emailValidator.isValid(model.name) ? _ratePerHourFocusNode : _nameFocusNode;
    FocusScope.of(context).requestFocus(newNode);
  }

  Future<void> _submit() async {
    try{
        await widget.bloc.submitToFirebase();
        Navigator.of(context).pop();
    } on PlatformException catch (e){
      PlatformExceptionAlertDialog(
        title: 'Error',
        exception: e,
      ).show(context);
    }
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<JobFormModel>(
      stream: widget.bloc.modelStream,
      initialData: JobFormModel(),
      builder: (context, snapshot) {
        final JobFormModel model = snapshot.data;
        return Scaffold(
          appBar: AppBar(
            title: Text('Create new job'),
            centerTitle: true,
            actions: <Widget>[
              TextButton(
                onPressed: model.isLoading ? null :  _submit,
                child: Text(
                  'SAVE',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16.0,
                  ),
                ),
              )
            ],
            leading: IconButton(
              icon: Icon(Icons.arrow_back),
              onPressed: () => !model.isLoading ? Navigator.of(context).pop() : null,
            ),
          ),
          body: Padding(
            padding: const EdgeInsets.all(16.0),
            child: Card(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                mainAxisSize: MainAxisSize.min,
                children: _buildContent(model),
              ),
            ),
          ),
        );
      }
    );
  }

  List<Widget> _buildContent(JobFormModel model) {
    return [

      _buildNameTextField(model),

      SizedBox(height: 8.0),

      _buildRatePerHourTextField(model),

      SizedBox(height: 8.0),

    ];
  }

  TextField _buildRatePerHourTextField(JobFormModel model) {
    return TextField(
      controller: _ratePerHourController,
      keyboardType: TextInputType.number,
      decoration: InputDecoration(
        labelText: 'Rate per hour',
        hintText: '0',
        errorText: model.ratePerHourErrorText ,
        enabled: model.isLoading == false,
      ),
      autocorrect: false,
      inputFormatters: [
        FilteringTextInputFormatter.digitsOnly,
      ],
      focusNode: _ratePerHourFocusNode,
      textInputAction: TextInputAction.done,
      onEditingComplete:  _submit,
      onChanged: widget.bloc.updateRatePerHour,
    );
  }

  TextField _buildNameTextField(JobFormModel model) {
    return TextField(
      controller: _nameController,
      focusNode: _nameFocusNode,
      decoration: InputDecoration(
        labelText: 'Job name',
        hintText: 'Blogging',
        errorText: model.nameErrorText,
        enabled: model.isLoading == false,
      ),
      autocorrect: false,
      textInputAction: TextInputAction.next,
      onChanged:  widget.bloc.updateName,
      onEditingComplete:() => _onEditingNameComplete(model),
    );
  }

}

*** JobFormModel():
import 'package:untitled/app/sign_in/validator.dart';

class JobFormModel with EmailAndPasswordValidator{
  JobFormModel(
      {
      this.isLoading = false ,
      this.ratePerHour = '10',
      this.name = '',
        this.submitted = false,
      });

  final bool isLoading ;
  final String ratePerHour;
  final String name;
  final bool submitted;

  bool get canPop {
    return !isLoading;
  }

   bool get canSave{
    return emailValidator.isValid(name) && emailValidator.isValid(ratePerHour) && !isLoading;
   }

   String get nameErrorText{
    bool show = !emailValidator.isValid(name) ;
    return show ? "Can't leave the Name field  empty" : null;
   }

   String get ratePerHourErrorText{
    bool show = !emailValidator.isValid(ratePerHour);
    return show ? "Can't leave this Field empty" : null;
   }

   JobFormModel copyWith({
      bool submitted,
      bool isLoading,
      String ratePerHour,
      String name,
}){
    return JobFormModel(
      isLoading: isLoading ?? this.isLoading,
      submitted: submitted ?? this.submitted,
      ratePerHour: ratePerHour ?? this.ratePerHour,
      name: name ?? this.name,
    );
}
}

*** JobFormBloc():
import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:untitled/app/home/job_form/job_form_model.dart';
import 'package:untitled/app/home/models/job.dart';
import 'package:untitled/services/database.dart';

class JobFormBloc {
  JobFormBloc({@required this.database});

  final Database database;
  // ignore: close_sinks
  final StreamController<JobFormModel> _modelController =
      StreamController<JobFormModel>();

  Stream get modelStream => _modelController.stream;

  JobFormModel _model = JobFormModel();

  void dispose() {
    _modelController.close();
  }

  Future<void> submitToFirebase() async {
    updateWith(
      isLoading: true,
      submitted: true,
    );
    try {
      await database.createJob(Job(
        name: _model.name,
        ratePerHour: int.parse(_model.ratePerHour),
      ));
    } catch (e) {
      updateWith(
        isLoading: false,
      );
      rethrow;
    }
  }

  void updateName(String name) => updateWith(name: name);

  void updateRatePerHour(String ratePerHour) =>
      updateWith(ratePerHour: ratePerHour);

  void updateWith({
    String name,
    String ratePerHour,
    bool submitted,
    bool isLoading,
  }) {
    _model.copyWith(
      name: name,
      ratePerHour: ratePerHour,
      isLoading: isLoading,
      submitted: submitted,
    );
    _modelController.add(_model);
  }
}

*** class Database():
import 'dart:async';
import 'package:meta/meta.dart';
import 'package:untitled/app/home/models/job.dart';
import 'package:untitled/services/api_path.dart';
import 'package:untitled/services/firestore_services.dart';

abstract class Database {
  Future<void> createJob(Job job);
  Stream<List<Job>> jobsStream();
}

final _service = FirestoreServices.instance;

class FirestoreDatabase implements Database {
  FirestoreDatabase({@required this.uid}) : assert(uid != null);
  final String uid;

  Future<void> createJob(Job job) async => await _service.setData(
    path: APIPath.job(uid, 'job_abc'),
    data: job.toMap(),
  );

  Stream<List<Job>> jobsStream() => _service.collectionStream(
    path: APIPath.jobs(uid),
    builder: (data) => Job.fromMap(data),
  );

}

A: The issue is with the updateWith method of the JobFormBloc.
Currently you have this below:
    _model.copyWith(
      name: name,
      ratePerHour: ratePerHour,
      isLoading: isLoading,
      submitted: submitted,
    );

_model.copyWith returns a new model with the updated value but it does not update the _model variable with it. The new model is unused.
So in order to update the value, you should assign the updated model to the _model variable like this:
_model = _model.copyWith(
  name: name,
  ratePerHour: ratePerHour,
  isLoading: isLoading,
  submitted: submitted,
);


text:
Q: How to use rufus to create bootable usb(Sony 16GB) for WIndows 10 iso file(Win10_1909_English_x64.iso of 5.04GB size)?
*

*Downloaded file Win10_1909_English_x64.iso

*Size of downloaded file - 5.04GB

*USB - Sony 16GB USB 2.0 (14.4GB available space)

*Downloaded Rufus 3.8.1580

*Using diskpart and typing list disk shows there is an asterisk mark under GPT for Disk 0

*System Information BIOS mode - UEFI

*Current OS - Windows 10 Home single language

*Cannot download more than 2GB per day in my internet connection, so I cannot use media creation tool and have downloaded the iso file

*Do not want to use reset as it keeps the bloatware. My main aim is to clean install Windows 10 on my laptop.

When I insert the USB and open Rufus it shows many options; what should I choose for:  (or is there another method or tool for making bootable USB?)

*

*Partition Scheme

*Target System

*File System

*Cluster size

After installing Windows 10, will it automatically activate if the laptop came preinstalled with it?

A: Partition Scheme and Target system - GPT Partitioning scheme for UEFI
File System - NTFS
Cluster size - Keep what is there default

OR is there another method or tool for making bootable usb.

There are tools but Rufus is fine.
From rufus

Oh, and Rufus is fast. For instance it's about twice as fast as Unetbootin, Universal USB Installer or Windows 7 USB download tool

......

And after installing Windows 10 Home single language ,will it get automatically activated if laptop came preinstalled with Windows 10 Home single language.

An example
For Dell taken from FAQ regarding product key

For Windows 8 and Windows 10, the Product Key is "injected" onto the
  computer motherboard at the factory. Installation and activation of
  Windows refer to the information in the BIOS of the computer to verify
  authenticity. Owners of these computers do not need a physical key to
  input.

A: You can perform a full reset from within Windows itself.
Settings > Update & Security > Recovery

Alternatively you can download the Media Creation Tool directly from Microsoft, which will correctly make your boot USB.
You Windows Activation is stored at Microsoft & will be automatically re-applied if you reinstall to the same hardware.


text:
Q: MATLAB : How to crop an object from a binary image by identifying some features? I have an image like shown here:
My ultimate aim is to extract the vein pattern in the finger. So What I am trying to do is the extraction of the finger object alone. For that purpose, I tried an Otsu thresholding step first, then an erosion and dilation. Now using the binary image as a mask I multiplied element wise with original image to obtain the finger alone (not that accurate though).
The code is as below:
I = imread('3.5.bmp');
[level] = graythresh(I);
BW = im2bw(I,level);
[BWm] = imerode(BW,strel('disk',10)); figure, imshow(BWm)
[BWmm] = imdilate(BWm,strel('disk',15)); figure, imshow(BWmm)
B = I.*uint8(BWmm); % BWmm is the mask
imshow(B)

Now I want to crop this finger part alone using the mask which I created before. How to achieve that?
For clarity I am uploading the image with the area to be cropped:  (And finally I don't want to do this manually or using imcrop() utility with pixel coordinates as input. I would like to get those pixel coordinate using some algorithms.)

A: You can find the pixel coordinates from the mask BWmm and then use the coordinates with imcrop.
To find the extermal points of BWmm use
projX = any( BWmm, 1 ); % projection of mask along x direction
projY = any( BWmm, 2 ); % projection of mask along y direction
fx = find( projX, 1, 'first' ); % first column with non-zero val in mask
tx = find( projX, 1, 'last' );  % last column with non-zero val in mask
fy = find( projY, 1, 'first' ); % first row with non-zero val in mask
ty = find( projY, 1, 'last' );  % last row with non-zero val in mask
cropRect = [fx, fy, tx-fx+1, ty-fy+1];
cImg = imcrop( I, cropRect );


text:
Q: Find pair of matches between an numpy array Python I have a numpy array in Python which contains labels for a classification problem. The array derived after the concatentation of two initial identical arrays.
labels = np.concatenate((labels1, labels2)) #labels1 and labels2 are identical

I want to generate positive/negative pairs which will contain all the indexes from labels (from which labels1 and labels2 are equal) and also the pairs with the negative ones. For example if my input is the following:
labels = {1, 1, 2, 2, 3, 1, 1, 2, 2, 3} # labels1 = labels2 = {1, 1, 2, 2, 3}

Then I want to return as positive pairs:
positive_pairs = {{1, 6}, {1, 7}, {2, 6}, {2, 7}, {3, 8}, {3, 9}, {4, 8}, {4, 9}, {5, 10}} # i dont want to have {1,2} or {3, 4} in within the positives
negative_pairs = {{1, 8}, {1, 9}, ...}

How can I do so in python?
EDIT: What in the case that labels1 and labels2 are not equal?

A: Here's a solution for positive_pairs:
labels1 = np.array([1, 1, 2, 2, 3])
length1 = len(labels1)
positive_pairs = []
for ii, label in enumerate(labels1, 1):
    for other in np.where(labels1 == label)[0] + length1 + 1:
        positive_pairs.append((ii, other))

negative_pairs is left as an exercise.

A: You can accomplish it like this
labels_1 = np.array([1,1,2,2,3])
labels_2 = np.array([1,1,2,2,3])
n = len(labels_1)
positive_pairs = [(i1+1, i2+n+1) for i1, l in enumerate(labels_1)
                                 for i2 in np.where(labels_2 == l)[0]]

[(1,6),(1,7),(2,6),(2,7),...]

negative_pairs = [(i1+1, i2+n+1) for i1, l in enumerate(labels_1)
                                 for i2 in np.where(labels_2 != l)[0]]

[(1,8),(1,9),(1,10),(2,8),...]

Though, I am not sure this is the most efficient way.

A: outp = []
len1 = len(labels) // 2 # assume initially labels was [label1, label1]
label1 = labels[:len1]
label2 = labels[len1:]
set1 = set(label1)
for v in set1:
    eq1 = np.where(label1 == v)[0] + 1
    eq2 = np.where(label2 == v)[0] + len1 + 1
    outp.append(np.transpose([np.tile(eq1, len(eq2)), np.repeat(eq2, len(eq1))]))
outp = np.concatenate(outp).tolist()

# Edit: Find "negative pairs"
eq3 = np.indices((len1, ))[0][np.in1d(label2, list(set1), invert=True)] + len1 + 1
outn = np.transpose([np.tile(np.arange(len1), len(eq3)), np.repeat(eq3, len1)]).tolist()

A: My solution used numpy broadcasting and np.where().
x, y = np.where(label1[np.newaxis, :] == label2[:, np.newaxis])
result = np.vstack([x, y+len(label1)]).T + 1

I thought this was an efficient/numpy way to solve your problem.  But, tarashypka's solution is faster on larger data sets.  (Anyone know why?)
def where_method(a, b):
    x, y = np.where(a[np.newaxis, :] == b[:, np.newaxis])
    return np.vstack([x, y+len(labels1)]).T + 1

def for_append_method(a, b):
    length1 = len(a)
    positive_pairs = []
    for ii, label in enumerate(a, 1):
        for other in np.where(b == label)[0] + length1 + 1:
            positive_pairs.append((ii, other))
    return positive_pairs

labels1 = np.sort(np.random.randint(low=10, high=7500, size=10000))
labels2 = labels1

%timeit where_method(labels1, labels2)
%timeit for_append_method(labels1, labels2)

326 ms ± 2.98 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
122 ms ± 1.71 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)


text:
Q: How to dynamically change jquery mobile page theme without reloading the page? jQuery mobile applies different class names on elements based on data-theme attribute when a page is initially loaded: like adding 'ui-bar-a' to a bar if data-theme='a'.
I want to dynamically change the theme on a JQM page, without reloading the page itself, like what JQM themeroller does: http://themeroller.jquerymobile.com/?ver=1.3.2
But changing the data-theme attribute doesn't trigger the theme switch, JQM javascript still needs to redo what it does at initial page load.
How to trigger jquery mobile to rerender the page? I looked at documentation but didn't find any API for this.
Relevant question:
Dynamically changing theme

A: Forget the triggering logic on page load and just remove and set classes yourself.
$(element).removeClass('ui-bar-a').addClass('ui-foo-b');


text:
Q: Calling a Slim CORS Web Service using Curl I'm having problems getting a Slim CORS web service to work using Curl
It works fine when called from a browser based Ajax Service but I cannot get it working when called from a script on the server. CORS has been setup to allow access from '*'
$url = "https://server.local/api/v1.0/issueJWTToken";

$ch1 = curl_init();

$headers = [
    "Origin: https://server.local",
    "Content-Type: text/plain",
    "Access-Control-Request-Headers: Content-Type, Origin"
];

curl_setopt_array($ch1, array(
    CURLOPT_URL => $url,
    CURLOPT_CUSTOMREQUEST => 'OPTIONS',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HEADER => true,
    CURLOPT_HTTPHEADER => $headers,
    CURLOPT_NOBODY => true,
    CURLOPT_SSL_VERIFYHOST => 0,
    CURLOPT_SSL_VERIFYPEER => false
));

$data = curl_exec($ch1);

curl_close($ch1);

This returns the following:
HTTP/1.1 200 OK
Date: Mon, 04 Jun 2018 12:33:51 GMT
Server: Apache/2.4.10 (Debian)
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: X-Requested-With, Content-Type, Accept,
Origin, Authorization
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Content-Length: 0
Content-Type: text/html;
charset=UTF-8

I then follow it with a POST transaction as follows:
$post_fields = "id=1" ;

$headers = [
    "Origin: https://server.local",
    "Content-Type: text/plain"
];

$ch = curl_init();

curl_setopt_array($ch,[
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_URL => $url,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_HEADER => true,
    CURLOPT_HTTPHEADER => $headers,
    CURLOPT_POSTFIELDS=> $post_fields,
    CURLOPT_SSL_VERIFYHOST => 0,
    CURLOPT_SSL_VERIFYPEER => false
]);

$data = curl_exec($ch);

But I get the following
HTTP/1.1 405 Method Not Allowed
Date: Mon, 04 Jun 2018 12:38:02 GMT Server: Apache/2.4.10 (Debian)
Allow: OPTIONS
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: X-Requested-With, Content-Type, Accept, Origin, Authorization
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Content-Length: 559
Content-Type: text/html;charset=UTF-8

        <title>Method not allowed</title>

Method not allowed

Method  not allowed. Must be one of: OPTIONS

Am I doing something wrong? The OPTIONS call seems to work OK but I cannot get the POST to succeed.
Is there something returned from the OPTIONS response that I should be passing back in the POST?
Any help greatly appreciated
Neil
Update: CORS settings shown below
$app->options('/{routes:.+}', function ($request, $response, $args) {
    return $response;
});

$app->add(function ($req, $res, $next) {
    $response = $next($req, $res);
    return $response
    ->withHeader('Access-Control-Allow-Origin', '*')
    ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
    ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
});

A: Turns out it was me being an idiot. I had the URL path wrong for the API. D'oh! . Thanks to those of you that responded. Neil


text:
Q: Not sure how to fix an error in the Handbook of Categorical Algebra (vol 3) In the proof of Theorem 1.5.7 (in which it is shown the the nuclei on a locale, when ordered by pointwise partial order, themselves form a locale) in the computation at the bottom of p.35, there is used an inequality
$$ j\Bigl( \bigl( j(b)\Rightarrow k(b)\bigr)\wedge b\Bigr) \Rightarrow k(b)  ~~\leq~~ j(b)\Rightarrow k(b)$$
however since $j(bla\wedge b) \leq j(b)$ and $- \Rightarrow k(b)$ is contravariant, I don't think that that's true.
I'm not sure what to do to avoid using this.

A: You have a point that the last step is unclear. It might have been clearer if the last inequality were written as an equality instead, since that would essentially force the reader to verify that $b = (j(b) \Rightarrow k(b)) \wedge b$, or simply that $b \leq j(b) \Rightarrow k(b)$, which is true since it is equivalent to $b \wedge j(b) \leq k(b)$, which follows from $b \leq k(b)$.


text:
Q: Remote desktop behavior with 3D3 Device and RDP window minimize In our C# WPF we use a 3rd party (unmanaged) library that display a map.
We use the System.Windows.Interop.D3DImage class.
The 3rd party library uses Direct3D for the the IntPtr32 surface location property.
When i open a remote desktop from another computer and trying to view the WPF Client, we see the map.
Once the WPF UI Client is up, and I minimize the RDP session or close the RDP i will get exception:
Direct3D device is lost

From my experience with video streaming applications, When a window is minimized, it is stop rendering the image in order to save bandwitdh.
I guess rdp is acting the same ? Is it configureable ? I wish to continue streaming even if window is minimized.
I know that there are additional settings in the .RDP file as mentioned here.
The directx is set to: redirectdirectx:i:1
Partial answer so far:
When RDP client application is connecting to RDP Service, when the window is shown, it is GUI mode, when it is minimized, it is GUI-LESS mode, and the Direct 3D Components are really lost. in order to keep them alive during minimize, a registry key must be turned on (RemoteDesktop_SuppressWhenMinimized)

A: From this page: http://www.networkautomation.com/urc/knowledgebase/running-interactive-tasks-in-minimized-remote-desktop-windows/4ecdf43e03470/

Use this key for 1 particular user (use HKLM for all users):
HKEY_CURRENT_USER\Software\Microsoft\Terminal Server Client\RemoteDesktop_SuppressWhenMinimized
type = DWORD
Values:
0 = SUPPRESS_WHEN_MINIMIZED_AUTO
1 = SUPPRESS_WHEN_MINIMIZED_ENABLE
2 = SUPPRESS_WHEN_MINIMIZED_DISABLED


text:
Q: Cast Dropbox class to JSON I am using the Python Dropbox package to pull team events:
dbx = dropbox.DropboxTeam(self.access_token)
result = dbx.team_log_get_events()

I need to pass the value of result along as a JSON object. When I try using json.dumps(result), I get this error:

TypeError: Object of type GetTeamEventsResult is not JSON serializable

Is there a way to cast to json/dict with the Dropbox package?
My other potential solutions would be to write my own method to cast it (seems tedious) or just make API calls instead of using the package.

A: Just heard back from a Dropbox Developer on the DB Forums:

The methods for calling the API in the Dropbox Python SDK don't return JSON-serializable objects (or the original JSON from the server), but I'll pass this along as a feature request. I can't promise if or when that might be implemented though.

You can transform the information in the returned native object however you wish, but you'd need to write the code to do so though unfortunately, as you mentioned.

Will keep this post updated if more information comes out.

A: Depending on the attributes that the team_log_get_events() returns, you can make a function to cast them to defaultdict()
For example from code I used to return dictionary of shared link meta data compatible with JSONResponse:
from collections import defaultdict
import dropbox

client = dropbox.Dropbox(DBX_TOKEN)

def shared_link_info(shared_link_url):
        """Information of the shared link provided."""
        temp = defaultdict(dict)

        result = client.sharing_get_shared_link_metadata(shared_link_url)

        temp["id"] = result.id
        temp["name"] = result.name
        temp["content_type"] = type(result).__name__
        temp["modified_date"] = result.client_modified.strftime("%Y-%m-%d")
        temp["allow_download"] = result.link_permissions.allow_download
        temp['path_lower'] = result.path_lower
        if result.size:
            temp["size"] = result.size
        else:
            result["size"] = None

        if result.expires:
            temp["link_expires"] = result.expires.strftime("%Y-%m-%d")
        else:
            result["link_expires"] = None

        return temp


text:
Q: Simple transistor for switching a computer power supply I am teaching myself about simple transistor circuit design and have been stumped by the simplest transistor behaviours. The task I have set is to use a transistor to switch on an ATX computer power supply. The principle is the power supply has a wire pulled to 5 V which when grounded causes the supply to switch on.
Ammeter testing shows the current in the grounded circuit is 333 uA so I figured pretty much any transistor could do the job required. Selecting almost at random from a bag of transistors I picked out a BC549B unit and found its datasheet. It appeared to be able to handle this current just fine so I set about making a little circuit that put the 5V wire to the collector and a ground wire to the emitter.
From a separate power supply I used a 2 V supply to the base through at first a large, (147 kOhm) resistor, with the ground of the separate supply coupled to the emitter of the transistor/ground of the ATX supply.
The first observation is interesting and unexpected. Firstly with the base disconnected from the second supply and grounded to zero, the 5 V wire held its full voltage. With the base floating, the 5V was pulled down to about 2.5 V. Is there an obvious explanation for this?
Now with the connected power supply putting out an actual 2.87 V, voltage on the 5V wire was pulled to 446 mV. Incrementally stepping up the input to 12.3 V, the 5 V wire was pulled to 128 mV from ground. Looking at the input currents to the base plotted against collector current, the collector current rose asymptotically toward a value seemingly below the 333 uA current required (about 325 uA.) I figured in this configuration the base resistor was too high and started dropping it's value. I'm at 661 Ohm now, with the full 12.3 V I am pulling the 5 V wire to 30 mV. Even so I am not seeing the supply switch on. I would think surely this is below the switching threshhold of the power supply, am I wrong?
Another strange behaviour is that with the ATX supply connected, if I instantaneously force closed the collector and emitter terminals to force the supply on, the circuit seems to energise itself and the supply stays on until I disconnect one wire from the circuit. Why would this be?
Finally, am I simply using an inadequate transistor for the job or is there some impossibility I am fighting against?

simulate this circuit – Schematic created using CircuitLab

A: The problem seems to be as obscure as expected. Not related to having the supply loaded or anything. I am simply using a capacitor to smooth out the signal to the base and the circuit works. Discovering further, this external power supply is intended to be earthed and wasn't. Even still, the capacitor seems to be necessary for startup to be successful.
I edited the above schematic, adding the 187uOhm resistor to pull the base down and open the main circuit, also to discharge the 680nF capacitor. With those the circuit works well, controlling the ATX PSU with on and off signals.


text:
Q: How can I resolve query object error - ValueError: Cannot query "mayur": Must be "User" instance I am trying to access my followers in the available module, I can get the number of count such as the number of followers and number of followings but I can't get the list of followers to see my followers. Need suggestions.
My module.py File:
from django.db import models

class FollowerFollowing(models.Model):
        user_from = models.ForeignKey('User', on_delete=models.SET_NULL, null=True, related_name='rel_from_set')
        user_to = models.ForeignKey('User', on_delete=models.SET_NULL, null=True, related_name='rel_to_set')
        created = models.DateTimeField(auto_now_add=True, db_index=True)

        class Meta:
            ordering = ('-created',)

        def __str__(self):
            return '{} follows {}'.format(self.user_from, self.user_to)

    User.add_to_class('following', models.ManyToManyField('User', through=FollowerFollowing, related_name='followers', symmetrical=False))

My views.py File:
def follower(request):
    print(request)
    if request.session['user_id']:
        query = FollowerFollowing.objects.filter(user_from=request.user)
        print(query)
        context = {
            'query': query
            }
        return render(request, 'Instagram_app/following.html', context)
    else:
        pass
    return HttpResponse("No user logged in")

follower.html (template)
{% extends 'Instagram_app/home.html'%}
{% block content %}

following

        {% for result in query %}

{{ result }}

        {% endfor %}

{% endblock %}

Console error is:
(value, opts.object_name))
ValueError: Cannot query "mayur": Must be "User" instance.
[20/Jun/2018 11:45:27] "GET /Instagram_app/follower HTTP/1.1" 500 105165

Need suggestions to solve this problem. Thank you

A: Try to change this part:
(user_from=request.user)
To this:
(user_from=User.objects.get(username=request.user))
Your user_from must be a User model instance, not a simple username.

A: Tried to change the code to display the following list according to logged in user session
from:
query = FollowerFollowing.objects.filter(user_from=request.user)

To:
query = FollowerFollowing.objects.filter(user_from=request.session['user_id'])

because request.user gives you the list of single and very first logged in user's following list for all users.


text:
Q: Looping through worksheet - Duplicate search values from array not written Hi I am fairly new to VBA and I am trying to achieve the following:

*

*Read the value of a column of a workbook into an array

*Open another workbook and in a worksheet look for these values in a column and copy the data in the adjacent columns in the worksheet.
3.Write the data to the workbook in point 1

This is the function that I have written so far:
Function getDetailsFromMasterSheet(ByRef numberArray As Variant, ByRef flagNameArray As Variant, nameSuffix As String, flow As String)
Dim arrayIndex As Integer
Dim curCell As Long
Dim pathToFile As String
Dim pathToXl As String
Dim orderNumber As Integer
Dim classType As String
Dim classNumber As Integer
Dim className As String
Dim bNumber As Integer
Dim bName As String
Dim cNumber As Integer
Dim cName As String
Dim logic As String
Dim allowClear As String
Dim testFlagName As String
Dim flowName As String
Dim flowNameSuffix As String
Dim newWorkSheetName As String
Dim ws As Worksheet
Dim ws2 As Worksheet
Dim ws3 As Worksheet
Dim sheetCount As Integer
Dim rowStart As Integer
Dim columnStart As Integer
Dim cellValue As String
orderNumber = 1
rowStart = 4
columnStart = 1
Dim retval As Boolean
pathToFile="C:\Projects\Project_Binning\Standard_Binning_J750HD_rev04.xlsx"
pathToXl = "C:\Projects\Project_Binning\MockDataBinning.xlsm"
logic = "S_ANY"
allowClear = "NO"
arrayIndex = 0

Set ws3 = Worksheets(newWorkSheetName)
Set ws = Workbooks.Open(pathToFile).Worksheets("Test")
ws.Activate
For curCell = 1 To ws.Cells(ws.Rows.Count, 8).End(xlUp).Row
If ws.Cells(curCell, 8).Value <> vbNullString Then
  cellValue = ws.Cells(curCell, 8).Value
  If StrComp(cellValue, numberArray(arrayIndex), vbTextCompare) = 0 Then
    classType = ws.Cells(curCell, 8).Offset(0, -7).Value
    classNumber = CInt(ws.Cells(curCell, 8).Offset(0, -6).Value)
    className = ws.Cells(curCell, 8).Offset(0, -5).Value
    If StrComp(flowNameSuffix, "LM", vbTextCompare) = 0 Then
        bNumber = CInt(ws.Cells(curCell, 8).Offset(0, -2).Value)
        bName = ws.Cells(curCell, 8).Offset(0, -1).Value
    Else
       bNumber = CInt(ws.Cells(curCell, 8).Offset(0, -4).Value)
        bName = ws.Cells(curCell, 8).Offset(0, -3).Value
    End If
    cNumber = numberArray(arrayIndex)
    cName = ws.Cells(curCell, 8).Offset(0, 1).Value
    ws3.Cells(rowStart, columnStart) = orderNumber
    ws3.Cells(rowStart, columnStart).Offset(0, 1) = classType
    ws3.Cells(rowStart, columnStart).Offset(0, 2) = classNumber
    ws3.Cells(rowStart, columnStart).Offset(0, 3) = className
    ws3.Cells(rowStart, columnStart).Offset(0, 4) = bNumber
    ws3.Cells(rowStart, columnStart).Offset(0, 5) = bName
    ws3.Cells(rowStart, columnStart).Offset(0, 6) = cNumber
    ws3.Cells(rowStart, columnStart).Offset(0, 7) = cName
    ws3.Cells(rowStart, columnStart).Offset(0, 8) = logic
    ws3.Cells(rowStart, columnStart).Offset(0, 9) = allowClear
    ws3.Cells(rowStart, columnStart).Offset(0, 10) = "'-" & flagNameArray(arrayIndex)
    arrayIndex = arrayIndex + 1
    rowStart = rowStart + 1
    orderNumber = orderNumber + 1
    End If
    End If
    Next curCell
    End Function

The data in the sheet from which I am copying is basically string and integers which has the format
classType, className, classNumber, bNumber, bName, cNumber, cName
Each of the data above is either a string or a number. These are copied into the variables which are in turn written to another worksheet
When there are no duplicate values in the number array, the code works as expected .i.e. the data gets read from the worksheet as expected and gets written to the expected worksheet. But, when there are duplicates in the array, only one of the values is considered and the rest are not. For example if the array consists of {65,75,65,80}. The value of 65 is written only once to the worksheet and the duplicate value is not.I checked to see if the array was getting populated correctly and it was. Not sure exactly as to what it is that I am doing wrong. Could anybody please let me know?

A: I found out the issue and was able to fix it. I noticed that in the for loop the control went from top to bottom and it happened only once. So, when the search condition was met once, it would never be met again. For example,
If the number 65 exists twice in the array, as soon as the number is found the writing to another worksheet task is done. But, what happens is if the number occurs again, since the iteration has already passed through the number 65 on the sheet once the number is never found  again. So, I added the following line of code
curCell = 1

at the end of the first if loop after
orderNumber = orderNumber+1

This set the control to the first row of the worksheet again and the duplicate numbers were successfully written to the worksheet!