text:
Q: Axios.post sends request two times I have a problem with axios.post sending two times the same request with the same body. I have tried to Google the problem but find nothing. How can I fix it?

App.js
import logo from './logo.svg';
import './App.css';
import Register from "./register";
import SendToken from "./sendToken";
import {BrowserRouter, Routes, Route} from "react-router-dom";
import Confirmation from "./Confirmation";

import {useParams} from "react-router-dom";

function App() {
  return (
      <BrowserRouter>

              <Routes>
                  <Route path="/registration" element={<Register/>}/>
                  <Route path="/confirmation" element={<Confirmation/>}/>
                  <Route path="/account/registrationConfirm/:data" element={<SendToken/>}/>
              </Routes>

      </BrowserRouter>

  );
}

export default App;

sendToken.js
import axios from 'axios';

const SendToken = () => {
    let parts = window.location.href.split('/');
    let length = parts.length;
    let token = parts[length - 1] == '' ? parts[length - 2] : parts[length - 1]

    axios.post("http://localhost:8080/api/v1/registration/registrationConfirm", {token}).then((data) => {
        console.log(data.status)
        console.log(data.data)
        console.log(token);
        }
    }).catch(() => {
        alert("An error occurred on the server")
    })

    return (

            Token send

    )
}

export default SendToken;

A: when you use to send request like this everytime that page rerenders it sends the request try using useEffect:
useEffect(() => {
    axios
    .post("http://localhost:8080/api/v1/registration/registrationConfirm", {token})
    .then((data) => {
        console.log(data.status)
        console.log(data.data)
        console.log(token);
    })
    .catch(() => {
        alert("An error occurred on the server")
    })
},[]}

the second parameter tells you that this code will run only one time.

A: You might need to use useEffect() with a second argument as an empty array in your SendToken component.
import {useEffect} from "react";

useEffect(() => {
  fetchData();
  }, []);

To make sure that it runs only once.


text:
Q: Xcode Can't Recognize my ViewController SignUpViewController2 - I have already identified this in Xcode. Xcode says "use of undeclared type SignUpViewController2". I don't know why Xcode doesn't know what SignUpViewController2 is.

A: In your identity inspector, under the "Class" attribute, you have it called "SignUp2ViewController", and you are programatically attempting to refer to it as "SignUpViewController2".

redpajama_set_name: RedPajamaStackExchange


text:
Q: Change the connectionString Arg by values data entry by the user in an input with Razor Web Page First, I quite apologize to you for my poor English (cause I'm french).
My problem is that, I need to recover some data like server IP, user name and password witch was get back by the user in some input on submit and use these data for change the connectionString witch is in web.config. But I don't know how to do.
I hope to have been clear and thank you in advance for your help.

A: Well, after a lot of search and work, I have chose to change my connectionString like it:
@{
    Layout = "~/_Layout.cshtml";
    Page.Title = "Dossier Racine";
    var srv = Request.QueryString["server"];
    var usr = Request.QueryString["username"];
    var pwd = Request.QueryString["password"];
    var db = Database.OpenConnectionString("server="+srv+";database=ReportServer;uid="+usr+";pwd="+pwd+"","System.Data.SqlClient");
    var sqlFile = " SELECT *"
        + " FROM Catalog";
    var selectedData = db.Query(sqlFile);
 }


text:
Q: Disabling keyboard input when using a UITextField + UIPickerview This project also click on the textfield pickerview opens, but the data shown above can be entered in the section. How can I turn it off? So just come to my choices below.

If the textfield is clicked, I open the pickerview:
import UIKit
import NVActivityIndicatorView

struct kategoriData {
    var text : String?
    var id : String?
}

class KonuEkleViewController: UIViewController,UITextFieldDelegate , NVActivityIndicatorViewable , UIPickerViewDataSource , UIPickerViewDelegate{
    @IBOutlet weak var txtBaslik: UITextField!
    @IBOutlet weak var txtYazi: UITextView!
    @IBOutlet weak var txtLink: UITextField!
    @IBOutlet weak var btnKonuAc: UIButton!
    @IBOutlet weak var txtKategoriSecimi: UITextField!

    let size = CGSize(width: 30, height: 30)
    let singleton = Global.sharedGlobal
    let ConnectString = Connect.ConnectInfo
    var kategoriList = [kategoriData]()
    let GirisView = GirisViewController()
    var secilenKategori : String?

    var dbKategoriIsim : String?
    var dbKategoriId:String?

    override func viewDidLoad() {
        super.viewDidLoad()
        txtKategoriSecimi.text = "Kategoriyi Seçiniz"
        KategoriGetir()
        pickerGrafik()
        txtYazi.layer.cornerRadius = 10
        btnKonuAc.layer.cornerRadius = 10

        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(GirisViewController.dismissKeyboard))
        view.addGestureRecognizer(tap)
    }
    func dismissKeyboard() {
        view.endEditing(true)
    }

    @IBAction func btnKonuEkle(_ sender: Any) {
       GirisView.LoadingIcon(tur: 0)
        if txtBaslik.text != "" && txtYazi.text != "" && secilenKategori != nil && txtKategoriSecimi.text != "Kategoriyi Seçiniz"
        {
            KonuEkle(uye: singleton.username, baslik: txtBaslik.text!, mesaj: txtYazi.text, kategori: secilenKategori!, link: txtLink.text!)
        }
        else
        {
            GirisView.Bildiri(baslik: "UYARI", mesaj: "Boş Alanları Doldurunuz", tur: 1)
        }
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.0) {
            self.GirisView.LoadingIcon(tur: 1)
        }

    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }
    func KonuEkle(uye:String , baslik:String ,mesaj:String , kategori:String , link:String)
    {
        var request = URLRequest(url: URL(string:ConnectString.conString + "/KonuEkle")!)
        request.httpMethod = "POST"
        var postString = "uye="+uye+"&&baslik="+baslik+"&&mesaj="+mesaj+"&&kategori="+kategori+"&&link="+link
        postString = postString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
        request.httpBody = postString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in

            if error != nil
            {
                print("error")
            }

            if let urlContent = data
            {

                do
                {
                    let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                    print(jsonResult)
                    if let gelenDizi = jsonResult as? NSArray
                    {
                        for i in 0..<gelenDizi.count
                        {
                            if let gelenMesaj = (gelenDizi[i] as? NSDictionary)?["mesaj"] as? String
                            {
                                DispatchQueue.main.async {
                                    self.Sonuc(mesaj:gelenMesaj)
                                }

                            }

                        }

                    }

                }
                catch
                {
                    print("server hatası")
                }
            }
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.0) {
                self.GirisView.LoadingIcon(tur: 1)
            }
        }
        task.resume()
    }

    func Sonuc(mesaj:String)
    {
        var mesajSonuc = ""
        var mesajBaslik = ""

        if mesaj == "basarili"
        {
            mesajSonuc = "Konu Açıldı"
            mesajBaslik = "Bilgi"
        }
        else
        {
            mesajSonuc = "Bir Hata Oluştu Lütfen Destek Bölümünden Bize Ulaşın"
            mesajBaslik = "Uyarı"
        }

        let appearance = SCLAlertView.SCLAppearance(showCloseButton: false)
        let alert = SCLAlertView(appearance: appearance)
        _ = alert.addButton("Tamam") {

            self.txtLink.text = ""
            self.txtYazi.text = ""
            self.txtBaslik.text = ""
            self.navigationController!.popViewController(animated: true)
        }
        if mesajBaslik == "Bilgi"
        {
        _ = alert.showSuccess(mesajBaslik, subTitle:mesajSonuc)
        }
        else
        {
        _ = alert.showNotice(mesajBaslik, subTitle:mesajSonuc)
        }

    }
        func pickerGrafik()
    {
        let pickerView = UIPickerView()

        pickerView.delegate = self

        txtKategoriSecimi.inputView = pickerView

        let toolBar = UIToolbar(frame: CGRect(x: 0, y: self.view.frame.size.height/6, width: self.view.frame.size.width, height: 40.0))

        toolBar.layer.position = CGPoint(x: self.view.frame.size.width/2, y: self.view.frame.size.height-20.0)

        toolBar.barStyle = UIBarStyle.blackTranslucent

        toolBar.tintColor = UIColor.white

        toolBar.backgroundColor = UIColor.black

        let defaultButton = UIBarButtonItem(title: "İptal", style: UIBarButtonItemStyle.plain, target: self, action: #selector(KonuEkleViewController.tappedToolBarBtn))

        let doneButton = UIBarButtonItem(title: "Tamam", style: UIBarButtonItemStyle.done, target: self, action: #selector(KonuEkleViewController.donePressed))

        let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: self, action: nil)

        let label = UILabel(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width / 3, height: self.view.frame.size.height))

        label.font = UIFont(name: "Helvetica", size: 12)

        label.backgroundColor = UIColor.clear

        label.textColor = UIColor.white

        label.text = "Kategoriyi Seçiniz"

        label.textAlignment = NSTextAlignment.center

        let textBtn = UIBarButtonItem(customView: label)

        toolBar.setItems([defaultButton,flexSpace,textBtn,flexSpace,doneButton], animated: true)

        txtKategoriSecimi.inputAccessoryView = toolBar
    }

    func donePressed(_ sender: UIBarButtonItem) {
        txtKategoriSecimi.resignFirstResponder()
    }

    func tappedToolBarBtn(_ sender: UIBarButtonItem) {

        txtKategoriSecimi.resignFirstResponder()
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return kategoriList.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return kategoriList[row].text
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        txtKategoriSecimi.text = kategoriList[row].text
        secilenKategori = kategoriList[row].id
    }

    func KategoriGetir()
    {
        kategoriList.removeAll()
        //SADECE 1 DEFA EKLENIYOR
        self.kategoriList.append(kategoriData.init(text: "Kategoriyi Seçiniz", id: "1"))
        GirisView.LoadingIcon(tur: 0)
        var request = URLRequest(url: URL(string:ConnectString.conString + "/KategoriGetir")!)
        request.httpMethod = "POST"
        var postString = "tur=1&&kategori="
        postString = postString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
        request.httpBody = postString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in

            if error != nil
            {
                print("error")
            }

            if let urlContent = data
            {
                do
                {
                    let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                    print(jsonResult)
                    if let gelenDizi = jsonResult as? NSArray
                    {
                        for i in 0..<gelenDizi.count
                        {

                            if let gelenKategori = (gelenDizi[i] as? NSDictionary)?["kategoriisim"] as? String
                            {
                                self.dbKategoriIsim = gelenKategori
                            }
                            if let gelenId = (gelenDizi[i] as? NSDictionary)?["id"] as? String
                            {
                                self.dbKategoriId = gelenId
                            }
                            self.kategoriList.append(kategoriData.init(text: self.dbKategoriIsim, id: self.dbKategoriId))

                        }

                    }

                }
                catch
                {
                    print("error")
                }
            }
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()) {
                self.GirisView.LoadingIcon(tur: 1)
            }
        }
        task.resume()
    }

}

