Q: Como mudar a cor do texto fora de uma função Tkinter? Estou tentando mudar a cor de um texto fora de uma função com Tkinter. Já tentei colocar o Label dentro da função mas fica sobrescrevendo um texto sobre o outro.
Segue o código.
from tkinter import *
from tkinter import ttk
import tkinter as tk

var_35='black'
fg1='black'

master = Tk()
master.geometry('850x700')
master.title('Vias Size')

w = Canvas(master, width=600, height=400, bg='white')
w.grid(row=20,column=0, columnspan=10)

def Solve():
    global fg1
    wth = int(cth.get())
    fg1='black'
    ring = "Ring size = %d µm" % (wth)
    if wth>120:
        fg1 = 'orange'
        print (fg1)
        var12.set(ring)
    elif wth>80:
        fg1= 'red'
        print (fg1)
        var12.set(ring)
    else:
        print (fg1)
        var12.set(ring)

var_1=StringVar()
Label_10 = Label(master, textvariable = var_1,font=('Arial',15),padx=5).grid(row=1,column=0, columnspan=5)

var12=StringVar()
print(fg1)
Label_12 = tk.Label(master, textvariable=var12, font=('Arial',12),padx=5, fg=fg1, bg='white').place(x=80, y=440)

Button(master, text='Solve',font=('Arial',14), command=Solve).grid(row=10,column=7, columnspan=1)

cth = ttk.Combobox(master, values=('25','35', '50','100', '150', '200'),font=('Arial',12) ,width=8)
cth.current(0)
cth.grid(row=6,column=3, columnspan=1)

mainloop()

A: Olá, tudo bem?
Bom primeiro temos que resolver um problema no código acima...
Você atribuiu a variável Label_12 a instancia de um Label já com o place, isso impossibilita você a trabalhar com as propriedades do Label, então primeiro você instancia o Label e depois realiza o place
    Label_12 = tk.Label(master, textvariable=var12, font=('Arial',12),padx=5, fg=fg1, bg='white')
    Label_12.place(x=80, y=440)

Agora dentro da função aplique o seguinte comando:
    **Label_12['foreground'] = fg1**

Assim você altera a cor de acordo com o parâmetro da função....
o seu código ficaria assim:
#########################################################

#########################################################
Uma outra dica, evite usar variável global, isso pode te causar alguns problemas para você, aplique a variável como parâmetro da função, ficaria melhor
Espero ter ajudado.


