text:
Q: How to detect UILabel (without set width just AutoLayout) is truncate like (Hello I am Test....) or not? I want to detect UILabel is truncate or not.
And I try a UILabel extension function in stackoverflow and it return true to me.
But the UILabel line just one and no truncated, why return true to me.
Have another function to detect this situation like this.
Have any idea to me to fix this question?
Thanks.

ViewController.swift
import UIKit
import SnapKit

class ViewController: UIViewController {

    let tableView = UITableView()

    var isExpand: Bool = false

    let titleArray: [String] = ["NAME", "AGE", "EMAIL", "TEL", "LOCATION"]
    let detailArray: [String] = ["abcdefghijklmnopqrstuvwxyz", "26", "XXXXXX@gmail.com", "XXXXXXXXXXX", "JP"]
    let hiddenArray: [Bool] = [false, true, true, false, false]

    override func viewDidLoad() {
        super.viewDidLoad()

        loadUI()
        loadLayout()
    }

    fileprivate func tableviewSetting() {

        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.estimatedRowHeight = 70
        self.tableView.rowHeight = UITableView.automaticDimension
        self.tableView.separatorStyle = .none
        self.tableView.backgroundColor = .clear
        self.tableView.register(TestTableViewCell.self, forCellReuseIdentifier: "TestTableViewCell")
    }

    fileprivate func loadUI() {

        self.tableviewSetting()

        self.view.addSubview(tableView)
    }

    fileprivate func loadLayout() {
        tableView.snp.makeConstraints { (make) in
            make.top.left.right.bottom.equalToSuperview()
        }
    }

    @objc func expandBtnPressed(sender: UIButton) {

        guard sender.tag == 0 else { return }

        let indexPath = IndexPath(row: sender.tag, section: 0)

        UIView.performWithoutAnimation {
            tableView.beginUpdates()
            self.isExpand = !isExpand
            tableView.reloadRows(at: [indexPath], with: .none)
            tableView.endUpdates()
        }
    }

}

extension ViewController: UITableViewDelegate, UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return self.titleArray.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        if indexPath.row == 0 {

            let cell1 = tableView.dequeueReusableCell(withIdentifier: "TestTableViewCell", for: indexPath) as! TestTableViewCell
            cell1.titleLabel.text    = self.titleArray[indexPath.row]
            cell1.subtitleLabel.text = self.detailArray[indexPath.row]

            let bool = cell1.subtitleLabel.isTruncated()

            print("bool : \(bool)") // why this return true.

            return cell1
        }

    }

}

extension UILabel {

    func countLabelLines() -> Int {
        self.layoutIfNeeded()
        let myText = self.text! as NSString
        let attributes = [NSAttributedString.Key.font : self.font!]

        let labelSize = myText.boundingRect(with: CGSize(width: self.bounds.width, height: CGFloat.greatestFiniteMagnitude), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attributes, context: nil)
        return Int(ceil(CGFloat(labelSize.height) / self.font.lineHeight))
    }

    func isTruncated() -> Bool {

        if (self.countLabelLines() > self.numberOfLines) {
            print("lines         : \(self.countLabelLines())") // print : 2
            print("numberOfLines : \(self.numberOfLines)") // print : 1
            return true
        }
        return false
    }

}

TestTableViewCell.swift
import UIKit

class TestTableViewCell: UITableViewCell {

    let titleLabel: UILabel = { () -> UILabel in
        let ui = UILabel()
        ui.font = UIFont.systemFont(ofSize: 16)
        ui.sizeToFit()
        ui.translatesAutoresizingMaskIntoConstraints = false
        return ui
    }()

    let subtitleLabel: UILabel = { () -> UILabel in
        let ui = UILabel()
        ui.font = UIFont.systemFont(ofSize: 16)
        ui.numberOfLines = 1
        ui.adjustsFontSizeToFitWidth = false
        ui.lineBreakMode = .byTruncatingTail
        ui.translatesAutoresizingMaskIntoConstraints = false
        return ui
    }()

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        self.selectionStyle = .none

        loadUI()
        loadLayout()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func loadUI() {

        addSubview(titleLabel)
        addSubview(subtitleLabel)
    }

    func loadLayout() {

        titleLabel.snp.makeConstraints { (make) in
            make.top.equalTo(defaultfifteenPt)
            make.left.equalTo(defaultfifteenPt)
            make.width.equalTo(defaultNinetyTwoPt)
        }

        subtitleLabel.snp.makeConstraints { (make) in
            make.top.equalTo(titleLabel.snp.top)
            make.left.equalTo(titleLabel.snp.right)
            make.bottom.equalTo(-defaultfifteenPt)
            make.right.equalTo(-defaultfifteenPt)
        }

    }

}

A: Hope this help you :
func isTruncated(label: UILabel, containerFrame: CGSize) -> Bool {
    let text = label.text ?? ""
    let estimatedSize = NSString(string: text).boundingRect(with: .init(width: 100000, height: containerFrame.height), options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font : label.font!], context: nil)
    return estimatedSize.width > containerFrame.width
}

Example:
let sampleLabel1 = UILabel()
sampleLabel1.text = "short text"
isTruncated(label: sampleLabel1, containerFrame: .init(width: 300, height: 15)) // return false

let sampleLabel2 = UILabel()
sampleLabel2.text = "short text fasjfojfosadjaof jasodfi jasodaj
foiasdjfo isadjfoi jasdofj asdojf osiadjfo s"
isTruncated(label: sampleLabel2, containerFrame: .init(width: 300, height: 15)) // return true


text:
Q: problems using react hooks im programming a bootcamp on MERN, i have a problem with the react hooks, the problem say 'React Hook "useEffect" is called in function "signup" that is neither a React function component nor a custom React Hook function.' But i used correctly the react hook library, this is my code
import axios from "axios"
import {useEffect} from 'react'
export default function signup(){

        useEffect(() =>{
          axios.get('http://localhost:27017/bootcamp/pruebas')
          .then(response => console.log(response))
          .catch(error => console.log(error));
        }, []);
  return(
    <>

Create a new account

        <form className="mt-8 space-y-6" action="#" method="POST">
          <input type="hidden" name="remember" defaultValue="true" />

                Email address

              <input
                id="email-address"
                name="email"
                type="email"
                autoComplete="email"
                required
                className="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-t-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm"
                placeholder="Email address"
              />

                Password

              <input
                id="password"
                name="password"
                type="password"
                autoComplete="current-password"
                required
                className="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-b-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm"
                placeholder="Password"
              />

            <button
              type="submit"
              className="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
            >

              Create!
            </button>

        </form>

  </>
)
}

on their code use a dependency with axios to create a CRUD and use a react hook library to use a method POST.

A: User defined components must be capitalized. Refer React documentation here.
So your component should look something like this.

import axios from "axios"
import {
  useEffect
} from 'react'
export default function SignUp() {

  useEffect(() => {
    axios.get('http://localhost:27017/bootcamp/pruebas')
      .then(response => console.log(response))
      .catch(error => console.log(error));
  }, []);
  return (
    <>JSX goes here</>
  )
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Qt Creator won't recognize any Qt version I've just installed Qt Creator from the Ubuntu Software Center.
When I try to open any project other than a Qt Quick project I get following error message:

No valid qt versions found.
  Please add a qt version in Tools/Options or via the maintenance tool of the SDK.

In Tools → Options → Qt4, qmake-qt4 was added to the list automatically.
This is what my Qt4 options menu looks like.

Here is the output of dpkg --get-selection | grep qt.
What am I missing to get Qt Creator to let me open Qt C++ projects?

A: The problem wasn't the missing Qt version but the missing tool chain.
In Tools → Options → Tool Chains add GCC and set your gcc path as the Compiler path.

A: I thought the qtCreator package would install g++, make, etc., but it doesn't.
Install build-essential to solve it :).

A: As to me, it looks perfectly fine. My Qt versions tab in options dialog looks identically.
The only thing that comes into my mind, is that Qt version is saved per-project, which means that you need to change Build Settings in Projects tab by explicitly selecting Default Qt Version.


text:
Q: Api telegram, отправка поста в канал php Отправляю через api почты в телеграм. Все работает. Единственное они (посты) все от имени бота в канале.
Как отправить пост в канал без автора? Или чтобы его не видел никто кроме администратора?
Еще, при отправке поста с ним идёт картинка, но телеграм показывает её в полный размер, разобрать что изображено не возможно, нужно создавать миниатюры перед отправкой? Или есть встроенный функционал телеграм для нормального отображения изображений?

A: Указывается в настройках канала его администратором - опция "Подписывать сообщения"