A: This isn't an actual problem when running on a real iPhone device, since no keyboard will be available to do the typing :)
This is only seems like an issue when running on the iOS simulator, since you can then use your Mac keyboard as well.

Having said, you definitely should go with Mr. Hedgehog answer if you still want to block text input to your field.
If, besides blocking input, you may also want to hide the caret on the text field, also try this:
class PickerBasedTextField: UITextField {
    override func caretRect(for position: UITextPosition) -> CGRect { .zero }
}

A: You can implement the UITextFieldDelegate method:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool

To return false so that entering any character by hand would be prevented.

A: If you want to prevent user from using paste action, you can make a subclass of UITextField to override canPerformAction.
public class PickerUITextField: UITextField {
    override public func canPerformAction(_ action: Selector, withSender
                                            sender: Any?) -> Bool {
        if action == #selector(UIResponderStandardEditActions.paste(_:)) {
            return false
        }
        return super.canPerformAction(action, withSender: sender)
    }
}

Here is a doc for list of actions.


text:
Q: Formatting Visual Studio C# Reports at runtime I asked a similar question yesterday. I have a large MS Access application that I want to convert into C#. On the whole I'm doing ok, but it's become apparent to me that I've got problems when formatting reports. Yesterday I was asking about changing a report title at runtime. I came up with a workaround for that. However, MS Access allows you at runtime to create, move, hide, reveal and resize report controls. In particular, my MS Access application constructs barcodes in reports at runtime. In the report I have an array of lines that my code places and resizes in order to construct the barcode. As far as I can see, this is completely impossible in a Visual Studio report. Do I have any options here? For instance are there any competent 3rd party solutions?

A: You have a couple of options.

*

*You can use a 3rd party custom report item like Aspose Barcode for Reporting Services.

*You can dynamically generate an image with embedded code.

Note: I've never attempted the 2nd option, but it seems like it has potential to be an easy way to dynamically generate images for a report...


text:
Q: The card is stuck to the top of the page bootstrap 4 I tried to align the container on the middle of the page but it seems to be stuck at the top of the page.
I have read a similar question but they don't seem to work. I copied some of the code snippets but in my firefox browser they still seem to be stuck at the top of the page. I am not sure if it is a browser issue.
Here is my code.

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Log In</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

Login

            <form>

                Username
                <input type="text" class="form-control" id="username">

                Password
                <input type="password" class="form-control" id="password">

                  <button type="submit" class="btn btn-success">Submit</button>

            </form>

A: you could achieve the desired behavior by adding:
align-items: center;

Css style to the class="container-fluid".

A: Here's how you can do that!
    <!DOCTYPE html>

      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Log In</title>
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

Login

                <form>

                    Username
                    <input type="text" class="form-control" id="username">

                    Password
                    <input type="password" class="form-control" id="password">

                      <button type="submit" class="btn btn-success">Submit</button>

                </form>


text:
Q: regexp_matches, array per row In PostgreSQL, I have a table as follow.
|    id    |     mycolumn   |
| -------- | -------------- |
| 1        | /1/2/8/        |
| 2        | /1/40/22/11/   |
| 3        | /1/15/35/      |

I am trying to get all the numbers, for each row, in an array.
So far I came up with the following:
    SELECT array_agg(matchx)
    FROM (
        SELECT unnest(regexp_matches(mycolumn,
                                     '[0-9]+',
                                     'g')) matchx
        FROM mytable
    ) x

What I want:
|  array_agg   |
| ------------ |
| {1,2,8}      |
| {1,40,22,11} |
| {1,15,35}    |

What I get:
|        array_agg              |
| ----------------------------- |
| {1,2,8,1,40,22,11,1,15,35}    |

How is it possible to get an array per row?

A: No need for unnesting, just turn it into an array directly:
select id, string_to_array(trim(both '/' from mycolumn), '/')
from mytable;

The trim() is necessary, because otherwise you'd have empty elements in the array.

Your original approach would work if you group while aggregating back:
SELECT id, array_agg(matchx)
FROM (
    SELECT id,
           unnest(regexp_matches(mycolumn,'[0-9]+','g')) matchx
    FROM mytable
) x
group by id;


text:
Q: How to move data from one column to another in sqlite3 I need some help formatting a table in sqlite3. I need to move all data points starting with the text "Source:" from the column they are in right now titled "Date" and put them in the column titled "Source".
I am using Python and also DB Browser. To be clear I am not trying to move all of the data points in column "Date" just the data points that start with "Source:"
Any help is greatly appreciated! Thanks!

A: You can assign values of attributes of a row to another attribute of the row within an UPDATE.
UPDATE elbat
       SET source = date
       WHERE date LIKE 'Source:%';

(Add date = NULL if you also want to delete the contents of date in the respective rows.)


text:
Q: variadic boost bind type resolution I'm trying to write an async logger which accepts variadic arguments that are then strung together using a variadic stringer and then pushed onto a single producer single consumer queue.
I'm stuck in my enqueue function part of my Log struct which looks as follows:
template <typename T>
std::string Log::stringer(T const & t){
    return boost::lexical_cast<std::string>(t);
}

template<typename T, typename ... Args>
std::string Log::stringer(T const & t, Args const & ... args){
    return stringer(t) + stringer(args...);
}

 template<typename T, typename ... Args>
 void Log::enqueue(T & t, Args & ... args){
     boost::function<std::string()> f
        = boost::bind(&Log::stringer<T &, Args & ...>,this,
                      boost::ref(t),
                      boost::forward<Args>(args)...);
 /// the above statement fails to compile though if i use 'auto f' it works ->
 /// but then it is unclear to me what the signature of f really is ?

 // at this point i would like to post the functor f onto my asio::io_service,
 // but not able to cause it's not clear to me what the type of f is.
 // I think it should be of type boost::function<std::string()>

 }

Inside main(), I call
  Log t_log;
  t_log.enqueue("hello"," world");

A: My suggestion for the function you ask about:
template <typename T, typename... Args> void enqueue(T &t, Args const&... args) {
    this->io_service->post([=]{
                auto s = stringer(t, args...);
                //std::fprintf(stderr, "%s\n", s.c_str());
            });
}

This works with GCC and Clang (GCC 4.9 or later because of a known issue with captured variadic packs).
But really, I'd reconsider the design at hand, and certainly start a lot simpler until you know what areas deserve further optimization.
Questionables
There are many things I don't understand about this code:

*

*Why are the arguments being taken by non-const reference