Q: Zoomable fullscreen image in portrait and landscape mode I am a beginner at programming. I have an app where you can tap into any of the images that are on display to show that image in full-screen mode and can pinch to zoom. The issue I am having is that if you rotate the phone then the image is only half visible.
I'm using a scroll view to achieve the zoom functionality as that seems to be the consensus of the best way to do it.
It works perfectly in portrait mode, or if I enter the fullscreen image while the app is already in landscape orientation, but If I go into the landscape while in the fullscreen image that's where it goes wrong. Here is the code:
class PictureDetailViewController: UIViewController, UIScrollViewDelegate {

@IBOutlet weak var scrollView: UIScrollView!
var routeData = IndividualRoute(numberOfRoute: UserDefaults.standard.integer(forKey: "currentRoute"))

var detailPicture = UserDefaults.standard.bool(forKey: "segueFromDetailvc")

var detailImage = UIImageView()

override func viewDidLoad() {
    super.viewDidLoad()

    routeData.routesValues()
    scrollView.delegate = self
    selectImage()
    scrollView.frame = UIScreen.main.bounds
    scrollView.addSubview(detailImage)
    scrollViewContents()
    setupConstraints()
    let scrollViewFrame = scrollView.frame
    let scaleWidth = scrollViewFrame.size.width / scrollView.contentSize.width
    let scaleHieght = scrollViewFrame.size.height / scrollView.contentSize.height
    let minScale = min(scaleHieght, scaleWidth)
    scrollView.minimumZoomScale = minScale
    scrollView.maximumZoomScale = 1
    scrollView.zoomScale = minScale
    let tap = UITapGestureRecognizer(target: self, action: #selector(dismissFullscreen))
    tap.numberOfTapsRequired = 2
    view.addGestureRecognizer(tap)

}

//****************************************

//Image Setup

func setupConstraints() {

    scrollView.translatesAutoresizingMaskIntoConstraints = false

    NSLayoutConstraint.activate([
        scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
        scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
        scrollView.topAnchor.constraint(equalTo: view.topAnchor),
        scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
        scrollView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
        scrollView.centerYAnchor.constraint(equalTo: view.centerYAnchor)])

    scrollView.contentSize = (detailImage.image?.size)!

}

func selectImage() {
    if !detailPicture {
        let foo = "\(routeData.achievements[UserDefaults.standard.integer(forKey: "currentAchievement")])"
        detailImage.image = UIImage(named: "\(foo.folding(options: .diacriticInsensitive, locale: nil)) 0")
    } else {
        let foo = "\(routeData.achievements[0])"
        detailImage.image = UIImage(named: "\(foo.folding(options: .diacriticInsensitive, locale: nil)) 0")
        print("\(foo.folding(options: .diacriticInsensitive, locale: nil)) 0")
    }

    guard let width = detailImage.image?.size.width else {
        return
    }
    guard let height = detailImage.image?.size.height else {
        return
    }

    let frame: CGRect = CGRect(x: 0, y: 0, width: width, height: height)
    detailImage.frame = frame
    detailImage.isUserInteractionEnabled = true

}

//**************************************

//Scrollview setup

@objc func dismissFullscreen(){
    scrollView.setZoomScale(1, animated: true)
}

func scrollViewContents() {

    let boundSize = UIScreen.main.bounds.size
    var contentFrame = detailImage.frame

    if contentFrame.size.width < boundSize.width {
        contentFrame.origin.x = (boundSize.width - contentFrame.size.width) / 2
    } else {
        contentFrame.origin.x = 0
    }
    if contentFrame.size.height < boundSize.height {
        contentFrame.origin.y = (boundSize.height - contentFrame.size.height) / 2
    } else {
        contentFrame.origin.y = 0
    }

    detailImage.frame = contentFrame

}

func scrollViewDidZoom(_ scrollView: UIScrollView) {
    scrollViewContents()
}

func viewForZooming(in scrollView: UIScrollView) -> UIView? {

    return detailImage
}

Sorry for posting so much code but its pretty much all relevant (I think).
Here are screenshots of the problem:

A: Okay, I've managed to fix it! Had a little jump around with delight.
I set up a new function called setupScale() that is called in viewdidload when the view is presented. I also added the viewwillLayoutSubview() override and called the setupScale() function inside it.
If looks like this:
private func setupScale() {

    scrollView.frame = UIScreen.main.bounds
    scrollView.contentSize = (detailImage.image?.size)!
    scrollViewContents()
    let scrollViewFrame = scrollView.frame
    let scaleWidth = scrollViewFrame.size.width / scrollView.contentSize.width
    let scaleHieght = scrollViewFrame.size.height / scrollView.contentSize.height
    let minScale = min(scaleHieght, scaleWidth)
    scrollView.minimumZoomScale = minScale
    scrollView.maximumZoomScale = 1
    scrollView.zoomScale = minScale
}
override func viewWillLayoutSubviews() {
    setupScale()
}

Results look perfect on my iPad and iPhone 7 in landscape and portrait.


Q: EXEC master.sys.sp_MSforeachdb error when looping through databases I am getting the following the error when executing the statement:
EXEC master.sys.sp_MSforeachdb
    'INSERT INTO AuditDatabase.dbo.[DataDictionary]
         exec sp_get_extendedproperty use [?] "?"'

Msg 102, Level 15, State 1, Line 23
Incorrect syntax near 'master'.
Msg 102, Level 15, State 1, Line 23
Incorrect syntax near 'tempdb'.
Msg 102, Level 15, State 1, Line 23
Incorrect syntax near 'model'.
Msg 102, Level 15, State 1, Line 23
Incorrect syntax near 'msdb'.
Msg 102, Level 15, State 1, Line 23
Incorrect syntax near 'AdventureWorks2014'.
Msg 102, Level 15, State 1, Line 23
Incorrect syntax near 'TestDatabase'.
Msg 102, Level 15, State 1, Line 23
Incorrect syntax near 'AuditDatabase'.

If I run it without the use syntax like this:
EXEC master.sys.sp_MSforeachdb
    'INSERT INTO AuditDatabase.dbo.[DataDictionary]
        exec sp_get_extendedproperty "?"'

It only loops through the AdventureWorks2014 and msdb databases. It does not loop through any other database.
sp_get_extendedproperty is on master db.

A: The use statement is in the wrong place. Try something like this:
I
   exec sp_MSforeachdb 'use ? rest of statement here  '
I just executed this and it worked fine:
exec sp_MSforeachdb 'use ? select * from sys.objects;'

If your proc is name sp_xxx and is in master it should be available in all databases.


Q: Find prev element source I know this code below doesn't work, but is it possible with a call to get the "src" from the prev, with a little tweak to the jquery below?
HTML:

    Diffuse green

        <button class="btn-publish chooseTheme">Choose Theme</button>

Jquery:
$(".chooseTheme").click(function () {
    var src = $(".chooseTheme").find("img");
    alert(src.text());
});

A: $(".chooseTheme").click(function () {
        var src = $(this).closest('li').find("img").attr('src');
        alert(src);
});

A: $(".chooseTheme").click(function () {
    var src = $("li").find("img").attr('src');
    alert(src);

});


Q: What should be passed as input parameter when using train-test-split function twice in python 3.6 Basically i wanted to split my dataset into training,testing and validation set. I therefore have used train_test_split function twice. I have a dataset of around 10-Million rows.
On the first split i have split training and testing dataset into 70-Million training and 30-Million testing. Now to get validation set i am bit confused whether to use splitted testing data or training data as an input parameter of train-test-split in order to get validation set. Give some advise. TIA
X = features
y = target

# dividing X, y into train and test and validation data 70% training dataset with 15% testing and 15% validation set

from sklearn.model_selection import train_test_split

#features and label splitted into 70-30
X_train, X_test, y_train, y_test = train_test_split(X, y,  test_size = 0.3, random_state = 0)

#furthermore test data is splitted into test and validation set 15-15
x_test, x_val, y_test, y_val = train_test_split(X_test, y_test, test_size=0.5)

A: Don't make a testing set too small. A 20% testing dataset is fine. It would be better, if you splitted you training dataset into training and validation (80%/20% is a fair split). Considering this, you shall change your code in this way:
X_train, X_test, y_train, y_test = train_test_split(X, y,  test_size = 0.2, random_state = 0)

x_test, x_val, y_test, y_val = train_test_split(X_train, y_train, test_size=0.25)

This is a common practice to split a dataset like this.


Q: Initialize a multidimensional array of JButtons declared in a different class using get method I have to create a battleship game where there is a multidimensional array of JButtons to denote the player grid. I  am supposed to initialize the JButtons in the main UI class but they need to be declared in a separate class holding the player grid. I have tried this to add the buttons:
for(int i = 0; i <= 10; i++){
        for(int j = 0; j <= 10; j++){
           playerOnePanel.add(playerOne.getBoard());
         }
    }

But this returns a null pointer exception. The class I'm trying to reference is:
public class Player {
    private Color shipColor;
    private String userName;
    private boolean isFirst;
    private JButton[][] buttonBoard = new JButton[rows][cols];
    private final static int rows = 10;
    private final static int cols = 10;

    public Player(String name){
        initComponents();
    }

    private void initComponents(){
        for(int i = 0; i <= rows; i++){
            for(int j = 0; j <= cols; j++){
                buttonBoard[i][j] = new JButton();
            }
        }
    }

     public JButton[][] getBoard(){
         return buttonBoard;
     }
}

And the code I want to use the object in is:
public class BattleshipUI extends JFrame {
    private JMenuBar menuBar;
    private JMenu gameMenu;
    private JMenu optionMenu;
    private JMenuItem playerPlayer;
    private JMenuItem playerComputer;
    private JMenuItem computerComputer;
    private JMenuItem exit;
    private JMenuItem game;
    private JMenuItem player;
    private JButton deploy;
    private JPanel shipLayoutPanel;
    private JPanel playerOnePanel;
    private JComboBox shipCb;
    private JComboBox directionCb;
    // Data arrays for various components on the UI
    private String[] rowLetters = {" ","A","B","C","D","E","F","G","H","I","J"};
    private String[] columnNumbers = {" ","1","2","3","4","5","6","7","8","9","10"};
    private String[] ships = {"Carrier","Battleship","Submarine","Destroyer", "Patrol Boat"};
    private String[] direction = {"Horizontal","Vertical"};
    private static final int PLAYER_ONE = 0;
    private static final int PLAYER_TWO = 1;
    private Player playerOne;
    private Player playerTwo;
    private Player[] players = new Player[2];
    private Color[] color = {Color.cyan, Color.green, Color.yellow, Color.magenta, Color.pink, Color.red, Color.white};

    public BattleshipUI(){
        initComponents();
        initObjects();
    }

    public BattleshipUI getThisParent(){
        return this;
    }

    private void initObjects(){
        playerOne = new Player("Player One");
        playerTwo = new Player("Player Two");
        players[1] = playerOne;
        players[2] = playerTwo;
    }

    private void initComponents(){
        this.setTitle("Battleship");
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setPreferredSize(new Dimension(500,500));
        this.setMinimumSize(new Dimension(500,500));

        menuBar = new JMenuBar();
        gameMenu = new JMenu("Game");
        optionMenu = new JMenu("Option");
        menuBar.add(gameMenu);
        menuBar.add(optionMenu);

        playerPlayer = new JMenuItem("Player vs. Player");
        playerComputer = new JMenuItem("Player vs. Computer");
        computerComputer = new JMenuItem("Computer vs. Computer");
        exit = new JMenuItem("Exit");
        gameMenu.add(playerPlayer);
        gameMenu.add(playerComputer);
        gameMenu.add(computerComputer);
        gameMenu.add(exit);
        playerPlayer.setEnabled(false);
        computerComputer.setEnabled(false);

        game = new JMenuItem("Game Options");
        player = new JMenuItem("Player Options");
        optionMenu.add(game);
        optionMenu.add(player);

        shipLayoutPanel = new JPanel();
        shipLayoutPanel.setBorder(BorderFactory.createTitledBorder("Select Ship and Direction"));

        shipCb = new JComboBox(ships);
        directionCb = new JComboBox(direction);
        deploy = new JButton("DEPLOY");
        deploy.setEnabled(false);

        shipLayoutPanel.add(shipCb);
        shipLayoutPanel.add(directionCb);
        shipLayoutPanel.add(deploy);

        playerOnePanel = new JPanel(new GridLayout(11,11));
        playerOnePanel.setMinimumSize(new Dimension(400,400));
        playerOnePanel.setPreferredSize(new Dimension(400,400));
        playerOnePanel.setBorder(BorderFactory.createTitledBorder("Player  One"));

        for(int i = 0; i <= 10; i++){
            for(int j = 0; j <= 10; j++){
               playerOnePanel.add(playerOne.getBoard());
             }
        }

        this.setJMenuBar(menuBar);
        this.add(shipLayoutPanel, BorderLayout.NORTH);
        this.add(playerOnePanel, BorderLayout.WEST);
        this.setVisible(true);
    }
}

Is there a way to do this? I need to use the methods and variables listed.

A: You seem to initialize the players (and their boards respectively) after trying to add their board to a panel, which is impossible since you did not create the players yet.
 public BattleshipUI(){
     initComponents(); //Here you try to add the board of a player
     initObjects(); //Here you initialize the players (ergo nullpointer)
 }

 private void initComponents(){
     for(int i = 0; i <= 10; i++){
         for(int j = 0; j <= 10; j++){
             //playerOne is not instantiated yet
             playerOnePanel.add(**playerOne**.getBoard());
         }
     }
 }

  private void initObjects(){
        **playerOne** = new Player("Player One");
        playerTwo = new Player("Player Two");
        players[1] = playerOne;
        players[2] = playerTwo;
}

A: Another thing I see is: You are trying to add a multi-dimensional JButton-Array at once to the JPanel. I think this will not work (please correct me if i am wrong). You have to do this Button by Button:
JButton[][] board = playerOne.getBoard();
for(int i=0;i<rowSize;i++){
   for(int j=0;j<columnSize;j++){
       playerOnePanel.add(board[i][j]);
   }
}

Notice: Obviously you have to get somehow the row size and column size and declare as a variable as here as rowSize and columnSize.


Q: How to run all javascript files in a folder with NodeJS? I want to have a folder with javascript files and be able to programmatically run whatever is on them asynchronously. For example:
async.each(folder_files, function(content, cb){
    run_script(content);

    cb();
},function(err){
    if(err){
        console.log(err);
    }else{
        console.log("All scripts ran succesfully :D");
    }
});

Is this even possible?
EDIT: Just to clarify, I want to be able to change the folder contents with any number of scripts and run them through the main JS file.

A: Here is a simple solution using  async  , but you need to put all your scripts inside scripts folder beside the main file
const fs = require('fs')
const exec = require('child_process').exec

const async = require('async') // npm install async

const scriptsFolder = './scripts/' // add your scripts to folder named scripts

const files = fs.readdirSync(scriptsFolder) // reading files from folders
const funcs = files.map(function(file) {
  return exec.bind(null, `node ${scriptsFolder}${file}`) // execute node command
})

function getResults(err, data) {
  if (err) {
    return console.log(err)
  }
  const results = data.map(function(lines){
    return lines.join('') // joining each script lines
  })
  console.log(results)
}

// to run your scipts in parallel use
async.parallel(funcs, getResults)

// to run your scipts in series use
async.series(funcs, getResults)


Q: PHP code in JavaScript to get variable When I press on any of the ‘region’ names in the list ('href' links), the matching list of 'cities' is showing underneath.
<?php while(has_list_regions()) { ?>
  <a href="javascript:show_region('<?php echo list_region_id() ?>');">
<?php } ?>

Is it possible to include PHP code within a section of JavaScript? Because I need to get the ID of the selected ‘href’ that I clicked. I am trying to include the PHP code in the above JavaScript function but it doesn’t work.

A: PHP runs on the server, generates the content/HTML and serves it to the client possibly along with JavaScript, Stylesheets etc. There is no concept of running some JS and then some PHP and so on.
You can however use PHP to generate the required JS along with your content.
The way you've written it won't work.

For sending the value of clicked_tag to your server, you can do something like (using jQuery for demoing the logic)
function show_region(chosen_region_id) {
    ...
    $.post('yourserver.com/getclickedtag.php',
        {clicked_tag: chosen_region_id},
        function(data) { ... });
    ...
}

A: In your script the variable chosen_region_id is already in the function so you don't really need to declare it again with PHP.


Q: unique form field validation in extjs4 Is there a cleaner way to define unique form field in extjs. Below is a sample code that is checking on client UID on client creation/edition. This code is working but has some bugs - for example on client creation if you enter a value that is already present in DB validator returns true until you unfocus the field.
Ext.define('AM.view.client.UniqueField', {
    extend: 'Ext.form.field.Text',
    alias : 'widget.uniquefield',

    vtype: 'UniqueUid',

    initComponent: function() {

    Ext.apply(Ext.form.field.VTypes, {

        UniqueUidMask : /[0-9]/i,
        UniqueUid : function(val,field) {
            if (val.length < 9) {
                Ext.apply(Ext.form.field.VTypes, {
                    UniqueUidText: 'Company ID is too small'
                });
                return false;
            } else {
              var paste=/^[0-9_]+$/;
              if (!paste.test(val)) {
                Ext.apply(Ext.form.field.VTypes, {
                    UniqueUidText: 'Ivalid characters'
                });
                return false;
               } else {

                 var mask = new Ext.LoadMask(field.up('form'),{msg:'Please wait checking....'});
                     mask.show();
                 var test= 0;
                 var store = Ext.create('AM.store.Clients');
                     store.load({params:{'uid':val, 'id': Ext.getCmp('client_id').getValue()}});
                     store.on('load', function(test) {
                      mask.hide();
                        if(parseInt(store.getTotalCount())==0){
                         this.uniqueStore(true);
                        }else{
                           Ext.apply(Ext.form.field.VTypes, {
                              UniqueUidText: 'Company ID is already present'
                           });
                         this.uniqueStore(false);
                        }
                     },this)

                return true;
               }
            }}
      },this);

    this.callParent(arguments);

    },

    uniqueStore: function(is_error){

        Ext.apply(Ext.form.field.VTypes, {
        UniqueUidMask : /[0-9]/i,
        UniqueUid : function(val,field) {
            if (val.length < 9) {
                Ext.apply(Ext.form.field.VTypes, {
                    UniqueUidText: 'Company ID is too small'
                });
                return false;
            } else {
              var paste=/^[0-9_]+$/;
              if (!paste.test(val)) {
                Ext.apply(Ext.form.field.VTypes, {
                    UniqueUidText: 'Ivalid characters'
                });
                return false;
               } else {

                 var mask = new Ext.LoadMask(field.up('form'),{msg:'Please wait checking....'});
                     mask.show();

                 var store = Ext.create('AM.store.Clients');
                     store.load({params:{'uid':val, 'id': Ext.getCmp('client_id').getValue()}});
                     store.on('load', function(test) {
                      mask.hide();
                        if(parseInt(store.getTotalCount())==0){
                         this.uniqueStore(true);
                        }else{
                         this.uniqueStore(false);
                        }
                     },this)

                return is_error;
               }
            }}
      },this);

    }

});

A: How about using server side validation?
I answered to similar issue here: extjs4 rails 3 model validation for uniqueness
Obviously you can change it to use "ajax" instead of "rest" proxy.


Q: Is it possible to set the initial topic assignments for scikit-learn LDA? Instead of setting the topic_word_prior as a parameter, I would like to initialize the topics according to a pre-defined distribution over words.  How would I set this initial topic distribution in sklearn's implementation? If it's not possible, is there a better implementation to consider?

A: If you have a predefined distribution of words in a pre-trained model you can just pass a bow_corpus through that distribution as a function.  Gensims LDA and LDAMallet can both be trained once then you can pass a new data set through for allocation without changing the topics.
Steps:

*

*Import your data

*Clean your data: nix punctuation, numbers, lemmatize, remove stop-words, and stem

*Create a dictionary
dictionary = gensim.corpora.Dictionary(processed_docs[:])
dictionary.filter_extremes(no_below=15, no_above=0.5, keep_n=100000)

*Define a bow corpus
bow_corpus = [dictionary.doc2bow(doc) for doc in processed_docs]

*Train your model - skip if it's already trained
ldamallet = gensim.models.wrappers.LdaMallet(mallet_path,
            corpus=bow_corpus, num_topics=15, id2word=dictionary)

*Import your new data and follow steps 1-4

*Pass your new data through your model like this:
  ldamallet[bow_corpus_new[:len(bow_corpus_new)]]

*Your new data is allocated now and you can put it in a CSV


Q: Why I should add '&' before the parameter which is an unordered_map? unordered_map<int, string>::iterator findElement(unordered_map<int, string> &intString, int index){
    return intString.find(index);
}

If I don't add the & before the intString, the code will crash.

A: The & in the type for the function-parameter intString means that the function gets a reference to the passed argument, instead of a copy of it.
Thus, the iterator which is returned from .find() and which it returns in turn will point into the passed argument, instead of being a dangling iterator pointing somewhere into a no longer existing copy.
And accessing destroyed objects, especially if the memory was re-purposed, can have all kinds of surprising results, which is why it is called Undefined Behavior (UB).


Q: Call Python google cloud endpoint api from android At this point I have created a python app-engine endpoint api called paper (as also noted in the app.yaml) file. I have placed all the jars, including the …-java-1.13.2-beta-sources.jar file, in the libs directory of my android project. How do I call one of my web services (aka endpoint methods)? As in I don't know the name of the package that would lead me to the api, which in the python backend is simply class PageApi(remote.Service):. Imagine the paper api has a method called countPages(self):. How would I call the service? I have already tried importing import com.appspot.api.services.[etc] but eclipse does not see the importing path.
EDIT:
I reload the api. I check that everything looks okay on api explorer. Then I found two packages that seem to be my packages -- except they contain no classes at all.
import com.google.api.services.page.*;
import com.google.api.services.page.model.*;

If they are indeed the packages, why would the classes be missing?

A: First.  Once you have your projects setup correctly then the same wizard that generated your client library will copy it to your Android project and extra the source files.  then you will find the packages you need in the endpoint-libs folders in your project explorer.  Take a look at this post for tips on getting that working.
Then you invoke an endpoint using Android code like this:
final HttpTransport transport = AndroidHttp.newCompatibleTransport();
JsonFactory jsonFactory = new JacksonFactory();

endpointname.Builder builder = new endpointname.Builder( transport, jsonFactory, null );
builder.setApplicationName( appName );

endpointname service = builder.build();

try {
   response = service.methodName( parameters ).execute();
} catch (IOException e) {
   Log.e(...);
}


Q: Skype doesn't work Ubuntu 18.04 I have installed skype with the following command:
sudo snap install skype --classic
the problem is when I want to open it, it doesn't work and automatically sign off. Even this happen writting skype on the terminal.

A: Try to remove your snap installation using this command
sudo snap remove skype

then download the .deb file from Official Skype website.
Then install it using dpkg for ex:
dpkg -i /path-to-/deb-file.deb

Note: check this answer for more information about snap.


Q: Upload de arquivos (imagens) em ASP.net não envia a imagem Eu não consigo enviar imagens (banners) na minha aplicação asp.net
Meu controller :
    [HttpPost]
    [ValidateAntiForgeryToken]
    [ValidateInput(false)]
    public ActionResult Save([Bind(Include = "BannerId,DatHorLan,Tit,Atv")] Banner banner)
    {
        try
        {
            banner.DatHorLan = DateTime.Now;
            banner.UsuarioId = 1;
            if (ModelState.IsValid)
            {
                // Se foi enviado um arquivo com mais do que 0 bytes:
                if (banner.File != null && banner.File.ContentLength > 0)
                {
                    // Extraindo nome do arquivo
                    var fileName = Path.GetFileName(banner.File.FileName);

                    var path = Path.Combine(Server.MapPath("/Uploads/Img/Banners"), fileName);
                    banner.File.SaveAs(path);

                    banner.Img = fileName;
                    ModelState.Remove("Img");
                }
                if (banner.BannerId == 0)
                {
                    banner.DatHorLan = DateTime.Now;
                    db.Banners.Add(banner);
                }
                else
                {
                    db.Entry(banner).State = EntityState.Modified;
                }
                db.SaveChanges();
                ViewBag.Message = "Registro gravado com sucesso.";
            }
        }
        catch (DataException)
        {
            ViewBag.Message = "Ocorreu um erro ao gravar o registro.";
        }
        return View("Form", banner);
    }

Meu Model :
[Table("Banners")]
public class Banner
{
    [Key]
    [Column("BannerId")]
    [Display(Name = "Banner")]
    public int BannerId { get; set; }

    [Required]
    [Column("Tit")]
    [Display(Name = "Título")]
    public string Tit { get; set; }

    [Required]
    [Column("Atv")]
    [Display(Name = "Atívo")]
    public int Atv { get; set; }

    [Column("Img")]
    [Display(Name = "Imagem")]
    public string Img { get; set; }

    [Display(Name = "Imagem")]
    [NotMapped]
    public HttpPostedFileBase File { get; set; }

    [Column("DatHorLan")]
    [Display(Name = "Data/Hora")]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy hh:mm:ss}", ApplyFormatInEditMode = true)]
    public DateTime DatHorLan { get; set; }

    [Column("UsuarioId")]
    [Display(Name = "Usuário")]
    public int UsuarioId { get; set; }
    [Display(Name = "Usuário")]
    public virtual Usuario Usuario { get; set; }

}

O meu HTML (View)
@model FiscoCorretora.Areas.Admin.Models.Banner

@{
    ViewBag.Title = "Páginas";
    Layout = "~/Areas/Admin/Views/Shared/_Layout.cshtml";
}

