Q: ¿Como numerar las linea de texto en un QtextEdit desde QtDesigner? estoy manejando PyQt desde la herramienta el Qt Designer, por lo no programo la interfaz grafica desde el código puro.
Mi pregunta es, si tengo el siguiente texto en un QtextEdit
linea 1
linea 2
linea 3

¿Como logro ver  a la par el numero de linea?
Lo que busco es que sea similar a un editor de código

pero no estoy seguro de si eso se puede hacer desde Qt Designer o voy a tener que programar la clase para el editor en si.
Gracias

A: Si programa la GUI desde un código limpio, se ve así:
from PyQt5.QtCore import Qt, QRect, QSize
from PyQt5.QtWidgets import (QWidget, QPlainTextEdit, QTextEdit,
            QMainWindow, QAction, qApp, QApplication)
from PyQt5.QtGui import QColor, QPainter, QTextFormat, QKeySequence, QFont

class LineNumberArea(QWidget):
    def __init__(self, editor):
        super().__init__(editor)
        self.codeEditor = editor

    def sizeHint(self):
        return QSize(self.editor.lineNumberAreaWidth(), 0)

    def paintEvent(self, event):
        self.codeEditor.lineNumberAreaPaintEvent(event)

class PlainTextEdit(QPlainTextEdit):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.lineNumberArea = LineNumberArea(self)

        self.blockCountChanged.connect(self.updateLineNumberAreaWidth)
        self.updateRequest.connect(self.updateLineNumberArea)
        self.cursorPositionChanged.connect(self.highlightCurrentLine)
        self.updateLineNumberAreaWidth(0)

    def lineNumberAreaWidth(self):
        digits = 1
        max_value = max(1, self.blockCount())
        while max_value >= 10:
            max_value /= 10
            digits += 1
        space = 3 + self.fontMetrics().width('9') * digits
        return space

    def updateLineNumberAreaWidth(self, _):
        self.setViewportMargins(self.lineNumberAreaWidth(), 0, 0, 0)

    def updateLineNumberArea(self, rect, dy):
        if dy:
            self.lineNumberArea.scroll(0, dy)
        else:
            self.lineNumberArea.update(0, rect.y(), self.lineNumberArea.width(), rect.height())
        if rect.contains(self.viewport().rect()):
            self.updateLineNumberAreaWidth(0)

    def resizeEvent(self, event):
        super().resizeEvent(event)
        cr = self.contentsRect()
        self.lineNumberArea.setGeometry(QRect(cr.left(), cr.top(), self.lineNumberAreaWidth(), cr.height()))

    def highlightCurrentLine(self):
        extraSelections = []
        if not self.isReadOnly():
            selection = QTextEdit.ExtraSelection()
            lineColor = QColor(Qt.yellow).lighter(160)
            selection.format.setBackground(lineColor)
            selection.format.setProperty(QTextFormat.FullWidthSelection, True)
            selection.cursor = self.textCursor()
            selection.cursor.clearSelection()
            extraSelections.append(selection)
        self.setExtraSelections(extraSelections)

    def lineNumberAreaPaintEvent(self, event):
        painter = QPainter(self.lineNumberArea)
        painter.fillRect(event.rect(), Qt.lightGray)
        block = self.firstVisibleBlock()
        blockNumber = block.blockNumber()
        top = self.blockBoundingGeometry(block).translated(self.contentOffset()).top()
        bottom = top + self.blockBoundingRect(block).height()
        height = self.fontMetrics().height()

        while block.isValid() and (top <= event.rect().bottom()):
            if block.isVisible() and (bottom >= event.rect().top()):
                number = str(blockNumber + 1)
                painter.setPen(Qt.black)
                painter.drawText(0, top, self.lineNumberArea.width(), height, Qt.AlignRight, number)

            block = block.next()
            top = bottom
            bottom = top + self.blockBoundingRect(block).height()
            blockNumber += 1

if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    app.setFont(QFont("Times", 12, QFont.Bold))
    codeEditor = PlainTextEdit()
    codeEditor.show()
    sys.exit(app.exec_())


Q: How to specify range of port while creating httpserver? I am trying to create an http server using JDK's com.sun.net.httpserver. I am able to run the server with certain endpoints successfully. And it return some random ephemeral port ranging from 0 to 65536.
HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);

I was going through the documentation but I couldn't see a way to specify some range instead of specific port.
Is there any way passing range can be achieved?
One hack to the solution is try for all ports in range and see whichever works as specified in the solution - How to find an available port?


Q: change - to + in Common Lisp Is there way to change - (minus) function to + (plus) function?
My homework is to implement sin calculation on Macluaurin series
sin(x) = x-(x^3/3!)+(x^5/5!) -(x^7/7!)+(x^9/9!)-...

Each article has different sign. This is my Lisp code
(defun sinMac (x series n plusminus)
  (cond ((= series 0) 0)
        (t (funcall plusminus
                    (/ (power x n) (factorial n))
                    (sinMac x (- series 1) (+ n 2) plusminus)))))

