text:
Q: Resize Bytes[] Of image I have a byte array [], is an image the byte array, is there a way to change the size of the image, but by directly transforming the byte array?

A: It depends on the format ot bytes[]. if the image is a JPG or a PNG than no, you cannot change its size with direct transformation, you need to load it to a texture, blit and grab from rendertexture.
It the data is raw, than yes, its possible to resize, but unlikely to give good results. You can create a new array and copy values at points corresponding to your new coordinate (by nearest neighbour sampling or by implementing some sort of interpolation engine).
https://en.wikipedia.org/wiki/Image_scaling

A: Here is an example that changes the size and saves to disk for checking.
I wrote for example, you can improve.
public class Resize : MonoBehaviour {

    [SerializeField]
    Sprite m_InSprite;
    [SerializeField]
    int width;
    [SerializeField]
    int height;

    [ContextMenu("RESIZE+++")]
    public void Test()
    {
        Texture2D tex = GetResizeText(m_InSprite.texture);
        File.WriteAllBytes(@"d:\test.png", tex.EncodeToPNG());
    }
    public Texture2D GetResizeText(Texture2D oldTex)
    {
        Func<Texture2D, int, int, Color> convert = delegate (Texture2D tex, int X, int Y)
        {
            float scaleI = tex.width / (float)width;
            float scaleJ = tex.height / (float)height;
            int I = (int)(scaleI * X);
            int J = (int)(scaleJ * Y);
            scaleI = (scaleI < 1) ? 1 : scaleI;
            scaleJ = (scaleJ < 1) ? 1 : scaleJ;
            int lengthI = (int)scaleI + I;
            int lengthJ = (int)scaleJ + J;
            List<Color> colors = new List<Color>();
            for (int i = I; i < lengthI; i++)
            {
                for (int j = J; j < lengthJ; j++)
                {
                    colors.Add(tex.GetPixel(i, j));
                }
            }
            //TO DO
            //here you need to find the median of the List colors, but I was too lazy
            int length = colors.Count;
            int m1 = length / 2;
            return colors[m1];
        };
        Texture2D texResize = new Texture2D(width, height);
        for (int x = 0; x < width; x++)
        {
            for (int y = 0; y < height; y++)
            {
                Color col = convert(oldTex, x, y);
                texResize.SetPixel(x, y, col);
            }
        }
        return texResize;
    }
}


text:
Q: heroku config:push not adding environment variables Hi I have done the following from the heroku tutorial.
 heroku plugins:install git://github.com/ddollar/heroku-config.git
 heroku config:push --overwrite

my .env file is in root of project directory
GOOGLE_RETURN_URL = http://example.herokuapp.com/auth/google/return
GOOGLE_REALM = http://example.herokuapp.com/

I also set the --overwrite flag as this answer suggested
however when I echo my heroku config it remains empty!

A: The issue is the spaces in your .env file.  Remove the spaces on either side of your "=" and the plugin will work.
Change:
GOOGLE_RETURN_URL = http://example.herokuapp.com/auth/google/return
GOOGLE_REALM = http://example.herokuapp.com/

To:
GOOGLE_RETURN_URL=http://example.herokuapp.com/auth/google/return
GOOGLE_REALM=http://example.herokuapp.com/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it possible to show a UIViewcontroller in a UITabviewcontroller that doesn't exist in tabs? I got a really weird situation; I have a tabviewcontroller that contains 5 tabs, and that tabviewcontroller is in a container that is in a uiviewcontroller which holds top and bottom bars. There are some extra pages and their linked buttons should not be shown in uitabbar, but in the parent uiviewcontrollers' top and bottom bars. When I open those extra pages, tabs, bottom bar and top bar should not disappear, only the container area in the tabviewcontroller should show that extra pages. I use latest version of swift and latest version of xcode.
Any ideas?

A: I made a sample Project Integrating Container View and Tab Bar Controller as you asked
Check - https://github.com/RockinGarg/ContainerView-TabBar.git
ScreenShot
Tab bar VC1 -

Tab VC2 -

Other Controller in same ContainerView when Clicked Second fro bottom ToolBar Added


text:
Q: How to compute a QPainterPath from a pixmap I have a QGraphicsPixmapItem that rotates through different pixmaps to simulate animation. I need to accurately implement the shape() function so the scene can properly determine collision with other objects. Each pixmap obviously has slightly different collision paths. Is there a simple way to create a QPainterPath from a pixmap by outlining the colored pixels of the actual image that border the alpha background of the bounding rect without having to write my own complex algorithm that tries to create that path manually?
I plan on having these paths pre-drawn and cycle through them the same way I do as the pixmaps.

A: You can use QGraphicsPixmapItem::setShapeMode() with either QGraphicsPixmapItem::MaskShape or QGraphicsPixmapItem::HeuristicMaskShape for this:
#include <QtGui>
#include <QtWidgets>

class Item : public QGraphicsPixmapItem
{
public:
    Item() {
        setShapeMode(QGraphicsPixmapItem::MaskShape);
        QPixmap pixmap(100, 100);
        pixmap.fill(Qt::transparent);
        QPainter painter(&pixmap);
        painter.setBrush(Qt::gray);
        painter.setPen(Qt::NoPen);
        painter.drawEllipse(0, 0, 100 - painter.pen().width(), 100 - painter.pen().width());
        setPixmap(pixmap);
    }

    enum { Type = QGraphicsItem::UserType };
    int type() const {
        return Type;
    }
};

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QGraphicsView view;
    view.setScene(new QGraphicsScene());
    Item *item = new Item();
    view.scene()->addItem(item);
    // Comment out to see the item.
    QGraphicsPathItem *shapeItem = view.scene()->addPath(item->shape());
    shapeItem->setBrush(Qt::red);
    shapeItem->setPen(Qt::NoPen);
    view.show();

    return app.exec();
}


text:
Q: I can't connect to my wifi anymore Yesterday and today morning it worked, but suddenly it does not anymore.
My wifi is working 100% since I can connect my phone to it and other computers.
https://paste.ubuntu.com/26365066/
I tried the Random Mac fix in NetworkManager.conf and restarted but no success.
I'm using Ubuntu 16.04.3 LTS 64-bit with Gnome Desktop

A: Wifi had always worked for me on my Ubuntu 20.04 laptop.  Suddenly, yesterday, it stopped working. (But weirdly, I could connect to the "guest" network of my wifi router, just not the main network.)
Restarting my laptop didn't solve the wifi problem for me.
What worked for me was to restart the ARRIS BGW210-700 wifi gateway that AT&T fiber requires me to use.


text:
Q: cannot save data to MongoDB with this assignment I'm learning MEAN stack with the book Getting MEAN with Mongo, Express, Angular, and Node.
I following the code and test everything, but I get a bug with no errors, in the book page 364, I cannot save salt and hash to MongoDB.
I use postman to test my code the same as the book, and I can get JWT in postman, but only can get _id, name, email and __v on MongoDB when I checked MongoDB with db.users.find() command.
the result like following listing:
"_id" : ObjectId("57f5f1a91093e2650f427081"),
"email" : "bb7@q.com",
"name" : "bb7",
"__v" : 0

I use arch Linux and MongoDB version is 3.2.9
and I guess setPassword methods cause the problem, but no error, weird.
the setPassword method is
userSchema.methods.setPassword = (password) => {
  this.salt = crypto.randomBytes(16).toString('hex');
  this.hash = crypto.pbkdf2Sync(password, this.salt, 1000,64,   'sha512').toString('hex');
};

and my entire code about register is
users.js
   var mongoose = require('mongoose');
var crypto = require('crypto');
 var jwt = require('jsonwebtoken');

var userSchema = new mongoose.Schema({
  email: {
   type: String,
    unique: true,
   required: true
 },
  name: {
  type: String,
   required: true
  },
 hash: String,
  salt: String
});

 userSchema.methods.setPassword = (password) => {
  this.salt = crypto.randomBytes(16).toString('hex');
 this.hash = crypto.pbkdf2Sync(password, this.salt, 1000,64, 'sha512').toString('hex');
};

userSchema.methods.validPassword = (password) => {
  console.log('this salt  '+this.salt);
 // pbkdf2 params is password, salt, iterations, hashBytes, digest
 var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64, 'sha512').toString('hex');
  console.log('this hash '+this.hash);
 return this.hash === hash;
   };

userSchema.methods.generateJwt = () => {
  var expiry = new Date();
  expiry.setDate(expiry.getDate() + 7);

 return jwt.sign({
_id: this._id,
email: this.email,
name: this.name,
exp: parseInt(expiry.getTime() / 1000) // Unix time in seconds
 }, process.env.JWT_SECRET);
 };

mongoose.model('User', userSchema);

authentication.js
  var passport = require('passport');
 var mongoose = require('mongoose');
 var User = mongoose.model('User');

 var sendJSONresponse = (res, status, content) => {
  res.status(status);
 res.json(content);
 };

 module.exports.register = (req, res) => {

  if(!req.body.name || !req.body.email || !req.body.password) {
   sendJSONresponse(res, 400, {
      'message': "All fields required"
   });
   return;
  }

  var user = new User();

  user.name = req.body.name;
  user.email = req.body.email;

  user.setPassword(req.body.password);

 user.save((err) => {
   var token;
   if(err) {
     sendJSONresponse(res, 404, err);
   } else {
     token = user.generateJwt();
     sendJSONresponse(res, 200, {
      'token': token
     });
  }
 })
  }

 /** login */
 module.exports.login = (req, res) => {
   if(!req.body.email || !req.body.password) {
    sendJSONresponse(res, 400, {
     'message':'All fields required'
   });
  return;
 }

   passport.authenticate('local', (err, user, info) => {
    var token;

     if(err) {
      sendJSONresponse(res, 404, err);
      return;
   }

    if(user) {
       token = user.generateJwt();
     sendJSONresponse(res, 200, {
       'token': token
      });
    } else {
      sendJSONresponse(res, 401, info); // info msg about why authentication failed
     }
 })(req, res);
  };

and whole code on github address is https://github.com/simonholmes/getting-MEAN/tree/chapter-11

A: Here is what I have done:

*

*clone repo: git clone git@github.com:simonholmes/getting-MEAN.git

*checkout branch: cd getting-MEAN; git checkout chapter-11

*Set JWT secret: export JWT_SECRET=secret

*start app: npm start
And send register request:
curl -v -X POST http://localhost:3000/api/register -d "email=user@gmail.com&password=pass&name=user"

In response received:
{"token":"some token"}

Then checked mongo db:
mongo
> use Loc8r
> db.users.find()

Hash & salt are stored together with rest attributes. So not sure what problem you have here? If you want to get more attributes in response simply extend what is returned in register method in authentication controller:
user.save(function(err, user) {
  var token;
  if (err) {
    sendJSONresponse(res, 404, err);
  } else {
    token = user.generateJwt();
    sendJSONresponse(res, 200, {
      "token" : token,
      "email": user.email,
      "id": user._id
    });
  }
});