        @if (Model.BannerId == 0)
        {

Banner - Novo

        }
        else
        {

Banner - Alterando

        }

    @using (Html.BeginForm("save","banners", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        @Html.AntiForgeryToken()

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        @Html.HiddenFor(model => model.BannerId)
        @Html.HiddenFor(model => model.DatHorLan)

                    @Html.LabelFor(model => model.Tit, htmlAttributes: new { @class = "control-label col-md-2" })

                        @Html.EditorFor(model => model.Tit, new { htmlAttributes = new { @class = "form-control input-sm" } })
                        @Html.ValidationMessageFor(model => model.Tit, "", new { @class = "text-danger" })

                    @Html.LabelFor(model => model.Atv, htmlAttributes: new { @class = "control-label col-md-2" })

                        @Html.DropDownList("Atv", new List<SelectListItem>
                                         {
                                            new SelectListItem{ Text="Não", Value = "0" },
                                            new SelectListItem{ Text="Sim", Value = "1" }
                                         }, new { @class = "form-control" })

                        @Html.ValidationMessageFor(model => model.Atv, "", new { @class = "text-danger" })

                    @Html.LabelFor(model => model.File, htmlAttributes: new { @class = "control-label col-md-2" })

                        @Html.TextBoxFor(model => model.File, new { type = "file", @class = "form-control" })
                        @Html.ValidationMessageFor(model => model.File)

                @ViewBag.Message

                 Voltar

            <button type="submit" id="btn-gravar" value="Gravar" class="btn btn-primary btn-sm pull-right" title="Grava o registro." style="margin-right: 5px;">
                 Gravar
            </button>

    }

@section Scripts{

}

Grava o registro no banco e tudo mais, porem nao envia a imagem
No controle :
if (banner.File != null && banner.File.ContentLength > 0)

Sempre ta nulo !

A: Este form encontra-se dentro de outro form?
Se sim remova new { enctype = "multipart/form-data" } e adicione ao form pai.


Q: Multipeer Connectivity Session in iOS7 I've looked into Apple's documentation but is still uncleared about one thing, the session.

*

*When - (void)advertiser:(MCNearbyServiceAdvertiser *)advertiser didReceiveInvitationFromPeer:(MCPeerID *)peerID withContext:(NSData *)context invitationHandler:(void (^)(BOOL, MCSession *))invitationHandler is called, we need to pass in a session to the invitationHandler. What will happen to this session?
When A invites B to join a session that A created, does B provide a new session to A as well? What is inside B's session? Is it just A alone or does it include all the peers that are currently in A's session? Should B keep track of the session that's been used to accept A's invitation?
Inside this article, http://nshipster.com/multipeer-connectivity/, the tutorial creates a new session on the fly and uses it to accept the invitation, wouldn't you lose the session once the function is ended; thus losing information to connected peers?

*Assuming that B, C and D are all invited by A, and now B wants to send something to C. Is it required that B needs to send the information to A first or can B send the information directly to C?

*According to the Apple's documentation, a single session can only hold no more than 8 peers. Is it possible to make an array of sessions so that you can invite more than 8 people to join your device? If that is the case, does client also need to respond with an array so that it can carry more than 8 peers in its list?

*Assuming A and B are now connected, and A now invites C to join. How does B know that C is now in the session?
Thank you for reading such a long post.

A: There's not much in the way of documentation on Multipeer Connectivity, so these answers are based on my own experiments:

*

*There are lots of questions inside this one question, but in a nutshell A's session(s) manage invitations that A has sent or accepted. So if B invites and A accepts, the session that A passes when accepting will then be used in the MCSessionDelegate session: peer: didChangeState: callback to say whether the connection happened. At this point the connectedPeers property of A's session will contain B (if the connection succeeded). The session that B used to send the invitation will also get the same callback once A accepts, and will contain A in connectedPeers. Neither A nor B will have any information on the other's session that managed this connection between them. And yes, if you want to send any data to the newly connected peer, you need to keep a reference to the session that handled the connection. I've yet to see any real advantage in creating a new session for each invitation.

*Based on the above, B has no information on who A is connected to. So if A is connected to B,C and D, the only peer B knows about is the peer that it connected to - A. What Multipeer Connectivity offers here is the ability for B to discover C or D via A. So if the A-B connection was made over WiFi, and A-C over Bluetooth, but B does not have Bluetooth enabled, and C is on a different WiFi network to B, B and C can still discover each other through A. The process of inviting and accepting is still up to B and C to handle though.

*I answered a question about session management here that may be helpful Best option for streaming data between iPhones

*B doesn't know anything about A connecting to C. All B can do is discover C for itself and add C to it's own session.

A: *

*From quickly looking over Chris's answer it seems accurate from what I've been working on at my job.

*I'm currently working on a game using multipeer connectivity and have found that:
(Assuming everyone is on wifi) if A connects to B and A connects to C, then B will be connected to C and be able to send messages to C.
the Multipeer Framework is a P2P framework and automatically connects everyone together.
even if (as in my current project) you set it up as a Server-client model, all peers will still be connected and you can send messages between B and C without going through A. Depending on what you are doing with your app.

*Go with Chris's answer

*Addressed in #2
I recommend looking at the example project in the Apple Docs and carefully watch what happens in the debug area when you connect.
Also, as a side note:
Scenario:(A is only on wifi),(B is on wifi and bluetooth),(C is on bluetooth only)

if A connects to B via wifi, and B connects to C via bluetooth, A will still be connected to C but you won't be able to send a message from A directly to C because they are on different networks.

A: @SirCharlesWatson:

(Assuming everyone is on wifi) if A connects to B and A connects to C, then B will be connected to C and be able to send messages to C.
the Multipeer Framework is a P2P framework and automatically connects everyone together.

My question is: when B automatically connected to C, will B & C receive a state change notification on the existed session?

*

*A: session:peer:B didChangeState(MCSessionStateConnected)

*B: session:peer:A didChangeState(MCSessionStateConnected)


Q: javascript to allow me to collapse accordion that is extended I have a side navigation bar that consists of multiple accordions that when expanded shows more navigation buttons. I have a bit of JavaScript that will only allow one of those accordions to be expanded at a time. However if I click on one accordion to expand it, when I click the same accordion it remain open.
I would like to get it so that I can expand and collapse the accordion without having to expand another accordion.
JavaScript:
var acc = document.getElementsByClassName("nav-link-bottom-main");
var i;
var last;
for (i = 0; i < acc.length; i++) {
    acc[i].onclick = function() {
        if (last) {
            last.nextElementSibling.classList.toggle("show");
        }
        this.nextElementSibling.classList.toggle("show");
        last = this;
    }
}

html:

    <button class="nav-link-bottom-main toggle">Endpoint Section 1</button>

        <button class="nav-link-bottom-sub toggle">GETendpoint 1.1</button>
        <button class="nav-link-bottom-sub toggle">GETendpoint 1.2</button>
        <button class="nav-link-bottom-sub toggle">GETendpoint 1.3</button>

    <button class="nav-link-bottom-main toggle">Endpoint Section 2</button>

        <button class="nav-link-bottom-sub toggle">GETendpoint 2.1</button>
        <button class="nav-link-bottom-sub toggle">GETendpoint 2.2</button>
        <button class="nav-link-bottom-sub toggle">GETendpoint 2.3</button>
        <button class="nav-link-bottom-sub toggle">GETendpoint 2.4</button>

A: It looks like whenever if (last) condition is true and it's the same element as this, you're toggling show class twice on same element, so probably this is why it remains open (actually it closes and opens again at the same time).
So try to check if you're not toggling same element like this:
if (last && last != this) {
    last.nextElementSibling.classList.toggle("show");
}
this.nextElementSibling.classList.toggle("show");

And I hope it helps.


Q: how can i plot series first bar's close price of super trend (long/short)? how can i plot series first bar's close price of super trend (long/short) ?
//@version=5
indicator("Supertrend", overlay=true, timeframe="", timeframe_gaps=true)
atrPeriod = input(10, "ATR Length")
factor = input.float(3.0, "Factor", step = 0.01)

[supertrend, direction] = ta.supertrend(factor, atrPeriod)

bodyMiddle = plot((open + close) / 2, display=display.none)
upTrend = plot(direction < 0 ? supertrend : na, "Up Trend", color = color.green,      style=plot.style_linebr)
downTrend = plot(direction < 0? na : supertrend, "Down Trend", color = color.red,     style=plot.style_linebr)

fill(bodyMiddle, upTrend, color.new(color.green, 90), fillgaps=false)
fill(bodyMiddle, downTrend, color.new(color.red, 90), fillgaps=false)

A: var float first_close = 0.
if barstate.isfirst
    first_close := supertrend

A: You will have to save the close price whenever the direction changes into a variable and then you can plot that variable. Example below
//@version=5
indicator("Supertrend", overlay=true, timeframe="", timeframe_gaps=true)
atrPeriod = input(10, "ATR Length")
factor = input.float(3.0, "Factor", step = 0.01)

[supertrend, direction] = ta.supertrend(factor, atrPeriod)

bodyMiddle = plot((open + close) / 2, display=display.none)
upTrend = plot(direction < 0 ? supertrend : na, "Up Trend", color = color.green,      style=plot.style_linebr)
downTrend = plot(direction < 0? na : supertrend, "Down Trend", color = color.red,     style=plot.style_linebr)

fill(bodyMiddle, upTrend, color.new(color.green, 90), fillgaps=false)
fill(bodyMiddle, downTrend, color.new(color.red, 90), fillgaps=false)
var firstbarsclose=close
if direction<0 and direction[1]>0
    firstbarsclose:=close
if direction>0 and direction[1]<0
    firstbarsclose:=close
plot(firstbarsclose,style=plot.style_stepline)


Q: I tried several times but still animation is not working, please help me to fix it CSS parts

Blockquote

I was just making a box and apply animation over it, these are respective lines of code
<style>
    .box {
        background-color:red;
        margin-top: 100px;
        width: 200px;
        height: 100px;
        position: relative;
        animation-name: raw;
        animation-duration: 2ms;
        animation-timing-function: ease-in;
    }

    @keyframes raw {
        0% {
            background-color: grey;
        }
        50% {
            background-color:lime;
        }
        100% {
            background-color:brown;
        }
    }
</style>

Body
Here it is a box over which I want to apply animation
<body>
    <div class="box">
        BOX
    </div>
</body>

A: You are using ms instead of s. Your animation is working, but it finishes so fast that you just can't see it. Therefore, you should give it a longer duration.


Q: Directional hypothesis testing in linear regression models using SPSS I have an alternative hypothesis which states H1: "The intelligence quotient (IQ) has a positive effect on school grades", i.e. $H_{1}: \beta_{1} < 0$. I am using a linear regression to check whether the slope ($\beta_{1}$) is statistically significant.
As far as I know, SPSS is using a different alternate hypothesis where it checks for inequality, i.e. $H_{1}: \beta_{1} \neq 0$
How can I now use the result of SPSS and with t-Test and its corresponding p-value of $0.03$, to validate my hypothesis. I am using a significance value of $\alpha = 0.05$


Q: Export data from database to sql file with PHP I need to export data (only the data, not the tables nor database) from the database to a SQL file and save it. How to write a PHP function that does that? I want to call this function in specific circumstances when running specific queries (updating a blog post, for example).
Something like:
/*
* Get the data from the database (already specified) and export it to a SQL file
*
* @param  string $dir Where to store the SQL file. Must be a full path.
* @return void
*/
function export_database_data(string $dir) {
  // some code that gets the data and store it in $data
  // don't know what to do here

  // create/update the file
  file_put_contents("$dir/data_backup.sql", $data);
}

Why this?
(You don't need to read the following to help me solve the problem. I'm including this because I'm sure if don't include this, someone will ask it).
I want to do that because I want to have a backup of the data (only the data; the tables do not matter because I already know how to handle them for backup).
I'm doing this because I will use the PHP function exec to run git commands and commit the change in the SQL file. The end goal is to keep track of the data in the database, which won't be updated often. I need the data in a SQL file and I aim to use git because it is easy to access and to collaborate with others (I could not think a better solution, and creating my own tracking system would require a lot of work and time).

A: You can run a mysqldump command using PHP exec function to only export data. Ex:
exec('mysqldump -u [user] -p[pass] --no-create-info mydb > mydb.sql');

More info:

*

*mysqldump data only

*Using a .php file to generate a MySQL dump


Q: If $x^* (x)=0$ for all $x^* \in X^*$, then $x=0$? If $X$ is any arbitrary vector space, and $X^*$ is its dual, is it true that if $x^* (x)=0$ for all $x^* \in X^*$, then $x=0$?

A: we can use Hahn-Banach theorem to prove it , we take x such that x $\neq$ 0 , we define a functional on $span(x)$ such that $f(x)=1$ for example ...
then there is an extention of $f$ in $X$ .

A: I am going to put my own answer here, expounding on Abderrahim Abdou's. We will use the second form of Hahn-Banach theorem (which can be found on Wikipedia). Suppose for contradiction that $x \neq 0$, then $\text{span}\{x\}$ is nontrivial, and $f(\alpha x)=\alpha$  for every $\alpha \in \mathbb{K}$ is a linear functional on $\text{span}\{x\}$. Consider the seminorm $g$ on $X$ where $g(y)=|f(y)|$ for $y \in \text{span}\{x\}$ and $0$ otherwise. Since $|f| \leq g $ in $\text{span} \{x\}$, then by Hahn-Banach theorem, $f$ extends to a linear function in whole of $X$, therefore, $f \in X^*$, but $f(x)=1 \neq 0$ which is a contradiction.


Q: Error while unzipping JSON file (Firefox) in my Node.js application I have a route where I am fetching a big chunk of JSON data from database (Postgres) and sending it in compressed format in a response. I am using Zlib module to gzip this data. I am setting Content-Type: application/gzip and Content-Encoding: gzip before sending a response. Now all this set up works well with Chrome and Safari browsers (unzipping data successfully) but for some reason this is not working in Firefox. Request header contains Accept-Encoding: gzip, deflate.
In browser(Firefox) console I see following errors
Attempt to set a forbidden header was denied: Accept-Encoding and
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Can anybody please guide me what this issue is and how can I solve it? Thanks!

A: Ok, I will answer my question with what worked for me.
On server side, I changed the way I was compressing the data. I am using deflate method of Zlib module instead of gzip. Also changed the response header with these values.
Content-Encoding: deflate and Content-Type: application/deflate
I am still not sure why gzip does not work (or at least did not work for me) but because of time constraint I am going with deflate for now.
Also gzip and deflate uses same compression algorithm and deflate is faster in encoding and decoding. I hope this helps and please correct me if I'm wrong at any place. Thanks!

A: In modern browsers, according to https://developer.mozilla.org/en-US/docs/Web/API/Headers,

For security reasons, some headers can only be controlled by the user agent. These headers include the forbidden header names and forbidden response header names.

Forbidden header names include "Accept-Encoding".


Q: What is the Thingsboard IoT platform's default system administrator account? What is the Thingsboard IoT platform's (https://thingsboard.io) default system administrator account after a fresh (Raspberry Pi) installation?
The existing documentation only refers to default "tenant" account, which is ok on my setup.
Thanks in advance.

A: Default system administrator account:

*

*login - sysadmin@thingsboard.org

*password - sysadmin

Default demo tenant administrator account:

*

*login - tenant@thingsboard.org.

*password - tenant.

Demo tenant customers:
Customer A user: customerA@thingsboard.org.
Customer B user: customerB@thingsboard.org.
Customer C user: customerC@thingsboard.org.
all users have “customer” password.
Take a look at demo-account documentation page for more information.


Q: How to Directly Upload file to other server So I have a project in which i want to upload video to dailymotion using api
So i want to Upload video directly to dailymotion server without uploading it to my local server
My Action
 [HttpPost]
 public async Task<ActionResult> Add(Video Videos)
 {
        var fileToUpload = @"E:\Courses\[FreeCourseLab.com] Udemy - C# Intermediate Classes, Interfaces and OOP\5. Polymorphism Third Pillar of OOP\3. Sealed Classes and Members.mp4";
        return RedirectToAction("AddVideo", "Admin");
 }

my View
@using (Html.BeginForm("Add", "Admin", FormMethod.Post, new { @class = "px-lg-4", role = "form" }))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary("", new { @class = "text-danger" })

        @Html.TextBoxFor(m => m.Videos.File,  new {@type="file" })

    <input type="submit" class="d-flex justify-content-center btn btn-block btn-primary" value="Create" />
}


Q: Choosing resistance in series with a photoresistor for best light-measurement resolution

simulate this circuit – Schematic created using CircuitLab
I have a photoresistor, R1, and as a voltage divider a fixed resistance, R2. There is a voltage of 5V over these two, and the voltage is measured over the photoresistor.
In my experiment I have a yellow LED on one side, a substance which I add blue color into, and the photoresistor on the other side. How do I decide what R2 to choose so that I can detect small changes in light (when increasing the opacity of the substance)?

A: Voltage dividers have the best sensitivity when R1 is equal to R2. The voltage given by the divider is:
$$ V_x = V_1\frac{R_1}{R_1+R_2} $$
The sensitivity is given by the first derivative:
$$ d\frac{V_x}{dR_1} = V_1\frac{R_2}{(R_1+R_2)^2} $$
Assuming you will make your measurements at about 10 lux, your sensor resistance will be \$R_1=29k\Omega\$. Not surprisingly, the maximum of sensitivity function occurs when \$R_2=29k\Omega\$ as well.

A: This is a voltage divider circuit, sometimes incorrectly called a bridge.  The one fixed known resistor in series with the unknown resistance produces a voltage that is a function of the unknown resistance all the way from zero to infinity.  In theory, any resistance can be measured.
However, the sensitivity is greatest when the output voltage is in the middle of its range.  This is when the unknown resistance is close to the fixed resistance.  Therefore, use a fixed resistor (R2) that matches the photoresistor value in the middle of your typical experiment.  You can find this by disconnecting the photoresistor from the circuit and measuring it with a ohmmeter.  Or, you can pick different fixed resistors for R2 until you get about 2.5 V out for your typical setup.
Is the photoresistor really only 100 Ω when used in your experiment?  That's rather low.  2.5 V across this 100 Ω draws 25 mA and causes 63 mW dissipation in the photoresistor.  That shouldn't be a problem by itself, but will cause some self-heating, which probably changes the resistance a bit.  This means the resistance will change quickly due to light, then more slowly due to different dissipation at the different light level.
Photoresistors come in many different resistance ranges.  I would look for something more like 1 kΩ at the intended light level.


Q: C fork - how to wait for all children before starting workload? I am trying to get fork() to create multiple processes all of which do the same work. I need all of them to get created first, and then at the same time start doing work. That is, I want all of the processes to wait for all of the other ones to get created, and once they are all ready, start doing the work at the same exact time.
Is this possible? Thanks.

A: The simplest approach would be simply using signals, do note however that there is no way to actually guarantee that the processes will indeed run in parallel.
That's for the OS to decide.


Q: Update existing SharePoint list from Excel file in library What I'm trying to do is to update the SharePoint list if there is an item in the Excel file that is not in SharePoint, for example
I have in the SharePoint list one item:

PR Number
Desc
Title
Priority
Link

0005689
lorem
example
(This is a dropdown)
http://example.com

And in the Excel I have three items:

Number
Desc
Title
Link

0005689
lorem
example
http://example.com

0003491
lorem
example
http://example.com

0001497
lorem
example
http://example.com

So basically I want to compare if each of the Number values in the Excel file exists in the SharePoint list, and if not, then add it to SharePoint so the final list will be like:

PR Number
Desc
Title
Priority
Link

0005689
lorem
example
(This is a dropdown)
http://example.com

0003491
lorem
example
(This is a dropdown)
http://example.com

0001497
lorem
example
(This is a dropdown)
http://example.com

So far I have tried with PowerAutomate (MS Flow) but it is quite confusing how to use it, I have just being able to set the recurrence to each day, and to get the items and the worksheet, but I don't find a way to handle the data and make the comparisson nor the addition to the list.
I did my research in the forum but the threads are more than 7 years old.

A: See the screenshots for a sample Power Automate below.

Detail 1

Detail 2


Q: OpenGL orientation. (Identity rotation looking in negative z) I'm implementing a renderer that handles every translation- / view- / model- / projection-matrix (I don't use glRotate / glTranslate etc.).
I have placed several blue objects along the positive z-axis and some red objects on the positive x-axis (So I should be able to see the red objects to my left and the blue ones straight ahead using identity rotation on my camera). It is right-hand-orientation, right?
The problem is that I have to turn 180 deg around the y-axis to see my objects. It appears as the identity rotation is looking in -z.
I'm constructing my View matrix by taking the inverse of the cameras matrix [Rot Tr] and then I put it in a array column-wise and pass it to my shader.
For the objects (World matrix) I just pass the matrix [Rot Tr] column-wise to the shader. Should I negate the translation?
The projection matrix is for now constructed in the vertex shader as I am working my way through. As you can se below I'm doing
position = proj*view*model*gl_Vertex;

At the moment I use gl_Vertex (I use glutSolidCube after loading identity matrix as my scene objects).
uniform mat4 view;
uniform mat4 model;

varying vec4 pos;

void main()
{

pos = gl_Vertex;

float aspect = 1.0;
float fovy = 1.5;
float f = 1.0 / tan(fovy * 0.5);
float near = 1.0;
float far = 100.0;
float tt = 1.0 / (near - far);

mat4 proj = mat4(f/aspect, 0.0, 0.0, 0.0,
        0.0, f, 0.0, 0.0,
        0.0, 0.0, (near+far)*tt, -1.0,
        0.0, 0.0, 2.0*near*far*tt, 0.0);

gl_Position = proj * view * model * pos;
}

In my fragment shader I set the color = pos so that I can see the color of the axis and the colors appears correct. I think the objects are correctly placed in the scene but with Identity matrix as rotation I'm still looking the opposite way.
What could I have missed? Am I passing the correct matrices in a correct manner?

A: A right-handed coordinate system always looks down the -Z axis. If +X goes right, and +Y goes up (which is how all of OpenGL works), and the view is aligned to the Z axis, then +Z must go towards the viewer. If the view was looking down the +Z axis, then the space would be left-handed.

A:
The problem is that I have to turn 180 deg around the y-axis to see my objects. It appears as the identity rotation is looking in -z.

Yes it is. The coordinate systems provided yb OpenGL in form for glOrtho and glFrustum are right handed (take your right hand, let the thumb towards the right, the index finger up, then the index finger will point toward you). If you modeled your matrix calculations along those, then you'll get a right handed system as well.

A: Alright completely rewrote this last night and I hope you find it useful if you haven't already came up with your own solutions or someone else who comes along with a similar question.
By default your forward vector looks down the -Z, right vector looks down the +X, and up vector looks down the +Y.
When you decide to construct your world it really doesn't matter where you look if you have a 128x128 X,Z world and you are positioned in the middle at 64x64 how would any player know they are rotated 0 degrees or 180 degrees. They simply would not.
Now you mentioned you dislike the glRotatef and glTranslatef. I as well will not use methods that handle the vector and matrix math. Firstly I use a way where I keep track of the Forward, Up, and Right Vectors. So imagine yourself spinning around in a circle this is you rotating your forward vector. So when a player wants to let's say Run Straight ahead. you will move them along the X,Z of your Forward vector, but let's say they also want to strafe to the right. Well you will still move them along the forward vector, but imagine 90 degrees taken off the forward vector. So if we are facing 45 degrees we are pointing to the -Z and -X quadrant. So strafing will move us in the -Z and +X quadrant. To do this you simple do negate the sin value. Examples of both below, but this can be done differently the below is rough example to better explain the above.
Position.X -= Forward.X; //Run Forward.
Position.Z -= Forward.Z;

Position.X += Forward.Z; //Run Backwards.
Position.Z += Forward.Z

Position.X += Forward.X; //Strafe Right.
Position.Z -= Forward.Z;

Position.X -= Forward.X; //Strafe Left.
Position.Z += Forward.Z;

Below is how I initialize my view matrix. These are to only be performed one time do not put this in any looping code.
glMatrixMode(GL_MODELVIEW);

view_matrix[4] =  0.0f; //UNUSED.

view_matrix[3] =  0.0F; //UNUSED.
view_matrix[7] =  0.0F; //UNUSED.
view_matrix[11] = 0.0F; //UNUSED.
view_matrix[15] = 1.0F; //UNUSED.

update_view();
glLoadMatrix(view_matrix);

Then this is the update_view() method. This is to only to be called during a change in the view matrix.
public void update_view()
{
    view_matrix[0] =  Forward[0];
    view_matrix[1] =  Up[1] *  Forward[1];
    view_matrix[2] =  Up[0] * -Forward[1];

    view_matrix[5] =  Up[0];
    view_matrix[6] =  Up[1];

    view_matrix[8] =  Forward[1];
    view_matrix[9] =  Up[1] * -Forward[0];
    view_matrix[10] = Up[0] *  Forward[0];
}

The Position vectors are matricies [12], [13], and [14] and are negated. You can choose to store these or just use matrix[12], [13], [14] as the vector for position.
view_matrix[12] =  -Position.x;
view_matrix[13] =  -Position.y;
view_matrix[14] =  -Position.z;


Q: uploading an array to server in swift using Alamofire This is how I'm saving the data successfully to model class when user login
var isLogin: IsLogin!
var loginDetail: LoginDetail!
var myDetail: MyDetail!

let decoder = JSONDecoder()
do{
    isLogin = try decoder.decode(IsLogin.self, from: response.data!)
    loginDetail = isLogin.success
    myDetail = loginDetail.user
}catch{
    print(error)
}

here is my model class where I'm saving response from the request
struct IsLogin: Decodable {
    var success: LoginDetail
}
struct LoginDetail: Decodable {
    var user: MyDetail
}

struct MyDetail: Decodable {
    var id: Int
    var emergency_contacts: [EmergencyContacts]?
}
struct EmergencyContacts: Decodable {
    var user_id : Int
    var number : String
}

I want to post EmergencyContacts in another request how do I do that? This is how im trying but in response array of EmergencyContacts is always empty
multipartFormData.append("\(myDetail.emergency_contacts!)".data(using: .utf8,allowLossyConversion: false)!,
`enter code here`withName: "emergency_contacts")

I have print all the values from model class and they are fine but guide me about how to send an array in a post request.Please suggest my some method using multipartformdara because I have been using this to send other parameters as well.below is the postman screenshot where If I send parameters like this then I can get the emergencycontacts in response 13 is the id of emergency contact


Q: How to use a template template argument from a member templated type alias of a struct I'm trying to use a template template argument coming from a member type alias of a struct, but I can't find the right syntax:
struct A
{
   template <typename T>
   using type = int;
};

template <template <typename> class C>
struct B
{
   // ...
};

B<typename A::type> b; // Does not compile: error: template argument for template template parameter must be a class template or type alias template
B<typename A::template type> b; // Does not compile: error: expected an identifier or template-id after '::'
B<typename A::template <typename> type> b; // Does not compile
B<typename A::template <typename> class type> b; // Does not compile

A: A::type is a template, not a typename.
B<A::template type> b1;  // OK
B<A::type> b2;           // OK


Q: Neural network to tag multiple textual topics in a single document I want to use a neural network to do some topic analysis in a textual corpus. I have used neural networks before where there is a clear decision boundary between the category to which some observation belongs. However, in topic modeling, a single document can have multiple topics present simultaneously.
So I want to know if I can train a neural network model to associate multiple topics to each document in the corpus. I suppose this could be some sort of vector that just indicates the probability of some topic existing in that document>
I was looking around for any papers on this topic, so if there are any citations that you want to pass along, that would help too.

A: Yes you can use neural networks in this way - it's an example of multi-label learning. There are many approaches, but one is to create binary target vectors indicating which labels should be applied to each document. Or a vector of probabilities as you suggest.
There are plenty of papers on multilabel learning, with or without neural nets - one recent review is Zhang & Zhou 2014.


Q: Low sound on xubuntu 18.04 (better than no sound of other distros I tried) I have got xubuntu 18.04 on old Toshiba Satellite M115-S1061 notebook.
The sound was great with WinXP, so no hardware problem.
I tried Lubuntu 16.04, Lubuntu 18.04 and Linux Mint Mate19.3. All with "no sound problem".
Now xubuntu 18.04 has at least some very very low sound in headphones. Alsamixer unmuted, Pavucontrol on maximum.
Plese, have you got some hint for me?
I hope you are ok and enjoying your quarantine.
 Josef

A: Citation from Low sound volume with headphones and System volume too low on Ubuntu 18.04
Open Alsamixer and set speaker volume to zero.

However this doesn't resolve your problem then,
pactl set-sink-volume 0 200%


Q: How to save on Camera Photo on Custom Location? I am currently using the following code here:
val cameraRequestCode = 1
val cameraPermissionCode = 1
var imageUri : Uri? = null

@RequiresApi(api = Build.VERSION_CODES.M)
override fun onActivityResult(
    requestCode: Int,
    resultCode: Int,
    data: Intent?
) {
    super.onActivityResult(requestCode, resultCode, data)
    if (requestCode == cameraRequestCode) {
        if (resultCode == Activity.RESULT_OK) {
            var stream: FileOutputStream? = null
            try {
                val photo: Bitmap =
                    MediaStore.Images.Media.getBitmap(contentResolver, imageUri)
                val saveFilePath: String = getRealPathFromURI(imageUri)
                stream = FileOutputStream(saveFilePath)
                photo.compress(Bitmap.CompressFormat.JPEG, 25, stream)
            } catch (e: IOException) {
                e.printStackTrace()
                Toast.makeText(
                    applicationContext,
                    "Can't save image !",
                    Toast.LENGTH_SHORT
                ).show()
            } finally {
                try {
                    if (stream != null) {
                        stream.close()
                        Toast.makeText(
                            applicationContext,
                            "Image saved successfully !",
                            Toast.LENGTH_SHORT
                        ).show()
                    } else {
                        Toast.makeText(
                            applicationContext,
                            "Can't save image, try again !",
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }

            farmersPixImageView.setImageURI(imageUri)
        } else if (resultCode == Activity.RESULT_CANCELED) {
            Toast.makeText(applicationContext, "Cancelled", Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(applicationContext, "Can't capture image !", Toast.LENGTH_SHORT)
                .show()
        }
    }
}

private fun getRealPathFromURI(contentUri: Uri?): String {
    val proj = arrayOf(MediaStore.Images.Media.DATA)
    val cursor: Cursor = managedQuery(contentUri, proj, null, null, null)
    val column_index: Int = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
    cursor.moveToFirst()
    return cursor.getString(column_index)
}

@RequiresApi(Build.VERSION_CODES.M)
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_add)

    farmersPixImageView.setOnClickListener {
        //if system os is Marshmallow or Above, we need to request runtime permission
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.CAMERA)
                == PackageManager.PERMISSION_DENIED ||
                checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_DENIED
            ) {
                //permission was not enabled
                val permission = arrayOf(
                    Manifest.permission.CAMERA,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                )
                //show popup to request permission
                requestPermissions(permission, cameraPermissionCode)
            } else {
                val values = ContentValues()

                values.put(
                    MediaStore.Images.Media.TITLE,
                    "${relativeFileName}_${System.currentTimeMillis()}"
                )
                values.put(
                    MediaStore.Images.Media.DISPLAY_NAME,
                    "${relativeFileName}_${getDate(
                        System.currentTimeMillis(),
                        "MM/dd/yyyy hh:mm:ss.SSS"
                    )}"
                )
                values.put(MediaStore.Images.Media.DESCRIPTION, "My Photos")
                values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")

                imageUri = contentResolver.insert(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    values
                )
                val cameraIntent =
                    Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
                startActivityForResult(cameraIntent, cameraRequestCode)
            }
        }
    }
}