text:
Q: "Natural" undecidable problems not reducible to the halting problem There is a lot of known examples of undecidable problems, a large amount of them not directly related to turing machines or equivalent models of computations, for example here: https://en.m.wikipedia.org/wiki/List_of_undecidable_problems
It is also known that the structure of turing degrees is extremely complicated, and that there are undecidable problems not reducible to the halting problems, the most basic example being "Does a turing machine with an oracle for the halting problem halts?"
So my question is: Is there a example of a problem not related to abstract machines that is undecidable but not reducible to the halting problem? (That is, that has turing degree different from 0')

A: Aaronson's "Consistent Guessing" problem: Consider a total function $f : M \to \{0,1\}$, where:

*

*$M$ denotes the set of Turing machines which either accept or reject their inputs, or fail to terminate

*$f(m) = 1$ whenever $m$ terminates in an accepting state

*$f(m)=0$ whenever $m$ terminates in a rejecting state.

*The value of $f(m)$ when $m$ does not terminate is left unspecified. But the function must yield a value in $\{0,1\}$ regardless.
The problem is uncomputable.
The above problem is related to the problem LLPO in constructive logic: Decide for a computable real $x$ whether $x \leq 0$ or $x \geq 0$. The halting problem instead corresponds to the problem LPO in constructive logic: Decide for a computable real $x$ whether $x < 0$ or $x = 0$ or $x > 0$. LPO is stronger.

A: The problems reducible to the halting problem are exactly the problems of complexity $\Delta^0_2$ in the arithmetic hierarchy, and there are indeed many natural problems outside of this class. In this sense, you are asking for natural examples of decision problems of high arithmetic complexity.

*

*Arithmetic truth, to decide if a given arithmetic sentence $\sigma$ is true in the standard model $\langle\mathbb{N},+,\cdot,0,1,<\rangle$, is undecidable, but not reducible to the halting problem.

*$\Sigma^0_n$ truth, restricted to sentences of this complexity, for $n\geq 2$ is undecidable, but not reducible to the halting problem.

*Projective truth, to decide if a given sentence $\sigma$ is true in the real field $\langle\mathbb{R},+,\cdot,0,1,<,\mathbb{Z}\rangle$, with the integers as a unary predicate, is undecidable, but not reducible to the halting problem.

*Set-theoretic truth in various models, to decide if a given sentence is true in the structure of hereditarily countable sets $\langle H_{\omega_1},\in\rangle$ or in the least Zermelo universe $V_{\omega+\omega}$ or the least Zermelo-Grothendieck universe $\langle V_\kappa,\in\rangle$, if there is one, is undecidable, but not reducible to the halting problem.

*To decide if a given c.e. group presentation is trivial generally has complexity $\Pi^0_2$ (because one must say every generator is trivial), and this will be undecidable, but not reducible to the halting problem. (Note, for c.e. presentations with finitely many generators, this is reducible to the halting problem.)

*To decide if a given c.e. graph on the natural numbers is connected generally has complexity $\Pi^0_2$, making it undecidable and not reducible to the halting problem.

*To decide if a given computable function is total has complexity $\Pi^0_2$, since one must say every input has a halting computation, and this is complete for that level of complexity, making it undecidable, but not reducible to the halting problem.

*To decide if a given computable function is surjective has complexity complete $\Pi^0_2$, and so this is undecidable, but not reducible to the halting problem. (Meanwhile, to decide if it is injective is $\Pi^0_1$ and hence reducible to the halting problem.)
There are many more examples. See for example the hierarchy of degrees of irrationality. All the examples higher in the hierarchy amount to undecidable decision problems that are not reducible to the halting problem.
A dual to your question. There is a dual version of your question that is fascinating and the subject of a research program in computability theory. Namely, are there natural decision problems that are undecidable, but such that the halting problem does not reduce to them?
To be sure, the Friedberg-Muchnik solution of Post's problem shows that there are undecidable c.e. Turing degrees strictly below the halting problem, and so there are indeed undecidable decision problems strictly below the halting problem. But these problems are constructed especially for this purpose, and in this sense, are not seen as "naturally" arising. Furthermore, it is widely regarded as an open question whether there are natural decision problems in this class (one proposal: the set of differences of primes). Although I often find such uses of "natural" to be empty, in computability theory there is a research program to formulate substantive versions of the question, via Martin's conjecture and other approaches. See my further discussion of this in my paper, Linearity and illfoundedness in the hierarchy of large cardinal consistency strength, especially sections 9, 10, and 11, which focus on naturality and computability theory.

A: There have already been excellent answers, with the property that they (with the exception of (3) and (4) of the above answer) are reducible to an iteration of the Turing jump along a computable well-ordering. So let me add a couple that are not.
The set of computable linear orderings that have a dense subordering,i.e., embed a copy of the rational numbers $\mathbb Q$, and the set of computable linear orderings that are not well-ordered, i.e., have an infinite descending sequence, are known to be $\Sigma^1_1$ complete. Conversely, the set of computable well-orderings is $\Pi^1_1$ complete. Not only are these sets not reducible to the Halting problem, even iterating the Turing jump along a computable well-ordering won't let you compute them.


text:
Q: How to hide numbering when there's one item with ng-repeat I'm using AngularJS, HTML, and Bootstrap/CSS to make my web application. I am trying to make an ordered list using the
 tag with a
 tag. I want to hide the numbers if there's only one item in the list. Any suggestions on how to approach this?
A snipet of my code:

{{cog}}

A: Add a class with ngClass, for instance ol--no-number, when there is only one item in the list:
.ol--no-number {
    list-style-type: none;
}

{{cog}}

A: You could do a hack with CSS like this:
ol li:last-child {
    list-style:none;
}

ol li + li {
    list-style: inherit!important;
}

Fiddle


text:
Q: mod_ssl.so not loading I am trying to run Apache with SSL for my website. But when I start the Apache it throws the error saying:
httpd: Syntax error on line 127 of /usr/local/custom/apache/conf/httpd.conf:
  Cannot load modules/mod_ssl.so into server: /usr/local/custom/apache/modules/mod_ssl.so:
  undefined symbol: apr_global_mutex_lockfile

A: I also encountered the same issue.
The root cause of the issue is a version mismatch in the apr version
In order to fix it, download the following: apr-util-1.5.4.tar.gz and apr-1.5.1.tar.gz.
These can be downloaded at : https://apr.apache.org/download.cgi
Assuming that you have http src untarred in /src/httpd, you untar the apr-1.5.1 and apr-util in the opt/src/httpd/srclib
So the unzipped structure would be opt/src/httpd/srclib/apr and opt/src/httpd/srclib/apr-util
After this is done, you can run the configure with the following command
./configure --prefix=/opt/httpd-2.4.10 --with-included-apr

make

make install

This will install httpd in
/opt/httpd-2.4.10

You can check if the correct version of APR is referenced using the following command
/opt/httpd-2.4.10/bin/httpd -V

You should see output as below.
Server version: Apache/2.4.10 (Unix)
Server built:   Dec 16 2014 11:46:58
Server's Module Magic Number: 20120211:36
Server loaded:  APR 1.5.1, APR-UTIL 1.5.4
Compiled using: APR 1.5.1, APR-UTIL 1.5.4
Architecture:   64-bit
Server MPM:     worker
  threaded:     yes (fixed thread count)
    forked:     yes (variable process count)
Server compiled with....
 -D APR_HAS_SENDFILE
 -D APR_HAS_MMAP
 -D APR_HAVE_IPV6 (IPv4-mapped addresses enabled)
 -D APR_USE_SYSVSEM_SERIALIZE
 -D APR_USE_PTHREAD_SERIALIZE
 -D SINGLE_LISTEN_UNSERIALIZED_ACCEPT
 -D APR_HAS_OTHER_CHILD
 -D AP_HAVE_RELIABLE_PIPED_LOGS
 -D DYNAMIC_MODULE_LIMIT=256
 -D HTTPD_ROOT="/opt/httpd-2.4.10"
 -D SUEXEC_BIN="/opt/httpd-2.4.10/bin/suexec"
 -D DEFAULT_PIDLOG="logs/httpd.pid"
 -D DEFAULT_SCOREBOARD="logs/apache_runtime_status"
 -D DEFAULT_ERRORLOG="logs/error_log"
 -D AP_TYPES_CONFIG_FILE="conf/mime.types"
 -D SERVER_CONFIG_FILE="conf/httpd.conf"


text:
Q: How to use CSS with Windows 8 Webview Control? I have a question about window's 8 apps Webview Control , is there anyway to use css to manage the look of the webview , i'm using it here to view a returned contents of a feeded html data but as you can see it's striped from all the CSS , so is there anyway that I can manage the CSS for the Webview ?
UPATED : This is the code
void ItemListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

            //  this code to populate the web view
            //  with the content of the selected blog post.
            // I'm passing the selected item from the previous items' page
            // and then pouplate the web view with the selected item Contents of the feed

            if (this.UsingLogicalPageNavigation()) this.InvalidateVisualState();

            Selector list = sender as Selector;
            FeedItem selectedItem = list.SelectedItem as FeedItem;
            if (selectedItem != null)
            {
                this.contentView.NavigateToString(selectedItem.Contents);
            }
            else
            {
                this.contentView.NavigateToString("");
            }

        }

A: If you navigate with NavigateToString() - you can put your css inside of the html string that you navigate to. Otherwise - it should just work and we would need more details for what you are actually doing.


text:
Q: Should I use a layout manager even if it seems unnecessary? I have a JPanel, on it are added an image and label, in that order.
It is very unlikely that more will be added to the panel.
The default formatting looks fine when it's displayed, in spite of me not using a Layout Manager.
Is it best practice to have them laid out by a LM anyway to be safe for future development, or is it not worth the extra dev time making it look essentially the same?

A: If you create a JPanel using the default constructor the panel will use a FlowLayout.  If you're happy with the results of using this layout manager then by all means don't change anything.
If however you wish to explicitly not use a layout manager you need to set the layout to null; e.g.
JPanel pnl = new JPanel();
pnl.setLayout(null);

This isn't recommended as the results are then highly dependent on the particular Look & Feel used.  More information here.

A: You're already using a layout manager. A JPanel has a FlowLayout manager by default


text:
Q: can't upload jpg files to private server on ububtu - error Image Paperclip::Errors::NotIdentifiedByImageMagickError I'm taking Mattan Griffel's Ruby on Rails course on OneMonth.com where we create a Pinterest clone. I'm at a part where I set up ImageMagick on my computer, after that I set up paperclip version 4.2.
Then I edited the "new.html.erb" file so that I can upload images.
I'm getting an odd error, I can upload GIF files just fine but when I try to upload a JPEG I get this weird message on the page.

2 errors prohibited this pin from being saved:
Image Paperclip::Errors::NotIdentifiedByImageMagickError
Image Paperclip::Errors::NotIdentifiedByImageMagickError

It doesn't go into an error page, all it does is just display this message on the upload page which allows me to try with another image.
In the file app/models/pin.rb the code looks like this:
class Pin < ActiveRecord::Base
    belongs_to :user

    has_attached_file :image, :styles => { :medium => "300x300>", :thumb => "100x100>" }
    validates_attachment :image, content_type: { content_type: ["image/jpg", "image/jpeg", "image/png", "image/gif"] }
end

I think the file should have some impact on this although it doesn't, removing the JPG and JPEG in the file doesn't have any impact. It doesn't even make the site prevent me from uploading GIFs if I remove them from the code.
I have an Ubuntu 14.04 LTS system. Ruby 2.2.2, Rails 4-ish. A lot of others who asked a similar question about this error had either a mac or a windows PC and each of them got a very different answer since they each tried to do something different.
What do I do?

A: Turns out that this is a problem with the version of imagemagick that I have in my computer. Maybe it isn't compatible with my version of linux ubuntu.
The problem doesn't exist in the Heroku server when I uploaded it. It isn't that big a deal since it's only a local problem.


text:
Q: Using NOT IN for multiple columns in Clickhouse I have a table which will have data following way
id, email, filename
1, abc,  file1
2, abc,  file1
1, abc,  file2
1, abc,  file3

I need unique users filename wise.
I need a query in a way that data containing in a file should not contain in other files.
Ex:
file1 has two different ids in that case it will have 2 unique users.
file2 data is same a file1 data so the unique users count should be 0
file3 has a different email so it should have 1 unique user
A file should have atleast id or email different from other files to calculate it as a unique user


text:
Q: Gnerate pdf from html using phonegap and IOS plugin Here is the link to generate pdf in ios but I want to make a plugin with same code for phonegap so that I can use it for my app which is build with html, css and js.
Someone please advise, how can I call the same function with js to generate pdf on background.
How to Convert UIView to PDF within iOS?


text: Q: Example of Activate() function in Visual Studio VB Ribbon Designer I have researched to death and am really stuck. I am using Visual Studio 2017 to develop an excel ribbon. How do I get it to refer to the active sheet? I do see the Activate() function but no examples of how it is used and I have tried a few things now. I just need an example and I can be on my way.