text:
Q: How to call a string in another class in java I'm a real noob so please if i ain't asking corectly sorry.
So here it is :
 public class carti extends JFrame {
    JTextField txttitlu;
    JTextField txtautor;
    JTextField txtcat;
    JTextField txtedi;
    JTextField txtpret;
    DefaultListModel model;
    JList lista;
    String editura;
    String titlu;
    String autor;
    String categorie;

This is the main class function that i have,and in this class i have 4 JTextFields that ar inserted into a JList by a button(here is the script for the adding button"caled "adauga"):
 public void Adauga() {

        autor = txtautor.getText().trim();
        titlu = txttitlu.getText().trim();
        categorie = txtcat.getText().trim();
        editura = txtedi.getText().trim();

        if (autor.equals("")) {
            JOptionPane.showMessageDialog(null, "Nu ati completat Titlu!");
            return;
        }
        if (titlu.equals("")) {
            JOptionPane.showMessageDialog(null, "Nu ati completat Autor!");
            return;
        }
        if (categorie.equals("")) {
            JOptionPane.showMessageDialog(null, "Nu ati completat Categorie!");
            return;
        }
        String numeComplet = autor + " / " + titlu + " : " + categorie;
        model.addElement(numeComplet);

    }

So what i want is: what the button "Adauga" is adding to my JList to be shown onto my extended new class that is called "detalii"(and here it is the code from the new class that si created ("detalii") :
public detalii(){

    this.setTitle("Detalii despre Carte");
    setSize(400, 300);
    setResizable(false);
    setLocation(370, 150);
    setLayout(null);
    JLabel lbltitlu= new JLabel("Titlu" +" : ");
    lbltitlu.setBounds(15, 5, 120, 25);
    this.add(lbltitlu);
    JLabel lblautor= new JLabel("Autor" +" : ");
    lblautor.setBounds(15, 25, 120, 25);
    this.add(lblautor);
    JLabel lblcategorie= new JLabel("Categorie" +" : ");
    lblcategorie.setBounds(15, 45, 120, 25);
    this.add(lblcategorie);
    JLabel lbleditura= new JLabel("Editura" +" : "  );
    lbleditura.setBounds(15, 65, 120, 25);
    this.add(lbleditura);

}

Thank you for the help and sorry if my explains are not done properly i'm really noob. Hope you can understand and did not waste your time.

A: If I understood you correctly, you want the "detalii" class to have its labels updated with the information provided by the "Adauga" method. I would suppose one way of doing that is to call a method within "detalii" from the "Adauga" method.
This is how I would change "Adauga":
public void Adauga() {

    autor = txtautor.getText().trim();
    titlu = txttitlu.getText().trim();
    categorie = txtcat.getText().trim();
    editura = txtedi.getText().trim();

    if (autor.equals("")) {
        JOptionPane.showMessageDialog(null, "Nu ati completat Titlu!");
        return;
    }
    if (titlu.equals("")) {
        JOptionPane.showMessageDialog(null, "Nu ati completat Autor!");
        return;
    }
    if (categorie.equals("")) {
        JOptionPane.showMessageDialog(null, "Nu ati completat Categorie!");
        return;
    }
    String numeComplet = autor + " / " + titlu + " : " + categorie;
    model.addElement(numeComplet);

    detalii.pushNewInfo(autor, titlu, categorie, editura);  // Add This Line!

}

And I would change "detalii" to the following:
private JLabel lbltitlu;
private JLabel lblautor;
private JLabel lbleditura;
private JLabel lblcategorie;

public detalii(){

    this.setTitle("Detalii despre Carte");
    setSize(400, 300);
    setResizable(false);
    setLocation(370, 150);
    setLayout(null);
    lbltitlu= new JLabel("Titlu" +" : ");
    lbltitlu.setBounds(15, 5, 120, 25);
    this.add(lbltitlu);
    lblautor= new JLabel("Autor" +" : ");
    lblautor.setBounds(15, 25, 120, 25);
    this.add(lblautor);
    lblcategorie= new JLabel("Categorie" +" : ");
    lblcategorie.setBounds(15, 45, 120, 25);
    this.add(lblcategorie);
    lbleditura= new JLabel("Editura" +" : "  );
    lbleditura.setBounds(15, 65, 120, 25);
    this.add(lbleditura);
}

public void pushNewInfo(String author, String title,
                        String category, String editor) {
    lblautor.setText("Autor : " + author);
    lbltitlu.setText("Titlu : " + title);
    lblcategorie.setText("Categorie : " + category);
    lbleditura.setText("Editura : " + editor);
}

This is probably not the best solution, but this is how I would solve your problem given the information you have provided.


text:
Q: Criteria Builder String based - Expression quot as double - JPA New to CB, I'm trying to use it instead of native queries. The reason is I'll need different grouping by situations.
Here's what I'm need to reproduce:
(1 - sum( field_1 [integer])::real / sum ( field_2 [integer])::real  ) * 100

Here's the code which suppose to do that:
Expression<Double> filed1Sum = cb.sumAsDouble(report.<Float>get("field1"));
Expression<Double> filed2Sum = cb.sumAsDouble(report.<Float>get("field2"));
Expression<Double> expected = cb.toDouble(cb.<Float>quot(filed1Sum, filed2Sum));

The problem is:  the expected value is coming as Long!!! As the field1 is aways less than field2 I've got 0 (zero). I'm wondering get 0.888 something like that.

A: I've solved by multiplying the dividend by 1.0D:
Expression<Number> expected = cb.quot(cb.prod(filed1Sum,cb.literal(1.0D)), filed2Sum);

That generates the query:
(sum(field1) * 1.0) / sum(field2)

Which returns a floating point correctly.
No explicit conversions were required.
Thank you for the efforts to help me


text:
Q: Wordpress Toolkit (Plesk) detects two sites on my domain when there is only one (+ strange ghosting effect...) Context
Hi, I recently created a new wordpress site for one of my clients. I first created it in a subdomain of the target domain. before dragging it to the target directory via FTP. Once finished, I moved the content of the old site file (a prestashop) from the root (httpdocs) to another file on the server, then I finally dragged the new wordpress site before on this same root (httpdocs). All this was done via FTP. All this was done via FTP, but I had to restart the moves several times.
Problem
Wordpress Toolkit now detects two Wordpress sites (see 1 2) on the main domain and I observe some really strange behaviors, for example :

*

*When I delete one of the two sites via the Toolkit, it then automatically returns to the list

*Both sites have exactly the same data (status, plug-ins, databases, ...) in the Toolkit

*Some changes made on Wordpress actually appear on the page in question, but when reloading, they go away, then come back, as if there were actually two sites that overlapped: one that is affected by the changes and the other that remains unchanged and that are randomly chosen to be displayed on my browser.

*Another finding that supports this is that when I log out of the WordPress admin console, and then return to the site as a visitor, the admin banner is still there at the top of the page, proving that I am still logged in
So I don't know if it's a problem with the configuration of WordPress files like .htaccess/wp-config or if other files were corrupted by the FTP moves or even both cases. It seems to me that there is only one Wordpress in my httpdocs and I don't really know where to look...

A: I deleted all the files from the server, having first uploaded the folder containing my wordpress via FTP. I then recreated httpdocs again then uploaded the site, some files were no longer present and created some 404, I added them by hand based on an old version of the site that I had in backup.


text:
Q: php - htaccess: redirect .png to .php page and display html I have a folder in the root called picture and I want to redirect (applying only to this folder) all the .png urls to:
/picture/index.php

displaying the index.php html content. I mean redirect urls like:
/picture.png, /picture/whatever.png, etc
Actually this is my .htaccess file inside the picture folder:
RewriteEngine On
RewriteRule ^/picture/(\w+)\.png$ /picture/index.php [L]

but if I go to domain.com/picture.png it returns 404

A: You can use this rule in /picture/.htaccess
RewriteEngine On
RewriteBase /picture/

RewriteRule \.png$ index.php [L,NC]


text:
Q: Is there RTL support in iPhone Application (Stoaryboard) I am newbie for iPhone application. I am fine with English and Arabic text (selecting language at the start of application) however just curious how to format the screen from LTR to RTL.
Is there support in iPhone storyboard for RTL in layout?

Answer
I have asked somewhat same question and there I found answer.
How to set Arabic text to right and English text to left on same label

A: I am definetly NOT an expert, but I do use hebrew in my iOS apps.
iOS 6 SDK has something called "Auto-Layout", and the guide specifies that it enables you not to worry about RTL languages.

Cocoa Auto Layout allows individual views to declare their own preferred size, which means you don't have to specify new layout if the label's text changes—for example, because of localization, as illustrated in the right window. You don't even have to specify new layout for languages like Hebrew and Arabic in which the left to right ordering of elements themselves should generally be reversed.

https://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/AutolayoutPG/Articles/Introduction.html

A: Alternatively, if you can view a language in a browser on the iphone you can try using a technology like phonegap.


text:
Q: Python sys instead of exiting to continue I am making a calculator program, using the sys library, that when parentheses are not closed, it prints that it is not valid, it should be noted that it is in a while loop
sys.exit ("Incorrect answer")
>>Incorrect answer
>> Finishe the program

I already tried to do it with
print ("Incorrect answer")
>>Incorrect answer
>>None

I have to make the program continue but if I use print it works but I get none
but I get none and I don't know why that is because someone knows of an alternative instead of using exit, a continue or something similar?

A: I managed to solve it instead of making a
print ("Incorrect answer")
>>Incorrect answer
>> None

use
return ("Incorrect answer")
>> Incorrect answer


text:
Q: Mongoid dependent :destroy vs :delete When using Mongoid referenced reletions what's the diffrence between dependent detroy and dependent delete since in the docs it tells:
:delete: Delete the child documents.
:destroy: Destroy the child documents.

A: *

*destroy runs model callbacks and then makes a REMOVE query to the DB.

*delete just makes a REMOVE query to the DB.

The names are taken from ActiveRecord, that's why they don't match mongo very well.
You could see delete as an optimization over destroy. When you use destroy, you make sure that before_destroy callbacks are executed, so proper cleanup is done. In the other hand, if you do something like Model.destroy_all, it has to load ALL elements, and then make a REMOVE query for each of them, whether Model.delete_all makes just one query.

A: In Mongoid (and also ActiveRecord I believe), delete just removes the object from the database.  destroy will delete the object and run all of the appropriate callbacks that the model has defined.  So if you have a before_destroy callback on a model and you delete an instance of that model, the before_destroy callback will not be called.
So dependent: :destroy runs the model's callbacks when deleting and dependent: :delete does not.


text:
Q: .hgignore website refresh files My ASP.NET website references refresh files that are being excluded because they reside in the ...\bin\ directory of projects.
What can I add to my .hgignore file to ensure just the ...\bin\*.refresh files are NOT excluded?
Note: I understand I could use hg add ...\bin\my.dll.refresh for each of the references and continue with my .hgignore, but I'd like to avoid needing to manually add specific files types as this is error prone and easy to forget.
# use glob syntax
syntax: glob

# Ignore Visual Studio 2008 files
src/**.obj
src/**.exe
src/**.pdb
src/**.user
src/**.aps
src/**.pch
src/**.vspscc
src/**_i.c
src/**_p.c
src/**.ncb
src/**.suo
src/**.tlb
src/**.tlh
src/**.bak
src/**.cache
src/**.ilk
src/**.log
src/**.lib
src/**.sbr
src/**.scc
src/***/[Bb]in      <---- Problem child
src/***/[Dd]ebug*/
src/***/obj/*
src/***/[Rr]elease*/
src/*_ReSharper*/
src/*[Tt]est[Rr]esult*
src/*[Bb]uild[Ll]og.*
src/*.[Pp]ublish.xml
src/***/PrecompiledWeb/

A: For "all except some names" you must use:

*

*regexp pattern

*add negative lookahead in regexp "all files"(get "all except in this subset" as result)

syntax: regexp
bin/(?!.*\.refresh$).+
in any case, check and debug this expression, using filenames with pattern bin\*.*refresh* and hg status command


text:
Q: Golang elastic search security auto-configuration HTTP CA" certificate is not trusted I am new to golang, trying to conenct golang with elastic search below is my code which I tried to connect using default package of go (go-elasticsearch)
Elastic Search Configuration
var _elasticSearchConfiguration = elasticsearch.Config{
    Addresses: []string{
        "https://localhost:9200",
    },
    Username: "elastic",
    Password: "123456",
    Transport: &http.Transport{
        MaxIdleConnsPerHost:   10,
        ResponseHeaderTimeout: time.Second,
        DialContext:           (&net.Dialer{Timeout: time.Second}).DialContext,
        TLSClientConfig: &tls.Config{
          MinVersion:         tls.VersionTLS12,
        },
    },
}

usage of the above configuration
func GetAllJsonObjectDemos(responseWriter http.ResponseWriter, request *http.Request) {
    _elasticsearch, err := elasticsearch.NewClient(_elasticSearchConfiguration)
    if err != nil {
        log.Fatalf("Error creating elasticsearch client: %v", err)
    }
    elasticSearchResponse, err := _elasticsearch.Info()
    if err != nil {
        log.Fatalf("Error getting response: %s", err)
    }
    defer elasticSearchResponse.Body.Close()
    log.Println(elasticSearchResponse)

}

I would really like to know what Am I missing here, Thanks to all the contributors.
I am expecting Connection code of golang & elastic search or any suggestion.

A: To resolve the error certificate is not trusted, you could add the certificate to RootCAs of tls config.
Sample codes
    rootCAs, _ := x509.SystemCertPool()
    if rootCAs == nil {
        rootCAs = x509.NewCertPool()
    }

    // Read the cert file
    certs, err := os.ReadFile("localCertFile")

    // add our cert to the system pool
    rootCAs.AppendCertsFromPEM(certs)

    var _elasticSearchConfiguration = elasticsearch.Config{
        Addresses: []string{
            "https://localhost:9200",
        },
        Username: "elastic",
        Password: "123456",
        Transport: &http.Transport{
            MaxIdleConnsPerHost:   10,
            ResponseHeaderTimeout: time.Second,
            DialContext:           (&net.Dialer{Timeout: time.Second}).DialContext,
            TLSClientConfig: &tls.Config{
                RootCAs:    rootCAs,
                MinVersion: tls.VersionTLS12,
            },
        },
    }


text:
Q: System.ServiceModel Error While trying to open ASP.net website I tried to open ASP.Net Website , but I received this error.
Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
what is this about ?

A: below links are very much helpful you can refer to it :
     http://blogs.msdn.com/b/webtopics/archive/2010/04/28/system-typeloadexception-for-system-   servicemodel-activation-httpmodule-in-asp-net-4.aspx
 http://social.msdn.microsoft.com/Forums/en/wcf/thread/39571e42-aca7-469d-8c68-aa59c2da4fcc

This error can occur when IIS is installed after installing .NET Framework 4, or if the 3.0 version of the WCF Http Activation module is installed after installing IIS and .NET Framework 4.
To resolve this problem, you must use the ASP.NET IIS Registration Tool (Aspnet_regiis.exe,) to register the correct version of ASP.NET. This can be accomplished by using the –iru parameters when running aspnet_regiis.exe as follows:
aspnet_regiis.exe -iru
OR
%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i
good luck


text:
Q: LASSO: Dual form problem. I would like to know the procedure, step by step, to arrive at the dual form of the optimization problem for lasso:
From:
\begin{equation}\label{ridge2}
\hat{\beta}^{lasso}=\min_{\beta}{\sum_{i=1}^{n}\left(y_{i}-\beta_{0}-\sum_{j=1}^{p}\beta_{j}X_{ij}\right)^2} \quad \mathrm{s.a} \quad \sum_{j=1}^{p}|\beta_{j}| \leq t
\end{equation}
To:
\begin{equation}
 \hat{\beta}^{lasso}=\min_{\beta} \left\lbrace \sum_{i=1}^{n}\left(y_{i}-\beta_{0}-\sum_{j=1}^{p}\beta_{j}X_{ij}\right)^2+\lambda\sum_{j=1}^{p}|\beta_{j}| \right\rbrace
\end{equation}
In all the books I have seen they say that the two forms are equivalent, using the Lagrange multipliers, but I don't know why. That part is always omitted. It may be trivial, but I don't understand it.


text:
Q: Get Complete URL I would like ask how to get full url address (even "GET" request type or any other types).
Does it have any software for Windows or Ubuntu users?
Initial link is that: "http://www.eclass.inha.uz"
But  I need to get "http://eclass.inha.uz/servlet/controller.homepage.MainServlet?p_process=main&p_grcode=N000001". It doest not matter which language is being used. I need result.
I am able to get complete url with Wireshark software, but " http.request.type == "POST" ".

A: The URL you give, http://www.eclass.inha.uz, does not resolve. However, if you strip off the initial www., it does resolve, and does indeed redirect as you say it does. cURL can show redirects, but it might be tricky in this specific case, as it's a javascript redirect, not a Location header:
$ curl -v http://eclass.inha.uz
* Rebuilt URL to: http://eclass.inha.uz/
*   Trying 195.158.19.238...
* Connected to eclass.inha.uz (195.158.19.238) port 80 (#0)
> GET / HTTP/1.1
> Host: eclass.inha.uz
> User-Agent: curl/7.47.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Length: 250
< Content-Type: text/html;charset=ISO-8859-1
< Server: Microsoft-IIS/8.5
< Set-Cookie: JSESSIONID=01A873B139B6FF2EF66B81C0D2540AD9; Path=/
< X-Powered-By: ARR/2.5
< X-Powered-By: ASP.NET
< Date: Fri, 21 Jun 2019 22:51:17 GMT
<

<html>
<head>

<Script Language='JavaScript'>
<!--
        var portNumber = "";

    document.location.replace("/servlet/controller.homepage.MainServlet?p_process=main&p_grcode=N000001");
//-->
</Script>
</head>
<body>
</body>
</html>

You might be able to parse something out of that.
For example,
$ curl -s http://eclass.inha.uz | grep document.location.replace | cut -d '"' -f2
/servlet/controller.homepage.MainServlet?p_process=main&p_grcode=N000001


text:
Q: Offered up in his support
There is nothing quite so vexing to the author of a scathing indictment as having the primary target of his venom offered up in his support.

It is from the book "A Mathematician's Lament" which is a criticism of math education in school. The writer criticises lack of reasoning, argument, aesthetic point of view and such things in teaching math in school and talks about his opinion that how a good teaching should be; Then he says some believe that high school geometry consists argumentative method and is a great part of school math curriculum, and then he starts a new section named "high school geometry: instrument of Devil" and criticises high school geometry. The sentence above is the first sentence of that section.
What does the author mean by the part "primary target of his venom offered up in his support"?

A: mathematician and educator here. A full answer to your question gets a little bit into the actual content of the essay, beyond just English language and usage issues. So, I'm not sure this is a great Q & A for this specific site, but I'm already here, so ... I'll answer your question.
English language & usage aspects: The sentence you quoted in your question essentially says: "I am writing against issue X. I believe that example Y supports my view. However, many people will use example Y against me, to support issue X." That is what is so "vexing" to the author: the common use (to him, misuse) of a specific example (namely, High School Geometry) to try to rebut his earlier points in the essay.
Mathematical aspects: (Caveat: I happen to support most of the author's points and regularly share and recommend this essay to others, including my own students.) Immediately preceding the quoted sentence in that essay is a section about what the high school curriculum is and should be about. It concludes with a hypothetical dialogue to illustrate the author's point that mathematics should be about proofs and demonstrating why facts are true, as opposed to just stating what the facts are and moving on. For many students, High School Geometry is their first introduction to actually writing mathematical proofs, constructing arguments that demonstrate why a fact is true. So, some people would naturally say, "Isn't that good, then? Shouldn't we keep teaching geometry as we do in high school, because you want students to learn about proofs?"
However, the author goes on to describe how, in fact, the way high school geometry is typically taught, it totally ruins students' understanding of how to create and share mathematical ideas. The methods are so formulaic and uncreative that they end up obscuring the practice of mathematics and turn students away from it forever. (I'm really paraphrasing, but that's the gist.)
I hope this extra detail about the content of the essay, regarding mathemtics and the teaching thereof, helps you make better sense of the English language issues.


text:
Q: Why doesnt my img show up in ASP.NET I created a C# web project with MSVS 9 and thats all i know about my configurations.
In my browser i can access any aspx files i have in my project. However when i use http://localhost:3288/img/test.png i see nothing. The working directory is ./root, the png file is in ./root/img/test.png How do i have ASP.NET display my images and everything else in the folder? (and subfolders).

A: Is the .png included in the solution?
When you hit the "play" button your essentially starting up a new website ( localhost:2383 ) so if its not in the solution it won't be copied over to the new, temporary, website that the debugger attaches too.
If this is the problem a quick fix is to hit the "Show all Files" button on the top of your solution explorer, this will show all the files in that folder on your hard drive.  Then right click on the .png you want to include and hit "Include in Project".

Based on your comment your only solution is to actually create an IIS site for your solution with the root dir the same as your web project.  Then in the project properties you'll have to tell the debugger to attach to your local IIS instead of visual studios.  Not sure the exact click path, right click on your project and go to properties, look for debugging options.

A: Give a look to the ASP Image control , you can specify paths starting in your app root (~):
<asp:Image id="Image1" runat="server"
           ImageUrl="~/Images/image1.png"/>

Or you can use relative paths to the page that are displayed.
Check this article about ASP .NET Website Paths.


text:
Q: Node.js + Express not writing to file using FS I have a file that I am trying to write to from a post. Currently, the FS does not error nor does it write to file. However, when taking the same code from the deployed build and running it locally, it works. I even kept the file path consistent since it was throwing no permissions error at first. I ensured this file wrote to the same directory so each Filewrite Stream process would look at the same directory and file.
Local build:
var fs = require('fs');
    const path = require('path');
    var user_name = 'Password';
    var password = 'test';
    var errSTR = ""
    fs.writeFile('C:\\hi.txt', 'Content to write', { flag: 'w' }, function(err) {
        if (err)
            return console.error(err);
      fs.readFile('C:\\hi.txt', 'utf-8', function (err, data) {
        if (err)
            return console.error(err);
        console.log(data);
      });
    });

Deployed Build:
app.route('/test')
    .get(function(req, res) {
      res.send('GET test');
    })
    .post(function(req, res) { // Start Post
      var boolTry = false;
      try {
        boolTry = true;
        var bool = false
        var user_name = "Password"//req.body.user;
        var password = "test"//req.body.password;
        var errSTR = ""
        fs.writeFile('C:\\hi.txt', user_name + password, { flag: 'w' }, function(err) {
          if (err)
              return console.error(err);
          fs.readFile('C:\\hi.txt', 'utf-8', function (err, data) {
            if (err)
                return console.error(err);
            res.send(500 + err);
            console.log(data);
          });
        })
      } catch (error) {
        bool = true
        errSTR = error
      }
      res.send('POST test' + " " + boolTry + " " + bool + " " + errSTR +  ";")
    })//END POST
    .put(function(req, res) {
      res.send('PUT test');
    });

The local build will properly write to the file, while the dev build appears to do nothing. It should be noted by booleans were being used to understand how the file writer works but here is the server response from build: successful response POST test true false ;
Using:
 IISNODE for iis: 7.x
 Express: 4.16.2
 node.js: v8.9.4
 cors: 2.8.4
 body-parser: 1.17.2

Sidenote: If you are confused by the writing portion of code, the intention was to write, check error then read, check error for assurance.
Update
Reoccurring error based on certain filewrite methods Error: EPERM: operation not permitted, open. Yes, all permissions for the directory are enabled along with ensuring read and write are checked.


text:
Q: Logfile not being generated while running a powershell script with windows task scheduler I have created the following powershell script:
stop-service ''3456''

start-sleep -s 60

stop-service "2354"

start-sleep -s 60

Restart-computer QY34 -Force

send -mailmessage -from operating.system@abc.com -To asdf@abc.com -subject test -attachment 'c:\Temp|test.log' -smtp server "127.0.0.1"

I have entered the following information on windows task scheduler
On Actions Tab;

C:\windows\System32\windowspowershell\v1.0\powershell.exe

Arguments Tab:

-file "c:\scripts\test.ps1"*>"c:\Temp\test.log"

Can anyone  please help me in getting the log file while running the script via Task Scheduler?

A: Change the arguments from
-file "c:\scripts\test.ps1"*>"c:\Temp\test.log"

to
 "c:\scripts\test.ps1" *> "c:\Temp\test.log"

and it should work as expected. Note the blank spaces before and afer *>.
I think the problem is that Powershell will read everything after -file as the file input. It'll still work, but as it just stops reading after the "file" bit, the > operator is ignored/not seen. Removing -file Powershell will still find the script using positional parameters, but it will also handle the > operator and output to file.
If you run if from a command line it'll work, I think because cmd.exe will handle the output instead of Powershell in that case, but don't quote me on that bit.


text:
Q: Is there a faster, other, different way to use an if statement This is my first mini project (I'm intermediate c++ programmer)
I wanted to practice using if statements because I wanted to find the extent of the command, and what I could use it for.
However, throughout my program, I constantly became very annoyed that I'm having to write all this code, to perform a simple task.
The basics of the code is that the user inputs their birth month, and the program outputs their astrology related sign and meaning. My question is,
Is there a way, that I could perform the same task, but in less code? Is there a command I could use, or something?
------extra-------------------------------------
In my cs1 class, we recently learned about switch cases. I was thinking that I could use switch cases to fix 1 problem I had, accuracy
Improving the accuracy of the users b-day. Instead of using tons of if statements which can only look for a specific month (or with even more if's month and day) I could use a case that said "1. January 1-20th"
However, now this just makes me want to be more accurate about the month.
***Could I possible use more if statements or perhaps something in the case that basically says if the user says <20 then they are Aquarius?
Is there also a different way I could do the program other than switch cases?
    string user_month;
    cout << "This program currently accepts these months in this spelling\n";
    cout << "january, february, march\n\n";

    cout << "Whats the month of your birthday? (lowercase)\n";
    getline(cin, user_month);

    cout << endl;
    cout << user_name << " ... You are about to see your astrological sign and its qualities.\n";
    cout << "Know that they might not be truly accurate and this is just for fun.\n\n";

    if (user_month == "january")
    {
        ;
        cout << endl;
        cout << "You are a Capricorn.\n";
        cout << "Capricorns are usually hardworking, tenacious, diligent, and responsible\n";
        cout << "No matter what the job is, you'll get it done to the best of your ability.\n";
        cout << "Even if you don t have a natural aptitude for a skill, you won t stop working until you ve mastered "
                "it\n.";
    }

    if (user_month == "february")
    {

        cout << endl;
        cout << "You are a Aqaurius.\n";
        cout << "An Aquarius ascribes to a progressive ideology. \n";
        cout << "Because of this you are willing to let go of ";
        cout << "past traditions that no longer serve the people of the future.\n";
        cout << "You aren t content with the answer 'but that s the way it s always been done.' \n";
        cout << "You are willing to try new things, because you know that even if they fail, \n";
        cout << "you know that your getting closer to the right solution.\n";
    }

    if (user_month == "march")
    {

        cout << endl;
        cout << "You are an Aries.\n";
        cout << "At your core, you do what they want and do things your way.\n";
        cout << "You are unafraid of conflict, highly competitive, honest and direct.\n";
        cout << "An Aries is not weighed down by the freedom of choice, and is the sign that is least conflicted about "
                "what they want.\n";
        cout << "You might throw themselves at the world eagerly and without fear.\n";
        cout << "It is one of your most commendable qualities, but also what causes you a great deal of pain and "
                "grief.\n";
    }
    // yes I'm aware my code does not include all the months
    return 0;
}

A: Sometimes, when you have to handle n different values in different ways, you end up with a switch or if-cascade with n branches.
But often, when you perform the same action (with different data) in all branches, there are other ways, e.g., a look-up table.
What are you trying to do? For each month, print a text. So the same action, different data.
Before we look at more complicated solutions, let's improve what you have with the stuff you have learned so far.
First off, you don't need to repeat cout every time, you can chain the stream operator <<:
std::cout << "Hello\n" << "My name is Bob.\n" << "I like potatoes.\n";

Even better, C++ will merge string literals "that are" "adjacent":
std::cout << "Hello\n"
   "My name is Bob.\n"
   "I like potatoes.\n";

You can also put these large text blocks into variables outside of your main, so you have them out of sight:
const char *capricorn = "You are a Capricorn.\n"
                        "Capricorns are hard...";

So you end up with code like:
string user_month;
getline(cin, user_month);
if (user_month == "january") {
    cout << capricorn;
} else if (user_month == "february") {
    cout << aquarius;
} else if (// etc...

A bit easier to read. Now we see the structure of our program much clearer. We just want to cout something depending on month.
Now, there are things you haven't learned about. E.g., using a "map" (a lookup table):
#include <unordered_map>

// In your function
// Map of key-value pairs
std::unordered_map<std::string, std::string> um =
{ {"january", "You are a Capricorn\n etc etc\n"} };

// Read month, then:
auto res = um.find(user_month);
if (res != um.end()) {
    // Found in map. res->first is key, res->second is value.
    std::cout << res->second;
} else {
    // Invalid month
    std::cout << "Error: invalid input";
}

Another way would be to store the strings in an array and map the months to array indices (0-11). But you'd need an if-cascade for that too, so maybe that defeats the purpose.
Note that for actual zodiac signs, the task would be a bit more difficult, because they are not about months, but date ranges (e.g., march 21. - april 19.).

A: Here's how I would set this up.
I would use a std::map to map from month names to the output you want to associate with it.
std::map::find will perform a lookup and return an iterator for a key-value pair of month and associated output, or an end iterator if it is not found.
A std::optional is a nice way of either having a value or not and it a little less heavy-handed than throwing an exception.
And finally, make good use of functions to describe your program in understandable pieces.
#include <optional>
#include <string>
#include <iostream>
#include <map>

std::map<std::string, std::string> signs = {
    { "january", "You are a capricorn..." },
    { "february", "You are an Aquarius..." },
    // ...
};

std::string getUserInput() {
    std::string input;
    getline(std::cin, input);
    return input;
}

std::optional<std::string> tryGetOutput(const std::string& month) {
    auto it = signs.find(month);
    if (it == signs.end()) return {};
    return it->second;
}

int main() {
    std::string input = getUserInput();
    std::optional<std::string> output = tryGetOutput(input);
    if (!output.has_value()) {
        std::cout << "unknown month" << std::endl;
        return -1;
    }
    std::cout << output.value() << std::endl;
}


text:
Q: Reloading div containing PHP script every minute My page has a div where the content is written by a PHP script.

     <?php

        if(isset($_COOKIE["datetoday"])) {
           echo $_COOKIE["datetoday"];
        }

        if(isset($_COOKIE["month"]) and isset($_COOKIE["day"]) and isset($_COOKIE["year"])) {
          $showfeast = file_get_contents('http://feed.evangelizo.org/reader.php?date='.$_COOKIE["year"].$_COOKIE["month"].$_COOKIE["day"].'&type=feast&lang=AM');
          $showliturt = file_get_contents('http://feed.evangelizo.org/reader.php?date='.$_COOKIE["year"].$_COOKIE["month"].$_COOKIE["day"].'&type=liturgic_t&lang=AM');
          $showsaints = file_get_contents('http://feed.evangelizo.org/reader.php?date='.$_COOKIE["year"].$_COOKIE["month"].$_COOKIE["day"].'&type=saint&lang=AM');
          if ( !empty($showfeast) ) {
            echo ' - '.$showfeast;
          }
          else if ( !empty($showliturt) ) {

            $stlit = strpos($showliturt, 'of the');
            if ( $stlit ) {
               $trunclitur = substr($showliturt, $stlit+7);
               echo ' - '.$trunclitur;
            }
            else {
              $stlits = strpos($showliturt, 'aint');
              if ( $stlits ) {
                ;
              }
              else {
               echo ' - '.$showliturt;

              }

            }

          }
          if ( !empty($showsaints) ) {
            echo ' - '.$showsaints;
          }
        }

        $widfeast = strlen($showfeast);

        $widlitur = strlen($trunclitur);

        $widsaint = strlen($showsaints);

        $widtha = $widfeast + $widsaint;

        $widthb = $widlitur + $widsaint;

        if ($widtha > 240 || $widthb > 240) {
          echo ''.$showsaints.'';
        }

     ?>

How do I tell the HTML page to reload this div after midnight of the current date?  The problem is that the information shown is outdated the first few times I open the page the next day.  Then it has the current information.  I store the date in cookies, then with the date I get the other information.  If I make the cookies expire too quickly, then I end up with no information at all.  So I want to try to refresh the div automatically.
How do I make a jquery call to reload the div every few hours, with the PHP script shown?

A: The PHP code is actually not relevant. The jQuery load() function will load the resulting HTML from any PHP page into a specified div
http://api.jquery.com/load/
This code will re-load the content into the div every 3,600,000 milliseconds (or every hour)
setInterval(function(){
    $('#divId').load('theContent.php');
}, 3600000);

A: You need to set the number of milliseconds until midnight.
window.setTimeout(function() {
     $('#myDiv').load('someScript.php');
},milliseconds)


text:
Q: how to display the table in c? #include <stdio.h>
#include <math.h>

int main(void)
{
    // input value

        int num, lower, upper;
        double squareroot;
        int square;
        int cube;

        printf("enter your number:\n");
        scanf_s("%d", &num);

        do
        {
            printf("the lower value limit is ");
            scanf_s("%d", &lower);
        } while (lower < 0 || lower > 50);

        do
        {
            printf("the upper value limit is ");
            scanf_s("%d", &upper);
        } while (upper < 0 || upper > 50);

        // the formular to find the squareroot, square, cube
        squareroot = sqrt(num);
        square = num * num;
        cube = num * num * num;

        //a for loop
        for (num = 0; num <= upper; num++) {

            printf("*base number*  ||  *square root*  ||  *square*  ||  *cube*\n");
            printf("*%d*           ||   *%f*      ||   *%ld*      ||  *%ld*\n",
                lower, squareroot, square, cube);

        }

    return 0;
}

i try to make a table to display the base number, square root, square, and cube
and set a limit for the table.
for example, if I input the lower number is 1 and the upper number is 5 then the table will stop at 5 then display the square root, square, and cube

A: At least this problem:
Mismatched specifiers/type
int square;
int cube;
...
printf("*%d*           ||   *%f*      ||   *%ld*      ||  *%ld*\n",
  lower, squareroot, square, cube);

Use "%d" with int, not "%ld".
Move assignments
Following assignments need to be inside the loop.
    for (num = 0; num <= upper; num++) {
      square = num * num;
      cube = num * num * num;

Save time.  Enable all compiler warnings

A: Try the Below Code Make all Changes I have added Comments to Clarify why I made The
#include <stdio.h>
#include <math.h>

int main(void)
{
    // input value
    int lower, upper;
    double squareroot;
    int square;
    int cube;

    //Read the Limits First
    printf("Enter the Lower Limit: ");
    scanf("%d", &lower);
    printf("Enter the Upper Limit: ");
    scanf("%d", &upper);

    //Instead of Declaring an Entire Loop You Can Just Use an If Statement this Reduces Code Complexity
    //You can also Set Your Limits
    if(upper > 0 && upper < 50 && lower > 0 && lower < 50)
    {
        //THen Enter Actual Code
        //Also Dont Set Lower to 0 It will Change Your Actual Value Instead Take another Loop Var
        for (int i = lower; i <= upper; i++)
        {
            //Then Perform all Functions on i
            squareroot = sqrt(i);
            square = i * i;
            cube = i * i * i;
            printf("*base number*  ||  *square root*  ||  *square*  ||  *cube*\n");
            printf("*%d*           ||   *%f*      ||   *%d*      ||  *%d*\n", i, squareroot, square, cube);
        }
    }
    return 0;
}

A: Several issues:

*

*You go to the trouble of asking for lower, but you don't use it to control your loop - your loop should befor( int num = lower; num <= upper; num++)
{
  ...
}
Put another way, if you always intend for your loop to start from zero, then you don't need lower at all.

*You need compute the square root, square, and cube of num for each iteration of the loop.  Instead, you're doing it once before the loop and just printing those same values over and over again;

*You only need to print your table header once, outside the body of the loop;

You can compute your square root, square, and cube all as part of the printf statement:
printf( "%d %f %d %d\n", num, sqrt((double) num), num * num, num * num * num );

Field width specifiers are your friends - you can tell printf exactly how wide you want each column to be.  Example:
printf( "%6d%12.2f%12d%12d", num, sqrt((double) num), num * num, num * num * num );

This means the column for num is 6 characters wide, the column for square root is 12 characters wide, with 3 characters reserved for the decimal point and two following digits, and the columns for square and cube are 12 characters wide.  Example:
printf( "%6s%12s%12s%12s\n", "base", "root", "square", "cube" );
printf( "%6s%12s%12s%12s\n", "----", "----", "------", "----" );

for (int i = lower; i <= upper; i++ )
  printf( "%6d%12.2f%12d%12d\n", i, sqrt( (double) i ), i*i, i*i*i );

Which gives output like this (lower == 1, upper == 10):
  base        root      square        cube
  ----        ----      ------        ----
     1        1.00           1           1
     2        1.41           4           8
     3        1.73           9          27
     4        2.00          16          64
     5        2.24          25         125
     6        2.45          36         216
     7        2.65          49         343
     8        2.83          64         512
     9        3.00          81         729
    10        3.16         100        1000

Full example:
#include <stdio.h>
#include <math.h>

int main( void )
{
  int lower = 0, upper = 0;

  printf( "Gimme a lower value: " );
  while ( scanf( "%d", &lower ) != 1 || (lower < 0 || lower > 50 ))
  {
    /**
     * Clear any non-numeric characters from the input stream
     */
    while ( getchar() != '\n' )
      ; // empty loop
    printf( "Nope, try again: " );
  }

  printf( "Gimme an upper value: " );
  while ( scanf( "%d", &upper ) != 1 || (upper < lower || upper > 50 ))
  {
    while( getchar() != '\n' )
      ; // empty loop
    printf( "Nope, try again: " );
  }

  printf( "%6s%12s%12s%12s\n", "base", "root", "square", "cube" );
  printf( "%6s%12s%12s%12s\n", "----", "----", "------", "----" );

  for (int i = lower; i <= upper; i++ )
    printf( "%6d%12.2f%12d%12d\n", i, sqrt( (double) i ), i*i, i*i*i );

  return 0;
}

I've written the input section such that it will reject inputs like foo or a123.  It will not properly handle inputs like 12w4, but that would make the example more complicated than it needs to be (you're not asking about input validation, you're asking about computation and formatting).  Example run:
$ ./table
Gimme a lower value: foo
Nope, try again: a123
Nope, try again: 123
Nope, try again: 1
Gimme an upper value: 100
Nope, try again: 50
  base        root      square        cube
  ----        ----      ------        ----
     1        1.00           1           1
     2        1.41           4           8
     3        1.73           9          27
     4        2.00          16          64
     5        2.24          25         125
     6        2.45          36         216
     7        2.65          49         343
     8        2.83          64         512
     9        3.00          81         729
    10        3.16         100        1000
    11        3.32         121        1331
    12        3.46         144        1728
    13        3.61         169        2197
    14        3.74         196        2744
    15        3.87         225        3375
    16        4.00         256        4096
    17        4.12         289        4913
    18        4.24         324        5832
    19        4.36         361        6859
    20        4.47         400        8000
    21        4.58         441        9261
    22        4.69         484       10648
    23        4.80         529       12167
    24        4.90         576       13824
    25        5.00         625       15625
    26        5.10         676       17576
    27        5.20         729       19683
    28        5.29         784       21952
    29        5.39         841       24389
    30        5.48         900       27000
    31        5.57         961       29791
    32        5.66        1024       32768
    33        5.74        1089       35937
    34        5.83        1156       39304
    35        5.92        1225       42875
    36        6.00        1296       46656
    37        6.08        1369       50653
    38        6.16        1444       54872
    39        6.24        1521       59319
    40        6.32        1600       64000
    41        6.40        1681       68921
    42        6.48        1764       74088
    43        6.56        1849       79507
    44        6.63        1936       85184
    45        6.71        2025       91125
    46        6.78        2116       97336
    47        6.86        2209      103823
    48        6.93        2304      110592
    49        7.00        2401      117649
    50        7.07        2500      125000


text:
Q: Objective-C display PDF from server I am trying to display a PDF from a server in my app.
I tried going the route of Document Interaction Controller, but that only display files within a app, not off the web :(
if (URL) {
    // Initialize Document Interaction Controller
    self.documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:URL];

    // Configure Document Interaction Controller
    [self.documentInteractionController setDelegate:self];

    // Preview PDF
    [self.documentInteractionController presentPreviewAnimated:YES];
}

Would UIWebView be my best solution to display PDF from server? Not a PDF on a website, but on a server \SEVERNAME\LHSD\PDFs\example.pdf

A: The best way to display pdf file in objective-c is load pdf file in UIWebView.
Try this :
NSString *stringUrl = @"YOUR-SERVER'S-PDF-FILE-URL";
    NSURL *url = [NSURL URLWithString:stringUrl];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

UIWebView *webViewObj = [[UIWebView alloc] initWithFrame:CGRectMake(10, 10, 300, 450)];
    [webViewObj loadRequest:request];
    [self.view addSubview:webViewObj];


text:
Q: Mongo db import / export Object id overwritten In my Mongo DB I have a number of collections that reference each other using the auto generated unique Object id e.g ObjectId("5459a7fb3fcd7efe772c0816");
Now, that's all fine.
I'm currently developing on the site on two different setups, importing / exporting my collections in order to format the data and keep it in sync. When doing so new Object Ids are created disregarding the existing ones. This causes the app to break since my application references ids across different collections.
Would it be better for me to create my own id and disregard the Object id?
Or is there an entirely different approach all together?

A: The answer to this question is: Read the documentation! http://docs.mongodb.org/manual/tutorial/backup-with-mongodump/


text:
Q: How to remove 0s and 1s from my JSON obj This is my code :
...
$response = mysqli_fetch_all($result);
$json = json_encode($response);

echo json_encode($json);
...

and it returns some kind of JSON like this:
"{0: mystring :D, 1: myotherstring :(}"

How can I remove those 0s and 1s? I know I didn't explain well, but it is actually hard for me to explain :(... Thanks in advance :)

A: Your "0"s and "1"s are the keys in your JSON object; if you want to remove them, it seems an array would suit your need better. You could convert it with the following and end up with an array which only contains the values:

var json = {"0":"foo","1":"bar"};
var array = [];

for (var x in json) {
  array.push(json[x]);
}


text:
Q: What should I store as my index in client code? I'm using Google App Engine and storing users. Before, I was using MySQL with an auto-incrementing int for my userId field, but now GAE auto generates a key for each new entity I store, such as g5kZXZ-aGVsbG93b3JsZHIKCxIEVXNlchgNDA, but they also automatically generate an auto-incrementing ID int too.
Which one should I use in my client code to store as the userId? Are there any advantages to using the long key that GAE generates, or is using the small int ID the same thing in terms of performance and look ups? Are there any advantages to one over the other, or is there practically no difference?
Edit: Sorry my question was not clear enough. Here's what I'm asking:
It's not about length, but does having the lookup key put me a step ahead of not having it? Because if I wanted to look up a user, I'd have to look him up by email, but now that I have the key for that row in the "table", does this give me any sort of advantage?

A: Either one is fine, there's no performance difference between using a long string of letters or a short one to identify users.

A: Remember that the generated entity ID is not guaranteed to be a monotonically increasing value.


text: Q: downloading ios7.1 simulator in xcode I have downloaded and installed version 5.1.1 of xcode. I have problem with downloading the ios 7.0 simulator and ios6.1 simulator. It is staying without any progress. I am having MAcOSX 10.9.2 . Any work around for me?


text:
Q: elasticsearch Cluster not rebalancing after adding nodes I have a cluster with 2 nodes,  I added 3 more nodes which joined the cluster.  I am able to send request to them and get results.  however when i check they dont have any documents.  I have a 5 shard index and i was expecting that each node would receive a shard?

{
    cluster_name: "es-poc",
    status: "green",
    timed_out: false,
    number_of_nodes: 5,
    number_of_data_nodes: 5,
    active_primary_shards: 5,
    active_shards: 10,
    relocating_shards: 0,
    initializing_shards: 0,
    unassigned_shards: 0,
    delayed_unassigned_shards: 0,
    number_of_pending_tasks: 0,
    number_of_in_flight_fetch: 0,
    task_max_waiting_in_queue_millis: 0,
    active_shards_percent_as_number: 100
}

A: Thanks for the responses,  the issue was that the versions where not the same on all the nodes,  the existing members had 2.3.4,  while the new members had 2.3.3.
i found this out by doing:
POST _cluster/reroute?explain
{
  "commands": [
    {
       "move" :
            {
              "index" : "event4", "shard" : 0,
              "from_node" : "Toad", "to_node" : "Amelia Voght"
            }
        }

  ]
}

in the response i saw this in the explain section
 {
               "decider": "node_version",
               "decision": "NO",
               "explanation": "target node version [2.3.3] is older than source node version [2.3.4]"
            },

A: Rebalancing depends on several settings.
Shards Allocation

Regardless of the result of the balancing algorithm, rebalancing might not be allowed due to forced awareness or allocation filtering.


text:
Q: Confidence intervals and functions of an estimator? I'm studying non-parametric estimators for survival functions and for the Nelson-Aalen estimator we have that the estimator for the survival function is $\exp(-\hat Y)$ (i.e. exponential of negative $\hat Y$ which is the estimator for the cumulative hazard rate).
Now my questions is, since the Survival function is just the negative exponential of the cumulative hazard, if we find a confidence interval for the cumulative hazard can I just take the negative exponential of that confidence interval to get an (approximate) confidence interval of the SURVIVAL function, or is there a better method (but not like using the delta method I've read about).
So lets say the 95% confidence interval for a cumulative hazard is [0.04,0.13]
then could I say that the 95% CI for the corresponding survival function is:
[exp(-0.13), exp(-0.04)] since Survival function = $\exp( - \text{cumulative hazard})$.
This actually is what one of the examples in my textbook does but I encountered a similar problem before when i was doing linear regression and I had something like
log(y)= a + bx + error and to construct a confidence interval for y I would need to do:
$y= \exp (a + bx + \text{error})$ so there was that exponential relationship and again if we had confidence intervals for the regression would there be any special allowance we have to make for the fact that we are exponentiating.
I know this may seem kinda broad and that I'm asking more for a detailed explanation then a simple answer so feel free just pour out your thoughts and examples, the more the merrier.

A: The issue raised in this question probably arose from the distinction between confidence intervals and prediction intervals and how they take into account the "error" terms. Confidence intervals represent error in the expected value. A prediction interval adds in the residual "error" to illustrate the uncertainty in predicting an individual case.
In a linear regression of the form $y=a+bx+\epsilon$, the confidence interval for a point estimate $\hat{y}_i = \hat a +\hat b x_i$, based on the estimates of the regression coefficients $\hat a$ and $\hat b$ and a covariate value $x_i$, doesn't explicitly involve $\epsilon$, as $\hat y$ is an estimate of the expected value (at $\epsilon=0$ under the assumptions of ordinary least squares). The variance in $\epsilon$ helps determine the (co)variances of $\hat a$ and $\hat b$ and thus the confidence interval for $\hat y$, but doesn't further enter the calculation.
In that situation, as the page linked by Kjetil B Halvorsen in a comment indicates, you are welcome to use any strictly monotone invertible transformation of $\hat y$ along with its confidence interval and still end up with a valid confidence interval for the transformed $\hat y$. Non-parametric survival models, as in the current question, are modeling expected survival, so that's what's done when transforming the confidence interval for an estimated cumulative hazard $\hat \Lambda(t)$ to the corresponding expected survival $\hat S(t) = \exp\left( -\hat \Lambda(t)\right)$.*
If you want to illustrate the error in making a prediction about an individual case, you must take into account the further variance arising from $\epsilon$. That's where you need to consider just how $\epsilon$ was incorporated into the model and how, in individual cases, it adds to the predicted expected value. That's the issue raised in the next to last paragraph of this question, and would differ, for example, between modeling individual observations in the form $\log(y) = a + bx +\epsilon$ and modeling the mean value $\bar y$ of the response with a generalized linear model, as explained on this page.
Parametric survival models that assume particular distributions of survival times around their expected values can provide prediction intervals in addition to confidence intervals. This document is a convenient reference to the underlying principles.

*This relationship between cumulative hazard and survival is general, not restricted to the Nelson-Aalen estimate mentioned in this question.


text:
Q: How to hide a :after link for mobile layout Bootstrap 3 I have created a navigation row that includes image sprites.  I would also like it to have a short text description on the right of each icon (eg Home, Services, etc), but need the text hidden for mobile layout and this is where I am getting stuck:
Stylesheet is as follows:
.lnx { position: relative; display: table-row; padding: 0; margin: 8px 0; }
.lnx li, .lnx a { height: 54px; display: table-cell !important; }
.lnx li.spritehom { left: 0; min-width: 50px !important; display: table-cell; background: url('../images/btnsprite.png') no-repeat 0 0; }
.lnx li.spritehom:hover, .lnx li.active.spritehom { background: url('../images/btnsprite.png') no-repeat 0px -54px; }

.spritehom:after { content: "home"; clear: left; display: table-cell !important; vertical-align: middle;height: 54px; }
.spriteabt:after { /*content: "about"; */
                clear: left; display: table-cell !important; vertical-align: middle; height: 54px; }
.spritesvs:after { /*content: "services"; */
                clear: left; margin: 0 15%; display: table-cell !important; vertical-align: middle; height: 54px; }
.spritepor:after { /*content: "portfolio"; */
                clear: left; margin: 0 15%; display: table-cell !important; vertical-align: middle; height: 54px; }
.spritecon:after { /*content: "contact"; */
                clear: left; margin: 0 15%; display: table-cell !important; vertical-align: middle; height: 54px; }

.lnx li.spriteabt { left: 0; min-width: 50px !important; display: table-cell;
 background: url('../images/btnsprite.png') no-repeat 0 -108px; }
.lnx li.spriteabt:hover, .lnx li.active.spriteabt  {
background: url('../images/btnsprite.png') no-repeat 0px -162px; }
.lnx li.spritesvs { left: 0; min-width: 50px !important; display: table-cell;
 background: url('../images/btnsprite.png') no-repeat 0 -216px; }
.lnx li.spritesvs:hover, .lnx li.active.spritesvs  {
background: url('../images/btnsprite.png') no-repeat 0px -270px; }
.lnx li.spritepor { left: 0; min-width: 50px !important; display: table-cell;
background: url('../images/btnsprite.png') no-repeat 0 -324px; }
.lnx li.spritepor:hover, .lnx li.active.spritepor  {
background: url('../images/btnsprite.png') no-repeat 0px -378px; }
.lnx li.spritecon { left: 0; min-width: 50px !important; display: table-cell;
 background: url('../images/btnsprite.png') no-repeat 0 -432px; }
.lnx li.spritecon:hover, .lnx li.active.spritecon  {
background: url('../images/btnsprite.png') no-repeat 0px -486px; }

Page layout is like this:
<!DOCTYPE html>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Test template</title>

<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/lfstyle.css" rel="stylesheet">
<link href="css/lfstyle.less rel="stylesheet/less">

&nbsp

Slogan

T: 01234 567890    E: me@you.com

Hello, world!

Please could anyone advise how I can hide the :after links for mobile layout?  I am very comfortable with CSS and HTML.  Not as much so with less, but I am always willing to learn.
Many thanks in advance.

A: Wrap the text in a span with class hidden-xs, and it will only show on sm, md and lg.

 Text


text:
Q: Society and Drill of Cambridge meaning When talked about James Clerk Maxwell, James Forbes wrote:

He is not a little uncouth in manners, but withal one of the most
original young men I have met. . . . He is a singular lad, and shy
[but] very clever and persevering. . . . I am aware of his exceeding
uncouthness, as well mathematical as in other respects. . . . I
thought the Society and Drill of Cambridge the only chance of
taming him and much advised his going . . . I should think he might
be a discoverer.

What does it mean here by the Society and Drill of Cambridge? I've searched on Google but there's hardly information on Internet.
Please help me.
Thanks.

A: "Society" - The social and cultural aspects of life at a university.
"Drill" - The rule-based and repetitive aspects of life at university.
"Cambridge" refers to the university of Cambridge, the top Maths and science university at the time.
The notion being that Young JCM needed to learn to work with others (work in scientific society) and to be required to follow regular rules (follow a drill) in order to become a useful mathematician and scientist.


text:
Q: How to resolve circular dependencies when using go modules and cgo In my project, I am using callbacks for bi-directional calls from C into go and vice versa using CGO. I resolved the issue of circular dependencies by compiling the C part into a library, then compiling the go part into a library, then a final linker pass puts it all together. This is working fine when not using go modules. Go source files are listed on the command line explicitly. I have been told that as of go 1.12 "this is not the right way to do it".
As the project has grown, I now want to use go modules. Unfortunately, this changes the behaviour of the go compiler. It now wants to resolve external dependencies and implicitly includes them in the output file. Due to the circular dependency, it now always ends up with an undefined reference or multiple definitions. How to resolve circular dependencies when using cgo and go modules "the right way"?
This is a minimal example to illustrate the problem. Remove the file-name "hello.go" from the call to go in the Makefile to see how it falls apart.
This is the error message:
hello.c:3: multiple definition of `c_hello'; $WORK/b001/_cgo_hello.o:/tmp/go-build/hello.c:3: first defined here

Makefile:
libchello.a: Makefile hello.c
    gcc -fPIC -c -o chello.o hello.c
    ar r libchello.a chello.o
libgohello.a: Makefile hello.go libchello.a
    env CGO_LDFLAGS=libchello.a go build -buildmode=c-archive -o libgohello.a hello.go
main: Makefile main.c libgohello.a libchello.a
    gcc -o main main.c libchello.a libgohello.a -pthread
.PHONY: clean
clean:
    rm -f main *.a *.o
    echo "extern void go_hello();" > libgohello.h

hello.go:
package main
/*
extern void c_hello();
*/
import "C"
import "time"
import "fmt"
//export go_hello
func go_hello() {
    fmt.Printf("Hello from go\n")
    time.Sleep(1 * time.Second)
    C.c_hello()
}
func main() {}

libgohello.h:
extern void go_hello();

hello.c:
#include "libgohello.h"
#include <stdio.h>
void c_hello() {
    printf("Hello from c\n");
    go_hello();
}

main.c:
void c_hello();
int main() {
    c_hello();
}

go.mod:
module hehoe.de/cgocircular

A: If you look at the verbose output from the go build command, you will see that when compiling the directory as a complete go package, the main.c file is being included as part of the C code used in hello.go.
From the documentation:

When the Go tool sees that one or more Go files use the special import "C", it will look for other non-Go files in the directory and compile them as part of the Go package

The easiest solution here is to separate the main C and Go packages, so that they don't interfere with each other's build process. Testing this out, removing the main.c file will build libchello.a and libgohello.a, and then adding it back in will complete the build of main.


text:
Q: Improve Tesseract result for scanned image I have a processed scanned image which I am attempting to perform OCR on. The image looks like 1 after converting it to binary and scaling it, however Tesseract is unable to retrieve the alphanumericals that stand out from the rest.
Processed image to perform OCR on
The expected result would be "123112" but I am getting jibberish such as "*53";.gxuimSaabz'ssiiämFi"???
1231 12 5
*".
Tessaract instantiated as follows through JNI (implemented in Java 8):
            instance = new Tesseract();  // JNA Interface Mapping
            instance.setLanguage("swe");
            instance.setOcrEngineMode(ITessAPI.TessOcrEngineMode.OEM_TESSERACT_ONLY);

Any ideas how I can improve the result?


text:
Q: When exactly is glClear(GL_DEPTH_BUFFER_BIT) and glClear(GL_COLOR_BUFFER_BIT) necessary? In a nutshell, when should the color buffer be cleared and when should the depth buffer be cleared? Is it always at the start of the drawing of the current scene/frame? Are there times when you would draw the next frame without clearing these? Are there other times when you would clear these?

A: Ouff... even though it's a simple question it's a bit hard to explain ^^
It should be cleared before drawing the scene again. Yes, every time if you want to avoid strange and nearly uncontrollable effect.
You don't want to clear the two Buffers after swapping when you bind the scene to a texture () but right after that there's no more use for it.
The Color Buffer is as the name says a buffer, storing the computed color data. For better understanding, imagine you draw on a piece of paper. Each Point on the Paper knows which color was drawn on top of it - and that's basically all of it.
But: without the Depth Buffer, your Color Buffer is (except some special cases like multiple renderpasses for FX effects) nearly useless. It's like a second piece of paper but in a gray scale. How dark the gray is decides how far the last drawn pixel is away from the screen (relative to the zNear and zFar clipping plane).
If you instruct OpenGl to draw another primitive, it goes pixel by pixel and checks, which depth value the pixel would have. If it's higher than the value stored in the Depth Buffer for that pixel, it draws over the Color Buffer in that position and does nothing if the value is lower.
To recap, the Color Buffer stores the picture to be drawn on your screen, and the Depth Buffer decides weather a part of your primitive get's drawn in this position.
So clearing the Buffers for a new scene is basically changing the Paper to draw in top. If you want to mess with the old picture, then keep it, but it's in better hands on the monitor (or on the wall^^).


text:
Q: iPhone SHA1 inconsistent I try to invoke the following code to get SHA1 working on the iPhone:
uint8_t digest[CC_SHA1_DIGEST_LENGTH] = {0};
CC_SHA1(keyData.bytes, keyData.length, digest);
keyData simply contains a constant string of hex code. However the hash hex that I get as a result of this does not match what online SHA1 generators output for the same input hex, but even more wierdly, it does not stay consistent. In other words, I run the hash function once and get one result, twice - another.
Can anyone help, or point me to what I'm doing wrong?
Thank you in advance!

A: Update:
I managed to fix the floating problem, I wasn't properly handling the data. The hash is now firmly crooked, although still incorrect. Here is a hex dump of the data:
<029a2112 0004231b 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 000000>
And here's a hex dump of the SHA1 hash:
<244b463b 7a0b2f48 96cfaa01 012823f5 25943ff5>

A: No, I was simply mistaken. Instead I used HashCalc by Slavasoft and its output matches that of the iPhone. Forget all the online crap! This issue is closed.


text:
Q: Ingress Nginx inject subpath to root URI I'm trying to do the following uri manipulation in the Ingress-Nginx controller (helm.sh/chart=ingress-nginx-4.2.0)
If the URI is exactly /, pass https://example.com/ -to-> https://backend_server/devportal/
But if the URI matches this pattern (/a|/b|/c), then just forward to https://backend_server/a|b|c
The seemingly simple requirement worked like this in an Nginx config:
server {
  listen       *:443 ssl; # Listen on port 443
  location / {
    proxy_pass            https://backend_server/devportal/;
    proxy_redirect        https://backend_server/devportal/ /;
    # proxy_cookie_path     /devportal /;
  }
  location ~ (/a|/b|/c) {
    proxy_pass      https://backend_server;
    proxy_redirect  https://backend_server/devportal/ /;
  }
}

Which I can't replicate on ingress-nginx. I tried the following:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/backend-protocol: HTTPS
    nginx.ingress.kubernetes.io/proxy-connect-timeout: 90s
    nginx.ingress.kubernetes.io/proxy-read-timeout: 90s
    nginx.ingress.kubernetes.io/proxy-redirect-from: /devportal/
    nginx.ingress.kubernetes.io/proxy-redirect-to: /
    nginx.ingress.kubernetes.io/proxy-send-timeout: 90s
    nginx.ingress.kubernetes.io/rewrite-target: /devportal/$1
    # nginx.ingress.kubernetes.io/app-root: /devportal
  name: multitenancy-ingress
  namespace: wso2
spec:
  rules:
  - host: example.com
    http:
      paths:
      - backend:
          service:
            name: my-svc
            port:
              name: servlet-https
        path: /(.*)
        pathType: ImplementationSpecific
  tls:
  - hosts:
    - example.com
    secretName: my-tls

When going to https://example.com/, the backend application receives a / request (GET / HTTP/1.1 302)

*

*Why isn't the rewrite working

*How would I cater for both use-cases in the ingress object

A: Did you try to use nginx.ingress.kubernetes.io/stream-snippet  annotation for ingress?
Can you try to use the working configuration by using this annotation like the in the docs :
https://github.com/kubernetes/ingress-nginx/blob/main/docs/user-guide/nginx-configuration/annotations.md#stream-snippet


text:
Q: Constraining  to the bounds of an angled  w/ CSS (JSFiddle link attached) I would like the <p> in my document to be contained within an angled <section> container so as to create stepped lines for the paragraph. Ideally I'd like the paragraph take the shape of an parallelogram. As it stands, when I rotate my my paragraph so that the lines are horizontal, the paragraph extends beyond the bounds of the <div>. See my JSFiddle link below:
http://jsfiddle.net/aredtiefilm/sUymx/2/
When I try overflow options, the best I can do is hide the sections of the paragraph that are outside the <section>. I'd like to force the contents of the paragraph to take the shape of the container, without hiding or scrolling.  Is this posible?

A: Use following css for paragraph element. It will work fine.
MODIFIED CSS :
p{
  border: 1px solid blue;
}

A: Not perfect, but this the best that I think that you can get.
Replace rotate by skew:
section{
    color: #4A2583;
    -ms-transform:skewX(10deg);
    -moz-transform:skewX(106deg);
    -webkit-transform:skewX(10deg);
    -o-transform:skewX(10deg);
    transform:skewX(10deg);
    width: 200px;
    border: 1px solid red;
    display: block;
    position: relative;
    left: 200px;
}

You don't need to style the p, it's useless. (You can not rotate the individual lines, you can only rotate it as a block)
You need to limit the angle because the letters are being also skewed, if you do it too much that will be ugly.
updated fiddle


text:
Q: Bash shell scripting , how to use pipes in command Trying to use pipes in bash script. This works fine on my Linux shell but bash script errors out. What am I doing wrong?
  #!/bin/bash
  #some code
  cmd="cat file2 | grep ':'  | awk -F \":\" '{print \$1}' > pool_names"
  echo $cmd
  exec $cmd

I see this error
cat: invalid option -- 'F'
Try 'cat --help' for more information.

A: The bash builtin exec command has a completely different goal, as explained at https://www.computerhope.com/unix/bash/exec.htm .
You have to substitute exec with eval in order to get your script working, or as alternative, as suggested by @Jonathan Leffler in a comment, you may use bash -c "$cmd".

A: In the shell, a "simple command" is a sequence of optional variable assignments and redirections, in any sequence, optionally followed by words and redirections, terminated by a control operator. (See https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_09_01), while a pipeline is a sequence of one or more commands separated by the control operator '|'  (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_09_02).  When the shell sees the line exec $cmd it does not see the control operator |, so that is a simple command.  (This has nothing to do with exec, and the same behavior will occur with any command.)  It then expands the variables in the line and follows the rule the first field shall be considered the command name and remaining fields are the arguments for the command, so exec is called with a bunch of arguments.  exec does not attempt to interpret the arguments as shell operators (perhaps you meant to use eval instead of exec), but just passes all the arguments on to cat.


text:
Q: Does pointer notation of structures have specific style of accessing elements? struct b
{
     int c;
};

struct a
{
  struct b d[10][10];
}*e;

for(i=0;i<10;i++)
{
    e->d[i][0].c=11;
    //(*(*(d+i)+0)) will give you the element at that location
    e->(*(*(d+i)+0)).c=22;
    //(*(d+i)+0)-> will give us pointer to that particular element.
    e->(*(d+i)+0)->c=33;
}

within the for loop first notation is working fine but the other two notations are showing an error saying

error: expected a field name

Two notations works fine if we use only with structure b as below
struct b d[10][10];

why is that? Is there any specification like we should not use '(' just after '->'?

A: What these lines are supposed to mean?
e->(*(*(d+i)+0)).c=22;
e->(*(d+i)+0)->c=33;

The only valid token after is -> is a field name. In this case, d.

I think, you want something like this:
(*(*(e->d+i)+0)).c=22;
(*(e->d+i)+0)->c=33;


text:
Q: Bisection Method number of steps for convergence For the bisection method, determine the formula
$$n \geq \frac{\log(b_0-a_0)-\log(\epsilon)}{\log(2)}-1$$
for the number of steps to guarantee that $|{r-c_n}| < \epsilon.$
This is one of the questions from my numerical analysis class. I understand how to use the bisection method, but I don't understand the analysis of the method or how to start deriving an answer.

A: You start with an interval $(a_0,b_0)$ which contains the root, so the error in the root is at most $\frac 12(b_0-a_0)$  Each step shrinks the interval by a factor $2$, so the error after $n$ steps is $\frac 1{2^{n+1}}(b_0-a_0)$  You need to solve $\frac 1{2^{n+1}}(b_0-a_0)\lt \epsilon$ for $n$


text:
Q: Use a for loop with google maps for adding a marker I want to add a for loop to loop through an array and add the markers to the map, I have tried to dabble something up but I just can't get a break, the lat / lon is being echo'd as (##.#########,-##.########) format I've tried many different ways but it just seems to not want to add it to the map.
<script>
var initialLocation;
var map;
var markersArray = [];
var gMarkerLatitude = new Array();
var gMarkerLongitude = new Array();
var markers = [];
<?php $i = 0; while($stmt -> fetch()) { ?>
gMarkerLatitude[<?php echo $i; ?>] = ["<?php echo $gLatitude; ?>"];
gMarkerLongitude[<?php echo $i; ?>] = ["<?php echo $gLongitude; ?>"];
<?php $i++; } ?>
function initialize() {
 var mapOptions = {
  zoom: 15,
  center: new google.maps.LatLng(56.7626362, -111.379652),
  mapTypeId: google.maps.MapTypeId.ROADMAP,
  disableDefaultUI: false,
  zoomControl: true,
  zoomControlOptions: {
    style: google.maps.ZoomControlStyle.LARGE
  }
};

  map = new google.maps.Map(document.getElementById('gmaps'),
  mapOptions);

  google.maps.event.addListener(map, 'click', function(event) {
    var latitude = event.latLng.lat();
    var longitude = event.latLng.lng();
    deleteOverlays();
    addMarker(event.latLng);
    updateTextFields(latitude, longitude);
  });

  google.maps.event.addListener(marker, 'click', function(event) {
    showInfo(window);
  });

}

function updateTextFields(lati, longi) {
  $('#inputLatitude').val(lati);
  $('#inputLongitude').val(longi);
}

function addMarker(location) {
  marker = new google.maps.Marker({
    position: location,
    map: map
  });
  markersArray.push(marker);
}

try {
for (i = 0; i < gMarkerLongitude.length; i++) {
  var marker = new google.maps.Marker({
    map: map,
    position: new google.maps.LatLng(gMarkerLatitude[i],gMarkerLongitude[i])
  })
  alert(new google.maps.LatLng(gMarkerLatitude[i], gMarkerLongitude[i]));
}

}
catch(err) {
  alert(err);
}

function deleteOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(null);
    }
    markersArray.length = 0;
  }
}

function loadScript() {
  var script = document.createElement('script');
  script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&' +
  'callback=initialize';
  document.body.appendChild(script);
}

$(document).ready(function() {
$(window).resize(function () {
    var h = $(window).height(),
        offsetTop = 190; // Calculate the top offset

    $('#gmaps').css('height', (h - offsetTop));
  }).resize();
  loadScript();
});

</script>

A: google.maps.LatLng takes two numbers as parameters but you are passing an array with a string in it. Try
gMarkerLatitude[<?php echo $i; ?>] = <?php echo $gLatitude; ?>;
gMarkerLongitude[<?php echo $i; ?>] = <?php echo $gLongitude; ?>;

assuming $gLatitude and $gLongitude are numeric

A: Which part is throwing the error? You might try adding visible: true to the markerOptions when creating each marker. Also make sure your lat/lng values are within the specified ranges:
Latitude is specified in degrees within the range [-90, 90].
Longitude is specified in degrees within the range [-180, 180].


text:
Q: Getting and setting state in scala Here is some code from the Functional Programming in Scala book:
  import State._

  case class State[S, +A](run: S => (A, S)) {
    def map[B](f: A => B): State[S, B] =
      flatMap(a => unit(f(a)))

    def map2[B, C](sb: State[S, B])(f: (A, B) => C): State[S, C] =
      flatMap(a => sb.map(b => f(a, b)))

    def flatMap[B](f: A => State[S, B]): State[S, B] = State(s => {
      val (a, s1) = run(s)
      f(a).run(s1)
    })
  }

  object State {
    type Rand[A] = State[RNG, A]

    def unit[S, A](a: A): State[S, A] =
      State(s => (a, s))

    // The idiomatic solution is expressed via foldRight
    def sequenceViaFoldRight[S, A](sas: List[State[S, A]]): State[S, List[A]] =
      sas.foldRight(unit[S, List[A]](List.empty[A]))((f, acc) => f.map2(acc)(_ :: _))

    // This implementation uses a loop internally and is the same recursion
    // pattern as a left fold. It is quite common with left folds to build
    // up a list in reverse order, then reverse it at the end.
    // (We could also use a collection.mutable.ListBuffer internally.)
    def sequence[S, A](sas: List[State[S, A]]): State[S, List[A]] = {
      def go(s: S, actions: List[State[S, A]], acc: List[A]): (List[A], S) =
        actions match {
          case Nil => (acc.reverse, s)
          case h :: t => h.run(s) match {
            case (a, s2) => go(s2, t, a :: acc)
          }
        }
      State((s: S) => go(s, sas, List()))
    }

    // We can also write the loop using a left fold. This is tail recursive like the
    // previous solution, but it reverses the list _before_ folding it instead of after.
    // You might think that this is slower than the `foldRight` solution since it
    // walks over the list twice, but it's actually faster! The `foldRight` solution
    // technically has to also walk the list twice, since it has to unravel the call
    // stack, not being tail recursive. And the call stack will be as tall as the list
    // is long.
    def sequenceViaFoldLeft[S, A](l: List[State[S, A]]): State[S, List[A]] =
      l.reverse.foldLeft(unit[S, List[A]](List()))((acc, f) => f.map2(acc)(_ :: _))

    def modify[S](f: S => S): State[S, Unit] = for {
      s <- get // Gets the current state and assigns it to `s`.
      _ <- set(f(s)) // Sets the new state to `f` applied to `s`.
    } yield ()

    def get[S]: State[S, S] = State(s => (s, s))

    def set[S](s: S): State[S, Unit] = State(_ => ((), s))
  }

I have spent hours thinking about why the get and set methods look the way they do, but I just don't understand.
Could anyone enlighten me, please?

A: The key is on the 3rd line:
case class State[S, +A](run: S => (A, S))

The stateful computation is expressed with the run function. This function represent a transition from one state S to another state S. A is a value we could produce when moving from one state to the other.
Now, how can we take the state S out of the state-monad? We could make a transition that doesn't go to a different state and we materialise the state as A with the function s => (s, s):
def get[S]: State[S, S] = State(s => (s, s))

How to set the state? All we need is a function that goes to a state s: ??? => (???, s):
def set[S](s: S): State[S, Unit] = State(_ => ((), s))

EDIT I would like to add an example to see get and set in action:
val statefullComputationsCombined = for {
  a <- State.get[Int]
  b <- State.set(10)
  c <- State.get[Int]
  d <- State.set(100)
  e <- State.get[Int]
} yield (a, c, e)

Without looking further down this answer, what is the type of statefullComputationsCombined?
Must be a State[S, A] right? S is of type Int but what is A? Because we are yielding (a, c, e) must be a 3-tuple made by the As of the flatmap steps (<-).
We said that get "fill" A with the state S so the a, c ,d are of type S, so Int. b, d are Unit because def set[S](s: S): State[S, Unit].
val statefullComputationsCombined: State[Int, (Int, Int, Int)] = for ...

To use statefullComputationsCombined we need to run it:
statefullComputationsCombined.run(1)._1 == (1,10,100)

If we want the state at the end of the computation:
statefullComputationsCombined.run(1)._2 == 100


text:
Q: Convert string into dataframe of speakers and text I would like to convert a string of text from a document into a dataframe with columns for section, speaker, role and text.
My input data is as follows. I have already extracted the list of speakers from another section of the document, and each speaker has the same role throughout the whole document, and the role is listed below the speaker every time they speak. Speakers and roles are text, not just identified by number, in the actual document - I just call them Speaker1 and Role1 for simplicity in this example.
all_text = """Section1\nSpeaker1\nRole1\nThis is the text spoken by the first speaker. Sometimes it contains
the string Speaker1, but when Speaker1 is in the words spoken section it is not on its own line.
Speaker2\nRole2\nNow someone else is talking.
Section2\nSpeaker2\nRole2\nMore words\nSpeaker1\nRole1\nMore words\nSpeaker2\nRole2
People can speak multiple times per section."""

section_list = ["Section1","Section2"]

speaker_list = ["Speaker1","Speaker2"]

So all_text looks like this:
print(all_text)

Section1
Speaker1
Role1
This is the text spoken by the first speaker. Sometimes it contains
the string Speaker1, but when Speaker1 is in the words spoken section it is not on its own line.
Speaker2
Role2
Now someone else is talking.
Section2
Speaker2
Role2
More words
Speaker1
Role1
More words
Speaker2
Role2
People can speak multiple times per section.

I would like to create the following output dataframe:
    Section     Speaker     Role    Text
0   Section1    Speaker1    Role1   This is the text spoken by the first speaker. ...
1   Section1    Speaker2    Role2   Now someone else is talking.
2   Section2    Speaker2    Role2   More Words
3   Section2    Speaker1    Role1   More words
4   Section2    Speaker2    Role2   People can speak multiple times per section.

Thank you in advance for any help!

A: With the data you provided it will be very difficult to fetch the data correctly.
So I had to tweek the data a little by adding Section for each data.
import pandas as pd

all_text = """Section1\nSpeaker1\nRole1\nThis is the text spoken by the first speaker. Sometimes it contains the string Speaker1, but when Speaker1 is in the words spoken section it is not on its own line.
Section1\nSpeaker2\nRole2\nNow someone else is talking.
Section2\nSpeaker2\nRole2\nMore words\nSection2\nSpeaker1\nRole1\nMore words\nSection2\nSpeaker2\nRole2
People can speak multiple times per section."""

li = all_text.splitlines()

speaker = []
section = []
role = []
text = []
print(li)
for index, item in enumerate(li):
    cat = index % 4
    print(cat, item)
    if cat == 0:
        section.append(item)
    elif cat == 1:
        speaker.append(item)
    elif cat == 2:
        role.append(item)
    else:
        text.append(item)

data_dict = {"Section": section, "Speaker": speaker, "Role": role, "text": text}

print(speaker, section, role, text)

df = pd.DataFrame(data_dict)

print(df)

I believe this is not the answer you are expecting.
If you do not want to change your data, then we EITHER need:

*

*List of Section names. (This can be used to identify if a section has changed when processing the data)

section_list = ["Section1", "Section2",..]
import pandas as pd

all_text = """Section1\nSpeaker1\nRole1\nThis is the text spoken by the first speaker. Sometimes it contains the string Speaker1, but when Speaker1 is in the words spoken section it is not on its own line.
Speaker2\nRole2\nNow someone else is talking.
Section2\nSpeaker2\nRole2\nMore words\nSpeaker1\nRole1\nMore words\nSpeaker2\nRole2
People can speak multiple times per section."""

li = all_text.splitlines()
section_list = ["Section1", "Section2", "Section3"]

speaker = []
section = []
role = []
text = []
temp_section = ""
section_list = ["Section1", "Section2", "Section3"]
for index, item in enumerate(li):
    cat = index % 4
    print(temp_section, "*", index, "*", item)

    if cat == 0 and item not in section_list:
        li.insert(index, temp_section)
        section.append(temp_section)
        continue

    if cat == 0:
        section.append(item)
        temp_section = item
    elif cat == 1:
        speaker.append(item)
    elif cat == 2:
        role.append(item)
    else:
        text.append(item)

data_dict = {"Section": section, "Speaker": speaker, "Role": role, "text": text}

print(speaker, section, role, text)

df = pd.DataFrame(data_dict)

print(df)

OR
2. We need number of rows you gonna have for each section.(also to identify change of section)
Count_section = {
"Section1": 2,
"Section2":3,...
}