I am using this because I could not get the sample from the Official Documentation to work.
I previously used:
    values.put(MediaStore.Images.Media.RELATIVE_PATH, relativeLocation)

but it is only available on Android Q onwards.
I also don't know how to use imageUri to save to custom location because it using contentResolver:
imageUri = contentResolver.insert(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                values
            )

How do I save the photo on custom location using the above code?


Q: Random access of multiple files and file caching This relates to some software I've been given to "fix". The easiest and quickest solution would make it open and read 10 random files out of hundreds and extract some very short strings for processing and immediately close them. Another process may come along right after that and do the same thing to different, or the same, random files and this may occur hundreds of times in a few seconds.
I know modern operating systems keep those files in memory to a point so disk thrashing isn't an issue as in the past but I'm looking for any articles or discussions about how to determine when all this open/closing of many random files becomes a problem.

A: When your working set (the amount of data read by all your processes) exceeds your available RAM, your throughput will tend towards the I/O capacity of your underlying disk.
From your description of the workload, seek times will be more of a problem than data transfer rates.
When your working set size stays below the amount of RAM you have, the OS will keep all data cached and won't need to go to the disk after having its caches filled.


Q: ¿Cómo detectar que parte de un script PHP provoca lentitud? Tengo un fichero script.php que se ejecuta todas las noches, y lo que ocurre es lo siguiente:

Como habrán podido apreciar, todas las madrugadas a la misma hora el uso del CPU se eleva al 100%, también se eleva la RAM y se disminuye el espacio en Disco considerablemente.
¿Cómo puedo hacer un Debug para poder determinar que zona del código genera esto? Yo estoy haciendo uso de múltiples procesos (script.php genera alrededor de 50 procesos hijos), y cada proceso hace miles de peticiones a CouchDB y a veces a Apache Lucene, estoy seguro que este ultimo es el causante de esto, pero ¿cómo lo puedo hacer debug?

A: Puedes perfilar el código utilizando herramientas tipo XDEBUG https://xdebug.org/docs/profiler o WebGrind https://github.com/jokkedk/webgrind
Puedes utilizar un sistema de mensajes tipo PHP-Resque https://github.com/chrisboulton/php-resque o RabbitMQ https://www.rabbitmq.com/
Optimizar las bases de datos utilizando caches con Memcached o Redis.
Supongo que CouchDB y Apache Lucene los tienes optimizados.


Q: Inverted a Responsive Size for an Image I'm attempting to use the following design on a responsive website. I'm curious if there's a way to set up some sort of inverse resizing method through jQuery / Javascript because as the viewport gets smaller, the copy will respond and get larger.
I've tried using jQuery to modify the image size, but I only know enough to manually resize it at different breakpoints
Here's my attempt at a solution:
var viewportWidth = $(window).width();