*Why are you subsequently using std::forward<> on them (you already now the value category, and it's not going to change)

*Why are you passing the stringization to an io_service?

*

*the queue is going to introduce locking (kind of refuting the lockfree queue) and

*the stringization is going to have its result ignored...

*Why would you use boost::function here? This incurs a (another) dynamic allocation and an indirect dispatch... Just post f

*Why are the arguments bound by reference in the first place? If you're going to process the arguments on a different thread, this leads to Undefined Behaviour. E.g. imagine the caller doing
char const msg[] = "my message"; // perhaps some sprintf output
l.enqueue(cat.c_str(), msg);

The c_str() is stale after the enqueue returned and msg goes out of scope soon, or gets overwritten with other data.

*Why are you using bind approaches when you clearly have c++11 support (because you used std::forward<> and attributes)?

*Why are you using a lockfree queue (do anticipate to be constantly logging at max CPU? In that case, logging is the core functionality of you application and you should probably think this through a bit (a lot) more rigorously (e.g. write into preallocated alternating buffers and decide on max backlog etc).
In all other cases, you probably want at most 1 single thread running on a lockfree queue. This would likely already be overkill (spinning a thread constantly is expensive). Instead, you could gracefully fallback to yields/synchronization if there's nothing to do n cycles.

*You can just bind to a shared_ptr. This is a lot safer and more convenient than binding to .get()

In my sample below I've just removed the need for scoped_ptrs by not allocating everything from the heap (why was that?). (You can use boost::optional<work> if you needed work.)

*The explicit memory-order load/stores give me bad vibes too. The way they're written would make sense only if exactly two threads are involved in the flag, but this is in no way apparent to me at the moment (threads are created all around).
On most platforms there will be no difference, and in light of the above, the presence of explicit memory ordering stands out as a clear code smell

*The same thing applies to the attempts to forcibly inline certain functions. You can trust your compiler and you should probably refrain from second guessing it until you know you have a bottleneck caused by suboptimal generated code

*Since you intend to give threads thread affinity, do use thread locals. Either use GCC/MSVC extensions in C++03 (__thread) or use c++11 thread_local, e.g. in pop()
thread_local std::string s;
s.reserve(1000);
s.resize(0);

This enormously reduces the number of allocations (at the cost of making pop() non-reentrant, which is not required.

I later noticed this pop() is limited to a single thread

*What is the use of having that lockfree queue if all you do is ... spinlock manually around it?
void push(std::string const &s) {
    while (std::atomic_flag_test_and_set_explicit(&this->lock, std::memory_order_acquire))
        ;
    while (!this->q->push(s))
        ;
    std::atomic_flag_clear_explicit(&this->lock, std::memory_order_release);
}

Cleanup Suggestion
Live On Coliru
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/atomic.hpp>
#include <boost/lockfree/spsc_queue.hpp>
#include <boost/thread/thread.hpp>

/*
 * safe for use from a single thread only
 */
template <unsigned line_maxchars = 1000>
class Log {
  public:
    Log(std::string const &logFileName, int32_t queueSize)
      : fp(stderr), // std::fopen(logFileName.c_str(),"w")
        _shutdown(false),
        _thread(&Log::pop, this),
        _queue(queueSize)
    { }

    void pop() {
        std::string s;
        s.reserve(line_maxchars);

        struct timeval ts;
        while (!_shutdown) {
            while (_queue.pop(s)) {
                gettimeofday(&ts, NULL);
                std::fprintf(fp, "%li.%06li %s\n", ts.tv_sec, ts.tv_usec, s.c_str());
            }
            std::fflush(fp); // RECONSIDER HERE?
        }

        while (_queue.pop(s)) {
            gettimeofday(&ts, NULL);
            std::fprintf(fp, "%li.%06li %s\n", ts.tv_sec, ts.tv_usec, s.c_str());
        }
    }

    template <typename S, typename T> void stringer(S& stream, T const &t) {
        stream << t;
    }

    template <typename S, typename T, typename... Args>
    void stringer(S& stream, T const &t, Args const &... args) {
        stringer(stream, t);
        stringer(stream, args...);
    }

    template <typename T, typename... Args> void enqueue(T &t, Args const&... args) {
        thread_local char buffer[line_maxchars] = {};
        boost::iostreams::array_sink as(buffer);
        boost::iostreams::stream<boost::iostreams::array_sink> stream(as);

        stringer(stream, t, args...);

        auto output = as.output_sequence();
        push(std::string(output.first, output.second));
    }

    void push(std::string const &s) {
        while (!_queue.push(s));
    }

    ~Log() {
        _shutdown = true;
        _thread.join();

        assert(_queue.empty());
        std::fflush(fp);
        std::fclose(fp);

        fp = NULL;
    }

  private:
    FILE *fp;
    boost::atomic_bool _shutdown;

    boost::thread _thread;
    boost::lockfree::spsc_queue<std::string> _queue;
};

#include <chrono>
#include <iostream>

int main() {
    using namespace std::chrono;
    auto start = high_resolution_clock::now();

    {
        Log<> l("/tmp/junk.log", 1024);

        for (int64_t i = 0; i < 10; ++i) {
            l.enqueue("hello ", i, " world");
        }
    }

    std::cout << duration_cast<microseconds>(high_resolution_clock::now() - start).count() << "μs\n";
}

As you can see, I've reduced the code by a third. I've documented the fact that it's only safe for use from a single thread.
Asio is gone. Lexical cast is gone. Things have meaningful names. No more memory order fiddling. No more thread affinity fiddling. No more inline envy. No more tedious string allocations.
The things that you'd likely benefit the most from is

*

*make the array_sinks/buffers pooled and stored in the queue by reference

*not flush on every log


text:
Q: Why the error asyncio.exceptions.TimeoutError As data, I transmit a list of categories and then collect information on the page.
The code works fine if process about 5000 records.
Exceeding this limit results in a Timeout Error after some time.
I tried ClientTimeout in ClientSession, but the result remains the same. Tell me what the problem is.
Code:
from aiohttp import ClientTimeout
timeout = ClientTimeout(total=600)
START = time.monotonic()
start_time = time.time()
code_VEND_list = []

class RateLimiter:
    """Rate limits an HTTP client that would make get() and post() calls.
    Calls are rate-limited by host.
    https://quentin.pradet.me/blog/how-do-you-rate-limit-calls-with-aiohttp.html
    This class is not thread-safe."""
    RATE = 2  # one request per second
    MAX_TOKENS = 5

    def __init__(self, client):
        self.client = client
        self.tokens = self.MAX_TOKENS
        self.updated_at = time.monotonic()

    async def get(self, *args, **kwargs):
        await self.wait_for_token()
        now = time.monotonic() - START
        print(f'{now:.0f}s: ask {args[0]}')
        return self.client.get(*args, **kwargs)

    async def wait_for_token(self):
        while self.tokens < 1:
            self.add_new_tokens()
            await asyncio.sleep(0.1)
        self.tokens -= 1

    def add_new_tokens(self):
        now = time.monotonic()
        time_since_update = now - self.updated_at
        new_tokens = time_since_update * self.RATE
        if self.tokens + new_tokens >= 1:
            self.tokens = min(self.tokens + new_tokens, self.MAX_TOKENS)
            self.updated_at = now

async def fetch_one(client, i):
    url = f'https://example.com/product/{i}'
    async with await client.get(url) as resp:
        resp_text = await resp.text()
        bs0bj = BeautifulSoup(resp_text, 'lxml')
        code_EAN = re.sub('^\s+|\n|\r|\s+$', '',
                          bs0bj.find('div', {'class': 'item_'}).get_text())
        code_VEND_list.append(code_EAN)

def file_writher():
    income1 = pd.DataFrame({'Code': code_VEND_list})
    income_sheets = {'MySite-Base': income1}
    writer = pd.ExcelWriter('./Test.xlsx', engine='xlsxwriter')
    for sheet_name in income_sheets.keys():
        income_sheets[sheet_name].to_excel(writer, sheet_name=sheet_name, index=False)
    writer.save()

async def main():
    vendor_seorce = []
    workbook = xlrd.open_workbook('Source.xlsx')
    worksheet = workbook.sheet_by_index(0)
    for vend_code in worksheet.col_values(0):
        vendor_seorce.append(vend_code)

    async with aiohttp.ClientSession(timeout=timeout) as client:
        client = RateLimiter(client)
        tasks = [asyncio.ensure_future(fetch_one(client, id_cat)) for id_cat in vendor_seorce]
        await asyncio.gather(*tasks)

    finish_time = time.time() - start_time
    print('Done!')
    print(f'Time: {finish_time}')
    file_writher()

if __name__ == '__main__':
    asyncio.get_event_loop().run_until_complete(main())

Error code:
Traceback (most recent call last):
  File "F:\Python\test\Stack.py", line 89, in <module>
    asyncio.get_event_loop().run_until_complete(main())
  File "C:\Users\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
    return future.result()
  File "F:\Python\test\Stack.py", line 81, in main
    await asyncio.gather(*tasks)
  File "F:\Python\test\Stack.py", line 52, in fetch_one
    async with await client.get(url) as resp:
  File "F:\Python\venv\lib\site-packages\aiohttp\client.py", line 1117, in __aenter__
    self._resp = await self._coro
  File "F:\Python\venv\lib\site-packages\aiohttp\client.py", line 544, in _request
    await resp.start(conn)
  File "F:\Python\venv\lib\site-packages\aiohttp\client_reqrep.py", line 905, in start
    self._continue = None
  File "F:\Python\venv\lib\site-packages\aiohttp\helpers.py", line 656, in __exit__
    raise asyncio.TimeoutError from None
asyncio.exceptions.TimeoutError


text:
Q: I am having trouble encapsulating the code while using Parser gem to create a static code analyzer in Ruby I am writing a very basic static code analyzer in Ruby. I am using the Parser gem to generate AST and then traversing to ananlyze code. Following is the snippet.
class Processor < AST::Processor

  def on_def(node)
    puts node.type
  end

end

parsed_code = Parser::CurrentRuby.parse(some_code) #parsing code to AST
processor = Processor.new
processor.process(parsed_code) #traversing throught the AST

Now, the problem is that I can only analyze the code within the class that has processed or traversed the AST. In the above case, that class is the processor class. This means that I will have to implement all my analyze methods within the processor class. But, I don't wanna do that, I want to encapsulate each and every analyzer method in their own class. For instance, like this
class CheckIndentation
end

class CheckNamingConvention
end

How can I achieve it?

A: Define Class/Module Methods with Self
Define a class/module method, rather than an instance method. You do that by explicitly using self as the receiver in your method definition so that it refers to the current class/module when the interpreter executes the method definition. For example, the following is untested because your code example was not a complete, verifiable example, but should do what you're trying to accomplish:
class Processor < AST::Processor
  def self.on_def(node)
    puts node.type
  end
end

See Also
For more complex use cases, it's also worth mentioning the Module#module_function method. This copies instance methods into independent module methods that can call a method with the module/class as the receiver. I mention it here only for completeness; IMHO it's overkill for your specific example.


text:
Q: Why Python isn't loading the ca certificate? I've added a bundle certificate to python default file
>>> import ssl; print(ssl.get_default_verify_paths())
DefaultVerifyPaths(cafile='/usr/lib/ssl/cert.pem', capath='/usr/lib/ssl/certs', openssl_cafile_env='SSL_CERT_FILE', openssl_cafile='/usr/lib/ssl/cert.pem', openssl_capath_env='SSL_CERT_DIR', openssl_capath='/usr/lib/ssl/certs')

and the certificate seems to work nicely
>>> import requests; requests.get('https://westeurope.experiments.azureml.net', verify='/usr/lib/ssl/cert.pem')
<Response [530]>

However, when I try to perform the same request without explicitly specifying the certificate file, it fails.
>>> requests.get('https://westeurope.experiments.azureml.net')
# ...
requests.exceptions.SSLError: HTTPSConnectionPool(host='westeurope.experiments.azureml.net', port=443): Max retries exceeded with url: / (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1051)')))

In my understanding this shouldn't happen, right? Why isn't Python not loading the certificate I provided in the default path?
I'm using Python 3.7.1
Thanks

A: requests does not use the defaults from ssl; it uses envvar REQUESTS_CA_BUNDLE or CURL_CA_BUNDLE if set and otherwise uses the (spunoff) certifi module which depending on how you installed requests&certifi which you didn't say and your environment which you didn't identify might use a system default (which might or might not be the same as the OpenSSL used in ssl) or might be its own copy of Mozilla. In the latter case it should include Digicert Global Root CA as needed for that site, because Firefox (also Mozilla) does.
Look at requests.certs.where() or python -m requests.certs
Mostly dupe
Python Requests - How to use system ca-certificates (debian/ubuntu)?
How to force requests use the certificates on my ubuntu system
Why python requests not use the system ssl cert by default?


text:
Q: Tabgroup does not open with IOS 6 simulator in titanium studio I'm new to mobile development with Titanium Studio. I was using tabgroup controller and it was working fine with IOS simulator version 5.1. But when I upgraded to IOS 6, when I tried running the same code I got the error below,
Script Error = -[UITabBarController setSelectedViewController:] only a view controller in the tab bar controller's list of view controllers can be selected. at app.js (line 45).

And here is my code:
var tabGroup = Titanium.UI.createTabGroup();

var win = Titanium.UI.createWindow({
    navBarHidden: true,
    tabBarHidden: true,
    url:'example.js',
});

var tab1 = Titanium.UI.createTab({
    height: 30,
    window:win,
});

tabGroup.addTab(tab1);

tabGroup.addEventListener('open', function(){
    tabGroup.setActiveTab(tab1);
})

tabGroup.open();

Please tell me if I can do something to solve it. Or if I can downgrade the simulator to 5.1 because I don't find the IOS simulator 5.1 in Run Configuration.
Thanks in advance.

A: This is fixed by updating your titanium SDK to the latest version. (Currently 2.1.3 RC2 http://developer.appcelerator.com/blog/2012/09/titanum-2-1-3-rc2-is-released-with-additional-fixes-for-ios-6-and-iphone-5.html)
I had the same issue and this fixed it for me.


text:
Q: Remove ALL CAP text words and colon I would like to be able to remove words using Notepad++'s Search (and Replace) that are all upper case followed by a colon - searching for and then removing both the uppercase word and colon from the line...example:
BRYAN: What happened? OK Judy, Is it true?
CONNOR: Well... he is done.
BRYAN: That much is true.

I believe the following expression will select ALL CAP WORDS, but need to add the option to include the colon with the word.
\b[A-Z]\w+[A-Z]\b

Anyone with a suggestion to revise the above line to select the colon as well?

A: I'm going to ignore the Notepad++ part of the question and focus on the regular expression you've supplied and the associated requirement.
It looks like a PCRE, since it uses \w. In any RE style you can use a literal : as itself. But the basis for the underlying RE is still wrong so it needs reformulating from scratch

*

*Anchor to start of line ^

*Match one or more uppercase characters [[:upper:]]+

*Match a colon :

*Follow with zero or more spaces \s*
The result is this
^[[:upper:]]+:\s*

Your own expression would match words of three characters or more, where the first and last characters were capitals. So BeD would match, as would LONGEST, but JO or done would not. Notice also that neither your solution nor mine will handle names (words) containing punctuation such as O'NEILL or CHOLMONDELEY SMYTHE


text:
Q: A problem with colors in WinEdt I have a problem with colors in WinEdt.
When I compile the MWE below in WinEdt, the text

this becomes a link

is correctly green.
But when I save it as a pdf file, then the color becomes incorrectly
black, though the clickability correctly persists.
%&latex
%\documentclass[12pt,a4paper]{book}

\documentclass[14pt]{book}
\topmargin 2mm
\oddsidemargin 10mm
\evensidemargin 10mm
\textwidth 150mm
\textheight 220mm

\usepackage[latin2]{inputenc}
\usepackage[czech]{babel}
%\usepackage{czech}
\usepackage{latexsym}
\usepackage{a4}
\usepackage{makeidx}
\usepackage{theorem}

\usepackage[pdftex,breaklinks,colorlinks,citecolor=blue,urlcolor=blue,pdftitle={Lecture 9},pdfauthor={Ryan Higginbottom},linkcolor=green,pdfsubject={LaTeX}]{hyperref}

%\makeindex

\renewcommand{\theenumi}{\roman{enumi}}

\begin{document}
Links\hyperlink{foo_1}{This becomes a link}.
\hypertarget{foo_2}{This is the target}.
\newpage

\hypertarget{foo_1}{This is the target}.
Links\hyperlink{foo_2}{This becomes a link}.

\end{document}

A: the first line
 %&latex

forces the pdflatex to act like latex, in dvi mode, not like pdflatex, as such if you run pdflatex on the file then you get the error
! Package hyperref Error: Wrong driver option `pdftex',
(hyperref)                because pdfTeX in PDF mode is not detected.

and no usable output.
If you delete that line it runs without error and produces

As you see here it is best to avoid driver options like [pdftex  as hyperref will choose a suitable driver if you do not force it to use the wrong one,


text:
Q: django values function strange behaviors? I have +5 hours training to explain how : Item.objects.values('type', 'state') returns a dictionary that contains only two keys.
However Item.objects.values('type', 'state').annotate(nb=Count('id')) works !!
How does the interpreter knows that id attribute exists if it's not returned by values function ?

A: Your model has id in background and also Django ORM is aware of your model definition
Django ORM is lazy loading and it wont execute nothing before result is called. So in moment when you are calling annotate it is not yet a dictionary it is still object. In moment that you ask for it result it triggers query to database and returns your result
Django ORM translates this into query to the database similar to this
SELECT type, state, count(id) as nb FROM items

A: It knows that the id attribute exists because Item.objects.values('type', 'state') isn't just a dictionary. It's a object that represents itself as a dictionary based on the parameters you give it.
Imagine the object is a piece of paper, let's call it paper A:
id : 1
type : cheese
state : melted

What you're actually seeing when you call it is a representation of that object created by only showing you the relevant parts, like a piece of paper with holes put on top of A, paper B:
████████████████████
████████████████████
+--------------------+
|type: cheese        |
+--------------------+
+--------------------+
|state: melted       |
+--------------------+

But paper A is still underneath paper B, intact. That's why Item.objects.values('type', 'state').annotate(nb=Count('id')) works: when annotate goes to look at the object, it's asking for what it actually is, not what it looks like to an outside observer. In other words, annotate looks at paper A, not paper B.
By having the object Item.objects.values('type', 'state') represent itself differently to the user and the system, it allows the system to retain as much information as possible in case it needs to check it. This is common in ORM models so that discrepancies don't arise between the database and representations of the database.

A: The first query does not return a dictionary with two keys. On the contrary, it returns a ValuesQuerySet; each element of that queryset is a dictionary.
The ValuesQuerySet, like any other queryset, retains a connection with the model, and it is therefore able to add any other elements to the query as necessary. The query as a whole is not executed until the queryset is iterated.


text:
Q: Jquery Datepicker with XML file an extension of my last question, getDate with Jquery Datepicker ,
I am trying to use the jquery datepicker to load specific info from xml file dependent on the date selected by the user. Similar code but i am trying to load and parse an xml file to read contents of the file for the particular date.
In a perfect world the user would tap a date and below the datepicker html output would give the  user specific times for the selected date instead of my last project of an image.
my probelm is nothing is loading, so my question is what am i doing wrong?
my code is as follows
<!DOCTYPE html>

    <link type="text/css" href="css/ui-darkness/jquery-ui-1.8.custom.css" rel="stylesheet" />


text:
Q: I need to automate a process to open files created by another application I have a JAVA application on a server that creates log files.
I have, in other server, an application (VB.NET) that process those logs to search some strings; if I manually select the file it works all OK.
Now I need that the second application automatically open every new log file on the remote server every one minute.
So I wonder if there's any way to know when a new log file is created or what are the new files created since last minute.
The files have the following format name server.log.*.log so the files with different format name must be ignored.
More info:
There's a second JAVA application on the first sever that delete logs older than one day.

A: You can use Directory.GetFiles every minutes to get the list of all the files in the folder. Compare it to the previous list (that you keep in memory) and process the new files.
An other option is to monitor the folder for any changes. This can be done using the System.IO.FileSystemWatcher class. By setting the Path and the proper NotifyFilter you can see which files were created with the Created event as soon (or almost) as they appear.


text:
Q: SIngle and Double click events not working as expected in canvas I have a Canvas which is present in a UserControl, I have attached the DoubleClick event to this UserControl like this
mainWindow.CanvasLayout.MouseDoubleClick +=
new MouseButtonEventHandler(CanvasLayout_MouseDoubleClick);

I am using this event handler to achieve full screen functionality.
Now, Canvas can have various controls placed inside it. Drag and drop functionality is implemented for these controls similar to this codeproject article.
Basically, I handle these events for a control -
this._dragSource.PreviewMouseLeftButtonDown +=
new MouseButtonEventHandler(DragSource_PreviewMouseLeftButtonDown);

this._dragSource.PreviewMouseMove +=
new System.Windows.Input.MouseEventHandler(DragSource_PreviewMouseMove);

this._dragSource.PreviewMouseLeftButtonUp +=
new MouseButtonEventHandler(DragSource_PreviewMouseLeftButtonUp);

Now, when user DoubleClicks on a control(present in canvas) both DoubleClick(Full Screen) and single Click(drag & drop) operations are performed, i.e. if user double clicks on control and change its mouse position quickly, control position is changed(its dragged and dropped to new position).
Is there any way I can prevent drag and drop operation when user double clicks on a control?

A: Got it, Instead of handling MouseDoubleClick event, I used PreviewMouseLeftButtonDown -
mainWindow.CanvasLayout.PreviewMouseLeftButtonDown
+= new MouseButtonEventHandler(CanvasLayout_PreviewMouseLeftButtonDown);

and
void CanvasLayout_PreviewMouseLeftButtonDown(object s, MouseButtonEventArgs e)
{
    if (e.ClickCount > 1)
    {
        // Do double-click code
        // Code for FullScreen
        e.Handled = true;
    }
}

A: What you need to do is, on mouse up start a timer the time should be retrieved from SystemInformation.DoubleClickTime, and do the click action on the timer tick (only if you didn't detect the double click in the mean time, obviously).
Likewise use SystemInformation.DragSize to prevent accidental drag&drop.
Note, the SystemInformation class is part of WinForms so you need to add a reference to System.Windows.Forms, this class will work just fine in WPF apps.


text:
Q: Kohana 3 ORM: How to get data from pivot table? and all other tables for that matter I am trying to use ORM to access data stored, in three mysql tables 'users', 'items', and a pivot table for the many-many relationship: 'user_item'
I followed the guidance from Kohana 3.0.x ORM: Read additional columns in pivot tables
and tried
    $user = ORM::factory('user',1);
    $user->items->find_all();

    $user_item = ORM::factory('user_item', array('user_id' => $user, 'item_id' => $user->items));
    if ($user_item->loaded()) {
        foreach ($user_item as $pivot) {
            print_r($pivot);
        }
    }

But I get the SQL error:

"Unknown column 'user_item.id' in
  'order clause' [ SELECT user_item.*
  FROM user_item WHERE user_id = '1'
  AND item_id = '' ORDER BY
  user_item.id ASC LIMIT 1 ]"

Which is clearly erroneous because Kohana is trying to order the elements by a column which doesn't exist: user_item.id.  This id doesnt exist because the primary keys of this pivot table are the foreign keys of the two other tables, 'users' and 'items'.
Trying to use:
$user_item = ORM::factory('user_item', array('user_id' => $user, 'item_id' => $user->items))
                    ->order_by('item_id', 'ASC');

Makes no difference, as it seems the order_by() or any sql queries are ignored if the second argument of the factory is given.
Another obvious error with that query is that the item_id = '', when it should contain all the elements.
So my question is how can I get access to the data stored in the pivot table, and actually how can I get access to the all items held by a particular user as I even had problems with that?
Thanks

A: By default, all of Kohana's ORM models expect the table's primary key to be 'id.'  You need to set $_primary_key in your model to something else.

A: $user_item = ORM::factory('user_item', array('user_id' => $user, 'item_id' => $user->items));
I think you need to provide a single item_id value for this to work, not an array of objects.
Also, to find all entries for a single user you should be able to do this:
$user_items = ORM::factory('user_item', array('user_id' => $user));
Does that answer your question?


text:
Q: GDB doesn't show source code when using list command I'm trying to debug a segfault, but it seems that some common gdb commands aren't working as expected. If I do the following:
gdb ./executable_name
break main
run
list

I get the following error:
(gdb) list
1   <built-in>: No such file or directory.

Similarly, if I let the program run until it segfaults, and then try and inspect a particular frame in the stack using
bt
up
list

I get a similar but shorter error:
(gdb) list
1   in <built-in>

I've used GDB on other Ubuntu-based systems before and haven't had a problem like this, so I'm assuming I still need to set GDB up correctly on my system so that it knows where to look for an executable's corresponding source code. Would anyone know how I could get GDB to display source code whilst using the list command when debugging?

A: I should have looked more before asking the above question. The above executable was not built in debug mode. I'm using ROS and catkin, so using catkin build -DCMAKE_BUILD_TYPE=Debug in the package directory solved the problem.


text:
Q: Typo3 Rich Snippets with typoscript I have not been successful to implement rich snippets in my typo3 site. Basically I have tried to wrap the html tag and include meta snippets to no avail but a chain of site errors.

page.meta.itemprop.name = name
page.meta.itemprop.description = description
page.meta.itemprop.image = http://www.example.com/img/01.png

The html code is the following

<html itemscope itemtype="http://schema.org/Organization">
<meta itemprop="name" content="name">
<meta itemprop="description" content="description">
<meta itemprop="image" content="http://www.example.com/image.png">

What typoscript should be used?

A: This worked out for me.

config.htmlTag_stdWrap {
    setContentToCurrent = 1
    cObject = COA
    cObject {
        1 = TEXT
        1.value = itemscope
        1.noTrimWrap = | | |
        2 = TEXT
        2.value = itemtype="http://schema.org/Organization"
        2.noTrimWrap = | | |
  3 = TEXT
        3.value = lang="en"
        wrap = <html | >
    }
}
page {
  headerData {
    4 = TEXT
    4.value (
<meta itemprop="name" content="Your site Name">
<meta itemprop="description" content="Your site description">
<meta itemprop="image" content="http://www.example.com/img/01.png">
    )
  }
}


text:
Q: Plesk infrastructure from 18.0.20 to 18.0.42 Could you please help as following points

*

*we need to update our php from 7.3 to 7.4 and our current version of  Plesk Obsidian is 18.0.20, so from the documentation it's understood to update the version from 18.0.20 to higher version(18.0.43-available version)
we need to retain the current php versions which are used for existing infrastructure(will the updating affect this?).
How can we update the Plesk?
How can we take manual backup from Plesk?
what's the restore procedure for this?
can anyone help me out here?

we need to update our php from 7.3 to 7.4 and our current version of  Plesk Obsidian is 18.0.20, so from the documentation it's understood to update the version from 18.0.20 to higher version(18.0.43-available version


text:
Q: How do I enable a Text class to accept html text and will I be able to calculate height and width? When showing the html I would need to know the height of the text box in order to align things below it properly.

A: In order to pass it html and have it rendered as such you would set the htmlText property instead of the text property. Once the text box has been added to the display list you can get it's height just like normal.

A: If you are trying to get the value of the height and width immediately after setting insance.htmlText, you are not going to get the calculated size of the container. You can add an event listener for FlexEvent.UPDATE_COMPLETE or force validation to do it synchronously and use getExplicitOrMeasuredHeight(). Be careful when forcing validation, it is expensive and does not necessarily need to be done in most cases. I've included a right and wrong way of making it synchronous that was not entirely obvious to me at first.
Wrong:
    var container : Box = new Box;
    var text : Text = new Text;
    container.addChild(text);
    text.htmlText = "THIS IS A TEST";
    trace( text.getExplicitOrMeasuredHeight() > 0 ) // False

Right:
    var container : Box = new Box;
    var text : Text = new Text;
    container.addChild(text);
    text.htmlText = "THIS IS A TEST";
    text.validateNow(); // Forces the validation methods to run and update the component
    trace( text.getExplicitOrMeasuredHeight() > 0 ) // True


text:
Q: Average of numbers in a specific range The question is :

What is the arithmetic mean of all multiples of 10 from 10 to 190 inclusive.

Now I know how many nos there are by using $\frac{190-10}{10}+1 = 19$ but how do I get their sum ?

A: 180+10 = 190;
170+20 = 190;
160+30 = 190;
...
how many numbers are there? 18..  we always add two numbers, so the sum is 190 * 9. now we add the last odd number - 190. so it's 190*10 -> 1900
gauss came up with that. pretty clever. thanks to him, you can do this in your head.
now the mean is just the sum divided by the number of parts, no?
we have 19 parts, and a sum of 1900.
1900/19..
holdon, lemme get muh calculatorz.

A: Between two numbers say $a$ and $b$ the arithmetic mean is $\frac{a+b}{2}$. For multiples of any number between two end multiples  $a$ and $b$ the arithmetic mean is still $\frac{a+b}{2}$.
In your question 10 and 190 both are multiples of 10 . The arithmetic mean of all multiples of 10 between these two numbers is $\frac{10+190}{2}$ . For any other number say 5; 10 and 190 are again the multiples of 5; so the multiples of 5 between 10 and 190 would again average $\frac{10+190}{2}$.


text:
Q: Elevated credentials HARDCODED into script EDITED FOR CLARITY:
We are using 3rd party software that is supposed to invoke a Python script (that I must create). This script sends values such as sender-ip=10.10.10.10 and the script is supposed to return the userId
This 3rd party software claims if we create a credential file, it will run that Python script using the elevated credentials.
So far, this 3rd party software has IGNORED the credentials file, hence the Python script runs with regular user credentials and does not give the desired output.
When I manually run the Python script using command prompt with elevated credentials, then it works.
I am under pressure to get the 3rd party software and the Python script to "play nice", so I must hardcode the elevated credentials in the script even though I was warned this is not good programming practice.
AND, I must be able to invoke the script by executing
C:\> python myscript.py sender-ip=10.10.10.10

Below is the code
import sys, subprocess, socket, string
import wmi, win32api, win32con

for args in [item.strip('sender-ip=') for item in sys.argv[1:]]:

    userIP = args
    userloggedon = ""

    # subprocess
    ping = subprocess.Popen(
        ["ping", "-n", "1", userIP],
        stdout = subprocess.PIPE,
        stderr = subprocess.PIPE
    )

    # can we ping the user's IP address?
    out, error = ping.communicate()

    # if we cannot ping user's IP address then userID is the error message, and exit
    if out.find("Reply from") == -1:
        errorMessage = "HOST unreachable."
        print 'errorMsg={}'.format(errorMessage)
        sys.exit()

    # if we cannot access wmi of user's IP address then userID is the error message, and exit
    try:
        c = wmi.WMI(userIP)
    except:
        errorMessage= "WMI unreachable"
        print 'errorMsg={}'.format(errorMessage)
        sys.exit()

    # perform system lookup of IP address
    user_list = []
    for us in c.Win32_LogonSession():
        try:
            for user in us.references("Win32_LoggedOnUser"):
                user_logins = user.Antecedent.Domain + "\\" + user.Antecedent.Name
                user_list.append(user_logins)

        except:
            pass

    userloggedon = user_list[0]
    print 'userId={}'.format(userloggedon)


text:
Q: Como saber que accion se ejecuto al usar updateOrCreate? Cuando utilizo el upsert updateOrCreate, por ejemplo
$flight = Flight::updateOrCreate(
    ['departure' => 'Oakland', 'destination' => 'San Diego'],
    ['price' => 99, 'discounted' => 1]
);

Existe algun metodo asociado o alguna otra forma para saber si la accion tomada fue creacion o actualizacion? Algo asi como:
$flight->actionTaken;

A: Puedes usar wasRecentlyCreated
$flight->wasRecentlyCreated;

este te devuelve un valor booleano, si crea un nuevo recurso devuelve true


text:
Q: Bind a WPF combobox and get selecteditem to a richtextbox I am using a dataset on the server, in this dataset I have a datatable that calls a stored procedure and returns column names from three tables. I call this stored procedure using a web service.
I manage to show all the column names in my combobox but when I want to click a button and insert selected column name into a richtextbox I get System.Data.DataRowView in the textbox instead.
My code:
'the combobox

'if I don't have this textblock all the values are shown vertical instead of the normal horizontal lines

'the stored procedure
SELECT COLUMN_NAME
FROM         INFORMATION_SCHEMA.COLUMNS
WHERE        (TABLE_NAME = 'Customer') OR
           (TABLE_NAME = 'Invoices') OR
           (TABLE_NAME = 'Orders')
'the button
    Private Sub btnAddColumnNames_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddColumnNames.Click
        ' Add column names to the richtextbox
        Dim tr As New TextRange(rtbText.Selection.Start, rtbText.Selection.End)
        tr.Text = cboColumnNames.SelectedItem.ToString()
        rtbText.Focus()
    End Sub
Any suggestions on how to get the selected text in the combobox to the richtextbox?
Any help is appreciated.

A: You can set the SelectedValuePath of the ComboBox to the member that you want to bind to.
<ComboBox ItemsSource="..." SelectedValuePath="COLUMN_NAME" />

Then instead of using SelectedItem you would use SelectedValue.
Dim tr As New TextRange(rtbText.Selection.Start, rtbText.Selection.End)
tr.Text = CStr(cboColumnNames.SelectedValue)
rtbText.Focus()


text:
Q: What is the correct way to update Jupyter Notebook extensions? What is the correct way to upgrade Jupyter Notebook extensions (e.g. RISE, ipywidgets)? I have a routine which keeps my Python packages updated by running pip install --upgrade, and this downloads and installs new Notebook extension versions too, when they are available.
Should I also run jupyter nbextension install --py --sys-prefix, and possibly even jupyter nbextension enable --py --sys-prefix for each of the Notebook extensions which pip gets a new package?
Thanks

A: jupyter nbextension install --py --sys-prefix installs the extension code in the correct place, so yes you should run this when you update an extension.
jupyter nbextension enable --py --sys-prefix just writes in a JSON file to load the relevant extension - so unless the extension changes its name then no, you don't need to rerun this.

A: Consider running jupyter labextension update --all in terminal to check and install updates.

A: if you've installed using anaconda you could open an anaconda prompt and write
conda update rise

for example. that seems to work for me.


text:
Q: How to use current date pattern in log4j2 fileName? <?xml version="1.0" encoding="UTF-8"?>
<Configuration>
    <Properties>
        <property name="filePattern">%d{yyyy-MM-dd}</property>
    </Properties>
    <Appenders>
        <RollingFile name="TEST"
                     fileName="application-${filePattern}.log"
                     filePattern="application-${filePattern}-rolled.log">
            <Policies>
                <TimeBasedTriggeringPolicy modulate="true"/>
            </Policies>
        </RollingFile>
    </Appenders>
    ...
</Configuration>

I'd like to use the current date directly in the written logfile. But the result of the configuration above is application-%{yyyy-MM-dd} as filename.
Why is the date placeholder not resolved?
By the way: the renamed file on midnight is properly renamed like application-2016-03-13-rolled.log. Why does it work there, but not in the current logfile?
I'm running  tomcat 8 and java 8, if that matters.

A: This one worked (whyever):
<property name="filePattern">${date:yyyy-MM-dd}</property>

A: I don't know why the placeholder isn't resolved but here is my working configuration:
<Appenders>
    <RollingFile name="Permament"
                 fileName="E:/workspace/myproject/logs/ergo.log"
                 filePattern="E:/workspace/myproject/logs/ergo.%d{yyyy-MM-dd.HH:mm}.log"
                 immediateFlush="true">
        <PatternLayout pattern="%d{HH:mm:ss.SSS} %5p{length=5} - %c{1} %m %ex%n"/>
        <Policies>
            <TimeBasedTriggeringPolicy/>
        </Policies>
    </RollingFile>
...

A: Remove the filename attribute. It worked for me. (got the solution from: https://issues.apache.org/jira/browse/LOG4J2-1859) Here is my working configuration
    <RollingFile name="File" filePattern="${basePath}/api_test_execution_log_%d{yyyy-MM-dd}_%d{HH-mm-ss}_%i.log" immediateFlush="true">
       <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>

       <Policies>
            <TimeBasedTriggeringPolicy interval="1" modulate="true"/>
            <SizeBasedTriggeringPolicy size="32 MB" />
            <OnStartupTriggeringPolicy/>
       </Policies>
    </RollingFile>

A: For those are using Log4j2 version 2.6.2 and below:

The fileName is indeed a file name that never changes while the
application is running. If you do not want this behavior upgrade to
the latest version of Log4j 2 and do not specify the fileName
attribute.

From https://issues.apache.org/jira/browse/LOG4J2-1859


text:
Q: How to grep a line if it include some strings? I have a settings file named student
grade1 class1 11 student
grade1 class1 12 student
grade2 class1 21 student
grade2 class2 22 student
......

Now I create a test.sh file to read student. If input gradename and studentnumber, the line include two strings will be copied to student_copy. The code will be like:
echo Input gradename and studentnumber
read gradename
read studentnumber

if (input gradename and studnetnumber);
then
    echo "the line include them" >> student_copy

For example:
if (input grade1 and 11);
then
    echo grade1 class1 11 student >> student_copy

A: grep doesn't do logical AND operations (e.g. match patternA AND patternB), the closest you can come is to construct a longer regexp that matches any one of the possible variations (e.g. grep -E 'patternA.*patternB|patternB.*patternA').  This gets very clumsy and unwieldy if you have lots of patterns to match.
The easiest way to do what you want is to use a scripting language like awk or perl instead of grep.
e.g. the following awk one-liner will match any lines where both patterns appear.
awk '/patternA/ && /patternB/'

Any of the pattern-matches can be inverted too, for example if you want to match any line containing patternA that does not contain patternB (i.e. an AND NOT operation):
awk '/patternA/ && ! /patternB/'

Note: one naive approach is to use grep patternA | grep patternB (or grep patternA | grep -v patternB) - that does achieve a logical AND (or AND NOT) but at the cost of running multiple grep commands rather than a single awk or perl command.

A: Say we want to find lines with grade1 and 11:
Sample data (not the same as in the question) and search keys:
$ cat student
grade1 class1 11 student
grade1 class1 111 student
grade11 class1 21 student
grade12 class2 22 student
$ grade=grade1
$ num=11

Straightforward grep to look for the given strings, note the \</\> anchors that match word edges. This needs them in order:
$ grep "^$grade\>.*\<$num\>" student
grade1 class1 11 student

Or with -w to match full words.
$ < student grep -w "$grade" |grep -w "$num"
grade1 class1 11 student

Both of the above might match any similar looking words elsewhere on the lines, so maybe it's better to do it with awk and compare just the appropriate fields. This assumes the fields are separated by whitespace, so they can't contain any white space in itself.
$ awk -vg=$grade -vn=$num '$1 == g && $3 == n' student
grade1 class1 11 student

If you need to have fields with spaces, then it would be best to have a distinct separator, like tab.

A: I run this command below,
awk '{
if ($1!="grade1" || $3!=11)
print "###";
else
print $0;
}' student

the output is
grade1 class1 11 student
###
###
###

which is the expected output
but if I run test.sh, the code is below:
read -p "Enter gradename: " gradename
read -p "Enter studentnumber: " studentnumber

echo "gradename = $gradename"
echo "studentnumber = $studentnumber"
awk '{
if ($1!="$gradename" || $3!=$studentnumber)
print "###";
else
print $0;
}' student > student2

cat student2

then the output will be:
Enter gradename: grade1
Enter studentnumber: 11
gradename = grade1
studentnumber = 11
###
###
###
###

It's very weird

A: Below awk one liner i have used to find the same and its works fine
 for i  in `awk '{print $1}' student.txt| sed -r "s/\s+//g"| sed '/^$/d'| sort -u` ; do awk -v i="$i" '$1 ~ i && $3 == "11"{print $0}'  student.txt ; done

I Checked for studentnumber 11 as constant so i mentioned $3==11 in script.
grade1 and grade2 as variable in "i"
You can change the student Number as per your requirement. Change the value of $3== "New  Student number" as per requirement


text:
Q: Textboxes in an Array, Connect 4 I'm trying to create a Connect 4 game using textboxes and buttons.
If you click on the button, the textbox background color is filled in and the text will either be filled with x or y.
    private void button2_Click(object sender, EventArgs e)
    {
        Output_textBox.AppendText("You have inserted in Column 2");
        Output_textBox.AppendText(Environment.NewLine);

        TextBox[] boxes = { textBox21, textBox22, textBox23, textBox24, textBox25, textBox26 };

        for (int i = 0; i < 6; i++)
        {
            if (boxes[i].BackColor != SystemColors.HotTrack)
            {
                boxes[i].BackColor = SystemColors.HotTrack;
                boxes[i].Text = "Y";
            }
        }
    }

(edited on 11/6/2013 2:25pm)
The Code above doesn't seem to work even though it seems to make perfect sense to me that it should.
 What i want is for the textbox to turn one by one. So if i click on the button once. textbox11 changes first. Then if textbox11 is filled, textbox12 is filled next when i click on the button again etc.
The coloring needs to be from bottom to top in a column
About me: I'm new to coding. Sorry for the trouble
Thank you in advanced


text:
Q: eBay APIs :: Get related categories using title string Ok, so this has been asked once before with no answers so i'll give it another bash..
On the eBay website one of the first things you do when listing an item is pass in a string which is the listing title. Given this title string, eBay will go and examine all the categories and pick out a short selection of categories where it thinks you listing will be best suited.
I need to use the bulk File Exchange API and need to find the best category programatically. How can I find the most appropriate categories using one of eBays APIs i.e. is there an API for that?
The only solution I have come up with is to get all the categories using those APIs, then traverse the every category performing some kind of ranking on my inputted listing title (cosine similarity or something).
Any ideas, thanks.

A: Sounds like you may be able to make use of GetSuggestedCategories.
From the documentation:

Specify keywords describing an item you are looking for using the
  Query input field. GetSuggestedCategories returns a list of up to 10
  categories that have the highest percentage of listings whose titles
  or descriptions contains the specified keywords.


text:
Q: Dissolve polygons with road network gaps I am using QGIS and have a shapefile of the blocks in a large city, where each polygon is a particular streetblock. The city is divided into various sectors, and each block has information on its sector. I can easily classify the blocks by this attribute to visually inspect the shape of these sectors:

The issue is that the gaps between the blocks is the road network. I would like to dissolve all blocks in the same sector into a contiguous polygon, but am unsure how to do this.
Does anyone know an easy way to "fill in" the gaps between the city blocks in order to make the dissolve work properly?


text:
Q: Unexpected error annotations everywhere since I installed version Oxygen I installed the last version (Oxygen) of Eclipse for PHP. But now there are lots of error annotations that I think they shouldn't be.
Almost all of them have to do with Exception:
throw new Exception('Exception message');

The annotation message in the popup hint is like so:
Exception cannot be resolved to a type
And the hint offers me some quick fixes, which are using the Exception class declared in libraries imported with Composer.
Why is that? As far as I know, Exception is still an internal PHP class (no need to import it). I know I should be using more specific Exception classes, but for now, Exception works for me. And it shouldn't be marked as an error in Eclipse. Prior versions didn't detect this as an error. Furthermore the application runs without any problem.
Is this a bug? Otherwise, how do I disable this type of error annotation?
EDIT:
Another annoying issue happening is that the code assistant is not displaying any php internal function. Only functions, classes and methods declared in my app or in imported libraries. For instance, if I type:
str
the code assistant displays classes from Doctrine, Geocoder, etc, and imported functions like "strip_quotes", but nothing about strstr, str_pad, strpos, etc

A: Did you forgot about namespaces and PSR-4?
throw new \Exception('Exception message');

So when you are using a class which must be autoloaded, you must declare it via use or call it with full path (with namespace).
If you don`t want to write correct code and this message is annoying you, then I'm pretty sure that you can turn off this message via Eclipse configuration.


text:
Q: update query in Oracle procedure updated with wrong value The below mentioned procedure is intended to:

*

*fetch jobids from cp_work_card which exist in cpTemplateWorkCard

*Fetch the first record of bhours for the jobid from the cp_work_card

*update the same to cpTemplateworkCard

Hwoever, all the rows of cpTemplateworkCard are updated with the value of bHours found in last row. But, the values in the variable are stored correctly while execution
DECLARE
     jobId       VARCHAR2(30);
     bHours      float;
     idx         NUMBER(4,0);
     CURSOR         c1
     IS
        select distinct
               cp.job_id
          from cp_work_card cp,
               cptemplateworkcard temp
         where cp.job_id = temp.JOBID;
BEGIN
   idx:=1;
   DBMS_OUTPUT.PUT_LINE('id : jobId  :  bHours');
   OPEN c1;
   LOOP
      FETCH c1 INTO jobId;
      EXIT WHEN C1%NOTFOUND;
      select cpw.BUDGET_HOUR
        into bHours
        from cp_work_card cpw
       where cpw.job_id=jobId
         AND rownum<2;
      /*DBMS_OUTPUT.PUT_LINE('Budget Hours: '||bHours);

      UPDATE TO CPTEMPLATE*/

      UPDATE cptemplateworkcard tmpCard
         SET tmpCard.BUDGET_HOUR=bHours
       where tmpCard.JOBID=jobId;

      DBMS_OUTPUT.PUT_LINE(idx || ' : ' || jobId || ' : ' || bHours);
      idx:= idx+1;

   END LOOP;

   CLOSE c1;
END;

A: Couldn't you achieve the same with a single SQL update statement?
UPDATE cptemplateworkcard tmpcard
   SET tmpcard.budget_hour = (SELECT budget_hour
                                FROM cp_work_card cp
                               WHERE cp.job_id = tmpcard.jobid
                                 AND rownum < 2)
 WHERE EXISTS
      (SELECT 1
         FROM cp_work_card cp
        WHERE cp.job_id = tmpcard.jobid);

I haven't tested this but the principle is the same...
EDIT: Given your constraints and if you must use a procedure then could you not:
DECLARE
   CURSOR c1
   IS
      SELECT DISTINCT
             cp.job_id,
             cp.budget_hour
        FROM cp_work_card cp
       INNER JOIN cptemplateworkcard temp
          ON (cp.job_id = temp.jobid)
       WHERE rownum < 2;
BEGIN
   DBMS_OUTPUT.put_line( 'job_id  :  budget_hour' );

   FOR c_rec IN c1
   LOOP
      UPDATE cptemplateworkcard tmpcard
         SET tmpcard.budget_hour = c_rec.budget_hour
       WHERE tmpcard.jobid = c_rec.job_id;

      DBMS_OUTPUT.put_line( c_rec.job_id || ' : ' || c_rec.budget_hour );
   END LOOP;
END;

EDIT:
FYI, your current procedure isn't working because you have named your variable holding the job ID as jobId which also happens to be the name of a column in the table cptemplateworkcard. Therefore when you perform your update it defaults to thinking your WHERE clause is comparing the table column with itself thereby updating every row with whatever the value of bHours is. When the procedure has finished, obviously the last value of bHours what the final value returned from the cursor hence you are seeing all the values in the table set to this final value.
If you rename your jobId variable to something like v_jobid then it should solve the problem.
Hope it helps...
If the only constraint is that it must be in a PL/SQL procedureal block then this will be the most efficient procedure:
BEGIN
   UPDATE cptemplateworkcard tmpcard
      SET tmpcard.budget_hour = (SELECT budget_hour
                                   FROM cp_work_card cp
                                  WHERE cp.job_id = tmpcard.jobid
                                    AND rownum < 2)
    WHERE EXISTS
         (SELECT 1
            FROM cp_work_card cp
           WHERE cp.job_id = tmpcard.jobid);

   DBMS_OUTPUT.put_line(SQL%rowcount||' record(s) updated');
END;

A: IF your statements/conditions are all correct then executing the following statement instead of your stored procedure should do exactly what you want:
UPDATE cptemplateworkcard tc
SET tc.BUDGET_HOUR=(SELECT cpw.BUDGET_HOUR FROM cp_work_card cpw where cpw.job_id=tc.JOBID AND rownum<2)
WHERE tc.JOBID IN (select cp.job_id from cp_work_card cp);


text:
Q: ngMock is throwing template load error because of ngRoute's $routeProvider...? I just included ngMock into my project because I need it for $httpBackend. I have a bunch of karma/jasmine tests setup, and after including ngMock, everything is breaking because of an error it causes:
PhantomJS 1.9.7 (Windows 7): Executed 0 of 41 SUCCESS (0 secs / 0 secs)
PhantomJS 1.9.7 (Windows 7) ERROR
  Error: Unexpected request: GET home/home.html
  No more request expected
  at C:/dev/app/bower_components/angular-mocks/angular-mocks.js:1181

Seems that it doesn't like ngRoute/$routeProvider. Specifically it breaks on the otherwise/redirectTo statement. If I comment-out that section, the karma/jasmine tests work without error.
  $routeProvider
    .when('/home', angularAMD.route({
      templateUrl: 'home/home.html',
      controller: ''
    }))
    .otherwise({
      redirectTo: '/home'
    });

Notice, I am using angularAMD (for lazy loading), but even when I rewrite that section to use just {} without the angularAMD.route(), it still throws the same error. ie:
  $routeProvider
    .when('/home', {
      templateUrl: 'home/home.html',
      controller: ''
    })
    .otherwise({
      redirectTo: '/home'
    });

Any idea why ngMock doesn't like ngRoute? For now I've created a workaround where I skip the $routeProvider section while running karma/jasmine tests. But I'm trying to understand what is going on, am I not supposed to be setting $routeProvider during unit-testing at all (is that bad practice)?
[Edit:] Issues seem to appear in other segments as well. I'm running a test that includes a service which is loading a template, and it also throws an error:
Error: Unexpected request: GET components/modal/modal.html
No more request expected
    at $httpBackend (C:/dev/app/bower_components/angular-mocks/angular-mocks.js:1181)

[Edit:] Seems to throw the error when I call $httpBackend.flush();
[Edit:] Great, found posts related to issue. Can't believe Google didn't show any relevant results when I searched. Solution: If you found yourself here from Google Results, take a look at these: post 1, post 2.
[Edit:] Couldn't get any of those solutions working with angularAMD. Any suggestions?

A: My issue was that I wasn't loading the complete module for the app (which is what I was associating ngRoute with).
In my User.tests.js file, I had
 beforeEach(module('App.services'));

In my app.js file I had:
  App = angular.module("App", [
    "ngRoute"
    "App.templates"
    "App.filters"
    "App.services"
    "App.controllers"
    "App.directives"
    "ui.bootstrap"
  ]);

In my User.js service, I was actually utilizing the $route. The solution for me was to switch my User.tests.js to use the mock module "App" - beforeEach(module("App")); this way the tests are loading all the correct dependencies.


text:
Q: Calculating the movement frequency of a metal rode We have a car with acceleration $a > 0$.
On the top of the car theres a metal rode with weight = $M$ and length = $L$, and the rode is balanced at some angel $\theta$ as can be seen here:

The metal rode moment of inertia is $I = \frac{1}{12}ML^2$.
I am trying to calculate the movement frequency of the metal rode around the balance point.
The frequency formula is $\omega = \sqrt{\frac{g}{L}}$.
According to the answers the frequency should be $\sqrt{\frac{3\sqrt{g^2+a^2}}{2L}}$.
How did they got from $\sqrt{\frac{g}{L}}$ to $\sqrt{\frac{3\sqrt{g^2+a^2}}{2L}}$?

A: This is easier to understand from the reference frame of the moving car. Since this reference frame is accelerated (with respect to the reference frame of the ground) all objects in this frame experience a force $-m \vec{a}$ and can be understood to be the reason the rod is at an inclination $\theta_0$ to the vertical.
Now the net force on the rod due to gravity and the above mentioned force is (in magnitude) given by $F=m\sqrt{a^2+g^2}$. This is along the rod in its equilibrium position.
For a small angular displacement (say $\theta$) the rod experiences a net torque (about the hinge) $$\tau =-F\cdot\frac{L}{2}\cdot\sin(\theta)\approx -m\sqrt{a^2+g^2}\cdot\frac{L}{2}\cdot\theta$$
where the negative sign indicates the torque is in the opposite sense as the angular displacement. This gives
$$I_\text{hinge}\cdot\alpha=\frac{mL^2}{3}\alpha=-m\sqrt{a^2+g^2}\cdot\frac{L}{2}\cdot\theta$$
$$\implies \alpha=-\frac{3\sqrt{a^2+g^2}}{2L}\cdot\theta$$
Applying simple harmonic concepts now yields $\omega = \sqrt{\frac{3\sqrt{a^2+g^2}}{2L}}$ as desired.


text:
Q: Manual suspension and afterwards Will I be able to post questions again after suspension ends?
Before I got manually suspended, I was able to post questions.
Now I get "we are no longer accepting questions from this account"

A: The post ban is calculated when you attempt to submit a question.  If, at that time, it determines that your total contributions are sufficiently problematic as to merit a post ban, it won't let you ask the question.
The exact formula isn't public, but as far as I know (and I don't know for sure, and SE may or may not choose to comment publicly on this) a manual suspension isn't taken into consideration by the post ban formula.  That said, if you've gotten downvotes, had posts closed, had posts deleted, etc. during your suspension then it's possible for those actions to have pushed you below the threshold.
So, in short, it could go either way.  But as far as I know you won't be post banned because of a manual suspension that has ended, even if you coincidentally end up post banned by the time the suspension ends.


text:
Q: excel with vba formula if then print I am trying to get this macro to work with excel. It will look at the value of three cells, if any cell is less than 60 it will print it. If not, it will move onto the next name on the data validation and continue. It keeps on printing the entire range.
Sub Macro2()
'
' Macro1 Macro
'
' Keyboard Shortcut: Ctrl+Shift+L
'
Dim r As Long, i As Long

r = Range("SOLDIERS").Cells.Count

For i = 1 To r
    Range("B12") = Range("SOLDIERS").Cells(i)

If e32 < 60 Or g32 < 60 Or h32 < 60 Then
ActiveSheet.PrintOut Copies:=1

Else: End If

Next i

End Sub

A: Specify Option Explicit at the top, and then the VBE will refuse to compile your code and complain about e32, g32 and h32 being undeclared variables - if these mean to be range addresses on the active sheet, then they should be Range("E32").Value, Range("G32").Value and Range("H32").Value, respectively.
Note that if either cell contains a cell error value (e.g. #VALUE!), then the comparisons will blow up with a type mismatch error. You can avoid this with e.g. If IsNumeric(Range("E32").Value) Then, so that the comparison is only executed when you're dealing with a numeric value (error values can't be compared to anything). You can also test specifically whether a cell contains an error value with the IsError function.


text:
Q: Why do php variables not work if inserted in a function, in a Linux pc? On PC Linux the php code does not correctly insert the indicated variables.
The same code on Windows PC works correctly.
Both PCs have PHP version 7.3, I tried to install different versions but it continues to fail.
<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

// include database and object files
include_once '../config/database_locale.php';
include_once '../objects/locale.php';

$data = json_decode(file_get_contents("php://input"));

$ipServerWebSocket = $data->ipServerWebSocket;

If I execute a print_f() of the variable $ipServerWebSocket the value is correct, but if I insert it in the part of code below it has as value "empty" and php returns the error:

[Thu Oct 10 18:32:56.509354 2019] [php7:notice] [pid 8133] [client
  10.99.99.126:44054] PHP Notice:  Trying to get property 'idEliminaCoda' of non-object in
  /var/www/html/factotumSidRomagna/api/locale/stampaEliminaCode.php on
  line 26, referer: http://10.99.99.25/factotumSidRomagna/ [Thu Oct 10
  18:32:56.509407 2019] [php7:notice] [pid 8133] [client
  10.99.99.126:44054] PHP Notice:  Trying to get property 'cEliminaCoda' of non-object in
  /var/www/html/factotumSidRomagna/api/locale/stampaEliminaCode.php on
  line 27, referer: http://10.99.99.25/factotumSidRomagna/ [Thu Oct 10
  18:32:56.509423 2019] [php7:notice] [pid 8133] [client
  10.99.99.126:44054] PHP Notice:  Trying to get property 'dEliminaCoda' of non-object in
  /var/www/html/factotumSidRomagna/api/locale/stampaEliminaCode.php on
  line 28, referer: http://10.99.99.25/factotumSidRomagna/ [Thu Oct 10
  18:32:56.509465 2019] [php7:notice] [pid 8133] [client
  10.99.99.126:44054] PHP Notice:  Trying to get property 'valoreCliente' of non-object in
  /var/www/html/factotumSidRomagna/api/locale/stampaEliminaCode.php on
  line 29, referer: http://10.99.99.25/factotumSidRomagna/ [Thu Oct 10
  18:32:56.509481 2019] [php7:notice] [pid 8133] [client
  10.99.99.126:44054] PHP Notice:  Trying to get property 'nomeImmagine' of non-object in
  /var/www/html/factotumSidRomagna/api/locale/stampaEliminaCode.php on
  line 30, referer: http://10.99.99.25/factotumSidRomagna/ [Thu Oct 10
  18:32:56.540199 2019] [php7:warn] [pid 8133] [client
  10.99.99.126:44054] PHP Warning:  fopen(../../app/assets/img/eliminaCode/_.png): failed to open stream:
  No such file or directory in
  /var/www/html/factotumSidRomagna/app/assets/php/fpdf.php on line 1259,
  referer: http://10.99.99.25/factotumSidRomagna/