text:
Q: How can I program a StreamReader in my app android? I am to develop an Android application that receives a message from server but I can connect to server but can't receive a message because when I clicked on Button connect blocks. I think it's because of the cycle but do not know how to resolve this situation in another way and would appreciate your help.
In short I want to know if there's another way to detect when I receive a message and presents it.
Update: I found the solution like this:
String IP;

String comando;

PrintWriter msgout;

BufferedReader msgin;

Socket socket;

    private ConnectedThread mConnectedThread;

public void connect(){ //Function to Button connect

    IP = edit.getText().toString();

    try {

     InetAddress serverAddr = InetAddress.getByName(IP); //TCPServer.SERVERIP

     Socket socket = new Socket(serverAddr, 4444); //Porta 4444 serverAddr
     PrintWriter out = new PrintWriter( new BufferedWriter( new  OutputStreamWriter(socket.getOutputStream())),true);
     msgout = out;

     BufferedReader in = new BufferedReader(new  InputStreamReader(socket.getInputStream()));
     msgin = in;

 zav.text1.setText("Connectado.");

  //Wait to mensages
  mConnectedThread = new ConnectedThread();
  mConnectedThread.start();

     } catch (Exception e) {
         text1.setText("Erro! Não conectado." + e);
    }
}

public void send(String message){

     try {

         msg.println(message);

     } catch(Exception e) {
         text1.setText("Erro! Comando não enviado." + e);
 }
}

private class ConnectedThread extends Thread {

    public void run(){

     while(true){

         //Read
     try {

                String str = msgin.readLine();
                 text1.setText(str);

              } catch(Exception e) {

                  text1.setText("Error" + e);

              }
         }
   }
}

A: Have you tried Push Notification? Here is a good place to start http://tokudu.com/2010/how-to-implement-push-notifications-for-android/


text:
Q: Django Rest Framework: How serialize list of list? How to serialize list of list of Floats using Django Rest serializers?
My data is (repr of my list of object):
[{
    'id': '413',
    'data': [
        [None, 32.33125, None, None],
        [None, 37.96, 48.70112359550562, 66.118],
        [None, None, 58.06576923076923, 77.31023809523809],
        [None, None, None, 110.0075],
        [None, None, None, 139.89]
    ]
}, {
    'id': '406',
    'data': [
        [None, 35.33125, None, None],
        [None, 37.96, 43.123, 66.118],
        [None, None, 58.12, 72,123],
        [None, None, None, 119.000234],
        [None, None, None, 139.89]
    ]
}]

For users trying to propose different approach, I need to explain that I need serializer class because I want to use generics.ListAPIView and I need to setup serializer_class property.

A: You must create Field class that will work with Null values:
class FixedFloatField(serializers.FloatField):
    def to_internal_value(self, data):
        if data is None:
            return data
        return super().to_internal_value(data)

    def to_representation(self, value):
        if value is None:
            return value
        return super().to_representation(value)

(because standard one throws TypeError: float() argument must be a string or a number, not 'NoneType')
Now use this Serializer (the trick is to use ListField):
class SearchResultSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    data = serializers.ListField(
        child=serializers.ListField(
            child=FixedFloatField(
                allow_null=True,
                required=False,
                default=None
            )
        )
    )

A: You can use the biult-in json module.
data = [{
    'id': '413',
    'data': [
        [None, 32.33125, None, None],
        [None, 37.96, 48.70112359550562, 66.118],
        [None, None, 58.06576923076923, 77.31023809523809],
        [None, None, None, 110.0075],
        [None, None, None, 139.89]
    ]
}, {
    'id': '406',
    'data': [
        [None, 35.33125, None, None],
        [None, 37.96, 43.123, 66.118],
        [None, None, 58.12, 72,123],
        [None, None, None, 119.000234],
        [None, None, None, 139.89]
    ]
}]

import json
json_data = json.dumps(data)

You can mix this with a DRF view:
from rest_framework.response import Response
...
json_data = json.dumps(data)
return Response(json_data)

EDIT
To use ListAPIView
assuming your data are coming from a model named Mymodel
# Serializer
from rest_framework import serializers

class MymodelSerializer(serializers.ModelSerializer):

    class Meta:
        model = Mymodel

# View
from rest_framework import generics

class MymodelList(generics.ListAPIView):

    queryset = Mymodel.objects.filter(whatever=whatever)

    def list(self, request):
        # Note the use of `get_queryset()` instead of `self.queryset`
        queryset = self.get_queryset()
        serializer = UserSerializer(queryset, many=True)
        return Response(serializer.data)

Taken from DRF docs


text:
Q: Bayesian Inference and Disease Testing I've been working my way through an introduction to Bayesian Inference in a Statistical Physics textbook (Tobochnik and Gould, 2010 - available online, excellent book). I've run across a problem that I can't quite wrap my head around, though I believed I understood Bayesian Inference up to that point (just before this was an amazing explanation of the Monty Hall problem using Bayes' Theorem).

What is happening here? I thought the chance of the test being right was 98%? Why would Bayes Theorem tell us that the chance of you actually having the disease given the positive result is less than 1 percent? What does that mean we're saying when we say that the test is 98% accurate? Does it have something to do with the fact that the disease is so rare?

A: You've got it. When the disease is very rare, the probability of a false positive becomes relatively high. One way to see how this might be is to draw a diagram of the four possibilities:

The red and purple areas represent incorrect test results while the blue and purple areas represent people who have the disease. As the blue-purple region gets thinner, i.e., the disease gets rarer, the red area of false positives gets bigger relative to it. If the disease is very rare, it can be much bigger.
This is why, for very rare diseases, testing the general population for the disease can be counterproductive.