if (viewportWidth <= 768) {
$("#curlybrace").css("width", "80px");
}

Is there a way to set up a dynamic scaling image?

A: Try looking into CSS and media queries, seems like it would be a neater solution than trying to do this with JS.

A: You would use something like this:
 function resizeFn() {
   var width = window.width();
   // ...
 }

 $(function() {
   $(window).resize(resizeFn).trigger('resize');
 });

Not possible to do an inverse with CSS, I don't think (I thought maybe through calc(), but I don't think it lets you do unit manipulations like that).
Fair warning, this doesn't sound like a good design unless you're trying to make it look nuts.


Q: Type of capacitor for crystal resonator The Atmega328p datasheet recommends the following circuit to work with its internal crystal resonator:

simulate this circuit – Schematic created using CircuitLab
I can't find any recommendations on the type of capacitors to use.  I think the reasonable options are mica and thin film. Maybe also ceramic NP0 (emphasis on the NP0 type), which is a lot less expensive.
Any advice?  I tend to believe that either type is ok, mica and thin film probably being the absolutely safe bet?  Again, any comments will be appreciated.

A: One might choose an X7R cap if was essential for profitability to shave a penny in small sizes or for gen. purpose use but in important applications where accuracy and quality is important, always choose NP0/COG 1% if the value is <1000 pF.  ( low k density)
So choosing an NP0/COG is wisest for several reasons. (low-microphonics, zero temp error (<50ppm) and stable accuracy with V, aging etc.)  But if your tolerance is high , you can use the internal RC oscillator.
For ceramic caps with stable temperature curves, N250 is -250 ppm/'C while  P150 is +150ppm/'C  and NP0 is 0 ppm +/-50ppm/'C  ( aka COG)

The value is twice the rated crystal load capacitance (in series becomes half) minus stray load proximity to ground plane and input capacitance (e.g. 2*C + 2~3pF = CL )
But the other answers are also correct, in a benign environment, any cap will help it oscillate.
AT cut Crystals have a 3rd order temperature curve that are cut for different tolerances and temperature,T,  ranges to control the peak frequency f(T) swings which crossover at room temp.   So the value of these caps shifts to Xtal curve at 25'C temp to the precise frequency specified for rated load within the specified ppm tolerance.  (25~100ppm)
Parallal Cap Xtals are always specified by f, Tolerance/ Stability/ aging and temp range.  e.g. XTAL, 10.000 MHz 50/50/5 ppm, -40 ~ +70'C  xxyy case
While Tuning fork resonators have a 2nd order (parabolic) temperature curve centered at room temp. so a cap. selection cannot compensate for this in a TCXO, only a varicap diode with a custom correction curve.

A: Unless you need absolute frequency stability, any capacitor should be just fine.
The crystal’s own temperature coefficient may affect the frequency more than the capacitor’s temperature coefficient.
If you need absolute frequency stability, you need to find capacitors whose temperature coefficient will compensate the crystal’s (that’s a TCXO) or make a circuit whose temperature is controlled (that’s an OCXO).

A: Worked with a gal who designed crystal oscillator circuits for MCUs.
She called me into the lab one day because "My amplitude at 40MHz is so high we are afraid the crystal will be overheated and break. Can you figure out why the VoltPP is so high?"
After a couple hours of lab observation and listening, and couple days of musing as worked on other tasks, I realized the ESD structures were consuming so much energy, at 40MHz, the stable amplitude was indeed higher than simulated.
The ESD losses needed to be in the simulation. Only recently, 10 years later, is that company learning to characterize their IOpads/circuits with Network Analyzers.
Summary: the capacitor losses matter. There is no difference between PCB capacitors and onchip ESD-diode-junction-capacitance. ESR matters.


Q: scraping only a particular tag without details from nested tag in that particular tag I have a page where the structure is something like