Code:
<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

// include database and object files
include_once '../config/database_locale.php';
include_once '../objects/locale.php';

// get id of product to be edited
$data = json_decode(file_get_contents("php://input"));

// set product property values
$ipServerWebSocket = $data->ipServerWebSocket;

// get database connection
$database = new DatabaseLocale();
$db = $database->getConnection($ipServerWebSocket);

// prepare product object
$locale = new Locale($db);

$locale->ideliminacoda = $data->idEliminaCoda;
$locale->codice = $data->cEliminaCoda;
$locale->descrizione = $data->dEliminaCoda;
$locale->valorecliente = $data->valoreCliente;
$locale->nomeImmagine = $data->nomeImmagine;

// update the product
if($locale->stampa()){ ....}

PHP FILE OBJECT LOCALE:
function stampa(){

        //define('__ROOT__', str_replace('\\', '/' , dirname(dirname(dirname(__FILE__)))));
        define('__ROOT__', dirname(dirname(dirname(__FILE__))));

        require_once (__ROOT__.'/app/assets/php/fpdf.php');
        $printerFolder = __ROOT__ . "/app/assets/printer/";

        // sanitize
        $this->ideliminacoda=htmlspecialchars(strip_tags($this->ideliminacoda));
        $this->codice=htmlspecialchars(strip_tags($this->codice));
        $this->descrizione=htmlspecialchars(strip_tags($this->descrizione));
        $this->valorecliente=htmlspecialchars(strip_tags($this->valorecliente + 1));
        $this->nomeImmagine=htmlspecialchars(strip_tags($this->nomeImmagine));

        $pdf = new FPDF('P','mm',array(79,79));
        $pdf->AddPage();
        $pdf->Image('../../app/assets/img/eliminaCode/'.$this->codice.'_'.$this->descrizione.'.png',34,0,10,0);

All this on Windows PC works properly without giving errors, Why?


text:
Q: sending null keyboardInfo as SIP is closed So my Android application keeps stopping when I try to start an intent and move to a new activity. This is the error I'm getting.
E/KeyboardInfoUtils: sending null keyboardInfo as SIP is closed
I've never seen this exception before, and can't find any help online. Can anyone help me please.


text:
Q: Why won't my range for loop change elements? I'm using this for loop to change all letters in a string to X.
string word{"banana"};
for (auto i : word)
    i = 'x';//why does this bit fail?
cout << word;

The output is supposed to be xxxxxx, instead its "banana" even though the loop works.

A: You need to use &i like so:
auto &i : word

i in your case stores a copy of the original element, so whatever changes you make to it are lost.

A: The the comments try to tell you is that your loop variable i is initialized by value meaning it's a copy of the value in the container, and you only modify the copy.
If you initialize by reference it will work.


text:
Q: Phonegap app on Android platform - keep app running I have a Phonegap app that functions as a communication service for a specific group of people. Using the local notification plugin found on the phonegap-plugins GitHub page, I have implemented notifications into the app, so that whenever someone receives a new message, a notification will appear if the app is in the background.
After about an hour, though, no more notifications will occur, and it appears the process was killed. When I go back into the app, it starts completely over instead of resuming from where I last left off. I'm assuming that after a certain amount of time, Android stopped running the app in the background.
Does anyone know how to keep the app running in the background until it is told by the user to stop, and prevent Android from killing the process?

A: As CommonsWare suggests, you could write a dummy service to keep your app alive, but also as he rightly suggests, if you're going to go to the effort of writing a native dummy service, you may as well write the actual service natively and have done with it.
As a bit of a quick and dirty solution, you could maybe use a partial wakelock (see here) to keep the CPU running your app while it's in the background.
I successfully used this approach to keep my Phonegap-based walk navigation apps alive in the background so they can continue to receive and process position updates.
In your case, staying alive to receive notifications isn't exactly what a partial wakelock was intended for and so I'm unsure whether android will kill your app anyway after a while since it's not doing anything (unlike mine which is constantly receiving and processing position updates) but it might do the job without needing to write a service, so may be worth a try.
Have a look at my answer to this question which contains my code for an updated version of the PowerManagement plugin for Android. I updated the plugin for use with Cordova 2.8.0 but also extended it to be able to acquire a partial wakelock.


text:
Q: How to map a String to a PriorityQueue inside a HashMap in Java? public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        long n = sc.nextLong();
        HashMap<String, PriorityQueue<Long>> hmap = new HashMap<String, PriorityQueue<Long>>();

        for (long i = 0; i < n; ++i) {

            String s = sc.next();
            long m = sc.nextLong();

            if(hmap.containsKey(s))
                hmap.get(s).add(m);
            else {
                PriorityQueue<Long> maxHeap = new PriorityQueue<Long>(Collections.reverseOrder());
                maxHeap.add(m);
                hmap.put(s, maxHeap);
            }
        }

        for (String str : hmap.keySet()) {
            System.out.println(str);
            System.out.println(hmap.get(str));
        }
}