Is it possible to change plusminus to exchange sign? if I get '+ function send '- to next recursive call. From that call (got '-) I call '+ and so on...

A: You could do it with a circular list. Like so:
(defun sin-mac (x series n plus-minus)
  (cond ((zerop series) 0)
        (t (funcall (car plus-minus)
                    (/ (power x n) (factorial n))
                    (sin-mac x (1- series) (+ n 2) (cdr plus-minus))))))

(sin-mac x series 1 '#0=(+ - . #0#))

Or even better, wrap up the initial arguments using labels:
(defun sin-mac (x series)
  (labels ((recur (series n plus-minus)
             (cond ((zerop series) 0)
                   (t (funcall (car plus-minus)
                               (/ (power x n) (factorial n))
                               (recur (1- series) (+ n 2) (cdr plus-minus)))))))
    (recur series 1 '#0=(+ - . #0#))))

A: If the function is a symbol, this is easy:
(defun next-function (function)
  (ecase function
    (+ '-)
    (- '+)))

(defun sinMac (x series n plusminus)
  (cond ((= series 0) 0)
        (t (funcall plusminus
                    (/ (power x n) (factorial n))
                    (sinMac x
                            (- series 1)
                            (+ n 2)
                            (next-function plusminus))))))

A: I would not swap the function but just the sign.  Using a loop for this also seems clearer to me (and is most likely more efficient, although there is still plenty of opportunity for optimization):
(defun maclaurin-sinus (x n)
  "Calculates the sinus of x by the Maclaurin series of n elements."
  (loop :for i :below n
    :for sign := 1 :then (- sign)
    :sum (let ((f (1+ (* 2 i))))
           (* sign
              (/ (expt x f)
                 (factorial f))))))

A few optimizations make this about 10 times faster (tested with n = 5):
(defun maclaurin-sinus-optimized (x n)
  "Calculates the sinus of x by the Maclaurin series of n elements."
  (declare (integer n))
  (loop :repeat n
    :for j :from 0 :by 2
    :for k :from 1 :by 2
    :for sign := 1 :then (- sign)
    :for e := x :then (* e x x)
    :for f := 1 :then (* f j k)
    :sum (/ e f sign)))


Q: Incompatible row dimensions The task is to encode all the text and categorical features and again combine them to form the data matrix but am getting the error incompatible row dimensions.
My work so far:
Encode categorical feature using Label Encoder
from sklearn.preprocessing import LabelEncoder

enc = LabelEncoder()

enc.fit(x_train[' Round'])

round_train_le = enc.transform(x_train[' Round'])
round_test_le = enc.transform(x_test[' Round'])

Encode Text feature category using TfIdfVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer

vectorizer1 = TfidfVectorizer(max_features=500)

vectorizer1.fit(x_train[' Category'])

category_train_enc = vectorizer1.transform(x_train[' Category'])
category_test_enc = vectorizer1.transform(x_test[' Category'])

print(category_train_enc.shape)
print(category_test_enc.shape)

Encode Text feature question using TfIdfVectorizer
vectorizer2 = TfidfVectorizer(max_features=5000)

vectorizer2.fit(x_train[' Question'])

question_train_enc = vectorizer2.transform(x_train[' Question'])
question_test_enc = vectorizer2.transform(x_test[' Question'])

print(question_train_enc.shape)
print(question_test_enc.shape)

Encode Text feature answer using TfIdfVectorizer
vectorizer3 = TfidfVectorizer(max_features=1000)

vectorizer3.fit(x_train[' Answer'])

answer_train_enc = vectorizer3.transform(x_train[' Answer'])
answer_test_enc = vectorizer3.transform(x_test[' Answer'])

print(answer_train_enc.shape)
print(answer_test_enc.shape)

Combining the encoded features:
from scipy.sparse import hstack
x_tr = hstack((round_train_le, category_train_enc, question_train_enc, answer_train_enc))
x_te = hstack((round_test_le, category_test_enc, question_test_enc, answer_test_enc))

print("Final Data matrix")
print(x_tr.shape, y_train.shape)
print(x_te.shape, y_test.shape)

And then am getting the following error:
ValueError                                Traceback (most recent call last)
<ipython-input-60-12e131ba4df4> in <module>
      1 # merge two sparse matrices: https://stackoverflow.com/a/19710648/4084039
      2 from scipy.sparse import hstack
----> 3 x_tr = hstack((round_train_le, category_train_enc, question_train_enc, answer_train_enc))
      4 x_te = hstack((round_test_le, category_test_enc, question_test_enc, answer_test_enc))
      5

~\anaconda3\lib\site-packages\scipy\sparse\construct.py in hstack(blocks, format, dtype)
    463
    464     """
--> 465     return bmat([blocks], format=format, dtype=dtype)
    466
    467

~\anaconda3\lib\site-packages\scipy\sparse\construct.py in bmat(blocks, format, dtype)
    584                                                     exp=brow_lengths[i],
    585                                                     got=A.shape[0]))
--> 586                     raise ValueError(msg)
    587
    588                 if bcol_lengths[j] == 0:

ValueError: blocks[0,:] has incompatible row dimensions. Got blocks[0,1].shape[0] == 145341, expected 1.

Please suggest what change i need to make in the code to resolve the error.

A: When using scipy.sparse.hstack() you have to ensure that all the elements you try to stack have the same 0's dimension, i.e., same number of rows. See the following example:
import numpy as np
from scipy.sparse import hstack

a = np.array([1, 2, 3, 4, 5])
b = np.array([1, 2, 3, 5])

c = hstack([a, b])
print(c)

Output:
 (0, 0) 1
  (0, 1)    2
  (0, 2)    3
  (0, 3)    4
  (0, 4)    5
  (0, 5)    1
  (0, 6)    2
  (0, 7)    3
  (0, 8)    5

On the other hand when the number of rows does not match - it results in the error you are getting:
import numpy as np
from scipy.sparse import hstack

a = np.array([1, 2, 3, 4, 5, 6])
b = np.array([[1, 2, 3], [4, 5, 6]])

c = hstack([a, b])
print(c)

Output:
ValueError: blocks[0,:] has incompatible row dimensions. Got blocks[0,1].shape[0] == 1, expected 2.

So you should check that all your items are of the same number of rows to join them row-wise
Cheers.


Q: Previous shell setting prevents console2 from starting Few months ago, I was using Cygwin and Console on windows 7  and created a bash session in Console. Now that I uninstalled Cygwin, Console complains with:
Unable to start a C:\cygwin\bin\bash.exe --login -i!

I sarched through the registry but couldn't find the remains of Console. How can I reset/get rid of this error?

A: Console stores profiles at:

C:\Users\ [USER] \AppData\Roaming\ [CONSOLE TAB NAME] \console.xml

Try Replacing it with original one located in Installation Directory,

C:\Program Files\Console2\console.xml

Path might be different depending on where you have installed it.

A: Do a registry cleanup with a software like Ccleaner, they are mutch better than you at finding orphaned keys. Otherwise uninstall console, restart the pc and reinstall it.


Q: How can I check if a window has WS_VISIBLE to set? (or if is visible) How can I do it? It's an external window, not from my program. Thanks

A: One nuance to be aware of. IsWindowVisible will return the true visibility state of the window, but that includes the visibility of all parent windows as well.
If you need to check the WS_VISIBLE flag for a specific window you can do GetWindowLong(hWnd, GWL_STYLE) and test for WS_VISIBLE.
... It sounds like you don't need to do this for your case, but adding this for future reference in case others run across this question.

A: Do you have an HWND to the window? If not, then you will need to obtain the window handle somehow, for example through FindWindow() (or FindWindowEx()).
Once you have the HWND to the window, call IsWindowVisible().


Q: cmd escaped after SoapUI test is finished I am calling SaopUI testrunnet from cmd file.
The problem is that lines after command for testrunner are not executed
I have unchecked "Fail testcase on error" checkbox in soap ui without any help.
Anyway, i have this issue regardless of test was successful or not
this is my command
%SoapUIPath%\testrunner.bat-sTestSuite %projectPath% -I -r -P var2=%var2% -P var1=%var1%
echo ###Test finished###

Echo "Test finished" will not be executed

A: If one batch file directly invokes another one, the execution flow is transfered to the called file, and not returned to the caller.
To retrieve the execution flow after the called file has ended, we need to use the call command
call "%SoapUIPath%\testrunner.bat" ....


Q: Cooper pairs and superconductivity This might be a dumb series of questions, because I'm not a theoretical or condensed matter physicist.
If there was a method of pairing all electrons before entering a semiconductor, would you essentially have a cheat code to turn any semiconductor into a superconductor, or does the lattice of semiconductors vibrate too much that pairs would still bump into it, disengaging the pairs, and losing energy to heat?
If the latter is true, is this because the energy required to maintain and disengage entanglement is low?
If the former may be true, would energy in the transmission of electrons still be lost due to the effort required to establish electron pairs?

A: Essentially, there is nothing special about the lattice of a semiconductor that would prevent it to "host" Cooper pairs.
The process that you describe of "pairing all electrons before entering [your preferred material here]" is called proximity effect. You just juxtapose a superconductor with another material (generally a non-superconducting metal, but semiconductors and even some insulators work) and the Cooper pairs from the superconductor will "take a walk" inside the other material. For your specific case, just google "proximity superconductivity in semiconductors" and you will find several references. Note that, here, superconductivity is not a property of the semiconducutor and will not survive inside it if you kill superconductivity in your nearby superconductor.
Besides the proximity effect, you can also have semiconductors that can show a superconducting transition by themselves (google "semiconductor superconductivity"). The key here is to dope the semiconductor in order to have a high enough mobile charge density (either electrons in the conduction band or holes in the valence band).


Q: Macbook Pro 5,1 will only boot after multiple SMC resets I have a Macbook Pro 5,1 (late 2008) running El Capitan (10.11), which is the latest officially supported OS for that machine. When I turn it off I cannot turn it back on without resetting the SMC multiple times (sometimes up to 20 times, sometimes just once is enough). The problem only occurs when the machine is turned off for at least a few hours, otherwise it turns on perfectly. This makes me think, that there could be some kind of small battery on the logic board which drains too fast due to the age of the Macbook? It doesn't matter how much the main battery is charged.
What I've tried so far:

*

*quick Apple Hardware Test without any results

*used different RAM

*used different internal HDD

*resetted NRAM/PRAM

*installed a new copy of the OS and then imported everything (Data and Settings) with the migration assistent

Any other Ideas?
Thanks in advance!

A: I’ve seen this before and it could be one of two things (generally speaking):

*

*failing power supply

*failing/failed SMC chip

When I mention "power supply" it can mean either the physical power supply like that in a Mac Pro (workstation) or the circuitry on the logic board of a MacBook (laptop) that manages where the current is sourced from - battery or external adapter.  There's power that goes to the SMC so that it can handle how and where power is distributed throughout the logic board.
It wouldn’t be a battery because when power is removed from an SMC chip, it actually resets.  So, resetting an already reset SMC wouldn’t do anything as you’ve demonstrated with the other numerous resets. However, what we have to remember is that when an SMC reset occurs, the whole system is being reset (warm power cycle).
The power supply (circuitry) could be failing in that not enough current is getting to the correct power rails until finally there’s enough capacity to get it to work; there could be dry solder contracts on any of the SMC components including the chip itself; or it could just be dying.
The least expensive DIY test you could do would be to replace the power supply with a known good one (if on a workstation), next followed by a replacement of the logic board.  Unfortunately, to get a proof positive diagnosis, you’d need high level told like an oscilloscope to accurately measure the power going to the individual power rails.
Ultimately, you'll need to send it in for service because there's nothing more that can be done from a DIY perspective.


Q: Ajax Caching and Correct Format used? I have a JavaScript event that is called like so:
function addEvent(date, resId) {

$("#appPlaceholder").load("/Schedule/Add?date=" + date.format()+"&resourceId="+resId,
             function () {
                 $('#eventModal').modal('show');
             });

    };

However am I using the correct standards to format/pass my variables?
.load("/Schedule/Add?date=" + date.format()+"&resourceId="+resId) ??
Also I need to make sure the load does not cache, how can I prevent this.
Any Examples much appreciated.

A: If you are not sure about URL encoding, use encodeURIComponent:
var date = encodeURIComponent(date.format());
var id = encodeURIComponent(resId);

To prevent from caching, add to the end some random value. For example:
'&v=' + Math.random()


Q: Почему выбрасывает ошибку mysql? CREATE TRIGGER marketing_list_update
AFTER UPDATE
ON cms_offers
FOR EACH ROW
begin
if NEW.status = 'active'
then UPDATE marketing_credits_requests SET sum_s=NEW.ammount, statut=NEW.status WHERE id_req=old.id;
else then UPDATE marketing_credits_requests SET  statut=NEW.status WHERE id_req=old.id;
end;

и ошибка

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version

Делал все по докам mysql, версия 5.5.25

A: Примерно так, после ELSE не нужен THEN он нужен для ELSEIF и IF что бы отделить условие, и после всего блока условий его надо закрыть
delimiter //
CREATE TRIGGER marketing_list_update
AFTER UPDATE
ON cms_offers
FOR EACH ROW
BEGIN
    IF NEW.status = 'active'
        THEN UPDATE marketing_credits_requests SET sum_s=NEW.ammount, statut=NEW.status WHERE id_req=old.id;
        ELSE UPDATE marketing_credits_requests SET  statut=NEW.status WHERE id_req=old.id;
    END IF;
END;//
delimiter ;

UPDATE P.S.: добавил разделитель


Q: Is it possible to call a function within qx? Here's a bit of Perl code that does what I want:
 my $value  = get_value();
 my $result = qx(some-shell-command $value);

 sub get_value {
   ...
   return ...
 }

Is it possible to achieve the same effect without using $value? Something like
my $result = qx (some-shell-command . ' '. get_value());

I know why the second approach doesn't work, it's just to demonstrate the idea.

A: my $result = qx(some-shell-command  @{[ get_value() ]});

# or dereferencing single scalar value
# (last one from get_value if it returns more than one)
my $result = qx(some-shell-command  ${ \get_value() });

but I would rather use your first option.
Explanation: perl arrays interpolate inside "", qx(), etc.
Above is array reference [] holding result of function, being dereferenced by @{}, and interpolated inside qx().

A: Backticks and qx are equivalent to the builtin readpipe function, so you could explicitly use that:
$result = readpipe("some-shell-command " . get_value());


Q: Application defined or object defined error - Excel VBA the following code gives me an Application defined or object defined error on the bold line. I set the range; however, apparently excel can't read it. I am not sure why that error appears. Any help is much appreciated! Thanks.
Public Sub specialattention()
'Loop to check whether issue needs spcial attention
Dim n As Variant
Dim nend As Range
Dim nrng As Range
Dim nnow As Date
Dim ninterval As Integer
ninterval = Sheets("Ranges").Range("AB3").Value
nnow = Sheets("Issues Database").Range("N5").Value
Set nend = Sheets("Issues Database").Range("M1048576").End(xlUp)
Set nrng = Sheets("Issues Database").Range("M6", nend)
For Each n In nrng
    If n.Value = "1" And nnow - n.Offset(0, 1).Value >= ninterval Then
        n.Offset(0, 2).Value = "1"
    Else
        n.Offset(0, 2).Value = "0"
    End If
    'Color Cells that need special attention
    If n.Offset(0, 2).Value = "1" Then
            Dim xrng1 As Range
            Dim xrng2 As Range
            Set xrng1 = n.Offset(0, -11)
            Set xrng2 = n.Offset(0, -1)
            **Sheets("Issues Database").Range(xrng1, xrng2).Interior.ColorIndex = 19**
        Else
            Dim xrng3 As Range
            Dim xrng4 As Range
            Set xrng3 = n.Offset(0, -11)
            Set xrng4 = n.Offset(0, -1)
            **Sheets("Issues Database").Range(xrng2, xrng3).Interior.ColorIndex = 2**
        End If
    Next
    End Sub

A: As long as the ranges passed to .Range are valid ranges, your code should work.
Based upon your code, the first instance:
Sheets("Issues Database").Range(xrng1, xrng2).Interior.ColorIndex = 19
should be fine.
However, your second instance:
Sheets("Issues Database").Range(xrng2, xrng3).Interior.ColorIndex = 2 is referencing ranges that are not in scope since you are reusing xrng2 which is defined in a different logic path.
Presumable updating your second problem line to this:
Sheets("Issues Database").Range(xrng3, xrng4).Interior.ColorIndex = 2 will give you your expected behavior.


Q: CSS Background Images Not Appearing on Mobile (iPhone) I have a header and several divs with background images that are not appearing on my mobile device (iPhone 5). Here is an example:
CSS:
#title_img {
    background: url("title.png") no-repeat scroll center top / 100% auto transparent;
    height: 125px;
}

The site I am working on is responsive, so at reduced window sizes, I reduce the size of height of the header:
#title_img {
    height: 80px;
}

HTML:
<header id="title_img" role="banner"></header>

A blank space where the image should be.
I also have several divs that use the similar CSS for displaying background images that are not appearing on the device. The images are all in the same directory as the CSS file. There is one image that is called through an  tag in the HTML and it displays fine on iPhone. Thanks!


Q: Is the preprocessor macro "#define TRUE FALSE'" valid? Is the following define statement valid in C?
#define TRUE FALSE

A: Since we should expect  TRUE is already defined when FALSE is defined too.
So in this case this would be a redefinition and be invalid.
If you stay intern the #define TRUE FALSE would be valid to the standard, but would be invalid according to all logics I could imagine.
But a way i have already often seen was :
#define FALSE 0
#define TRUE !FALSE

A: You have to remember that preprocessor macros are simply substituted. If you do e.g.
#define TRUE FALSE

then the processor simply replaces all places where it finds TRUE will be replaced by whatever FALSE is defined to.
So indeed it's a good definition. And yes it will most likely change the program workflow, possibly in very unexpected ways that may even cause undefined behavior.


Q: discord.js write and read JSON file I have a question. How can I let my DiscordBot write and read a JSON file? I have already programmed something but have only error. Can someone help me out? I would appreciate any help.
const Discord = require("discord.js")
const botconfig = require("../botconfig.json");
const colours = require("../colours.json");
const superagent = require("superagent");
const { report } = require("superagent");
const usedCommand = new Set();

module.exports.run = async(bot, message, args) => {
    message.delete();

    if (usedCommand.has(message.author.id)) {
        message.reply("du kannst diesen Command erst in 15 Sekunden wieder verwenden.").then(msg => msg.delete({ timeout: "10000" }));
    } else {
        let member = message.mentions.members.first() || message.guild.members.cache.get(args[0])

        let reason = args.slice(1).join(" ");
        if (!reason) message.reply("Bitte gebe einen Beweis in Form von einem Link (Video: Youtube, Bild: prnt.sc) an!")

        var fs = require("fs");
        var sampleObject = {
            username: member,
            proof: reason
        };

        fs.writeFile('../rpp.json', JSON.stringify(sampleObject, null, 4), (err) => {
            if (err) {
                console.error(err);
                return;
            };
            console.log("File has been created");
        });

        usedCommand.add(message.author.id);
        setTimeout(() => {
            usedCommand.delete(message.author.id);
        }, 15000);
    }
}

module.exports.config = {
    name: "rpp",
    description: "Bans a user from the guild!",
    usage: "+ban",
    accessableby: "Members",
    aliases: ["proofwrite"]
}

I want my Discord bot to enter the tagged user and a reason into the JSON file using the "writerrp" command. After that I want the bot to read the data of a user with the "readrrp" command.

A: here is an example of reading from a .json file.
Set up the json file correctly, using the right syntax.
{
  "token": "<a token goes here>" //in your local json file - called config.json in this case
}

client.login(config.token) //reads from the config.json file as an obj, which calls the token param

When reading from the json file, you need the fs package
const fs = require('fs');
//assuming your bot has args
let reason = args.slice(1,2) //removes the command and the @
let user = message.mentions.users.first()

//create a new obj
var obj = {
   table: []
};

//add some data to it e.g.
obj.table.push({reason: `${reason}`, user:`${user.username}`});

//convert it to json using the json#stringify() method
var json = JSON.stringify(obj);

//write to the json file
fs.writeFile('myjsonfile.json', json, 'utf8', callback);

//if you want to append, do this:
fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){
    if (err){
        console.log(err);
    } else {
    obj = JSON.parse(data); //now it an object
    obj.table.push({id: 2, square:3}); //add some data
    json = JSON.stringify(obj); //convert it back to json
    fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back
}});

credit for the above goes to @kailniris here


Q: DRAM Self-Refresh not the Lowest Power Mode I have a DDR3L Samsung DRAM on my Laptop. Based on page 23 of its datasheet, IDD6 or the Self-Refresh current is much higher than IDD2P0, IDD2P1 and IDD3P, which are the Precharge/Active Power-Down modes. Of course, IDD5B (i.e., the Burst Refresh current, which is responsible for refresh when Self-Refresh is not used) should be scaled based on the refresh period and added to the latter three values. But, even after that, it seems that the Self-Refresh power mode, is not the deepest power mode in this DRAM device. Am I missing something?


Q: How to combine subtotal and sumif with a range of criteria I'm trying to create a formula to combine a SUMIF (using a range of criteria) and a subtotal.
The SUMIF statement:
=SUMPRODUCT(SUMIF(E:E,O2:O21,G:G))

And where I've gotten on making that SUMIF subtotal:
=SUMPRODUCT(SUBTOTAL(9,OFFSET(G2,ROW(G2:G5000)-ROW(G2),0)),(E2:E5000=O2:O21)+0)

That last statement returns an #N/A error. I'd appreciate any input y'all can provide.
Thank you.
Example:
Order  | Date  | Mach  | Rem
-------|-------|-------|-------
A      |01/20  | 01    | 1200
B      |01/11  | 02    | 400
C      |01/21  | 01    | 420
D      |01/28  | 04    | 1180
E      |01/20  | 01    | 1200
F      |01/11  | 04    | 400
G      |01/21  | 03    | 420
H      |01/28  | 04    | 1180

No t sure I got the table right, so here's an image of what I see.

What I'm trying to do is filter based on the date - say, all orders that occur before 1/21 - and then give the amount remaining in a list of machines.
So, if I wanted the total from Machine 1 and 4, the output from that table (with the date filter on) would be 2800, summing order A, D, E, and F.  With the filter off it'd be 5580.

A: Try this formula:
=SUMPRODUCT(NOT(ISERROR(MATCH($C:$C;J:J;0)))*SUBTOTAL(103;OFFSET(C1;ROW(C:C)-MIN(ROW(C:C));0));$D:$D)

Excel structure:

After applying a filter:

You can also include date criteria already in the formula:
=SUMPRODUCT(NOT(ISERROR(MATCH($C:$C;J:J;0)))*($B:$B<$L$1);$D:$D)

Where L1 is date criteria.
But, of course, if you need filter usage, use the first solution.


Q: red-green color blindness compatible vim theme I am looking for a vim theme accessible to users with red green color blindness. In particular, the red text on a dark terminal background all but disappears. Do any of you know of a good theme? Or have resources useful for designing one?

A: I am not colorblind so I don't really know what works and what doesn't. I use the desert color scheme which works great for me, but your best guess would be to go to http://code.google.com/p/vimcolorschemetest/ and just check them all out.

A: In my .vimrc I added:
set background=dark

That helped a lot.

A: https://github.com/romainl/vim-dichromatic
"A dark colorscheme for color blind vimmers"

A: For anyone that comes accross this post I recommend jellybeans
https://github.com/nanotech/jellybeans.vim


Q: Voltage vs. Voltages Is 'voltages' the plural for voltage? When requesting for someone to check voltage more than once, would you state that you're documenting 'voltages'?

A: If you check the voltage of different things, your checking the voltages.
If you double-check the same voltage, you're repeatedly checking the voltage.
If the voltage changes over time, or in different conditions, then you can use the singular:

The voltage dropped steadily over two hours use.

But you can also use the plural, especially if the different conditions are well-defined:

The maximum, mean and minimum voltages are within a narrow range.
Different readings showed massively different voltages.

A: If it is the voltage at the same place which is being checked at intervals, as implied, I think I would say that I am documenting 'voltage readings'. 'Voltages' might imply checking the voltage in two different places.

A: If it is measured at the same place, I would use the singular. There's only one voltage there at a time. Measure the "battery voltage" at two temperatures. If there are two batteries, then you would measure the two voltages.
Once the measurements are made, you should use the plural to refer to the measurements. Measure the battery voltage at 0°C and at 100°C, then subtract the two voltages to determine the change in battery voltage. I hope that's not too confusing.
Perhaps someone can contribute a specific rule that covers this.


Q: How can I mimic the redis MONITOR command in a python script using redis-py? Unfortunately, the redis-py library does not seem to have a Monitor routine. I would like to read all of the commands received by the redis server, filter them, and then log the ones I am interested in. Does anybody have an idea of how to do this?

A: Here is some minimal code to implement the monitor code in python.
Note :

*

*I adapted this from the PubSub class in redis-py. See client.py

*This does not parse the response, but that should be simple enough

*Doesn't do any sort of error handling

import redis

class Monitor():
    def __init__(self, connection_pool):
        self.connection_pool = connection_pool
        self.connection = None

    def __del__(self):
        try:
            self.reset()
        except:
            pass

    def reset(self):
        if self.connection:
            self.connection_pool.release(self.connection)
            self.connection = None

    def monitor(self):
        if self.connection is None:
            self.connection = self.connection_pool.get_connection(
                'monitor', None)
        self.connection.send_command("monitor")
        return self.listen()

    def parse_response(self):
        return self.connection.read_response()

    def listen(self):
        while True:
            yield self.parse_response()

if  __name__ == '__main__':
    pool = redis.ConnectionPool(host='localhost', port=6379, db=0)
    monitor = Monitor(pool)
    commands = monitor.monitor()

    for c in commands :
        print(c)

A: Now, the redis library already included the monitor support itself.
https://github.com/andymccurdy/redis-py/blob/master/redis/client.py#L3422


Q: Spring4 without XML - web.xml - translate to Java I do have couple of JNDI resources in my web.xml
This is for reading a external property file and path depends on environment.
<resource-ref id="resourceRef">
    <res-ref-name>config/file</res-ref-name>
    <res-type>java.lang.String</res-type>
    <res-auth>Container</res-auth>
    <res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>

This is for JNDI JDBC DB definition
    <resource-ref id="MyDatabase">
    <description></description>
    <res-ref-name>jdbc/MyDB</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
    <res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>

and this for old ejb (EJB2.x)
<ejb-ref id="service">
    <description />
    <ejb-ref-name>ejb/AgencyService</ejb-ref-name>
    <ejb-ref-type>Session</ejb-ref-type>
    <home>ejb.Home</home>
    <remote>ejb.Service</remote>
</ejb-ref>

How can translate these resources to Java (Servlet 3.x)?
An existing application is migrating from servlet 2.5 and EJB 2.x to Servlet3, Rest and EJB3. My new application uses Spring4 (MVC, Security etc) and OpenJPA 2.1.x. Our design goal is not to use "xml" (no web.xml, SpringContext.xml etc).
I created Java class that extends AbstractAnnotationConfigDispatcherServletInitializer
that would be equivalent to Web.xml.
How can I migrate resource-ref and ejb-ref to Java class??
Much appreciated your help!
Note :- edited

A: Basically Spring and JEE stack are "competing" with each other. From what you've stated: EJB3 + JPA clearly belong to JEE stack, on the other hand SpringMVC is obviously from Spring universe + spring boot is obviously in a Spring camp.
Now, web.xml is kind of a bootstrap point for regular spring application (excluding spring boot of course). So, in general you should specify a web listener that will load up the spring. When you've tagged a spring boot in the question everything has mixed up. In two words, spring boot indeed alows to configure everything with annotation but it still "assumes" you're using spring under the hood.
Regarding the resources,
If you are working with DAO layer, you should define beans for those, but bottom line they will be managed by spring then.
But in this case there is no need for EJB. Of course you can still use JPA out of spring DAO (people tend to use Hibernate directly IMO this day if they really need ORM, and Hibernate implements JPA these days) if you wish, but in any case its again will be used by spring.
On the other hand if you need a JEE stack I doubt spring boot can really fit you.
JEE stack is a kind of "all-in-one" bundle which is supported by various application servers, and spring from this point of view is "take parts and combine by yourself" solution. So for spring project you can use tomcat/jetty which are not by any means fully compliant JEE servers. BTW this is exactly what spring boot does.
So I think for the sake of the project you should decide in which camp do you want to be, JEE or Spring. Both technologies look appealing these days, each of them has its benefits/drawbacks, but bottom line it boils down to:

*

*Spring is more flexible and innovative, you get changes faster

*Spring is more complicated to bootstrap (although if there are seasoned developers familiar with spring, it should not be an issue)

*JEE is standardized

A: Use Spring Boot - no need for xml there.
Spring Boot embeds Tomcat (or optionally Jetty), and so does not support EJB.
I'd rewrite the EJB' 's functionality as a "plain old Java" class, using spring features where needed.
For the external config file, Spring has several ways of providing configuration options at runtime / external to the deployment, so no need for JNDI.


Q: Testcafe test fails because "Failed to find a DNS-record for the resource" with VPN, but without VPN it works The test fails when I'm connected through the VPN but without it works fine. It performs a click to this URL:
https://www.google.com/search?q=let+me+google+that+for+you
I tried with the --proxy-bypass setting but I suppose I'm not doing it right, any guidance on how it should look like?

A: A VPN should not affect your tests. Judging by the symptoms, it looks like you are using a proxy, not a VPN. If it's true, the proxy server address should be specified using the --proxy option as described here mentioned below.
--proxy <host>

Specifies the proxy server used in your local network to access the Internet.
testcafe chrome my-tests/**/*.js --proxy proxy.corp.mycompany.com
testcafe chrome my-tests/**/*.js --proxy 172.0.10.10:8080

You can also specify authentication credentials with the proxy host.
testcafe chrome my-tests/**/*.js --proxy username:password@proxy.mycorp.com

As for the --proxy-bypass option, it has the opposite meaning. You can use it to specify resources that are not proxied, for example, the ones that are hosted inside of your local network.


Q: wso2is in distributed architecture i am a beginner in wso2 and working on a academic project that consists of deploying wso2 in a distributed architecture. I've been looking in wso2 documentation but I couldn't find something that can help me in this project. if u have any clue, that would be very helpful.

A: I do not clearly get what you requirement is. However you can create a distributed deployment of WSO2 APIM as  in [1].
There is no specific distributed deployment scenario of wso2 IS. However IS can be used in clustering as in previous answer.
Other than that, WSO2 products can be deployed by clustering. Refer this [2] such clustering patterns.
[1] https://docs.wso2.com/display/AM210/Distributed+Deployment+of+API+Manager
[2] https://docs.wso2.com/display/AM210/Distributed+Deployment+of+API+Manager

A: You can find the clustering documentation for WSO2 IS 5.4.0 in https://docs.wso2.com/display/IS540/Setting+Up+Deployment+Pattern+1


Q: submit action doesnt work in Rails 4 when I submitted the form, the new data don't save in database and as a result I can not see them, but when I make a new data like welcome= Welcome.new and welcome.title="your are" by rails console they work and I can only see things that I have made in console not by application. It seems submit bottom doesnt save any data.
new.html.erb

 Submite

  <form action="new" method="post" class="form-horizontal" role ="form">

       kind
      <input type="string" id="kind" name="kind" class="form-control">

       title
      <input type="string" id="title" name="title" class="form-control">

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

      <input type="submit" value="Submit" class="btn btn-primary">
  List

index.html.erb
        <% @welcomes.each do |welcome| %>

<%= welcome.title %>

          <% end %>

welcomes_controller
    def index
    @welcomes = Welcome.all
    end

    def new
         @welcome = Welcome.new
    end

    def create
         @welcome = Welcome.new(user_params)
        if @welcome.save
         flash.keep[:notice]="Successfuly created"
               render :index
        else
        render :new
        #  format.json { render json: @user.errors, status: :unprocessable_entity }
        end

       end

    private

     def user_params
        params.require(:welcome).permit(:kind, :title, :text)
      end

A: Your form is not submitting to the right route. Use form builder instead:
<%= form_for @welcome do |f| %>
   <%= f.label :kind %>
   <%= f.text_field :kind %>

   <%= f.submit  %>
<% end %>

This will put right route for form submission into your HTML


Q: Dividing conditioned probability into separate probability terms I have a conditioned probability problem as following:
$P(x|y,z,k)$
if $z$ and $k$ are independent and there is not any correlation between them, can I write the problem as following:
$P(x|y,z,k)=P(x|y,z)P(x|y,k)$
Is it a true statement?

A: No, this statement is incorrect. If $Z$ and $K$ are independent, the joint density of $(X,Y,Z,K)$ simplifies into
$$p(z)p(k)p(y|z,k)p(x|y,z,k)$$but this does not change the conditional density of $X$. In any addition, a density in $x$ like the lhs is rarely equal to a product of two densities in $x$ like the rhs, an exception being when all three terms are constant (uniform distribution).


Q: How to throw an error when an attribute is changed? I want to make sure an error gets thrown when an attribute of an object gets changed outside the class. Here's how I tried to do it:

class Example {
  constructor(index) {
    this.index = index;

    Object.defineProperty(this, 'index', {
      set() {
        throw new AssertionError("can't set attribute");
      }
    });
  }
}

class AssertionError extends Error {
  constructor(message) {
    super();
    this.name = "AssertionError";
    this.message = message;
  }
}

let example = new Example(5);
console.log(example.index); //prints undefined instead of 5
example.index = 10; // I want to throw an AssertionError here

The error gets thrown just like I wanted, but the index value is undefined. I still want to be able to change the attribute inside of the class, but I want to prevent the attribute from changing outside of the class.

A: You redefine the property with the call to defineProperty. You should give it a getter:
Object.defineProperty(this, 'index', {
  get() { return index; },
  set() {
    throw new AssertionError("can't set attribute");
  }
});

Any given property name can only be used once; a property has to either be a plain property or a property with getter/setter functions.


Q: How to convert IntPtr to int A window handle sometimes of type int and other times of type IntPtr
int example:
 [DllImport("user32.dll")]
    static extern uint GetWindowThreadProcessId(int hWnd, int ProcessId);

IntPtr example:
  [DllImport("user32.dll", CharSet = CharSet.Auto)]
    static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, int wParam, StringBuilder lParam);

I don't seem to be able to convert/cast from one to the other.
When I try this.ProcessID = GetWindowThreadProcessId(windowHandle.ToInt32(),0) I get an error cannot implicitly convert from uint to int

A: I think that error cannot implicitly convert from uint to int refers to = statement. The field this.ProcessID is int, but GetWindowThreadProcessId returns uint.
Try this
this.ProcessID = unchecked((int)GetWindowThreadProcessId(windowHandle.ToInt32(),0))

A: The SendMessage signature is
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);

or this
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, StringBuilder lParam);

Don't exchange int and IntPtr. They are nearly equivalent only at 32 bits (equal in size). At 64 bits an IntPtr is nearly equivalent to a long (equal in size)
The GetWindowThreadProcessId signature is
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

or
static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);

In this case, a ref or a out to "something" are managed references to something, so they are internally converted to IntPtr when passed to Native API. So out uint is, from the point of view of the Native API, equivalent to IntPtr.
Explanation: what is important is that the "length" of the parameters is the correct one. int and uint are equal for the called API. And a 32bit IntPtr is the same too.
Note that some types (like bool and char) have special handling by the marshaler.
You shouldn't EVER convert an int to an IntPtr. Keep it as an IntPtr and live happy. If you have to make some math operations not supported by IntPtr, use long (it's 64 bits, so until we will have Windows 128, there won't be any problem :-) ).
IntPtr p = ...
long l = (long)p;
p = (IntPtr)l;

A: I was getting "Arithmetic operation resulted in an overflow", whenever I was:
IntPtr handler = OpenSCManager(null, null, SC_MANAGER_CREATE_SERVICE);
if (handler.ToInt32() == 0) //throws Exception

instead of that:
IntPtr handler = OpenSCManager(null, null, SC_MANAGER_CREATE_SERVICE);
if (handler == IntPtr.Zero) //OK


Q: Make An Integer Null I have an update function that updates an sql server db table through a dataset. One of the fields in the table is an integer and accepts null values. So when I am populating the update function I need a way to enter a null in when the function wants an integer.
I tried to do it this way but  _intDLocation = "" throws an exception
Dim _dLocation As String = udDefaultLocationTextEdit.Text
    Dim _intDLocation As Integer
    If _dLocation <> "" Then
        _intDLocation = Integer.Parse(udDefaultLocationTextEdit.Text)
    Else
        'NEED HELP HERE
        _intDLocation = ""
    End If

A: Try this:
Dim _dLocation As String = udDefaultLocationTextEdit.Text

Dim _intDLocation As Nullable(Of  Integer)

If Not String.IsNullOrEmpty(_dLocation) Then
     _intDLocation = Integer.Parse(_dLocation)
End If

A: Integers cannot be set to Null.  You have to make the integer "nullable" by adding a question mark after the word Integer.  Now _intDLocation is no longer a normal integer.  It is an instance of Nullable(Of Integer).
Dim _dLocation As String = udDefaultLocationTextEdit.Text
Dim _intDLocation As Integer?
If _dLocation <> "" Then
    _intDLocation = Integer.Parse(udDefaultLocationTextEdit.Text)
Else
    _intDLocation = Nothing
End If

Later on, if you want to check for null you can use this handy, readable syntax:
If _intDLocation.HasValue Then
   DoSomething()
End If

In some cases you will need to access the value as an actual integer, not a nullable integer.  For those cases, you simply access
_intDLocation.Value

Read all about Nullable here.

A: My application uses a lot of labels that start out blank (Text property), but need to be incremented as integers, so I made this handy function:
    Public Shared Function Nullinator(ByVal CheckVal As String) As Integer
    ' Receives a string and returns an integer (zero if Null or Empty or original value)
    If String.IsNullOrEmpty(CheckVal) Then
        Return 0
    Else
        Return CheckVal
    End If
End Function

This is typical example of how it would be used:
Dim Match_Innings As Integer = Nullinator(Me.TotalInnings.Text)

Enjoy!

A: _intDLocation = Nothing


Q: How to add row in DefaultTableModel under spcific index? I'm building a java application with swing component.
Now I want to create a JTable with 4 fixed row.
In detail I want a JTable(DefaultTableModel) with the last 4 row as fixed with my default value, and throught a Button I want to insert a new row upper this 4 row. There is a metohd to insert a row in a specific point?


Q: Prevent WebView to open links in other browsers I have a webview and I wish that if target=_blank, then do not open it in the browser, but remains open in webview.
I tried the code below:
private async void webView_LoadCompleted(object sender, NavigationEventArgs e)
{
    await webView.InvokeScriptAsync("eval", new[]
    {
        @"(function()
        {
            var hyperlinks = document.getElementsByTagName('a');
            for(var i = 0; i < hyperlinks.length; i++)
            {
                if(hyperlinks[i].getAttribute('target') != null)
                {
                    hyperlinks[i].setAttribute('target', '_self');
                }
            }
        })()"
    });
}

But there are some websites that can remain open in the webview and there is a website that opens in a browser. How do I fix this so that all links remain open on webview?

A: Your code didn't work because the "Select" button in your image is a HTML <button> element not a <a> element. When user click this button, it calls JavaScript functions to open in new window. So your code won't work for this scenario.
For handling the new window request, I'd suggest using WebView.NewWindowRequested event. This event occurs when a user performs an action in a WebView that causes content to be opened in a new window. We can provide custom handling of the new window request and set the Handled property to true to prevent the default browser from being launched. Following is a simple sample:
private void webView_NewWindowRequested(WebView sender, WebViewNewWindowRequestedEventArgs args)
{
    webView.Navigate(args.Uri);

    args.Handled = true;
}

For more info, please see Remarks and Examples in WebView.NewWindowRequested event.


Q: Entry Point Not Found Exception I'm trying to use a C++ unmanaged dll in a C# project and I'm getting an error when trying to call a function that says that entry point cannot be found.
public class Program
{

    static void Main(string[] args)
    {
        IntPtr testIntPtr = aaeonAPIOpen(0);
        Console.WriteLine(testIntPtr.ToString());
    }

    [DllImport("aonAPI.dll")]
    public static extern unsafe IntPtr aaeonAPIOpen(uint reserved);
}

Here is the dumpbin for the function:
5    4 00001020 ?aaeonAPIOpen@@YAPAXK@Z

I changed the dll import to [DllImport("aonAPI.dll", EntryPoint="?aaeonAPIOpen")] and [DllImport("aonAPI.dll", EntryPoint="_aaeonAPIOpen")] and no luck.

A: It looks like the function you're trying to call is compiled as a C++ function and hence has it's name mangled.  PInvoke does not support mangled name.  You need to add an extern "C" block around the function definition to prevent name mangling
extern "C" {
  void* aaeonAPIOpen(uint reserved);
}

A: Using the undname.exe utility, that symbol demangles to
 void * __cdecl aaeonAPIOpen(unsigned long)

Which makes the proper declaration:
    [DllImport("aonAPI.dll", EntryPoint="?aaeonAPIOpen@@YAPAXK@Z",
        ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
    public static extern IntPtr aaeonAPIOpen(uint reserved);


Q: How to hide dash between the bars in waterfall charts of Highcharts in iOS Basically I want to hide dash between the bars from waterfall chart.I am using highcharts iOS wrapper.I can only change type of dash but there is no option to hide or disable the same

A: You need to set lineWidth property to 0:
let plotOptions = HIPlotOptions()
plotOptions.waterfall = HIWaterfall()
plotOptions.waterfall.lineWidth = 0
options.plotOptions = plotOptions

API Reference: https://api.highcharts.com/ios/highcharts/


Q: Как сделать круглую кнопку с картинкой Android Studio Имеется кнопка:
<Button
        android:id="@+id/account"
        android:layout_width="75dp"
        android:layout_height="75dp"
        android:background="@drawable/round_button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.049"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.056"
        tools:ignore="SpeakableTextPresentCheck" />

Она уже круглая, как добавить на нее картинку?

A: Вам нужна кнопка с картинкой, а значит необходимо использовать ImageButton.
Где вы примените форму и вставите картинку с помощью android:src=


Q: Is there a way to provide environment variables to a VSTS CI npm task? Essentially, I need a way to inject environment variables for my app since I don't want to check a .env file into my repo. I was hoping to run something like API_URL=api.example.com npm run build, but it looks like you can't prepend things before the task command.
Is there a way to do this or is there a better way to create environment variables for a node app hosted in Azure?

A: You can add some build variables to the build definition and then reference those in your build steps somewhere. For example, for your API_URL add a build variable with the same name and value. If you need the variable to be secret for any reason (passwords, etc.) just click the lock icon next to the value field.

Then add a new cmd task to your build and move it to the top to set your environment variables before you start your build. The way you reference the build variables is like this...
set API_URL=$(Build.API_URL)

In the UI it will look like this:

I added two cmd tasks to a test build just to show that it is working. The first one is used to set the environment variable and then I used the second to dump all the environment variables so I could see them. You can see in the build logs that it worked.

If you want to reference the build variables using something other than the command line you can find examples of the different ways to reference build variables here. There are also examples of how to use secret variables on that page.
EDIT:
Since you have some concerns about it not being available in your node app I tested it out in the console real quick to show that it will definitely work.

A: Using yaml config you can switch to script task and then do something like this:
- script: 'npm run'
  workingDirectory: 'src'
  displayName: 'npm run'
  env:
    { API_URL: 'api.example.com' }

A: tehbeardedone's answer is great for the build machine, and the answer is similar for when running your app in an Azure app service, which I'm thinking is what you really need. This is for if you need your access to these .env files just previous to or after your app has started (post build).

*

*To the Azure portal we go.

*Navigate to your app service.

*Click "Configuration" under the "Settings" heading.

For each of the variables you'll need during a production run of your app you'll need to:

*Click "New application setting"

*Paste the name of the variable (exactly as it appears in your .env) into the "Name" field.

*Similarly, paste the value of the variable into the next field.

*Check the "deployment slot setting" checkbox. As nebulous as this field is, it's necessary. When I didn't do this, the app didn't have access to this variable after running the start command.

Restart your app. If you deployment when well, then your app should have access to the variables add in the manner specified above.


Q: Get first text inside a tag using beautiful soup I need to get the salary range from span tag. I tried using find().text but doesn't work as the span tag has other tags in it.
job_list = soup.find_all("div", class_="d-flex flex-column pl-sm css-1buaf54 job-search-key- 1mn3dn8 e1rrn5ka0")

for job in job_list:
   salary = job.find("span", class_="job-search-key-1hbqxax e1wijj240")
   print(salary)

The output I have:

₹362,870 - ₹955,252 is my desired output

A: What you actually want to do here is get the text inside the div class but not the text in the nested tags within it.
You can use soup.find with option text = True and recursive = False
Creating the data
from bs4 import BeautifulSoup
html_doc = '''
₹362,870 - ₹955,252 (Glassdoor Est.)  <svg class="SVGInline-svg greyInforcon-svg" height="16" viewbox="0 @ 16 16" width="16" xmlns="http://www.w3.org/2000/svg"> <g fill="none" fill-rule="evenodd" id="prefix__info-16-px" stroke="none" stroke-width="1">
<path d="M8 14A6 6 @ 118 2a6 6 @ 010 12zme- 1A5 5 @ 108 3a5 5 @ 880 18zm-.6-5.60.6.6 8 111.2 8v11a.6.6 @ 01-1.2 8v7.42MS 5.62.6.6 110-1.2.6.6 @ 810 1.2z" fill="#505863" id="prefix_a"></path>
</svg>

 '''
soup = BeautifulSoup(html_doc, 'html.parser')

Generating the output
soup.find(class_='job-search-key-1hbqxax elwijj240').find(text=True, recursive=False).strip()

Output
This gives us
'₹362,870 - ₹955,252'


Q: nested resources with optional verbs as resources in angular.js I'm having a bit of trouble figuring out how to create my angular resource properly.
.factory('Favorite', function ($resource) {
    return $resource('/api/user/:id/favorites/:verb/:favid', {
        id: "@_id",
        favid: "@favid"
    }, {
        jobs: {
            method: 'GET',
            params: {
                verb: 'jobs'
            }
        },

        resumes: {
            method: 'GET',
            params: {
                verb: 'resumes'
            }
        }
    });
});

The trick is I want to provide a list function at /api/user/:id/favorites that lists all types of favorites (jobs, etc).
However each favorite type needs to have a CRUD interface for it.
So I also need to support GET/PUT/POST/DELETE for /api/user/:id/favorites/jobs/:jobid
I'm not really sure if I'm doing this right, nor do I know if I can actually do CRUD operations where the jobs and resumes are defined or how I would actually call them.


Q: ac load control using a microcontroller via relay when i switching ac induction motor  by micro controller via a relay it some times hanging up or restart the controller while I'm using optical couple r for isolation between 12v supply of relay and 5v supply of micro-controller. I'm trying to use large capacitors on supply but in vain

A: Also, if possible, it would be great to have some sort of isolated circuit to determine when the AC is at around 0 volts (zero crossing) and switch the relay at that point. This would certainly extend the life of your relay and reduce the chances of getting a large electromagnetic pulse from the motor, which may induce spurious signals in the traces (if it's nearby) or the wiring to your microcontroller board. A Snubber is a good idea as stated. Does the problem still occur if you disconnect the motor and just operate the relay?
If so it may be switching spikes from the relay coil itself. Make sure you have some capacitance near the relay to dampen that, and also if possible don't use the same ground plane on your circuit board, for the relay and the microcontroller. Run a separate trace for the relay ground to the power input connector. You may also want to put a diode (e.g. 1N4007 or similar) across the relay coil (reverse biased) to help kill spikes.


Q: A sequence of measurable functions doesn't converge with the following properties Let $\{f_n\}$ be a sequence of measurable functions defined on $[0,1]$ with the following properties:

*

*$f_n(x)\in[0,1]$ for any $x\in[0,1]$ and $n\geq 1$.

*$\lim_{n\to\infty} \int_{[0,1]} f_n = 0$.

*$\{f_n(x)\}$ doesn't converge for any $x\in[0,1]$.

My thought was to construct a sequence of functions that are zero almost everywhere to satisfy 2). For example, the Dirichlet function on $[0,1]$ and doesn't depend on $n$. But this sequence of functions seems not to satisfy 3) as it would converge to $1$ for any $x\in\mathbb{Q}$.
How do I construct such a sequence of functions? Any hints?

A: Let $D = \{(k,m) \in \mathbb N^2 : m > 0, \; 0 \le k < m\}$. For $(k,m) \in D$, define $I_{(k,m)} = \left[ \frac{k}{m}, \frac{k+1}{m} \right]$. We can enumerate $D$ with a bijection $e \colon \mathbb N \to D$ sequentially, so $e(0) = (0,1)$, $e(1) = (0,2)$, $e(2) = (1,2)$, $e(3) = (0,3)$, $e(4) = (1,3)$, $e(5) = (2,3)$, and so on. The sequence $\{f_n\}$ where $f_n$ is the indicator function of $I_{e(n)}$ will satisfy the desired properties.
Intervals are measurable, so their indicator functions will be as well. Notice that the integral of the indicator function of $I_{(k,m)}$ is $\frac{1}{m}$, so these will converge to $0$. However, every point of $[0,1]$ gets 'visited' by infinitely many intervals in this sequence, so for any $x \in [0,1]$ the sequence $\{f_n(x)\}$ will be mostly $0$'s and the occasional $1$ but it will never stay $0$ forever, so it does not converge.


Q: Facebook ads python sdk get_stats doesn't return "actions" field I can't get AdCampaign's get_stats() method to return the "actions" field. Snippet:
stats = list(ad_campaign.get_stats(fields=[
    'impressions',
    'spent',
    'clicks',
    'actions',
]))
print stats[0]
>>> <AdStats> {"clicks": 0, "impressions": 0, "spent": 0}

I have also tried to get the report on AdAccount, AdSet and AdGroup levels, but none of them had the "actions" field.
I'm assuming I have misconfigured my campaign, so here's a basic rundown:

*

*AdCampaign:

*

*status: "PAUSED"

*objective: "WEBSITE_CONVERSIONS"

*AdCampaign has one AdSet:

*

*bid_type: "ABSOLUTE_OCPM"

*bid_info: {'ACTIONS': 1}

*promoted_object: {'pixel_id': <valid pixel id string>}

*start_time: one month in the future

*AdSet has one AdGroup:

*

*objective: "WEBSITE_CONVERSIONS"

I also queried the AdGroup object for conversion_specs, they are set and match defaults described in the doc.

A: You don't actually have to specify any fields for the get_stats method, but the reason you're not seeing any actions is probably because you don't have any. Try it against a campaign that you know people have taken action on. :)
Evan


Q: Tracing a path on a polar coordinate grid I attempt to trace the path of a point when shift-dragged on a polar coordinate as shown on the picture below. But I only managed to snap the point to the grid. Insight on how to accomplish this? Any help would be much appreciated.
VPOS = {1, 1};
oVPOS = {1, 1};

angle[p_] := (
  ang = ArcTan[Abs@p[[2]]/Abs@p[[1]] // N ];
  Which[p[[1]] >= 0 && p[[2]] >= 0 , Return[ang ],
   p[[1]] < 0 && p[[2]] >= 0 , Return[Pi - ang ],
   p[[1]] < 0 && p[[2]] < 0 , Return[-Pi + ang ],
   p[[1]] >= 0 && p[[2]] < 0 , Return[-ang ]
    ];)

cnt[p_] := (
  d = Round@EuclideanDistance[{0, 0}, p];
  the2 = Abs@Ceiling[ArcTan[p[[2]]/p[[1]]]/(Pi/12)];
  Return[{Sign[p[[1]]] d Cos[the2*Pi/12 ], Sign[p[[2]]] d Sin[the2 *Pi/12 ]}];)

cnt2[p_] := (
  od = Round@EuclideanDistance[{0, 0}, oVPOS];
  othe2 = Ceiling[angle[oVPOS]/(Pi/12) ] ;

  d = EuclideanDistance[{0, 0}, p];
  the2 = angle[p];

  dd = Round@d;
  dthe2 =   Ceiling[the2/(Pi/12)];

  Dthe = Abs[od*(  the2 - othe2) ] ;
  Dd = Abs[ d - od];
  If[Dthe > Dd,
   Return[{  dd Cos[ the2],  dd Sin[ the2 ]}],
   Return[{  d Cos[dthe2*Pi/12],  d Sin[dthe2*Pi/12]} ]
    ]
  )

grids[min_, max_] :=
  Join[Range[Ceiling[min], Floor[max]],
   Table[{j + 1, Lighter@Lighter@Lighter@Lighter@Green}, {j,
     Round[min], Round[max - 1], 1}]];

DynamicModule[{pnt = {1, 1} },
  EventHandler[
    Dynamic@Graphics[
      {PointSize[Large], Red, Point[cnt2[VPOS]]},
      Axes -> True,
      GridLines -> grids,
      PlotRange -> {{-10, 10}, {-10, 10}},
      Prolog -> {
        Lighter @ Lighter @ Blue,
        Table[Circle[{0, 0}, r], {r, 1, 14}],
        Table[Line[{{-15 Cos[the], -15 Sin[the]},
                    {15 Cos[the], 15 Sin[the]}}],
        {the, 0, Pi, Pi/12}]}],
  {"MouseDragged" :> (
    oVPOS=VPOS;
    VPOS = MousePosition["Graphics"])}]]

This is what my code produces:

This is what I want to see:

A: Here's one solution that meets the criterions. I'll walk through the main ideas step by step.
First I started by creating a list of circles and a list of lines. Then I formed a region from those elements, which I called grid. I also added the gridlines that were used originally and so recreated the plot:
circles = Table[Circle[{0, 0}, r], {r, 1, 14}];
lines = Table[Line[{{-15 Cos[the], -15 Sin[the]}, {15 Cos[the], 15 Sin[the]}}], {the, 0, Pi, Pi/12}];
grid = RegionUnion[circles, lines];

gridLines[min_, max_] := Join[Range[Ceiling[min], Floor[max]], Table[{j + 1, Lighter@Lighter@Lighter@Green}, {j, Round[min], Round[max - 1], 1}]]

bg = Graphics[{
   Lighter@Lighter@Blue, circles, lines
   },
  Axes -> True,
  PlotRange -> {{-10, 10}, {-10, 10}},
  GridLines -> gridLines
  ]

Next I created a list of all the points where circles meet lines. Then I discretized the grid using DiscretizeRegion and retrieved the points generated by that algorithm.
nodes = Join[
   Flatten[Table[N@{r Cos[the], r Sin[the]}, {the, 0, Pi, Pi/12}, {r, -15, 15}], 1],
   MeshCoordinates@DiscretizeRegion[grid]
   ];

Show[bg, Graphics[{Red, Point@nodes}]]

If I had generated the points manually I could have distributed them more evenly and so on. It would have yielded a better result. The idea is that when you move the locator over any of these points they will be added to a list of "visited" points. Then all I'll draw a red line through all of these visited points.
The locator is constrained to the grid in such a way that it doesn't allow for diagonals crossings or any other discontinuous moves. The basic principle is the same that I wrote about here. The final code looks like this:
DynamicModule[
 {
  pt = {4, 0},
  regNearest = {0, 0},
  nodes = Join[
    Flatten[
     Table[N@{r Cos[the], r Sin[the]}, {the, 0, Pi, Pi/12}, {r, -15, 15}], 1],
    MeshCoordinates@DiscretizeRegion[grid]
    ],
  visited = {}
  },
 LocatorPane[
  Dynamic[pt, (
     regNearest = RegionNearest[grid, #];
     If[
      Norm[regNearest - pt] < 0.5,
      pt = RegionNearest[grid, #]
      ];
     visited = Join[
       visited,
       Select[nodes, Norm[pt - #] < 0.25 &]
       ]
     ) &],
  Dynamic@Show[
    bg,
    Graphics[{Red, Thickness[Large], Line[visited]}]
    ]
  ]
 ]

A: Here is some code to get you started. I say "started" because this isn't a fool-proof solution. For one thing, it doesn't provide a way to retract a segment should the user make an bad drag. There are also some refresh issues to be dealt with. A full solution will a fair amount of additional work, and I don't have time to work it out right now.
cnt[p_] := Module[{
    d = Round @ EuclideanDistance[{0, 0}, p],
    the2 = Abs @ Ceiling[ArcTan[p[[2]]/p[[1]]]/(Pi/12)]},
  {Sign[p[[1]]] d Cos[the2 Pi/12], Sign[p[[2]]] d Sin[the2*Pi/12]}]

grids[min_, max_] :=
 Join[Range[Ceiling[min], Floor[max]],
  Table[{j + 1, Lighter @ Lighter @ Lighter @ Green}, {j, Round[min], Round[max - 1], 1}]]

With[{start = {4. Cos[15. °], 4. Sin[15. °]}},
  DynamicModule[{pnt = start, VPOS = start, path = {start}},
    EventHandler[
      Dynamic @ Graphics[
        {Red, PointSize[Large],
         Thick, Point[cnt @ VPOS], Line[AppendTo[path, cnt @ VPOS]]},
        Axes -> True,
        GridLines -> grids,
        PlotRange -> {{-10, 10}, {-10, 10}},
        Prolog -> {
          Lighter @ Lighter @ Blue,
          Table[Circle[{0, 0}, r], {r, 1, 14}],
          Table[Line[{{-15 Cos[the], -15 Sin[the]},
                      {15 Cos[the], 15 Sin[the]}}],
            {the, 0, Pi, Pi/12}]}],
      {"MouseDragged" :> (VPOS = MousePosition["Graphics"])}]]]


Q: C#: System.IO.DirectoryNotFoundException: 'Could not find a part of the path I am getting an error as shown in the title. I have no idea why im getting this or as to how im supposed to fix this. Visual Studio is giving me the error shown in the title on this line: var f = System.IO.File.OpenRead(fil1);
class Program {
    static void Main(string[] args) {

        Stopwatch sw = Stopwatch.StartNew();

        string fil1 = "C:\Users\mariu\Desktop\Jobboppgave\CaseConsoleApp\Prisfile.txt";

        ***var f = System.IO.File.OpenRead(fil1);***
        int length = (int)(new System.IO.FileInfo(fil1).Length);

A: Your path is incorrect because you didn't escape \ in it. The fastest way to do it is using @:
string fil1 = @"C:\Users\mariu\Desktop\Jobboppgave\CaseConsoleApp\Prisfile.txt";

Rebuild your project and problem will be resolved.


Q: How to prevent scrolling to the right in this jsfiddle I have the following jsfiddle http://jsfiddle.net/KfPOQ/
using a web browser it is fine however when on the ebay app on iphone or ipad i have to scroll right to see the full page how do I eliminate this issue?

A: You need to have the content of the page fit within your viewport (or screen) dimensions for the given media type. You can have different stylesheets based on the media type in a link/stylesheet tag. Say, for the iphone, use media="handheld" and try to keep the content within around 600px, or whatever looks good on your mobile device.
Here is another resource from w3c.


Q: Can I print to an Epson Expression XP-102?
Possible Duplicate:
Ubuntu 12.10 driver for Epson XP-202

I own a Epson Expression XP-102, but I cannot find a way to make it work.
I am new to Ubuntu.
Is there any way to make print to the Epson Expression?

A: I have had trouble too. If you go to the link below and download one of the drivers at the bottom of the page marked packages (I used the top one of the six), this gets the printer going. I am yet to get the scanner going but will let you know if I suss this out.
http://avasys.jp/eng/linux_driver/download/lsb/epson-inkjet/escpr/
Hope this helps,
Miles


Q: Got parse error with Mail config headers in ZF2 I use Zend\Mail\Transport\Smtp to send an email. Below is my code.
use Zend\Mail\Message;
use Zend\Mail\Transport\Smtp as SmtpTransport;
use Zend\Mail\Transport\SmtpOptions;
 public function smtpConfig($message)
    {
        $transport = new SmtpTransport();
        $options   = new SmtpOptions(array(
        'name' => localhost,
        //'host' => 10.92.32.81,
        'port' => 25,
        ));

    $transport->setOptions($options);
    echo $transport->send($message);
}
public function sendMail($to,$from,$subject,$body)
    {
        $message = new Message();
        $message->addTo($to)
                ->addFrom($from)
                ->setSubject($subject)
                ->setBody($body);
        $this->smtpConfig($message);
    }

I have configured smtp in local system and I'm able to receive email without any warnings/low priority errors. I delivered this code for project testing. Mail functionality is working fine in their system but in browser console following warning/error is displayed and I dont see this error in my local setup.
Parse error: syntax error, unexpected '[' in D:\applications\www-php\kiosquebo\vendor\zendframework\zend-mail\src\Headers.php on line 39

Any solution given is appreciated.

A: According to the line in the file you're getting the error, PHP is failing to parse this line:
protected $headersKeys = [];

The only issue that is possible here is that your PHP version is too old and does not work with the [] array definer.
You should update your PHP version to at least 5.4.


Q: should I add app.js file in gitignore for nodejs/vuejs app? I am new to vuejs. Recently I noticed that when I pull, it says conflict in app.js file. But I can't find the issue as app.js file is big.
Sould I add this file to gitignore file?
what is best practice to work with vue js?

A: I imagine you are building to a folder /dist and the app.js being conflited is the one inside of it.
You should ignore the /dist altogether. This folder is generated on the building process, meaning everyone that runs the project will update and create it.

A: Here is the default vue-cli .gitignore:
.DS_Store
node_modules
/dist

# local env files
.env.local
.env.*.local

# Log files
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw*

Not that not anything here may be useful to put in your own .gitignore. But you should for sure have at least node_modules and /dist.

A: If you are building the Vue project by scratch then I can say the following, when building/compiling your Vue project, best practices say that you should handle your entire production ready project in a dist/ or build/ directory where your main app.js file where the conflicts you are having would occur. This directory is only reserved for deploying the app and is not saved into your code repository, hence on why you should add to the .gitignore file the directory that holds such production files.


Q: Can't use Twilio with python I used the code from the Twilio website to send a text message using python. I used real values, that I obtained during registration in the actual code. There aren't any XXXXXX in my program.
I removed the {{}} too. the code's still not working.
from twilio.rest import TwilioRestClient

account_sid = "{{ AC3XXXXXXXXXXXXXXXXXXXXXXXXXXXXX }}" # Your Account SID from www.twilio.com/console
auth_token  = "{{ 04e4c31XXXXXXXXXXXXXXXXXXXXXXXXXX }}"  # Your Auth Token from www.twilio.com/console

client = TwilioRestClient(account_sid, auth_token)

message = client.messages.create(body="Hello from python. ",
    to="+447XXXXXXXXXX",    # Replace with your phone number
    from_="+4417XXXXXXXXXXX") # Replace with your Twilio number

print(message.sid)

This is the error I'm getting. What does this mean?
Thanks!
Traceback (most recent call last):
  File "C:/Users/Pawel/Desktop/Courses/Udacity/Python/send_text.py", line 10, in <module>
    from_="+441753254382") # Replace with your Twilio number
  File "C:\Python27\lib\site-packages\twilio-6.3.dev0-py2.7.egg\twilio\rest\resources\messages.py", line 122, in create
    return self.create_instance(kwargs)
  File "C:\Python27\lib\site-packages\twilio-6.3.dev0-py2.7.egg\twilio\rest\resources\base.py", line 365, in create_instance
    data=transform_params(body))
  File "C:\Python27\lib\site-packages\twilio-6.3.dev0-py2.7.egg\twilio\rest\resources\base.py", line 200, in request
    resp = make_twilio_request(method, uri, auth=self.auth, **kwargs)
  File "C:\Python27\lib\site-packages\twilio-6.3.dev0-py2.7.egg\twilio\rest\resources\base.py", line 164, in make_twilio_request
    uri=resp.url, msg=message, code=code)
TwilioRestException:
[31m[49mHTTP Error[0m [37m[49mYour request was:[0m

[36m[49mPOST https://api.twilio.com/2010-04-01/Accounts/{{ AC3ea248ea5628ce024619440468334835 }}/Messages.json[0m

[37m[49mTwilio returned the following information:[0m

[34m[49m[0m

A: account_sid = "{{ account_sid }}" # Your Account SID from www.twilio.com/console

This does not mean place the value in the {{ }}. It means replace that entire string with your value.


Q: enable button only if older than 90 days Good Day
I have a delete button which deletes entries on my database, problem is I want to disable the button and only enable it if it is older than 90 days.
I used this code and it's working but if it's not older than 90 days it still replies "successfully deleted" although it was not actually deleted and that is why I thought it would be easier to disable the delete button and only enable it if the entry is older than 90 days
please assist
Thanking you
$sql="DELETE FROM client_post WHERE id = '$id' AND date < DATE_SUB(NOW(), INTERVAL 90 DAY)";
$result=mysql_query($sql);

if($result){
         echo('Entry '.$id.' successfully deleted
');
} else{
         echo('
Failed to delete');
};

A: Change if statement to:
  if($result && mysql_affected_rows() > 0){

Problem with your code is that you are checking if the $result is true, while $result is just an identifier of mysql_query() results. You should check also how much rows where affected by the query.

A: Can you show the rest of the code?
I guess you want to make a check if there are any entries older than 90 days, the button is enabled.
Do you have some kind of list where all entries are shown, and on each entry there is a delete button?
To answer your actual question, you'll need to supply us with more code.

A: As michal said you can use the affected rows to actually check if a row got deleted with:
if($result && mysql_affected_rows() > 0){

If you still want to disable the button tho you can use
SELECT
     IF( DATEDIFF( CURRENT_DATE( ), date ) > 90, 1, 0 )
FROM
     client_post
WHERE
     id = $id

This will return true or false depending on the entry age. Depending on that you can show the button or not.
Also, take a look at PDO much better. MySQL api is deprecated.


Q: How to calculate size of directory on FTP? How to calculate size of FTP folder? Do you know any tool or programmatic way in C#?

A: If you have FileZilla, you can use this trick:

*

*click on the folder(s) whose size you want to calculate

*click on Add files to queue
This will scan all folders and files and add them to the queue. Then look at the queue pane and below it (on the status bar) you should see a message indicating the queue size.

A: WinSCP (free GUI on Microsoft Windows):

A: If you just need the work done, then SmartFTP might help you, it also has a PHP and ASP script to get the total folder size by recursively going through all the files.

A: You can use the du command in lftp for this purpose, like this:
echo "du -hs ." | lftp example.com 2>&1

This will print the current directory's disk size incl. all subdirectories, in human-readable format (-h) and omitting output lines for subdirectories (-s). stderr output is rerouted to stdout with 2>&1 so that it is included in the output.
However, lftp is a Linux-only software, so to use it from C# under Windows you would need to install it in the integrated Windows Subsystem for Linux (WSL) or using Cygwin or MSYS2. (Thanks to the commenters for the hints!)
The lftp du command documentation is missing from its manpage, but available within the lftp shell with the help du command. For reference, I copy its output here:
lftp :~> help du
Usage: du [options] <dirs>
Summarize disk usage.
 -a, --all             write counts for all files, not just directories
     --block-size=SIZ  use SIZ-byte blocks
 -b, --bytes           print size in bytes
 -c, --total           produce a grand total
 -d, --max-depth=N     print the total for a directory (or file, with --all)
                       only if it is N or fewer levels below the command
                       line argument;  --max-depth=0 is the same as
                       --summarize
 -F, --files           print number of files instead of sizes
 -h, --human-readable  print sizes in human readable format (e.g., 1K 234M 2G)
 -H, --si              likewise, but use powers of 1000 not 1024
 -k, --kilobytes       like --block-size=1024
 -m, --megabytes       like --block-size=1048576
 -S, --separate-dirs   do not include size of subdirectories
 -s, --summarize       display only a total for each argument
     --exclude=PAT     exclude files that match PAT

A: You could send the LIST command which should give you a list of files in the directory and some info about them (fairly certain the size is included), which you could then parse out and add up.
Depends on how you connect to the server, but if you're useing the WebRequest.Ftp class there's the ListDirectoryDetails method to do this. See here for details and here for some sample code.
Just be aware, if you want to have the total size including all subdirectories, I think you'll have to enter each subdirectory and call it recursively so it could be quite slow. It can be quite slow thought so normally I'd recommended, if possible, to have a script on the server calculate the size and return the result in some way (possibly storing it in a file you could download and read).
Edit: Or if you just mean that you'd be happy with a tool that does it for you, I think FlashFXP does it and probably other advanced FTP clients will as well. Or if it's a unix server I have a vague memory that you could just login and type ls -laR or something to get a recursive directory listing.

A: I use the FTPS library from Alex Pilotti with C# to execute some FTP commands in a few production environments. The library works well, but you have to recursively get a list of files in the directory and add their sizes together to get the result. This can be a bit time consuming on some of our larger servers (sometimes 1-2 min) with complex file structures.
Anyway, this is the method I use with his library:
/// <summary>
/// <para>This will get the size for a directory</para>
/// <para>Can be lengthy to complete on complex folder structures</para>
/// </summary>
/// <param name="pathToDirectory">The path to the remote directory</param>
public ulong GetDirectorySize(string pathToDirectory)
{
    try
    {
        var client = Settings.Variables.FtpClient;
        ulong size = 0;

        if (!IsConnected)
            return 0;

        var dirList = client.GetDirectoryList(pathToDirectory);
        foreach (var item in dirList)
        {
            if (item.IsDirectory)
                size += GetDirectorySize(string.Format("{0}/{1}", pathToDirectory, item.Name));
            else
                size += item.Size;
        }
        return size;
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
    return 0;
}

A: Simplest and Efficient way to Get FTP Directory Size with it's all Contents recursively.

var size = FtpHelper.GetFtpDirectorySize("ftpURL", "userName",
  "password");

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading;
using System.Threading.Tasks;

public static class FtpHelper
{
    public static long GetFtpDirectorySize(Uri requestUri, NetworkCredential networkCredential, bool recursive = true)
    {
        //Get files/directories contained in CURRENT directory.
        var directoryContents = GetFtpDirectoryContents(requestUri, networkCredential);

        long ftpDirectorySize = default(long); //Set initial value of the size to default: 0
        var subDirectoriesList = new List<Uri>(); //Create empty list to fill it later with new founded directories.

        //Loop on every file/directory founded in CURRENT directory.
        foreach (var item in directoryContents)
        {
            //Combine item path with CURRENT directory path.
            var itemUri = new Uri(Path.Combine(requestUri.AbsoluteUri + "\\", item));
            var fileSize = GetFtpFileSize(itemUri, networkCredential); //Get item file size.

            if (fileSize == default(long)) //This means it has no size so it's a directory and NOT a file.
                subDirectoriesList.Add(itemUri); //Add this item Uri to subDirectories to get it's size later.
            else //This means it has size so it's a file.
                Interlocked.Add(ref ftpDirectorySize, fileSize); //Add file size to overall directory size.
        }

        if (recursive) //If recursive true: it'll get size of subDirectories files.
            //Get size of selected directory and add it to overall directory size.
            Parallel.ForEach(subDirectoriesList, (subDirectory) => //Loop on every directory
        Interlocked.Add(ref ftpDirectorySize, GetFtpDirectorySize(subDirectory, networkCredential, recursive)));

        return ftpDirectorySize; //returns overall directory size.
    }
    public static long GetFtpDirectorySize(string requestUriString, string userName, string password, bool recursive = true)
    {
        //Initialize Uri/NetworkCredential objects and call the other method to centralize the code
        return GetFtpDirectorySize(new Uri(requestUriString), GetNetworkCredential(userName, password), recursive);
    }

    public static long GetFtpFileSize(Uri requestUri, NetworkCredential networkCredential)
    {
        //Create ftpWebRequest object with given options to get the File Size.
        var ftpWebRequest = GetFtpWebRequest(requestUri, networkCredential, WebRequestMethods.Ftp.GetFileSize);

        try { return ((FtpWebResponse)ftpWebRequest.GetResponse()).ContentLength; } //Incase of success it'll return the File Size.
        catch (Exception) { return default(long); } //Incase of fail it'll return default value to check it later.
    }
    public static List<string> GetFtpDirectoryContents(Uri requestUri, NetworkCredential networkCredential)
    {
        var directoryContents = new List<string>(); //Create empty list to fill it later.
        //Create ftpWebRequest object with given options to get the Directory Contents.
        var ftpWebRequest = GetFtpWebRequest(requestUri, networkCredential, WebRequestMethods.Ftp.ListDirectory);
        try
        {
            using (var ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse()) //Excute the ftpWebRequest and Get It's Response.
            using (var streamReader = new StreamReader(ftpWebResponse.GetResponseStream())) //Get list of the Directory Contentss as Stream.
            {
                var line = string.Empty; //Initial default value for line
                while (!string.IsNullOrEmpty(line = streamReader.ReadLine())) //Read current line of Stream.
                    directoryContents.Add(line); //Add current line to Directory Contentss List.
            }
        }
        catch (Exception) { throw; } //Do nothing incase of Exception occurred.
        return directoryContents; //Return all list of Directory Contentss: Files/Sub Directories.
    }
    public static FtpWebRequest GetFtpWebRequest(Uri requestUri, NetworkCredential networkCredential, string method = null)
    {
        var ftpWebRequest = (FtpWebRequest)WebRequest.Create(requestUri); //Create FtpWebRequest with given Request Uri.
        ftpWebRequest.Credentials = networkCredential; //Set the Credentials of current FtpWebRequest.

        if (!string.IsNullOrEmpty(method))
            ftpWebRequest.Method = method; //Set the Method of FtpWebRequest incase it has a value.
        return ftpWebRequest; //Return the configured FtpWebRequest.
    }
    public static NetworkCredential GetNetworkCredential(string userName, string password)
    {
        //Create and Return NetworkCredential object with given UserName and Password.
        return new NetworkCredential(userName, password);
    }
}

A: As the answer by @FranckDernoncourt shows, if you want a GUI tool, you can use WinSCP GUI. Particularly its folder properties dialog.

If you need a code, you can use WinSCP too. Particularly with WinSCP .NET assembly and its Session.EnumerateRemoteFiles method it is easy to implement in many languages, including C#.
It is also doable with .NET built-in FtpWebRequest, but that's lot more work.
Both are covered in How to get a directories file size from an FTP protocol in a .NET application.

A: Just use FTP "SIZE" command...

A: You can use The FileZilla client. Download here: https://filezilla-project.org/download.php?type=client
If you want more readable size go to:
Edit -> Settings -> Interface -> filesize format -> size formatting -> select binary prefixes using SI symbols.
When you select a directory you can see its size.


Q: Theme Choosing on the basis of a certain API value I am working on a front-end project. My task is to receive an API token, then conditionally choose a theme (CSS file) for different API values.
now I have some plans,
1. doing something with package.json
2. using sass/compass
3. using webpack

According to project owner , I am not allowed to use less or sass. Is there any way to do so? I am using Nuxt.js .
N.B: what is have to do within the entry point of project, i.e. before loading the whole project

A: i did this simple task and worked like charm:
data(){
     return{
       api_value:0
     }
   },
   beforeCreate(){
     axios.get('my-api-link)
         .then(response=>{
          this.api_value = response.data.api_value
      })

   },

     computed:{
         inject_theme(){
           if(this.api_value ==1)
             return '/theme/dark.css'
           else if (this.api_value ==2)
              return '/theme/dark.1.css'
           else if (this.api_value ==3)
              return '/theme/dark.2.css'
         }
       },

   head () {
    return {
      title: this.title,
      meta: [
        { hid: 'description', name: this.inject_theme, content: 'My custom description' }
      ],
      link:[
        {rel:'stylesheet',href:this.inject_theme}
      ]
    }
  }


Q: Highlight/mark/indicate certain lines in LaTeX in Emacs I use Emacs to edit LaTeX source. I preface notes which I have made with % as required, so that they are considered as comments. These lines appear in Emacs in a different face.
However, when working on a document, I sometimes would like to highlight/indicate/mark certain lines so that they appear in a different face. For example, if I am done with a section of notes I have made, but would like to keep these in the source file, I would like to "flag" these lines so that they appear in a different face in Emacs.
Is there a way to do this? Any solution would obviously still need to be considered valid LaTeX code. Maybe lines starting with %% could use a different face?

A: What a great idea, thanks for making me go and find a solution! What you need to do is add the following lines to your ~/.emacs file:
(add-hook 'tex-mode-hook
  (lambda ()
    (font-lock-add-keywords nil
       '(("\\(%%.*\\)" 1
        font-lock-warning-face t)))))

You can change the %% to anything else you want. Personally, I think I will use %# that way I can still have stretches of % for horizontal separators.


Q: Construction of dense $C_4$-free graph Yesterday I created the topic where we discussed the following theorem:
If $G=(V,E)$ is a simple and $C_4$-free graph, then $|E|\leq \dfrac{|V|}{4}(1+\sqrt{4|V|-3})$.
It is important to notice that this result is false if graph has loops and multiple edges.
In the following page of that book you can find the following:
I would like to ask only two questions:

*

*I would like to check that $G$ is undirected graph. As far as I know in the case of directed graphs edges are ordered pairs of vertices. How to check that $G$ is undirected graph?

*In the theorem graph should be a simple. However, in this example some edges are loops. So it does not that the bound in Theorem 2.4 is optimal up to a constant. Am I right?

A: *

*The condition defining the edges of $G$ is symmetric with respect to the endpoints of the edge, so the graph is undirected.

*There are at most $n$ loops, which is much less than the number of edges, so after removing the loops there are still $\Omega(n^{3/2})$ edges.
As a side note, the 'polarity graph' provides an optimal construction which gives equality for the initial theorem you posted, for infinitely many values of $n$.


Q: subsetting using a threshold in R and returning a neighboring row using for loops So I have been stumped on this problem for being able to build a table based off a threshold using R.  All I want to do is groupby(set_a,set_b) and select a value based on whether rank_of_values is greater than .80 (utilizing some paste a the same time) to build a table.  My criteria is, select the max rank_of_values and return the value in a table if true in the table.  If that part is false, append in the table the first and second rank_of_values =value in the table.  I was able to figure this out previously when there was only one group in set_b but now that there are multiple I am having trouble.  I also have tried to figure out the warning but have been stumped tried for length error but no luck so far. Any help and advice would be appreciated.
library(data.table)

#create sample data
set_a <- c("a","a","a","a","b","b","b","b","c","c","c","c","a","a","a","a","b","b","b","b","c","c","c","c","a","a","a","a","b","b","b","b","c","c","c","c")
set_b <- c("red","red","red","red","red","red","red","red","red","red","red","red","blue","blue","blue","blue","blue","blue","blue","blue","blue","blue","blue","blue","green","green","green","green","green","green","green","green","green","green","green","green")
#value <- c(sample(1:100,size = 36,replace = T))
value <- c(19,15,3,62,61,17,2,31,16,511,2,64,81,51,58,94,81,79,23,35,9,40,54,78,78,56,11,58,99,74,36,58,5,47,39,98)
a = data.frame(set_a,set_b,value)

a = data.table(a)

#This function calculates the average of the counts
a = a[,rank_of_values:= value/sum(value), by=list(set_a,set_b)]
head(a)

mn <- c() #create matrix to fill
mn0 <- c() #temp matrix
colu = unique(as.character(a$set_a))
colu2 = unique(as.character(a$set_b))

for (i in seq_along(colu))
{
  #subset the data table for the set_a:
  t = subset(a, set_a == colu[i])

  for (i in seq_along(colu2)){
    t2 =  subset(t, set_b == colu2[i])
    #subsetting the data by the set_b
    if(t2$rank_of_values > .8){
      mn <- cbind(as.character(t2$set_a[i]),paste0(t2$set_b[i],"_a"),t2$value[i])
      mn0 <- rbind(mn,mn0)
      mn2 <- cbind(as.character(t2$set_a[i]),paste0(t2$set_b[i],"_b"),t2$value[i])
      mn0 <- rbind(mn0,mn2)

    }
    else
    {
      t2[order(-rank_of_values)][,.SD[1:2]] #create a second data table to select for
      #order the data.table and

      mn3 <- cbind(as.character(t2$set_a[1]),paste0(t2$set_b[1],"_a"),t2$value[1])

      mn0 <- rbind(mn0,mn3)
      mn4 <- cbind(as.character(t2$set_a[2]),paste0(t2$set_b[2],"_b"),t2$value[2])
      mn0 <- rbind(mn0,mn4)
    }
  }
}

mn0

Current result:
     [,1] [,2]      [,3]
 [1,] "a"  "red_a"   "19"
 [2,] "a"  "red_b"   "15"
 [3,] "a"  "blue_a"  "81"
 [4,] "a"  "blue_b"  "51"
 [5,] "a"  "green_a" "78"
 [6,] "a"  "green_b" "56"
 [7,] "b"  "red_a"   "61"
 [8,] "b"  "red_b"   "17"
 [9,] "b"  "blue_a"  "81"
[10,] "b"  "blue_b"  "79"
[11,] "b"  "green_a" "99"
[12,] "b"  "green_b" "74"
[13,] "c"  "red_a"   "16"
[14,] "c"  "red_b"   "511"
[15,] "c"  "blue_a"  "9"
[16,] "c"  "blue_b"  "40"
[17,] "c"  "green_a" "5"
[18,] "c"  "green_b" "47"

Desired Result:
        [,1] [,2]      [,3]
 [1,] "a"  "red_a"   "62"
 [2,] "a"  "red_b"   "19"
 [3,] "a"  "blue_a"  "94"
 [4,] "a"  "blue_b"  "81"
 [5,] "a"  "green_a" "78"
 [6,] "a"  "green_b" "58"
 [7,] "b"  "red_a"   "61"
 [8,] "b"  "red_b"   "31"
 [9,] "b"  "blue_a"  "81"
[10,] "b"  "blue_b"  "79"
[11,] "b"  "green_a" "99"
[12,] "b"  "green_b" "74"
[13,] "c"  "red_a"   "511"
[14,] "c"  "red_b"   "64"
[15,] "c"  "blue_a"  "78"
[16,] "c"  "blue_b"  "54"
[17,] "c"  "green_a" "98"
[18,] "c"  "green_b" "47"

Warning Message Received:
Warning messages:
1: In if (t2$rank_of_values > 0.8) { :
  the condition has length > 1 and only the first element will be used
2: In if (t2$rank_of_values > 0.8) { :
  the condition has length > 1 and only the first element will be used
3: In if (t2$rank_of_values > 0.8) { :
  the condition has length > 1 and only the first element will be used
4: In if (t2$rank_of_values > 0.8) { :
  the condition has length > 1 and only the first element will be used
5: In if (t2$rank_of_values > 0.8) { :
  the condition has length > 1 and only the first element will be used
6: In if (t2$rank_of_values > 0.8) { :
  the condition has length > 1 and only the first element will be used
7: In if (t2$rank_of_values > 0.8) { :
  the condition has length > 1 and only the first element will be used
8: In if (t2$rank_of_values > 0.8) { :
  the condition has length > 1 and only the first element will be used
9: In if (t2$rank_of_values > 0.8) { :
  the condition has length > 1 and only the first element will be used

A: I came up with a solution to my question after searching the forums.
mn <- c() #create matrix to fill
mn0 <- c() #temp matrix
colu = unique(as.character(a$set_a))
colu2 = unique(as.character(a$set_b))

for (i in colu){
  for (j in colu2){

    t = a[a$set_a %in% i & a$set_b %in% j,][order(-rank_of_values)]
    for(z in t$rank_of_values[[nrow(t)]]){
      if(t$rank_of_values[[z]] > .8){
        print(z)
        mn <- cbind(as.character(t$set_a[[z]]),paste0(t$set_b[[z]],"_a"),t$value[[z]])
        mn0 <- rbind(mn,mn0)
        mn2 <- cbind(as.character(t$set_a[[z]]),paste0(t$set_b[[z]],"_b"),t$value[[z]])
        mn0 <- rbind(mn0,mn2)
      }
      else{
         #create a second data table to select for
        #order the data.table and

        mn3 <- cbind(as.character(t$set_a[[1]]),paste0(t$set_b[[1]],"_a"),t$value[[1]])

        mn0 <- rbind(mn0,mn3)
        mn4 <- cbind(as.character(t$set_a[[2]]),paste0(t$set_b[[2]],"_b"),t$value[[2]])
        mn0 <- rbind(mn0,mn4)
      }
    }
  }
}

Result
     [,1] [,2]      [,3]
 [1,] "a"  "red_a"   "62"
 [2,] "a"  "red_b"   "19"
 [3,] "a"  "blue_a"  "94"
 [4,] "a"  "blue_b"  "81"
 [5,] "a"  "green_a" "78"
 [6,] "a"  "green_b" "58"
 [7,] "b"  "red_a"   "61"
 [8,] "b"  "red_b"   "31"
 [9,] "b"  "blue_a"  "81"
[10,] "b"  "blue_b"  "79"
[11,] "b"  "green_a" "99"
[12,] "b"  "green_b" "74"
[13,] "c"  "red_a"   "511"
[14,] "c"  "red_b"   "64"
[15,] "c"  "blue_a"  "78"
[16,] "c"  "blue_b"  "54"
[17,] "c"  "green_a" "98"
[18,] "c"  "green_b" "47"


Q: Match function? VBA not working properly I have a following code and i have "name" in cells B11 , B19 and B25 and i was expecting a result of 19 or 25 with the code but it returns Y=1. Could anyone tell me what is the problem?.
Sub mat()

Y = Application.Match("name", ActiveSheet.Range("B19:B30"), 0)
MsgBox Y

End Sub

A: According to the documentation for MATCH:

MATCH returns the position of the matched value within lookup_array, not the value itself.

and with 0as the optional third argument (match_type):

If match_type is 0, MATCH finds the first value that is exactly equal to lookup_value. Lookup_array can be in any order.

So the returned 1refers to the position on B19in the array Range("B19:B30") and the code sample is indeed behaving as expected.

A: Application.Match("name", ActiveSheet.Range("B19:B30"), 0)

The MATCH function searches for a specified item in a range of cells, and then returns the relative position of that item in the range
So parsing the parameter ActiveSheet.Range("B19:B30") means that B19 equals relative position =1.

A: add slgn
Sub mat()
    Y = Application.Match(slng(range("a4").value), ActiveSheet.Range("B19:B30"), 0)
    MsgBox Y
End Sub

ex2:
Application.WorksheetFunction.Match(CLng(TextBox1.Text), sheet110.Range("B6:B" & ls), 0)


Q: Spliting tables with *almost* same values I have different kind of documents which have common fields (not all of them, but most) and I thought to put them in the same table and use ENUM to differentiate them.
Then I realized that if have thousands of docs of every kind I will have a (very?) slow SELECT/UPDATE's right?
So my question is: should I split the tables and have one table for each document? or is the initial approach the way to go?
Thank you

A: Certainly not one table for each document.  Perhaps one for each document type.
In general you are correct - reading or writing to larger tables typically takes longer than the same operation on smaller tables.  There are techniques to help with this - indexing for example.  Modern DBMSs can easily handle tables of several million rows, however, so unless you are pushing these limits it is better for your design to match your requirements than to work around the limitations of the technology.
If you commonly update several different documents of different types simultaneously then a single table would be beneficial.  If each document type is processed independently then separate tables would be better.