Now what I want is I want to extract all 'a' tags inside an article but such that no 'a' tag comes from any nested
that is
articles = browser.find_elements_by_tag_name("article")
for i in article:
    print(i.find_elements_by_tag_name("a")

for first article
now i.find_elements will return all 'a' tags inside this article tag which will also include 'a' tags inside 'article tag' that is itself nested in current article tag but i dont want that
I want if i call find_elements on article no 1 'a' tags in article no 2 or in any nested article should not come

A: If you want links from not nested articles, try:
articles = browser.find_elements_by_tag_name('article'):
for article in articles:
    print(article.find_elements_by_xpath('./*[not(descendant-or-self::article)]/descendant-or-self::a'))

A: Parse the article element with BeautifulSoup and get all the anchor tags in ease.
from bs4 import BeautifulSoup
articles = browser.find_elements_by_tag_name("article")
links = []
for i in articles:
    soup = BeautifulSoup(i.get_attribute('outerHTML'), 'html5lib')
    a_tags = soup.findAll('a')
    links.extend(a_tags)

Hope this helps! Cheers!

A: using BeautifulSoup,
try to find all  under <articla> like ('article a')
then use find_parents() method of beautifulsoup.
If length of ('article a').find_parents('article') is bigger than 2, that might be nested like this.

  ..

    ..

so if you remove them you will get  that has only one
 parent
all_a = soup.findAll('article a')

direct_a = [i for i in all_a if len(i)>2]


Q: Is it possible to automatically detect types in Specflow tables? If I have a Techtalk.Specflow.Table, is it possible to detect automatically the appropriate types of the elements in the table ?
For exemple, if I have the following steps :
Given the following ticket sold on the 2019-01-01
|TicketId|Owner     |Amount|Seat|
|0033    |John Doe  |20.00 |3F  |

If I define my step like this
[Given(@"Given the following ticket sold on the (.*)")]
public void GivenTheFollowingPosition(DateTime date, Table table)
{
}

Specflow is capable of detecting and cast the date correctly. Therefore I assume it should also be capable of doing so for the elements of the table. Do you know if it is possible to achieve it and how ?
Have a nice day

A: Have a look at SpecFlow Assist Helpers. There are a few helpful methods, you can try to use table.CreateInstance<T> method to convert row in your table to object for future use. You can also specify the custom mapping using TableAliases attribute, see Working Effectively with SpecFlow Tables article for details


Q: Can we override wsa:To value in SOAP 1.2 I want to override wsa:To element value in SOAP 1.2 message. Can I do this by adding "To" HTTP header to the request ?
Could you explain the use of this wsa:To element value on the SOAP 1.2 message header ?

A: No. wsa:To is a SOAP header block, not an HTTP header.


Q: Postgres: is it posible to see how a Database View is constructed is it posible to see how a Database View is constructed in Postgres, to see wich query was used to create that view?

A: In psql:
\d+ the_view

--or

select definition from pg_views where viewname = 'the_view';


Q: First link of pagination shows 404 page in CodeIgniter I am working on pagination of category page. my route is
$route['category/(:any)/(:num)'] = 'public_controller/category/$1';

And url to go to category page is http://localhost/ecom/category/seats but it shows 404 error page. but when I give http://localhost/ecom/category/seats/1 it works fine and pagination also works fine second and third links are also working but when I click on 1 in pagination it shoes 404 error page. my controller code is
   public function category($cat_slug = null,$offset = null){
 $cat_id = $this->db->where('cat_slug',$cat_slug)->get('categories')->row_array();
 $config['base_url'] = base_url() .'category/'.$cat_slug;
    $config['total_rows'] = $this->db->where('cat_id',$cat_id['cat_id'])->count_all('products');
    $config['per_page'] = 4;
    $config['uri_segment'] = 3;
$config['use_page_numbers'] = TRUE;
    $config['full_tag_open'] = "
";
    $config['full_tag_close'] ="
";
    $config['num_tag_open'] = '
';
    $config['num_tag_close'] = '
';
    $config['cur_tag_open'] = "

";
    $config['cur_tag_close'] = "
";
    $config['next_tag_open'] = "
";
    $config['next_tagl_close'] = "
";
    $config['prev_tag_open'] = "
";
    $config['prev_tagl_close'] = "
";
    $config['first_tag_open'] = "
";
    $config['first_tagl_close'] = "
";
    $config['last_tag_open'] = "
";
    $config['last_tagl_close'] = "
";

    $this->pagination->initialize($config);
 $data['products'] = $this->public_model->category_page($cat_slug,$config['per_page'],$offset);
 $id['cat_slug'] = $cat_slug;
 $this->load->view('public_temp/header1');
 $this->load->view('public_temp/left1',$id);
 $this->load->view('public/category',$data);
 $this->load->view('public_temp/footer1');
}

What can I try to resolve this?

A: It shows because your router expect 2 parameter but you are giving 1 parameter seats
Define your route this way
$route['category/(:any)/(:num)'] = 'public_controller/category/$1/$2';

Now call your route http://localhost/ecom/category/seats/0 for category page
http://localhost/ecom/category/seats/1 for first pagination
if you want to separate your category route Define two route one for category page and other for category pagination
For category page
$route['category/(:any)'] = 'public_controller/category/$1';

For category pagination
$route['category/(:any)/(:num)'] = 'public_controller/category/$1/$2';

A: So, I created a demo for your problem and this is what worked for me ↓↓
$route['category']               = 'my_controller/category';       // this route handles all the requests without any additional segments
$route['category/(:any)']        = 'my_controller/category/$1';    // this route handles the requests when only one segment is present
$route['category/(:any)/(:num)'] = 'my_controller/category/$1/$2'; // this route handles the requests when there are two segments(2nd parameter being a number)

This is possible because

Routes will run in the order they are defined. Higher routes will
  always take precedence over lower ones.(Reference)

I also found a similar question you might wanna take a look at.
Hope this resolves your issue.


Q: Using Case Statements with Not Exists as Part of Where Clause I'm calculating the depreciation of vehicles and need to grab the previous month's values if it exists.
I've written a case statement in the where clause to see if the value exists. If it does, then I want to subtract one month and use that value to get the previous months data. If it does not exist then I want the current month's data. But it'll only do one or the other. Am I messing up where the exists is?
SELECT b.*
--this is month we want to compare (For example month 45)
FROM #changes AS a
--this has all the months  (for example month 1-50)
INNER JOIN work.dbo.DepreciationSchedule AS b
    ON b.VehicleID = a.VehicleID
--If the previous months value exists in table b (Ex month 44), then take take that months value otherwise take the current value of table a (Ex month 45)
WHERE b.Month = CASE
                    WHEN EXISTS(SELECT *
                                 FROM #changes AS innerA
                                 WHERE innerA.month = a.month - 1)
                    THEN a.Month - 1
                    ELSE a.Month
                END

A: I figured it out. There were two things that I had to change.

*

*Add the vehicle ID to the current subquery to make sure that I only wanted those vehicles in the temp table

*Change the subquery table to the depreciation schedule
Select b.*
    --this is month we want to compare (For example month 45)
    From #changes As a
    --this has all the months  (for example month 1-50)
    Inner Join work.dbo.DepreciationSchedule As b
    On b.VehicleID = a.VehicleID
    --If the previous months value exists in table b (Ex month 44), then take take that months value otherwise take the current value of table a (Ex month 45)
    Where b.Month = Case When  Exists (Select * From work.dbo.DepreciationSchedule As innerA Where innerA.month = a.month - 1 and innerA.VehicleID = a.vehicleID) Then a.Month -1  Else a.Month end


Q: overloading operator== complaining of 'must take exactly one argument' I am trying to overload the operator==, but the compiler is throwing the following error:
‘bool Rationalnumber::operator==(Rationalnumber, Rationalnumber)’ must take exactly one argument

My short piece of code is as follows:
bool Rationalnumber::operator==(Rationalnumber l, Rationalnumber r) {
  return l.numerator() * r.denominator() == l.denominator() * r.numerator();
}

Declaration:
bool operator==( Rationalnumber l, Rationalnumber r );

Does anyone have any ideas why it's throwing the error?

A: As a member operator overload it should only take one argument, the other being this.
class Foo
{
    int a;

public:
    bool operator==(const Foo & foo);
};

//...

bool Foo::operator==(const Foo & foo)
{
    return a == foo.a;
}

A: If operator== is a non static data member, is should take only one parameter, as the comparison will be to the implicit this parameter:
class Foo {
  bool operator==(const Foo& rhs) const { return true;}
};

If you want to use a free operator (i.e. not a member of a class), then you can specify two arguments:
class Bar { };
bool operator==(const Bar& lhs, const Bar& rhs) { return true;}

A: You should remove your operator== from a RationalNumber to somewhere else.
As it is declared inside a class it is considered that 'this' is the first argument. From semantics it is seen that you offer 3 arguments to a compiler.

A: friend bool operator==( Rationalnumber l, Rationalnumber r );

when you declare it as non-member function, it can take two arguments.
when you declare it as member function, it can only take one argument.


Q: Referencing Question I made the BibTeX file for the references, what I want is; as a result to have in the text the author name and the year and list it in the bibliography
I write it in this way
\documentclass [12pt]{article}
\usepackage{float}
\usepackage{authblk}
\usepackage{etoolbox}
\usepackage{amsmath}
\usepackage{graphicx}
\usepackage{subcaption}
\usepackage{tabularx,ragged2e,booktabs,caption}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage{caption}
\usepackage{amssymb}
\usepackage{graphicx,epstopdf}
\usepackage{caption}
\usepackage{graphicx,kantlipsum,setspace}
\usepackage{mathptmx}
\usepackage{pgfplots}
\captionsetup{font={stretch=1.0}}  %% this affects both figure and table
\setstretch{1.0}
\captionsetup[figure]{font=small,labelfont=bf}
\usepackage[left=6cm,top=3cm,right=2cm,bottom=3cm]{geometry}
\usepackage{lipsum}
\usepackage{setspace}
\usepackage[export]{adjustbox}
\usepackage{natbib}
\setstretch{1.5}
\newcolumntype{C}[1]{>{\Centering}m{#1}}
\renewcommand\tabularxcolumn[1]{C{#1}}
\newcommand\seqwlimits[3]{\{#1\}_{\mathstrut#2}^{\mathstrut#3}}
\begin{document}
bla bla .... \cite{BOLLERSLEV1986307}

\bibliography{refrences}
\bibliographystyle{plain}

\end{document}

My BiB file I wrote it like this:
@article{NIETO2016475,
title = "Frontiers in VaR forecasting and backtesting",
journal = "International Journal of Forecasting",
volume = "32",
number = "2",
pages = "475 - 501",
year = "2016",
issn = "0169-2070",
doi = "https://doi.org/10.1016/j.ijforecast.2015.08.003",
url = "http://www.sciencedirect.com/science/article/pii/S016920701500120X",
author = "Maria Rosa Nieto and Esther Ruiz"
}

@article{article,
    author = {Haas, Markus},
    year = {2006},
    month = {01},
    pages = {},
    title = {Improved Duration-Based Backtesting of Value-at-Risk},
    volume = {8},
    booktitle = {Journal of Risk}
}

@article{PRITSKER2006561,
    title = "The hidden dangers of historical simulation",
    journal = "Journal of Banking & Finance",
    volume = "30",
    number = "2",
    pages = "561 - 582",
    year = "2006",
    note = "Risk Management and Optimization in Finance",
    issn = "0378-4266",
    doi = "https://doi.org/10.1016/j.jbankfin.2005.04.013",
    url = "http://www.sciencedirect.com/science/article/pii/S037842660500083X",
    author = "Matthew Pritsker",
}

@ARTICLE{perigon,
    title = {The level and quality of Value-at-Risk disclosure by commercial banks},
    author = {Pérignon, Christophe and Smith, Daniel},
    year = {2010},
    journal = {Journal of Banking & Finance},
    volume = {34},
    number = {2},
    pages = {362-377},}

@book{jorion2001value,
    title={Value at Risk: The New Benchmark for Managing Financial Risk},
    author={Jorion, P.},
    isbn={9780071355025},
    lccn={00033239},
    series={MacGraw-Hill international editions: Finance series},
    url={https://books.google.de/books?id=S2SsFblvUdMC},
    year={2001},
    publisher={McGraw-Hill}
}

@article{BOLLERSLEV1986307,
    title = "Generalized autoregressive conditional heteroskedasticity",
    journal = "Journal of Econometrics",
    volume = "31",
    number = "3",
    pages = "307 - 327",
    year = "1986",
    issn = "0304-4076",
    doi = "https://doi.org/10.1016/0304-4076(86)90063-1",
    url = "http://www.sciencedirect.com/science/article/pii/0304407686900631",
    author = "Tim Bollerslev"
}

@article{Riskmetrics,
    title = " RISKMETRICS. Risk management: a practical guide. 1st Edition. NewYork: RMG,
    year = "1999",}

@mastersthesis{Nieppola,
    title={Backtesting Value-at-Risk Models},
    author={Nieppola, Olli},
    year={2009},
    language={en},
    pages={78},
    type={G2 Pro gradu, diplomityö},
    url={http://urn.fi/URN:NBN:fi:aalto-201111151093},
}

@article{haas2001new,
    title={New methods in backtesting},
    author={Haas, Marcus},
    year={2001}
}

@article{campbell2005review,
    title={A review of backtesting and backtesting procedures},
    author={Campbell, Sean D and others},
    year={2005},
    publisher={Divisions of Research \& Statistics and Monetary Affairs, Federal Reserve Board}
}

@article{christoffersen2004backtesting,
    title={Backtesting value-at-risk: A duration-based approach},
    author={Christoffersen, Peter and Pelletier, Denis},
    journal={Journal of Financial Econometrics},
    volume={2},
    number={1},
    pages={84--108},
    year={2004},
    publisher={Oxford University Press}
}

@article{christoffersen1998evaluating,
    title={Evaluating interval forecasts},
    author={Christoffersen, Peter F},
    journal={International economic review},
    pages={841--862},
    year={1998},
    publisher={JSTOR}
}

@article{pajhede2017backtesting,
    title={Backtesting Value-at-Risk: A Generalized Markov Test},
    author={Pajhede, Thor},
    journal={Journal of Forecasting},
    volume={36},
    number={5},
    pages={597--613},
    year={2017},
    publisher={Wiley Online Library}
}

@article{berkowitz2011evaluating,
    title={Evaluating value-at-risk models with desk-level data},
    author={Berkowitz, Jeremy and Christoffersen, Peter and Pelletier, Denis},
    journal={Management Science},
    volume={57},
    number={12},
    pages={2213--2227},
    year={2011},
    publisher={INFORMS}
}

@article{ziggel2014new,
    title={A new set of improved Value-at-Risk backtests},
    author={Ziggel, Daniel and Berens, Tobias and Wei{\ss}, Gregor NF and Wied, Dominik},
    journal={Journal of Banking \& Finance},
    volume={48},
    pages={29--41},
    year={2014},
    publisher={Elsevier}
}

@article{santos2012,
    title={A new class of independence tests for interval forecasts evaluation},
    author={Santos, P Ara{\'u}jo and Alves, MI Fraga},
    journal={Computational Statistics \& Data Analysis},
    volume={56},
    number={11},
    pages={3366--3380},
    year={2012},
    publisher={Elsevier}
}

I got many errors and not all entrys has been listed.

A: To get all entrys cited you have in your bib file you can simply use command \nocite{*}.
You did not tell us which errors you got, but in your bib file are 3 errors in the following entrys:
@article{PRITSKER2006561,
    title = "The hidden dangers of historical simulation",
    journal = "Journal of Banking \& Finance",   <==========================

@ARTICLE{perigon,
    title = {The level and quality of Value-at-Risk disclosure by commercial banks},
    author = {Pérignon, Christophe and Smith, Daniel},
    year = {2010},
    journal = {Journal of Banking \& Finance},  <==========================

@article{Riskmetrics,
    title = "RISKMETRICS. Risk management: a practical guide. 1st Edition. NewYork: RMG",  <==========================
    year = "1999",}

In the first two entrys you have to mask & with \: \&. In the third entry is a closing " missing. Correct this entry completly!
So with the following MWE (package filecontents is only used to get an compilable MWE)
\RequirePackage{filecontents}
\begin{filecontents*}{\jobname.bib}
@article{NIETO2016475,
title = "Frontiers in VaR forecasting and backtesting",
journal = "International Journal of Forecasting",
volume = "32",
number = "2",
pages = "475 - 501",
year = "2016",
issn = "0169-2070",
doi = "https://doi.org/10.1016/j.ijforecast.2015.08.003",
url = "http://www.sciencedirect.com/science/article/pii/S016920701500120X",
author = "Maria Rosa Nieto and Esther Ruiz"
}

@article{article,
    author = {Haas, Markus},
    year = {2006},
    month = {01},
    pages = {},
    title = {Improved Duration-Based Backtesting of Value-at-Risk},
    volume = {8},
    booktitle = {Journal of Risk}
}

@article{PRITSKER2006561,
    title = "The hidden dangers of historical simulation",
    journal = "Journal of Banking \& Finance",
    volume = "30",
    number = "2",
    pages = "561 - 582",
    year = "2006",
    note = "Risk Management and Optimization in Finance",
    issn = "0378-4266",
    doi = "https://doi.org/10.1016/j.jbankfin.2005.04.013",
    url = "http://www.sciencedirect.com/science/article/pii/S037842660500083X",
    author = "Matthew Pritsker",
}

@ARTICLE{perigon,
    title = {The level and quality of Value-at-Risk disclosure by commercial banks},
    author = {Pérignon, Christophe and Smith, Daniel},
    year = {2010},
    journal = {Journal of Banking \& Finance},
    volume = {34},
    number = {2},
    pages = {362-377},}

@book{jorion2001value,
    title={Value at Risk: The New Benchmark for Managing Financial Risk},
    author={Jorion, P.},
    isbn={9780071355025},
    lccn={00033239},
    series={MacGraw-Hill international editions: Finance series},
    url={https://books.google.de/books?id=S2SsFblvUdMC},
    year={2001},
    publisher={McGraw-Hill}
}

@article{BOLLERSLEV1986307,
    title = "Generalized autoregressive conditional heteroskedasticity",
    journal = "Journal of Econometrics",
    volume = "31",
    number = "3",
    pages = "307 - 327",
    year = "1986",
    issn = "0304-4076",
    doi = "https://doi.org/10.1016/0304-4076(86)90063-1",
    url = "http://www.sciencedirect.com/science/article/pii/0304407686900631",
    author = "Tim Bollerslev"
}

@article{Riskmetrics,
    title = " RISKMETRICS. Risk management: a practical guide. 1st Edition. NewYork: RMG",
    year = "1999",}

@mastersthesis{Nieppola,
    title={Backtesting Value-at-Risk Models},
    author={Nieppola, Olli},
    year={2009},
    language={en},
    pages={78},
    type={G2 Pro gradu, diplomityö},
    url={http://urn.fi/URN:NBN:fi:aalto-201111151093},
}

@article{haas2001new,
    title={New methods in backtesting},
    author={Haas, Marcus},
    year={2001}
}

@article{campbell2005review,
    title={A review of backtesting and backtesting procedures},
    author={Campbell, Sean D and others},
    year={2005},
    publisher={Divisions of Research \& Statistics and Monetary Affairs, Federal Reserve Board}
}

@article{christoffersen2004backtesting,
    title={Backtesting value-at-risk: A duration-based approach},
    author={Christoffersen, Peter and Pelletier, Denis},
    journal={Journal of Financial Econometrics},
    volume={2},
    number={1},
    pages={84--108},
    year={2004},
    publisher={Oxford University Press}
}

@article{christoffersen1998evaluating,
    title={Evaluating interval forecasts},
    author={Christoffersen, Peter F},
    journal={International economic review},
    pages={841--862},
    year={1998},
    publisher={JSTOR}
}

@article{pajhede2017backtesting,
    title={Backtesting Value-at-Risk: A Generalized Markov Test},
    author={Pajhede, Thor},
    journal={Journal of Forecasting},
    volume={36},
    number={5},
    pages={597--613},
    year={2017},
    publisher={Wiley Online Library}
}

@article{berkowitz2011evaluating,
    title={Evaluating value-at-risk models with desk-level data},
    author={Berkowitz, Jeremy and Christoffersen, Peter and Pelletier, Denis},
    journal={Management Science},
    volume={57},
    number={12},
    pages={2213--2227},
    year={2011},
    publisher={INFORMS}
}

@article{ziggel2014new,
    title={A new set of improved Value-at-Risk backtests},
    author={Ziggel, Daniel and Berens, Tobias and Wei{\ss}, Gregor NF and Wied, Dominik},
    journal={Journal of Banking \& Finance},
    volume={48},
    pages={29--41},
    year={2014},
    publisher={Elsevier}
}

@article{santos2012,
    title={A new class of independence tests for interval forecasts evaluation},
    author={Santos, P Ara{\'u}jo and Alves, MI Fraga},
    journal={Computational Statistics \& Data Analysis},
    volume={56},
    number={11},
    pages={3366--3380},
    year={2012},
    publisher={Elsevier}
}
\end{filecontents*}

\documentclass[10pt,a4paper]{article}

\usepackage{showframe}  % to visualise the typing area and margins
\usepackage{natbib}
\usepackage{hyperref}

\begin{document}

This is text with \cite{BOLLERSLEV1986307} or \citet{BOLLERSLEV1986307}.

\nocite{*} % to test all bib entrys
\bibliographystyle{plainnat} % plain
\bibliography{\jobname}

\end{document}

you get the following result:

As you will see there a seven warning because there are details for several entrys missing, for example journals or authors.  Entry Riskmetrics needs to be completly reworked ...
If you have other errors in your TeX code I omitted please add the exact error messages to your question!


Q: Sumproduct VBA with Loop I know this question has been asked ad nauseum in some form or other, but all of my Googling hasn't led me to a solution.  I want to use Sumproduct in a VBA loop with moving criteria references.  I know that Sumproduct doesn't work the same in VBA as it does in a spreadsheet.  The formula I'm trying to replicate is as follows:
=Sumproduct([KNA_Amt]*--([KNA_Dt]=h$25)*--([KNA_Cat]=$b47)*--([KNA_Prgm]=$D$8))

and in an worksheet, this would be dragged down 6 lines and across 12 columns.
In VBA, I have the following code, which obviously doesn't work...
sub CalcualteSFA()
Dim r As Long
Dim c As Long

r = 87: c = 8
For for_col = 1 To 12
Cells(r, c) = WorksheetFunction.SumProduct([KNA_Amt]*--([KNA_Dt]=Cells(25, c))*--([KNA_Cat]=cells(r,2))*--([KNA_Prgm]=cells(8,4))
r=r+1
next
r=87
c=c+1
next
end sub

So I know that the coding doesn't work, but can someone help me by figuring out a code that would?
Thanks so much!

A: Multiple formulas can be assigned at the same time, and the relative (without $) row/column references will be auto adjusted :
Sub CalcualteSFA()

    Dim r As Range
    Set r = [H87:S92]

    r.Formula = "=Sumproduct([KNA_Amt]*--([KNA_Dt]=h$25)*--([KNA_Cat]=$b47)*--([KNA_Prgm]=$D$8))"

    r.Value = r.Value  ' optional to convert the formulas to values

End Sub