Hi - I am learning how to use data structures in Java. Here, I am trying to use the PriorityQueue as a Max-Heap. But when I am printing the PriorityQueue associated with each String in the Hashmap - the numbers are not in the descending order as I would have expected. Could someone help me understand why ?


text:
Q: Return numeric pattern with function parameter as its length I need to return numeric pattern using a function and function has parameter length.
This is what i tried,
export const numericPattern = (length: number) => /[\d]{length}/;

I just want to return the pattern with given length and if length is not given as parameter, i need to return only /[\d]/.
Thanks

A: const numericPattern = (length) => {
  const tail = length ? "{" + length + "}" : "";
  return new RegExp(`[\\d]${tail}`);
};

console.log(numericPattern(1)); // -> /[\d]{1}/
console.log(numericPattern()); //  -> /[\d]/

A: This should work:

function rx(l){
 return new RegExp("[\\d]"+(l===undefined?"":`{${l}}`),"g");
}

const tst=["7864","abc"],
      larr=[undefined,0,1,3];

tst.forEach(t=>{
 console.log("String:",t);
 larr.forEach(l=>{
  let r=rx(l);
  console.log(l,r.toString(),t.match(r));
 })
});


text:
Q: How to Determine typical rate of progression with haphazardly collected data? We are studying various parameters in extant patient records. Some patients were tested once. Some patients many times. All at different ages. but all have the same disease.
We would like to use the age vs. parameter data to determine the typical course of progressive deterioration in our disease population. What is the right approach to doing this, mindful that individuals may progress at different rates, but also that there must be some "typical" course?  SPSS preferred.
I'm trying to solve this with a random effects "MIXED" model, but if that's right, I can't quite figure it out.
Thanks!
EDIT
In an attempt to clarify the above, let me add the following:
We have patients who visit us at all different ages; we track many of their characteristics, from biometric ones like height or weight, to functional ones like visual acuity.
Because patient visits are not part of a planned study, we don't have uniform sampling, and sometimes have cross-sectional data (when a patient had a characteristic measured once) and other times longitudinal data (when we have several visits from the same patient).
When data are sampled in this kind of haphazard way, I am unsure how to generate norms and, ideally, prediction limits for the course of a characteristic of interest (AKA, a parameter).  For example, in patients with an inherited blinding disorder, it would be nice to know what the typical pattern of vision loss is as a function of age.
EDIT 2
I think I have achieved something close to the desired outcome in MATLAB.  I created a table, T, with 4 columns.  The first is a categorical subject identifier (in my case the patient medical record number, MRN).  The second is a scaler, the age at test (AAT) in years.  The third is a categorical indicator of the eye that was tested (left vs right), and the fourth is a scaler, the parameter of interest, visual acuity (VA).
To perform the analysis, I ran
lme = fitlme(T, 'VA ~ 1 + AgeAtTest * Eye + (1 | MRN)', 'FitMethod', 'REML')