text:
Q: Easy Auto Complete, referencing deeply nested values I'm working with a neat auto-complete program called "Easy Auto Complete".
The program works great, however I'm stumped on how to reference deeply nested node sets. The javascript running the show uses an attribute labelled "listlocation" that pulls values nested beyond the root of the JSON feed.
However, when attempting to pull data (ID for example) from the "player" data set, I have no success (developer tools tell me I'm not receiving data). I've tried "player", "playerstatsentry.player", "cumulativeplayerstats.playerstatsentry" and other variations of.
When I use a JSON feed where values reside on the root or ONE level up (as per the documentation), the feature works great.
What is the best way to reference the player array to pull the ID value?
JSON
{
"cumulativeplayerstats": {
    "lastUpdatedOn": "2018-02-13 1:59:59 PM",
    "playerstatsentry":
        [
            { "player": { "ID": "5107" } }
            ....

JAVASCRIPT
var options = {
    url: "assets/data.json",
    listLocation: "cumulativeplayerstats.playerstatsentry.player",
    getValue: "LastName"
    list: {
        match: {
            enabled: true
        }
    }
};
$("#provider-json").easyAutocomplete(options);

A: The plugin expects a collection of objects and a property name which will be used as a autocomplete help. You need to restructure the data.json file logically:
Case 1: When JSON structure is as
{
   "cumulativeplayerstats": {
      "lastUpdatedOn": "2018-02-13 1:59:59 PM",
      "playerstatsentry": [
         {
            "player": {
               "ID": "5106"
            },
            "LastName": "Test 1"
         },
         {
            "player": {
               "ID": "5107"
            },
            "LastName": "Test 2"
         },
         {
            "player": {
               "ID": "5108"
            },
            "LastName": "Test 3"
         }
      ]
   }
}

Than use autocomplete configuration as:
<input id="provider-json" />
<script>
var options = {
    url: "assets/data.json",
    listLocation: function(data) {
        return data.cumulativeplayerstats.playerstatsentry;
    },
    getValue: "LastName",
    list: {
        match: {
            enabled: true
        }
    }
};
$("#provider-json").easyAutocomplete(options);

Case 2: Because getValue property also supports function in this plugin. If the JSON structure is as:
{
   "cumulativeplayerstats": {
      "lastUpdatedOn": "2018-02-13 1:59:59 PM",
      "playerstatsentry": [
         {
            "player": {
               "ID": "5106",
               "LastName": "Test 1"
            }
         },
         {
            "player": {
               "ID": "5107",
               "LastName": "Test 2"
            }
         },
         {
            "player": {
               "ID": "5108",
               "LastName": "Test 3"
            }
         }
      ]
   }
}

use the autocomplete code as:
var options = {
    url: "assets/data.json",
    listLocation: function(data) {
        return data.cumulativeplayerstats.playerstatsentry;
    },
    getValue: function(item) {
        return item.player.LastName;
    },
    list: {
        match: {
            enabled: true
        }
    }
};
$("#provider-json").easyAutocomplete(options);

Hope this helps!!


text:
Q: Constant errors with check constraint in MS Access using SQL I'm creating the table with this command:
CREATE TABLE Comp (
SerialNumber Number Primary Key Not Null,
Make Text(12) Not Null,
Model Text(24) Not Null,
ProcessorType Text(24) Null,
ProcessorSpeed Int Not Null,
MainMemory Text(15) Not Null,
DiskSize Text(15) Not Null
);

Which works I then try to add the constraint:
ALTER TABLE Comp
ADD CONSTRAINT CheckSpeed
CHECK (ProcessorSpeed > 0);

Which returns the error: "Syntax Error in CONSTRAINT Clause".
I've tried adding:
CHECK (ProcessorSpeed > 0)

To the table creation command but it returns the same error. Is there any way to solve this?

A: You need to run against a connection and Comp is a reserved word.
ss = "ALTER TABLE [Comp] ADD CONSTRAINT CheckSpeed CHECK (ProcessorSpeed > 0)"
CurrentProject.Connection.Execute ss

Info: Constraints
Reserved words in Jet/Access pre 2007 and ACE/Access 2007-


text:
Q: Redirect to another page using php and ajax I have two pages one for filling data and other one for initializing data I am sending the filled data via post method using ajax, I want to redirect the user from initializing page, i used simple header("Location: somelocation"); in the initialize page but it seems it does not work this way and it just sends the html value of the target page using ajax (I checked it with firebug),so what is the alternatives here ? should i use ajax it self for the redirection part?

A: You should return your location via json response, for example {"location": "somelocation"}, and then handle it in ajax success callback and go to page you need:

document.location.href = somelocation

A: You should use javascript for the redirection, not ajax.
When your ajax request has completed successfully you should then do a window.location = 'new/path/to/some/location';
Using the header("Location: ...") in your destination PHP script (the one that receives the data) will only return to you the html in the ajax response body, but not interpret it.


text:
Q: unable to find content_transformer in tm Is content_transformer function removed from tm package 0.6-2 ??
library(tm)
docs<-Corpus(DirSource("Dname"))
docs<-tm_map(docs,content_transformer(gsub), pattern="using",replacement="use")
Error: could not find function "content_transformer"

A: You may need to update the package. This GitHub repository shows that the function is exported and is also present in the code.
> library(tm)
Loading required package: NLP
> content_transformer
function (FUN)
function(x, ...) {
    content(x) <- FUN(content(x), ...)
    x
}
<environment: namespace:tm>

> sessionInfo()
R version 3.2.3 (2015-12-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)

locale:
[1] LC_COLLATE=Slovenian_Slovenia.1250  LC_CTYPE=Slovenian_Slovenia.1250    LC_MONETARY=Slovenian_Slovenia.1250
[4] LC_NUMERIC=C                        LC_TIME=Slovenian_Slovenia.1250

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] tm_0.6-2  NLP_0.1-9

loaded via a namespace (and not attached):
[1] rsconnect_0.4.1.4 parallel_3.2.3    tools_3.2.3       slam_0.1-35


text:
Q: Popup modal: To display Success message in popup model in magento 2 I have created form in popup modal and it works successfully. After submitted  a form it shows an alert. But I need success message instead of alert, in Popup itself after submitted a form. Please provide me a solution.
history.phtml

                                <a href="#" id="click" class="click-me" data-id="<?= $_order->getEntityId(); ?>" >Cancel

                                <form action="<?php echo $block->getBaseUrl() . 'oxsales/index/index'; ?> " method="post" id="form-validate" enctype="multipart/form-data" autocomplete="off" data-mage-init='{"validation":{}}' data-hasrequired="<?php /* @escapeNotVerified */ echo __('* Required Fields') ?>">

                                    Reason:<textarea id="reason" rows="4" cols="10" name="reason"></textarea>
                                </form>

A: Inside of your ajax request
success: function (data) {
  alert('success');
}, error: function (result) {
  alert("error");
}

Replace alert with your implementation.
If you are using jQuery then appropriate solution would be:
1 - Add html message block somewhere

;

2 - In success/error callback add message inside of element
$('[data-message]').text(YOUR_MESSAGE);


text:
Q: Get common records from list of list in linq I have a list contains another list where I supposed to get the common elements.
Class model:
PlanInfo has shiftName, ilist of Plan.
Plan has start time, end time
public class Plan
{
    public int Start { get; set; }
    public int End { get; set; }
}

public class PlanInfo
{
    public string  ShiftName { get; set; }

    public IList<Plan> lstPlan { get; set; }
}

iList of PlanInfo contains
["shift1", [1000,1200]],
["shift2",[1000,1100]],
["shift3",[1000,1200]]

Expected output in this should be empty since 1000,1200 doesn't exist in shift2
["shift1", [1000,1200]],
["shift2",[[1000,1200],[1000,1100]],
["shift3",[1000,1200]]

Should return [1000,1200] since it's common in all lists.
I tried using intersect, but here IList<PlanInfo is not fixed length. it could have more than one records.
Kindly suggest me which LINQ query serve the above result

A: Hmm, If I understand the requirements: Given a list of PlanInfo, find any Plans common to all PlanInfo...
var totalPlanInfos = planInfos.Count();
var commonPlans = planInfos
    .SelectMany(x => x.Plans
        .Select(p => new { x.ShiftName, Plan = p }))
    .GroupBy(x => x.Plan)
    .Where(x => x.Count() == totalPlanInfos)
    .Select(x => x.Key)
    .ToList();

This assumes that a Plan can only be counted once within a PlanInfo. (No duplicate plans) This also assumes that the plan info references for the same start/end times are pointing to the same object instance. If not, then you cannot group on the Plan, you will need a unique key (Like a plan ID) to group on. If these are EF entities pulled from a DbContext then they will be the same reference.
First get the total # of plan infos. In your example this would return 3.
Next, for all plan infos, use SelectMany to fetch the Plans, but compose that down into the PlanInfo.ShiftName + the Plan. This flattens your one to many. Next group by the Plan so that we can count the # of PlanInfos that each Plan appears in. Any/all counts that match the total number of PlanInfos means a Plan that appears in all PlanInfos, Select the Key to get that grouped Plan(s) and that should have it.
Edit: adding an example...
    [Test]
    public void TestPlanCheck()
    {
        var plan1 = new Plan { Start = 1, End = 2 };
        var plan2 = new Plan { Start = 2, End = 3 };
        var plan3 = new Plan { Start = 3, End = 4 };

        var planInfos = new List<PlanInfo>
        {
             new PlanInfo{ Name = "Test1", Plans = new []{ plan1, plan2}.ToList() },
             new PlanInfo{Name = "Test2", Plans = new []{plan2, plan3}.ToList()},
             new PlanInfo{Name = "Test3", Plans = new []{ plan3, plan2}.ToList() }
        };

        var totalPlanInfos = planInfos.Count();
        var commonPlans = planInfos
            .SelectMany(x => x.Plans
                .Select(p => new { x.Name, Plan = p }))
            .GroupBy(x => x.Plan)
            .Where(x => x.Count() == totalPlanInfos)
            .Select(x => x.Key)
            .ToList();

    }

    private class Plan
    {
        public int Start { get; set; }
        public int End { get; set; }
    }

    private class PlanInfo
    {
        public string Name { get; set; }
        public List<Plan> Plans { get; set; }
    }

That was the test I had run using these stub classes. In this case the test will return back 1 match, for the Plan 2 value.
To outline the issue with ensuring plan references for the same start/end times match: If the setup looked like this:
    [Test]
    public void TestPlanCheck()
    {
        var plan1 = new Plan { Start = 1, End = 2 };
        var plan2A = new Plan { Start = 2, End = 3 };
        var plan2B = new Plan { Start = 2, End = 3 };
        var plan3 = new Plan { Start = 3, End = 4 };

        var planInfos = new List<PlanInfo>
        {
             new PlanInfo{ Name = "Test1", Plans = new []{ plan1, plan2A}.ToList() },
             new PlanInfo{Name = "Test2", Plans = new []{plan2B, plan3}.ToList()},
             new PlanInfo{Name = "Test3", Plans = new []{ plan3, plan2B}.ToList() }
        };

        var totalPlanInfos = planInfos.Count();
        var commonPlans = planInfos
            .SelectMany(x => x.Plans
                .Select(p => new { x.Name, Plan = p }))
            .GroupBy(x => x.Plan)
            .Where(x => x.Count() == totalPlanInfos)
            .Select(x => x.Key)
            .ToList();
    }

In this case even though plan 2A and 2B have the same start/end time, the group by would not group them together because they represent 2 references to 2 objects.  This though would be fine:
        var plan2A = new Plan { Start = 2, End = 3 };
        var plan2B = plan2A;

Both point to the same reference. If you do have different references for the same plan ranges, you would need a planID then group on a PlanId. Ideally though I would check why the references don't match because they should to avoid potential errors based on assumptions of equality.

A: One can use Aggregate with Intersect on PlanInfo.Plans like:
var plansCommon = planInfoList.Select(p => p.Plans)
                              .Aggregate<IEnumerable<Plan>>((p1, p2) =>
                                                 p1.Intersect(p2, new PlanComparer()))
                               .ToList();

// Implement IEqualityComparer
class PlanComparer : IEqualityComparer<Plan>
{
    public bool Equals(Plan x, Plan y)
    {
        if (x.Start == y.Start &&
                        x.End == y.End)
            return true;

        return false;
    }

    public int GetHashCode(Plan obj)
    {
        return obj.Start.GetHashCode() ^ obj.End.GetHashCode();
    }
}

The Intersect will recursively apply on Plans list of each PlanInfo to provide list of Plan common across all.


text:
Q: How to print the route of a packet in hwmp ns3 I would like to know how can i print the route of a packet in a mesh topology that implements hwmp. I don't mean the entire routing table but the intermediate nodes that a packet has traverse in order to reach the destination.
Thanks in advance,
Mary

A: You can do something like this :
YansWifiPhyHelper wifiPhy =  YansWifiPhyHelper::Default ();
....
....
....
....
AsciiTraceHelper ascii;
wifiPhy.EnableAsciiAll (ascii.CreateFileStream ("wifi-simple-adhoc-grid.tr"));

This will create a trace file named wifi-simple-adhoc-grid.tr, which you can analyse to determine the route of each packet. See example in examples/wireless/wifi-simple-adhoc-grid.cc

A: I am not sure where, but you must be able to track packets through log files!
In the other hand, if you are interested by the number of hops, you can fetch that from FlowMonitor (timeForwarded metric).

How?
  AvrgHopCount= 1 + (flowmon.timesForwarded/flowmon.rxPackets)

A: You can print routing table using :
Ipv4GlobalRoutingHelper globalRouting;
Ptr<OutputStreamWrapper> routingStream = Create<OutputStreamWrapper> ("result/leapstar2.routes", std::ios::out);
globalRouting.PrintRoutingTableAllAt (Seconds(0.1), routingStream );


text:
Q: In WinRT assembly.GetManifestResourceNames() gives no ResourceNames I am using to get the assembly for following
Assembly assembly = Application.Current.GetType().GetTypeInfo().Assembly;
and i get the ResourceNames form that assembly for using
var resources=assembly.GetManifestResourceNames()
but it gives no resource names in assembly.
Please help me how to achieve it?

A: In VB.NET, I do that:
Public Function LoadResourceStr(sResID As String) As String
    Dim ctx As Windows.ApplicationModel.Resources.Core.ResourceContext = New Windows.ApplicationModel.Resources.Core.ResourceContext()
    ctx.Languages = {Globalization.CultureInfo.CurrentUICulture.Name}
    Dim rmap As Windows.ApplicationModel.Resources.Core.ResourceMap = Windows.ApplicationModel.Resources.Core.ResourceManager.Current.MainResourceMap.GetSubtree("Resources")
    Return rmap.GetValue(sResID, ctx).ValueAsString
End Function

The MainResourceMap is a collection of all resources of application. Important: the files into directories of app (embedded compiled) need is configured to "Content", not "embedded resource". In this case, you can change string ID from "Resources" to "Files".
The sample above show the resource strings into xml files, to translate your app.


text:
Q: Representation theory. Please help by finding the error leading to absurd conclusion Claim: all irreducible representations of a given group, $G$, are pairwise isomorphic.
Proof: Let $[r(g), V]$ and and $[p(g), W]$ be irreducible representations of group $G$. Select a fixed vector $v_0$ in $V$, which is NOT an eigenvalue of $r(g)$ for any $g$, except $**1**$. Define the transformation $T$, that maps vector $r(g)v_0$ (in $V$) to vector $p(g)w_0$ in $W$. Extend this mapping to include any $g$ in $G$.
The map $T$ intertwines the two representations.  Consider any group element $h$
$T r(h)r(g)v_0 = T r(hg)v_0 = p(hg)v_0 = p(h)p(g)v_0 = p(h) T r(g)v_0$
Because the representations are irreducible, the map is defined for all of $V$ (i.e. $r(g)v_0$ includes all of $V$, for different $g$ in $G$), and is surjective onto all of $W$. By Schur's lemma, a surjective map between irreducible representations must be an isomorphism.

A: The best thing to do when confronted with something that seems absurd is to look at an example and see what happens.
Consider $G=S_3$, consider $V$ = sign representation, and $W$ the trivial representation (so they are both one-dimensional and irreducible).
You can immediately see that your first requirement fails here: any vector is an eigenvector for $r(g)$ (which is either the identity or multiplication by $-1$), so you cannot select your $v$ (this means that you'd have to take out the "all irreducible representations" above, maybe you meant "all irreducible representation of dimension more than one"?).
Moreover, I assume that you meant "is not an eigenvector for any $g \neq 1$", since any nonzero vector is an eigenvector for the identity matrix $r(1)$.
Now consider $G=S_4$. Pick $V$ as the degree two irreducible representation, the one in which the normal $V_4$ acts trivially, and the quotient (isomorphic to $S_3$) acts as the unique $2$-dimensional irreducible representation of $S_3$. Here we have a kernel! So there are other elements that act as the identity, therefore, again, there is no such $v_0$.
We could now go search for "all irreducible faithful representations of dimension more than one"... and we would get a problem when we notice that $T$ cannot be extended to all $g \in G$. (what is $w_0$, by the way? Same as $v_0$ but for $W$?) but before elaborating on that, are you sure this is what you wanted?


text:
Q: How can I prevent Bash expansion from passing files starting with "-" as argument? I'm trying to recursively search a string with grep but I get this:
$ grep -r "stuff" *
grep: unrecognized option '---corporate-discount.csv'
Usage: grep [OPTION]... PATTERN [FILE]...
Try 'grep --help' for more information.

How can I prevent Bash from passing files starting with - as argument?

A: To prevent Bash expansion from passing files starting with "-" you can use:
echo [!-]*

Which works portably in most shells, or, specific to ksh, bash, zsh:
echo !(-*)

For example: in a directory with this files
$ echo *
a b c ---corporate-discount.csv d -e --option.txt

Will list only (provided extglob is active):
$ shopt -s extglob
$ echo !(-*)
a b c d

$ echo [!-]*
a b c d

But if what you want is to process all files while telling grep to avoid interpreting files stated with a - as options, then just add a ./:
grep -r "stuff" ./*

Or, if there is guarantee that no file called exactly - exists in the files listed (grep will interpret a lonely - as read from stdin), you can use:
grep -r -- "stuff" *

A: First, note that the interpretation of arguments starting with dashes is up to the program being started, grep or other. The shell has no direct way to control it.
Assuming you want to process such files (and not ignore them completely), grep, along with most programs, recognizes -- as indicating the end of options, so
grep -r -e "stuff" -- *

will do what you want. The -e is there in case stuff starts with a - as well.
Alternatively, you can also use:
grep -r -e "stuff"  ./*

That latter one would also avoid the problem if there was a file called - in the current directory. Even after the -- separator, grep interprets - as meaning stdin, while ./- is the file called - in the current directory.


text:
Q: Filtering Comment Reply Links (comment_reply_link_args) for "infinite replies" in nested comments UPDATE: I'm going to update this one up at the top, because the solution I've found was with a differing filter hook. I'm going to look again at reply_link-specific hooks now that I better understand how to use them, but the solution to the main problem turned out to be easy once I found the right one: 'thread_comments_depth_max', which sets the default highest maximum depth to be set in Admin/Settings/Discussion.
Rather than explain it in detail, I'll link you to my github on the freshly minted plug-in.
https://github.com/CKMacLeod/WordPress-Nested-Comments-Unbound
For now, the rest of this question  is overall obsolete, though kind of a record of alternative ways of achieving the same thing with greater difficulty and less general applicability.

Since 4.1, WordPress has made the filter "comment_reply_link_args" available, apparently (?) with the intention of letting us intercept and modify particular options normally set in the admin panel as they apply to comment reply links, while leaving everything else intact.
Though there are many aspects of the reply link that one might want to modify via alteration of the "args," the one that prompted this investigation on my part was max_depth, so I'll use it as my prime example.
When a nested comment thread reaches its maximum depth, the default functionality is for the comment reply link to disappear, but, on a comment thread with an active discussion at maximum_depth, continued conversation can be much easier to continue if the reply link continues to appear at the bottom of every comment - or alternatively, though a more complex implementation, at the bottom only of the thread - as if the comment thread at max-depth becomes a simple columnar/chronological thread.
The first alternative is easy to achieve via a hack of comments_template.php (linked below), deleting two lines:
if ( 0 == $args['depth'] || $args['max_depth'] <= $args['depth'] ) {
return;
}

However, since one of course does not want to hack WordPress core, the more common, preferred way to accomplish this end would be via theme or child-theme files and application of a callback comments function. Given how many different customized comment forms there are in different themes, this option might be preferable. However, if all you wanted to do was offer the "infinite replies" option for any theme or design using common WP functions, then the preferred method would be, if I am not mistaken, to filter the above $args where they hook up with comment reply link function(s).
In order to achieve the desired effect, or the simple version of it, a theme modification that works with an elaborate custom callback function is:
comment_reply_link( array_merge( $args,array(
'depth' => $depth,
'max_depth' => $args['max_depth'] + 1,
 ) ) );

I am copying everything except for the +1 modification as found to work applied to an actual theme's callback function. I am not completely sure about how all of the variables are declared, since, in my attempts to render the above as a filtering function used in a different theme, I continually ran into missing argument and argument not array errors.
Leaving off more complicated attempts to correct those errors, in a simple world the following would work:
function infinite_replies() {

$comment_reply_link_args = array(
   'max_depth' => $args['max_depth'] + 1
   );

   return $comment_reply_link_args;
}

add_filter('comment_reply_link_args','infinite_replies', $comment, $post);

It does succeed in obliterating the reply link altogether - but nothing more. But at least it doesn't produce error messages... so I guess that's something.
I hope that the solution to this problem will point to ways to achieve other, more complex, potentially theme-independent comment thread modifications.
For reference, the basic documentation on comment_reply_link_args is here - http://wpseek.com/hook/comment_reply_link_args/ - and points directly to the relevant portion of comment-template.php.

A: Here's my solution. It relies on removing the original comment link and recreating it by appending it to the comment itself: https://www.webhostinghero.com/adding-infinite-replies-in-wordpress/
The only caveat is to make sure that wp_list_comments has been called with the default style argument. If it's not, then that element needs to be changed as explained in my article. Most of the time, the comments will be denoted by "div-content" so it won't be a problem.

A: Thanks for raising this issue, it interests me as well. After searching everywhere for an acceptable solution, this is how I approach the problem on my site, at least for now:
comment_reply_link(array_merge( $args, array('depth' => $depth, 'max_depth' => '25' )))

If you change '25' to, say, '1000', this will give you pretty much 'infinite replies', or am I missing something?

A: See update and plug-in Git linked there. I'll link it again: The answer to the question is that comment_reply_link() may be the wrong hook. Full answer explained and implemented at https://github.com/CKMacLeod/WordPress-Nested-Comments-Unbound


text:
Q: Checkbox not showing in react import React from 'react'
import PropTypes from 'prop-types'
import axios from 'axios';
import Select from 'react-select';
import { Link } from "react-router-dom";
import moment from "moment";

class orders extends React.Component {
  state= {
    orders: [],
    checked: false
  }

  componentWillMount() {
    this.loadOrders();
  }

  loadOrders() {
    axios({
      method: 'get',
      url: `http://localhost:4200/api/orders/getallorders`
      }).then(res => {
        this.setState({orders: res.data.orders})

    }).catch(err => console.log(err))
  }

  handleCheck(e){
   this.setState({
    checked: e.target.checked
   })
   }

  render () {
    return (

Orders

            <input id ="checkbox_id" type="checkbox" checked={this.state.checked} onChange={this.handleCheck}/>

        {this.state.orders.map(order => {
            return (

{order._id}

{moment(order.date).format('MM/DD/YYYY')}

{order.shippingstatus}

                <Link to={{ pathname: '/admin/orders/vieworder', state: {order} }}> <button className={'btn'} style={{marginTop: '8px'}}>View Order</button> </Link>

            )
        })}

    )
  }
}

export default orders;

Hello everyone, I'm using react and I have a very strange problem, the checkbox is not showing at all in the browser, I searched online but didn't find any answers that could help, any idea why it's not showing and how to fix it?
I tried adding and removing "PreventDefaults" but no use.

A: So it turns out to be an error with https://materializecss.com I should have added <form action="#"> as in their docs https://materializecss.com/checkboxes.html


text:
Q: Failed to convert 'x$date' to class "Date" in R Okay so I have been trying to use this package from Facebook, but for some reason I keep seeing this error.
library(tidyquant)
library(quantmod)
library(prophet)
library(dplyr)

SPY <-tq_get(get = "stock.prices", "SPY", from = "2016-01-01")

df<-select(SPY,c(date,close))
df$date <- as.Date(as.character(df$date),format="%Y-%m-%d")
colnames(df)<-c("ds","y")
m<-prophet(df)
future<-make_future_dataframe(m,periods=52, freq = "d")
forecast <- predict(m,future)
plot(m,forecast)

When I run the plot function, I would see this error message:

Error in as.Date.default(x$date, format = "%d/%m/%Y") :  do not know how to convert 'x$date' to class "Date"

I tried using as.Date function, strptime function, and format function but it was in no use.
forecast$ds<-as.Date(paste(forecast$ds),"%Y-%m-%d")
forecast$ds<- format(forecast$ds, "%d/%m/%Y")
forecast$date<-forecast$ds
m$date<-forecast$ds

This didn't work
df$newdate<- strptime(as.character(df$ds),"%Y-%m-%d")
df$newdate<- format(df$newdate, "%d/%m/%Y")
df$newdate<-as.Date(df$newdate)
dp<-data.frame(df$newdate,y)

and this didn't work either. They were some answers provided by other similar postings but I do not really see what is causing the issue. Any help would be appreciated.

A: The error message is caused by some quirks of as.Date(). The workaround is to save the dataset as a CSV file using write.csv() and then read in again as a CSV using read.csv(). And then use as.Date(). This will eliminate the error message.
Another workaround is to use as.data.frame() first for your entire dataset before using as.Date().

A: library(lubridate)
df$date <- ymd(df$date) # ymd stands for year, month, date

or
library(anydate)
df$date <- anydate(df$date)

Plotting works afterwards for me.


text:
Q: Show that there are infinitely many solutions $x, y, z \in\mathbb N$ of the following equation $x^2 + y^3 = z^7.$ Show that there are infinitely many solutions $x, y, z \in\mathbb N$ of the following equation
$x^2 + y^{3} = z^7$.
I am thinking about using proof by infinite descent, but I am not too sure how to start or how to show there are infinitely many solutions in the natural numbers.

A: For any $k\in \mathbb N$:
$$
((k^2+1)^3\cdot k)^2 + ((k^2+1)^2)^3
= (k^2+1)^6\cdot k^2 + (k^2+1)^6
=(k^2+1)^7
$$
(found by looking for a solution in the form $x=kt^3, y=t^2$)

A: For every $a \in \mathbb{N}$,
$$(x,y,z)=(2213459a^{21}, 1414a^{14}, 65a^6)$$
is a solution.

A: You see that
$$ (2^3)^2+(2^2)^3=2\cdot 64 = 2^7$$
is a solution.
So, one idea would to think, whats about powers of $2$.
Then we have
$$(2^a)^2+(2^b)^2=(2^c)^7.$$
In the example we furthermore have $x^2=y^3$, so we can also try this, which leads to
$$2^{7c}=2^{2a+1}=2^{3b+1}.$$
This is equivalent to $7c=2a+1=3b+1$.
For $a=3d$ and $b=2d$ we get $7c=6d+1$. Hence, it suffices to show that there are infinite $c,d\in \mathbb{N}_0$ such that $7c-6d=1$. This is a typical linear Diophantine equation which can be solved by the usual procedure (or WolframAlpha) or you just see that $d=7n+1$ and $c=6n+1$ is a solution for all $n\in\mathbb{N}_0$.
Back substitution gives you that
$$(2^{3(7n+1)},2^{2(7n+1)},2^{6n+1})$$
is a solution for all $n\in\mathbb{N}_0$.

A: This is a generalization of the answer by Zermelo-Fraenkel. Start with any one specific solution; Z-F identifies $8^2+4^3=2^7$, but it is possible to start with any other specific solution.
For all $k\in \mathbb N$, $(8k^{21})^2+(4k^{14})^3=(2k^{6})^7$
More generally, if $x,y,z$ is a solution, then $(x\cdot k^{21})^2+(y\cdot k^{14})^3=(z\cdot k^{6})^7$
Thus, if there are any solutions (and there is at least one), there are infinity many solutions.


text:
Q: Create an array from images in a folder and present a given number of them at random (Objective-C) I am trying to display a predesignated number of .PNG images (e.g. 20) at random from a folder containing a much larger number of images (120).
Here is my code based on the several examples I could find; I am calling this method within viewDidLoad.
-(void)displayImagesInRandomOrder {

    // Obtain set number of attempts
    imageArrayLength = 20; // arbitrary choice in this example

    // Build array from all (120) .PNG images in folder
    NSArray *_imageArray = [[NSBundle mainBundle] pathsForResourcesOfType:@".png" inDirectory:@"(Folder directory)/."];

    // Create a random integer for each of the (120) images in the array
    int randomIndex = arc4random_uniform((uint32_t) _imageArray.count);

    // Select an image from the array using the random number
    UIImage *randomImage = [_imageArray objectAtIndex:randomIndex];

    // Add the UIImage to a UIImageView and display it on the screen
    UIImageView *tempImageView = [[UIImageView alloc] initWithImage:randomImage];

    // Set position of the image
    tempImageView.contentMode = UIViewContentModeScaleAspectFit;

}

All help/advice graciously received, since I have been staring at this for far too long. Many thanks in advance :)
EDIT ///
Here is the first of my revised methods to build an array of 20 images selected at random from the folder:
NSMutableArray *imageQueue;

- (void)buildArrayOfRandomImages {

    // Build array of pathnames to images in folder
    NSArray *pathArray = [[NSBundle bundleForClass:[self class]] pathsForResourcesOfType:@"png" inDirectory:@"(Folder directory)"];

    // Obtain preset number of attempts
    imageQueueLength = 20;

    // Create image queue (new array) of predetermined length

    // use a loop to add correct number of images to image queue
    for(int i = 1; i <= imageQueueLength; i++) {

        // Select an integer at random for each image in the array of pathnames
        int randomIndex = arc4random_uniform((uint32_t) [pathArray count]);

        // Add images to the image queue
        [imageQueue arrayByAddingObject:[UIImage imageWithContentsOfFile:[pathArray objectAtIndex:randomIndex]]];
    }
}

Here is the second method:
- (void)displayImageFromArray {

    // Add the UIImage to a UIImageView and display it on screen
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[imageQueue objectAtIndex:imageCount]];

    // Set screen position of image
    imageView.contentMode = UIViewContentModeScaleAspectFit;

    // increment count every time method is called
    imageCount++;
}

I felt confident that this would work, but the imageQueue array remains empty from the buildArrayOfRandomImages method.

A: Let's see if we can help you along:

-(void)displayImagesInRandomOrder {

   // Obtain set number of attempts
   imageArrayLength = 20; // arbitrary choice in this example

   // Build array from all (120) .PNG images in folder
  NSArray *_imageArray = [[NSBundle mainBundle] pathsForResourcesOfType:@".png" inDirectory:@"(Folder directory)/."];

This produces an array of paths (see the documentation). What is the value of this array when you run your code? Are any paths found?

   // Create a random integer for each of the (120) images in the array
   int randomIndex = arc4random_uniform((uint32_t) _imageArray.count);

   // Select an image from the array using the random number
   UIImage *randomImage = [_imageArray objectAtIndex:randomIndex];

You have an array of paths, indexing it won't produce a UIImage. Read Creating Image Objects in the UIImage documentation.

   // Add the UIImage to a UIImageView and display it on the screen
   UIImageView *tempImageView = [[UIImageView alloc] initWithImage:randomImage];

   // Set position of the image
   tempImageView.contentMode = UIViewContentModeScaleAspectFit;
}

There is no code here to select 20 elements. When you want to select N different cards at random from a deck of playing cards how do you do it? Now read the NSArray documentation... HTH

Addendum After Your Comment & Question Edit
You've made some good progress, but as you say it still doesn't work. Let's take a look at your new code:

Here is the first of my revised methods to build an array of 20 images selected at random from the folder:
NSMutableArray *imageQueue;

There are a couple of problems here, one design, one programming:

*

*Never use a global variable just to return a value from a method

*This declares a variable, imageQueue, which is capable of storing a reference to an NSMutableArray. All objects need to be created, you don't create an array here, and this variable will have the value nil – i.e. it references nothing.

Try a design along the lines of:
- (NSArray *) buildArrayOfRandomImagesWithLength:(NSUInteger)imageQueueLength
{
   // create a mutable array to hold the images
   NSMutableArray *imageQueue = [NSMutableArray arrayWithCapacity:imageQueueLength];

   // your code to fill the array
   ...

   // return the final array, by convention immutable (NSArray) so copy
   return [imageQueue copy];
}

Back to your code:

- (void)buildArrayOfRandomImages {

   // Build array of pathnames to images in folder
   NSArray *pathArray = [[NSBundle bundleForClass:[self class]] pathsForResourcesOfType:@"png" inDirectory:@"(Folder directory)"];

There is nothing wrong with this per se, but have you checked (using the debugger or logging statements) that pathArray contains any elements? While (Folder Directory) is a valid name for a folder did you actually call your folder this name?

   // Obtain preset number of attempts
   imageQueueLength = 20;

   // Create image queue (new array) of predetermined length

   // use a loop to add correct number of images to image queue
   for(int i = 1; i <= imageQueueLength; i++) {

       // Select an integer at random for each image in the array of pathnames
       int randomIndex = arc4random_uniform((uint32_t) [pathArray count]);

Again there is nothing wrong with this per se, it produces a random index for you. However it could produce the same index more than once, do you not want 20 different images?
My playing card analogy obviously was detailed enough: How do you typically select N random cards from a deck? You shuffle the deck and then deal the required N cards off the top. Take another look at NSArray...

       // Add images to the image queue
       [imageQueue arrayByAddingObject:[UIImage imageWithContentsOfFile:[pathArray objectAtIndex:randomIndex]]];
   }
}

This doesn't do what you expect. The method arrayByAddingObject: is from NSArray and it creates a new NSArray from an existing one and the new element, the method then returns this new array. This code ignores the return value, thus discarding the new array...
However you don't have an NSArray but an NSMutableArray, so you don't need to create a new array each time you need to add an object to your mutable array. Take a look at NSMutableArray again...

Here is the second method:
- (void)displayImageFromArray {

   // Add the UIImage to a UIImageView and display it on screen
   UIImageView *imageView = [[UIImageView alloc] initWithImage:[imageQueue objectAtIndex:imageCount]];

   // Set screen position of image
   imageView.contentMode = UIViewContentModeScaleAspectFit;

   // increment count every time method is called
   imageCount++;
}

First this method should have a declaration like:
- (void) displayImage:(NSUInteger)imageCount fromArray:(NSArray *)imageQueue

i.e. pass in the required data, don't use global variables. Or better yet just:
- (void) displayImage:(UIImage)theImage

as there is no need to pass the array & index and if defined this way the image doesn't need to come from an array at all.
However the above declarations are probably insufficient – your method as written won't display any images and the additional code to do that may require a further argument as well.
Why won't it display any images? An UIImageView will only display its image on screen if it is part of the current view hierarchy. Now that is another whole topic in itself, so unless you've omitted code for brevity you've some more reading to do.

Postscript
Don't try to extend this question further, that is not how SO works. If in researching and designing your new solution you hit an issue ask a new question on that new issue. You can include a reference to this question so people assisting you can trace back the history.

A: @CRD, as requested I didn't update the question any more, but wanted to show you my progress. Many thanks again for getting me this far!!
[As you sensibly suggested, I will limit this thread to the creation of the array of randomly selected images, since displaying them is quite a different issue.]
Solution 1 (seems to work but inelegant):
- (NSArray *) buildArrayOfRandomImagesWithLength:(NSUInteger)imageQueueLength {

    // Build array of pathnames to images in folder (nil directory was the only one that actually worked for me)
    NSArray *pathArray = [[NSBundle bundleForClass:[self class]] pathsForResourcesOfType:@"png" inDirectory:nil];

    // Create a mutable array to hold the images
    NSMutableArray *imageQueue = [NSMutableArray arrayWithCapacity:imageQueueLength];

    // Fill the imageQueue array using pathnames
    for(int i = 1; i <= imageQueueLength; i++) {
        // Select a random integer
        int randomIndex = arc4random_uniform((uint32_t) [pathArray count]);
        // Use the random integer to select a pathname and create an image object
        UIImage *image = [UIImage imageWithContentsOfFile:[pathArray objectAtIndex:randomIndex]];
        // Ensure all elements are unique
        if (![imageQueue containsObject:image]) {
           // Add image to the image queue
           [imageQueue addObject:image];
        } else {
           i--; // ensure the array is the correct length
        }
    }
    // Return the final array, by convention immutable (NSArray) so copy
    return [imageQueue copy];
}

Solution 2: (much more elegant but requires an import of the GameplayKit Framework, which also must be linked to the project - see https://stackoverflow.com/a/47404462/11137617)
- (NSArray *) buildArrayOfRandomImagesWithLength:(NSUInteger)imageQueueLength {
    // Build array of pathnames to images in folder
    NSArray *pathArray = [[NSBundle bundleForClass:[self class]] pathsForResourcesOfType:@"png" inDirectory:nil];

    //Create a shuffled copy of pathArray
    NSArray *shuffledPaths;
    shuffledPaths = [pathArray shuffledArray];

    // Create a mutable array to hold the images
    NSMutableArray *imageQueue = [NSMutableArray arrayWithCapacity:imageQueueLength];

    // Fill the image queue array using pathnames
    for(NSUInteger i = 1; i <= imageQueueLength; i++) {
    UIImage *image = [UIImage imageWithContentsOfFile:[shuffledPaths objectAtIndex:(i - 1)]];
        [imageQueue addObject:image];
    }
    // Return the final array, by convention immutable (NSArray) so copy
    return [imageQueue copy];
}

Solution 3: (avoids importing GameplayKit by using a separate array shuffling method, based largely on this: https://stackoverflow.com/a/56656/11137617, which itself is based on the Fisher–Yates shuffle that @CRD recommended)
- (NSArray *) buildArrayOfRandomImagesWithLength:(NSUInteger)imageQueueLength {
    // Build array of pathnames to images in folder
    NSString *directory = nil;
    NSArray *pathArray = [[NSBundle bundleForClass:[self class]] pathsForResourcesOfType:@"png" inDirectory:directory];

    //Create a shuffled copy of pathArray
    NSArray *shuffledPaths;
    shuffledPaths = [self shuffleArray:pathArray];

    // qCreate a mutable array to hold the images
    NSMutableArray *imageQueue = [NSMutableArray arrayWithCapacity:imageQueueLength];
    // Fill the image queue array using pathnames
    for(NSUInteger i = 1; i <= imageQueueLength; i++) {
        UIImage *image = [UIImage imageWithContentsOfFile:[shuffledPaths objectAtIndex:(i - 1)]];
        [imageQueue addObject:image];
    }
    // Return the final array, by convention immutable (NSArray) so copy
    return [imageQueue copy];
}

Array shuffling method:
- (NSArray *) shuffleArray:(NSArray*)array {
    NSMutableArray *shuffledArray = [NSMutableArray arrayWithArray:array];

    for (NSUInteger i = 0; i < [shuffledArray count] - 1; ++i) {
        NSInteger remainingCount = [shuffledArray count] - i;
        NSInteger exchangeIndex = i + arc4random_uniform((u_int32_t )remainingCount);
        [shuffledArray exchangeObjectAtIndex:i withObjectAtIndex:exchangeIndex];
    }
    return [shuffledArray copy];
}


text:
Q: how to ssh / su - by passing the password initially itself? Anyone knows how to ssh / su - by passing the password initially itself?
Like:
ssh username@hostname  -p [password]
pbrun su - unix_owner -p [password]

How can I achieve this?
It shouldn't popup for password or any RSA authentication like yes/no.

A: I think you will probably need a sudoers file to get stuff done in a su like manner without being prompted for a password.
I have never used ssh without a password prompt, but found this which suggests it can be done...

A: passing a password in clear text is not intended by ssh.
Try to learn about ssh key authentication (google would help), you won't need to type your password anymore.
ok, more detailed, try this:
on the remote machine
> mkdir -p ~/.ssh  #if neccessary
> touch ~/.ssh/authorized_keys2
> chmod go-rwx $HOME/.ssh/authorized_keys2

on your local machine:
> ssh-keygen # if neccessary
> cat ~/.ssh/id_rsa.pub | ssh root@remotehost "cat >> .ssh/authorized_keys2 && chmod 0600 ~/.ssh/authorized_keys2"

A: A better approach would be using ssh keys, like other answers recommend, but if you really need it, you can use expect for that.
Just create a expect.file like this one:
#!/usr/bin/env expect

set username youruser
set pass yourpassword
set host yourhost

spawn ssh ${username}@${host}

expect -re "password:"
send "${pass}\r"

expect -re "$"

interact

and execute it:
expect expect.file

A: Can't do it. You're invoking the passwd program on the remote machine. If it had a way to change a password without prompting for the old one, ANYONE could change your password if they got onto your console. You'd still need to pass the password in over the ssh link

A: As for SSH, you could use RSA keys, and those won't prompt you for passwords.
As for SU, it would have to be hardcoded or you would have to create your own application to serve as a wrapper of sorts.

A: I don't think you can pass in password directly to the ssh command (It will be stored in your history otherwise). Why don't you use keys to skip the authentication prompt.


text:
Q: How to map 3 or 4 FirebaseListObservable using common $key value? I have three node in Firebase database, I want to join there three different object in to single one firebaseListObservable and render into html using *ngFor list derivative, so I don't know it's possible or what is best way to join this nosql data using rxjs. I am new to reactive programming to haven't knowledge how to combine all object into one.
Database structure as like this:
live_markets : {
  id(45789) : {
   type : "NUF",
   openPrice : 465.45,
   closePrice : 789.89,
   ....
  },
  id(78982), id(57455)...
}

market_description : {
 id(45789): {
  name: "Abc Comapny",
  expire : "08/07/2017",
  symbol : "ABCS17AY",
  ...
 },
 id(78982), id(46447)...
}

users : {
   uid(Kd234w3423fd435): {
     profile : {...},
     watchList : {
      45789 : true,
      78982 : true,
      57455 : true,
   },
   uid ...
}

There are three FirebaseListObservable and i successfully  map two but can't all in to one.
import { Component, OnInit } from '@angular/core';
import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database';
import { Observable } from 'rxjs/Observable';

@Component({
  selector: 'app-market',
  templateUrl: './market.component.html',
  styleUrls: ['./market.component.scss']
})
export class MarketComponent implements OnInit {

  liveMarket: FirebaseObjectObservable<any>;
  //market_description: FirebaseListObservable<any>;

  constructor(private db: AngularFireDatabase) {

   const watchlist$: FirebaseObjectObservable<any> = db.object('users/Kd234w3423fd435/watchList');
   watchlist$.map((Keys) => {
     return  db.object('/market/' + `${Keys.$value}`);
   }).subscribe( (items) => {
      this.liveMarket = items;
   });

  }

  ngOnInit() {

  }

}

It works well, but how to join (map) market_description KEY  with this.liveMarket using user/uid/watchList KEYS, what is the proper method?


text:
Q: Django: Update Record before save Model:

class Tester:
    test = models.ForeignKey(Platform)
    count = models.Integer()
    status = models.CharField(max_length=1, default='A')

I need to change the status to 'D' every time I insert a new record for the same test.
I tried using Signals pre_save, but that function went into a loop. I would really appreciate any help.

A: Signal fucntion probably goes into an infinite loop because you save the same model's instances in that function, in turn each one triggering the signal function itself. With a little care you can prevent this from happenning:
from django.db.models.signals import pre_save

@receiver(pre_save, sender=Tester)
def tester_pre_save(sender, instance, **kwargs):
    if not instance.pk:
        # This means that a new record is being created. We need this check as you want to do the operation when a new entry is **inserted** into table
        Tester.objects.filter(test=instance.test).update(status='D')

or, with the post_save signal:
from django.db.models.signals import post_save

@receiver(post_save, sender=Tester)
def tester_post_save(sender, instance, created, **kwargs):
    if created:
        # This means that a new record has been created. We need this check as you want to do the operation when a new entry is **inserted** into table
        Tester.objects.filter(test=instance.test).update(status='D')

Important points here is. as we are using update method of a query set to update existing entries, those won't trigger signals, because they don't use the model's save method, so that signal method won't be triggered for other instances we update here. And even if it were to be triggered, as we are doing the update operation under a condition check (if a new instance is being created), signal methods for those other saves wouldn't do anything, hence they would not cause an infinite loop.

A: Override the save method of our Tester class:
def save(self, *args, **kwargs):
    if Tester.objects.filter(test=self.test).count()>0:
        self.status="D"
    else:
        self.status="A"
    super(Model, self).save(*args, **kwargs)

Put this into the class definition of Tester.


text:
Q: One server wrongly redirecting to another when using https I have a server with two websites. One of them has https and the other has not. My problem is that when I access the server that doesn't have https, It redirects to the server that has it.
I'm using Ubuntu 12.04.5 LTS and Apache 2.2
I tried finding every place I used rewrite and none of them helped me out.
Here is the config of the first website (that has https)
<VirtualHost *:80>
 ServerName www.first_site.com.br
 ServerAlias www.first_site.com.br
 ServerAdmin info@first_site.com.br
 DocumentRoot /var/www/first_site

 ErrorLog /var/log/apache2/first_site/error.log
 LogLevel warn
 CustomLog /var/log/apache2/first_site/access.log combined

</VirtualHost>

<IfModule mod_ssl.c>
<VirtualHost *:443>
 ServerName www.first_site.com.br
 ServerAlias www.first_site.com.br
 ServerAdmin info@first_site.com.br
 DocumentRoot /var/www/first_site

 ErrorLog /var/log/apache2/first_site/error.log
 LogLevel warn
 CustomLog /var/log/apache2/first_site/access.log combined

SSLEngine on
SSLCertificateFile /etc/apache2/wildSSL/STAR_first_site_com_br.crt
SSLCertificateKeyFile /etc/apache2/wildSSL/STAR_first_site_com_br.key
SSLCertificateChainFile /etc/apache2/wildSSL/STAR_first_site_com_br.ca-bundle
SSLProtocol All
</VirtualHost>

</IfModule>

This is the second site config
<VirtualHost *:80>
 ServerName www.second_site.com.br
 ServerAlias www.second_site.com.br
 ServerAdmin info@second_site.com.br
 DocumentRoot /var/www/second_site

 ErrorLog /var/log/apache2/exati/error.log
 LogLevel warn
 CustomLog /var/log/apache2/exati/access.log combined
</VirtualHost>

Also, always when I access the first website without https, it automatically redirects to the https version.

A: Add for the second site
<VirtualHost *:443>
      ServerName www.second_site.com.br
      ServerAlias www.second_site.com.br
      RewriteEngine on
      RewriteRule (.*) http://%{HTTP_HOST}/$1 [L,R=permanent]
</VirtualHost>

Source: http://forum.slicehost.com/index.php?p=/discussion/2731/mix-of-ssl-and-non-ssl-sites-on-apache-2-2/p1


text:
Q: Block a resource for only one user in laravel PHP AJAX and redirect the other to a readonly form I create an application with laravel 5.5. I use so PHP AJAX and MySQL.
I have a problem. An user connect with his account on the application and when he will click on an element (for example a contact card), I want to redirect this user on a form in readonly because another user is in current card. This another user see the form to edit the card.
In fact, I want to block a resource for only one user in edit. The other users will be in readonly (redirect to another route)
Is it possible to use a middleware? Use the cookies? Or launch an Ajax route when the user close his browser or tab page?
Help me....

A: Add new nullable field to the database on your resource to keep current user id that responsible for the edit. Then add a middlware which will check if this field is null then free to edit, if not be readonly.
for example you have a products table:
id  title    group_id editor_id

1   bicycle  1        5

2   car      3        null
Resource id 1 only be editable by user id 5.

Resource id 2 is editable any user who start editing.
and then after the user exit or any other behavior you like, try to make it null again to be editable by others.
middlware code:
// find the resource
$resource = Resource::find($request->resource_id);

// current user is last user. so no need to check.
if($resource->editor_id == auth()->user()->id) return $next($request);

// check if 10 minutes passed from last edit by another user.
if(Carbon::now()->diffInMinutes(Carbon::parse($resource->updated_at)) >= 10) {
    // replace current user id with last one.
    $resource->editor_id = auth()->user()->id;
    $resource->save();
} else {
    return response('You dont have permission to edit.');
}

A: I believe you should use both the approach;

*

*Handle it through Laravel Middleware on server side - You would need to create a middleware that should check on resource call. You would also need to maintain the update flag against resource for a particular session request so that it shouldn't be available to others.

*Client Side check on availability of the resource - Once a resource is dispatched by other user current user who is seeing the resource as Ready Only , can work on it with the latest data on the form.

Moreover, you can manage the queue of requests to handle such priority so that if multiple users are viewing the resource they should be able to get as per their precedence depending on the priority set bu you.


text:
Q: Locate roads that are close to steep slopes which risks landslides I've a query, I'm trying to locate all the roads which are basically at risk of erosion (landslide?) when it's raining heavily for a municipality.
What I have to work with is this:

*

*A shape layer containing lines for the roads (centerlines)

*Contourlines for the terrain

*Raster with elevation model

*ArcGIS Advanced Desktop with 3d and spatial analyst

My first thought was to create some lines perpendicular to the roadlines, in a range of for instance 20 meters, and there after count how many contourlines i cross. This is pretty lowtech, but so far it's the best I've come up with.
Does anybody have a smarter approach? Or perhaps tried doing something similar?


text:
Q: Mongo aggregation of ISODate into 45 minute chunks I have a series of documents that have an ISODate object. I'm trying to group those into 45 minute blocks. So minutes 0-45 would be one group and minute 45-next min 30 would be another.
My first idea was to divide the time but since these aren't unix timestamps I've been unable to do math with the ISODate. My second idea was to $project out the hour, minute, days, etc, but realized it will be challenging to group when the timeblock span two separate days.
# This doesn't work since you cant do the division.
query = [
    {
        "$match": {
            '_id.t': {
                '$gte': new Date(2014, 1, 1, 1, 0, 0),
                '$lte': new Date(2014, 6, 1, 1, 0, 0)
            }
        }
    },

    {
        "$project": {
            "milliseconds": { '$millisecond': '$_id.t' }
        }
    },

    {

        "$project": {
            "timeblock": {
                "$divide": [
                    '$milliseconds', 900000
                ]
            }
        }
    },

    {
        "$group": { "_id": { "timeblock": "$timeblock" } }
    }
]

A: I think following can solve the question:
var baseDate = new Date(2014, 09, 17, 14, 25, 0);  // any value as you want
var startDate = new Date(2014, 09, 17, 14, 25, 0);
var endDate = new Date(2014, 09, 20, 14, 25, 0);
var divisor = 45 * 60 * 1000; // milliseconds of 45 minutes

db.cc.aggregate([ {
    $match : {
        date : {
            $gte : startDate,
            $lt : endDate
        }
    }
}, {
    $group : {
        _id : {
            $subtract : [ "$date", {
                $mod : [ {
                    $subtract : [ "$date", baseDate ]
                }, divisor ]
            } ]
        },
        dates : {
            $push : "$date"
        }
    }
} ]).pretty();

Explanation for grouping:
_id : {
    $subtract : [ "$date", {                    /* start date of each block */
        $mod : [ {                              /* remainder */
            $subtract : [ "$date", baseDate ]   /* offset */
        }, divisor ]
    } ]
},


text:
Q: How to emulate "window" object in Nodejs? When running in a browser, everything attached to the "window" object will automatically become global object. How can I create an object similar to that in Nodejs?
mySpecialObject.foo = 9;
var f = function() { console.log(foo); };
f();  // This should print "9" to console

A: You can use the predefined object global for that purpose. If you define foo as a property of the global object, it will be available in all modules used after that.
For example, in app.js:
var http = require('http');
var foo = require('./foo');

http.createServer(function (req, res) {
  //Define the variable in global scope.
  global.foobar = 9;
  foo.bar();
}).listen(1337, '127.0.0.1');

And in foo.js:
exports.bar = function() {
  console.log(foobar);
}

Make sure you don't use the var keyword as the global object is already defined.
For documentation, check out http://nodejs.org/api/globals.html#globals_global.

A: you can attach global stuff to process instead of window

A: You can now use globalThis instead of both global and window regardless of the environment. Every recent browser and Node 12+ supports it. It's part of ES2020
// BEFORE
global.foo = 9;     // ⚠ Node only
window.foo = 9;     // ⚠ Browser only, no service workers

// AFTER
globalThis.foo = 9; // ✅ Everywhere!

A: You can use the GLOBAL object.
fruit = 'banana';
console.log(GLOBAL.fruit); // prints 'banana'

var car = 'volks';
console.log(GLOBAL.car); // prints undefined

A: If you were to compare the Web Console to Node running in terminal (both Javascript) :
window <-> global (Note: GLOBAL is deprecated)
in Web Console : window.wgSiteName (random to show functionality)
in Node (Terminal): global.url
document <-> process (Note: program process running right now)
in Web Console : document.title
in Node (Terminal): process.title

A: I've come to this simple solution:
var mySpecialObject = global;

In normal browser:
var mySpecialObject = this;  // Run this at global scope


text:
Q: How can I print SelectedRows in DBGrid using Rave Report? To report current record in dataset I have made (one record by page):
RvSystem1.SystemPrinter.FirstPage := DataSet.RecNo;
RvSystem1.SystemPrinter.LastPage := DataSet.RecNo;

So, how we can report only selected records in DataSet when all records appears in the same page. Something like:
RvProject1.SelectReport('Report1');
for I := 0 to DBGrid1.SelectedRows.Count - 1 do begin
  /// ???
end;
  RvProject1.Execute;

Thanks in advance.

A: Maybe that can be done by filtring DataSet with SelectedRows than execute report.


text:
Q: Elementary integrals and Riemann surfaces An article of Brian Conrad "Impossibility theorems for elementary integration" says that a way of proving the following elliptic integral

If $P(x)$ is a monic polynomial of degree $\ge 3$ without repeated roots, then $$\int \frac{dx}{\sqrt{ P(x)}}$$
  is not an elementary integral.

After that, Conrad says that this theorem is a consequence of general facts about compact Riemann surfaces, because the formula obtained by the Liouville theorem for elementary integrals is equivalent to the equality for meromorphic $1$-forms
$$\left({dy}/{y}\right)=\sum c_j (dg_j)/(g_j)+dh$$
on the compact Riemann surface associated to $y^2=P(x)$, and for degree of $P>2$ the left side of the formula is a holomorphic $1$-form on $C$, and a non-zero holomorphic 1-form on a compact Riemann surface never admits an expression like the above expression.
I don't know anything about Riemann surfaces, and my question is: where can I find the information to understand this reasoning? I don´t know if this it's very difficult or it's very elementary in the theory of Riemann surfaces. I appreciate any answer. Thanks

A: Davenport, James, On the integration of algebraic functions. Lecture Notes in Computer Science, 102. Springer-Verlag, Berlin-New York, 1981.
J. Ritt, Integration in finite terms, Columbia UP, 1948.
Hardy, G. H. The integration of functions of a single variable. Reprint of the second edition, 1916. Hafner Publishing Co., New York, 1971.


text:
Q: How do I share models using a library that should be directly extended upon in a binary with Rust? I want to be able to share the data structures (models) in the code base for the service I am building.
I have currently split up the code in a library named domain and a binary named log_service.
In the domain library I have defined a structure that will contain the information for a Log as shown below.
pub struct Log {
    pub id: u32,
    pub message: String,
}

In the log_service binary I want to use diesel as a database ORM and use this structure defined in the domain library as a table. The diesel documentation states that in order to use this structure as a database table, you need to derive certain traits (e.g. Queryable) and possibly apply other attributes.
However Rust does not allow extension of this struct from within another crate, and because inheritance does not exist in Rust, there is usually the option of using composition to wrap the domain Log. But because diesel uses the struct to directly map to a table, it's not possible to use composition to expose the fields, because they should be top level on the struct.
Preferably I wouldn't want to copy paste this struct in both crates.
I've been thinking of using a macro to  generate these structures in both code bases from a single source, which would still allow extending the Log in the binary.
What would be the optimal way to solve this?

A: No. This can't be (easily) done if you absolutely have to maintain the current structure of your project.
Rust's orphan rules states:

... that every trait implementation must meet either of the following conditions:

*

*The trait being implemented is defined in the same crate.

*At least one of either Self or a generic type parameter of the trait must meet the following grammar, where C is a nominal type defined within the containing crate:
 T = C
   | &C
   | &mut C
   | Box<C>

Simply put, either the trait or the struct has to be local to the crate in order for you to implement it.
So the easiest option for you would be to derive diesel::deserialize::Queryable for your Log struct in domain crate itself.


text:
Q: Create settings for myApplication Iphone I am new to iPhone development.
I've seen many applications, which have their settings stored in the iPhone's setting app.  For example, Default User Name & Password are stored in settings for "myApp."
Whenever the user starts "myApp", userName & password are loaded from the settings app.
How would I implement this functionality into my own app?
any links / any help / any source code / samples
Thanks in advance for being nice to me.

A: Here are some relevant docs to take a look at:

*

*Apple's doc for settings within the settings app

*tutorial on creating settings within the settings app

A: [NSUserDefaults standardUserDefaults] will get you the defaults object, from which you can access keyFor and setKeyFor to get/set values. For example [[NSUserDefaults standardUserDefaults] boolForKey:@"UseSounds"] returns 'true' if the user has elected to turn sounds off, and your settings pane defines 'UseSounds' as the key.
NSUserDefaults reference