This produces coefficients for Intercept, AAT, Eye and AAT:Eye, as well as P values.  Neither Eye nor AAT:Eye are significant, but the intercept and AAT are.  Thus, I now have a "typical" rate of progression for the disease from the AAT parameter.  This is a start.  I still am not certain this is right (although it looks pretty reasonable) nor do I have any idea how to do the equivalent in SPSS, which I would like to know.


text:
Q: Using curl and Oauth2 client_credentials with Azure AD Graph API I am trying to get an access token from Microsoft's Azure AD Graph API using curl, but I keep getting a 400 Bad Request.
Here is the command I'm running:
curl -v --data "grant_type=client_credentials&client_id=<my id>&client_secret=<my secrect>"  https://login.windows.net/<my app guid>/oauth2/token?api-version=1.0

The response I get is:
{"error":"invalid_request","error_description":"ACS90004: The request is not properly formatted.\r\nTrace ID: 095ca93a-744c-41b1-b531-0db5b8ec9e07\r\nCorrelation ID: 46eb70ad-6053-498a-8fd5-6ee7b52d5e72\r\nTimestamp: 2013-11-07 17:51:15Z","error_codes":[90004],"timestamp":"2013-11-07 17:51:15Z","trace_id":"095ca93a-744c-41b1-b531-0db5b8ec9e07","correlation_id":"46eb70ad-6053-498a-8fd5-6ee7b52d5e72"}


text:
Q: Convert google.protobuf.Timestamp to ISO format in Fabric 1.4 in NodeJS I am running a Hyperledger Fabric 1.4 chaincode and try to retrieve the history of a key with getHistoryForKey stub method. I am iterating over each entry and want to convert them for standardization in all my chaincode functions.
Now, I can handle all keys in the iterator, except the timestamp which is a google.protobuf.Timestamp. Any tries of mine fail to convert it to an ISO datetime string.
Code
// Entry method to retrieve the full history of any asset
async (stub, args) => {
  const idToSearch = args.id
  const historyIterator = await stub.getHistoryForKey(idToSearch)
  let historyData = []
  await iterate(historyData, historyIterator)
  if (historyData.length === 0) throw errors.ASSET_NOT_FOUND(idToSearch)
  return historyData
}

// I use node v8 and thus cannopt use for await to iterator and must write recursive helper func
const iterate = async (historyData, historyIterator) => {
    const element = await historyIterator.next()
    if (!element) return historyIterator.close()
    const {value} = element
    if (!value) return historyIterator.close()

    historyData.push({
        value: value.value.toString('utf8'),
        isDeleted: value.is_delete,
        txId: value.tx_id,
        timestamp: value.timestamp // <-- WANT TO CONVERT TO ISO DATE TIME STRING
    })
    await iterate(historyData, historyIterator)
}

My Approaches
1. toISOString()
Regarding the documentation of the protobuf of timestamp it says "In JavaScript, one can convert a Date object to this format using the standard toISOString()". This does not work, since I get "toISOString is not a function".
2. new Date()
Further, I tried to run new Date(protobufTimestamp), which results in "Invalid Date".
3. Using the seconds
I though maybe I can utilize the seconds which are on of two keys (Object.keys(protobufTimestamp) => [seconds, nanos]) in the timestamp to create the Date. But that date object also says "Invalid Date". That could be explained since I read that Protobuf Timestamp covers the ranges from year 0 to 9999. So, maybe the conversion fails.
Question
Can someone explain me how to convert the google protobuf timestamp to an ISO timestamp in Fabric 1.4 in NodeJS?

A: You can try something like
new Date(protobufTimestamp.seconds * 1000).toISOString()