text:
Q: Make and Re-Compiling Headers with Sub-Directories There are a few different questions already related to what I'm trying to do, such as this, this, and this. However, I've looked at what is there and what they link to and I'm still not able to get it to work.
I have the following make file (I had some help with this here). It builds .os in a build directory from .cpps in a source directory. I want to adjust this so that if the headers are updated, then it properly re-compiles those so I don't have to make clean the whole thing (most particularly the ones from the INC_DIR1 folder).
CC = g++
CFLAGS = -g -Wall

INC_DIR1 = include
INC_DIR2 = C:/CPPFiles/CPP_Extra_Libraries/armadillo-4.200.0/include
INC_DIR = $(INC_DIR1) $(INC_DIR2)
INCLUDES = $(foreach d, $(INC_DIR), -I$d)

BUILD_DIR = build
SRC_DIR = test

SRC = $(wildcard */*.cpp)

VPATH = $(SRC_DIR)

OBJS = $(addprefix $(BUILD_DIR)/, $(notdir $(SRC:.cpp=.o)))

MAIN = armadillo_extra_functions_test

.PHONY: depend clean

all: $(BUILD_DIR) $(MAIN)
    @echo  compilation complete

$(BUILD_DIR):
    mkdir -p $@

$(BUILD_DIR)/%.o: %.cpp
    $(CC) $(CFLAGS) $(INCLUDES) -c $< -o $@

$(MAIN): $(OBJS)
    $(CC) $(CFLAGS) $(INCLUDES) -o $(MAIN) $(OBJS)

clean:
    $(RM) *.o *~ $(MAIN) $(BUILD_DIR)/*.o

depend: $(SRC)
    makedepend $(INCLUDES) $^

The latest thing I tried was to remove the depend and makedepend statements and then replace the $(BUILD_DIR/%.o: %.cpp statement with
DEPS = $(patsubst %.o, %.d, $(OBJS))

-include $(DEPS)

$(BUILD_DIR)/%.o: %.cpp
    $(CC) -c $(CFLAGS) $(INCLUDES) $< -o $@
    $(CC) -c $(CFLAGS) -MMD  $< > $(DEPS)

Without the last line of these adjustments, the make file runs, though it will not update headers. However, when I add in the last line  I get an error about the $(BUILD_DIR)/%.d files not being there.

A: Basically you need to construct the makefile so that the .cpp files depend on the headers. In this way, changes to the headers will trigger recompilation of the .cpp files. To make this easier, ideally the header dependencies of each .cpp file would be automatically determined.
I recommend using either the GNU autotools approach (great for software you will publish in source form), jam (very simple configuration), or (my current favorite) CMake. All of these essentially automatically generate the makefile from another file (or set of files). They automatically handle the dependency detection and management, too. I would only hand-roll a makefile for self-education or for something with only a handful of source files, or perhaps something weird and complex.

A: You were almost right with the -MMD flag, but there is no need to complicate things:
INC_DIR1    :=  include
INC_DIR2    :=  C:/CPPFiles/CPP_Extra_Libraries/armadillo-4.200.0/include
INC_DIRS    :=  $(INC_DIR1) $(INC_DIR2)

BUILD_DIR   :=  build
SRC_DIR     :=  test

SRCS        :=  $(wildcard $(SRC_DIR)/*.cpp)
OBJS        :=  $(SRCS:$(SRC_DIR)/%.cpp=$(BUILD_DIR)/%.o)
DEPS        :=  $(OBJS:.o=.d)

LDLIBS      :=  # -l flags
LDFLAGS     :=  # -L flags

CPPFLAGS    :=  -MMD -MP $(foreach DIR, $(INC_DIRS), -I $(DIR))
CXXFLAGS    :=  -W -Wall

MAIN        :=  armadillo_extra_functions_test

.PHONY: all clean

all:    $(MAIN)
    @echo "compilation complete"

$(MAIN):    $(OBJS)
    $(CXX) $(LDFLAGS) $^ $(LDLIBS) -o $@

clean:
    $(RM) -r $(MAIN) $(BUILD_DIR)

-include $(DEPS)

$(BUILD_DIR):
    mkdir $@

$(BUILD_DIR)/%.o: $(SRC_DIR)/%.cpp | $(BUILD_DIR)
    $(CXX) $(CPPFLAGS) $(CXXFLAGS) -o $@ -c $<

Some quick notes :

*

*You're using C++. Drop the $(CC) and $(CFLAGS) C variables for their C++ versions: $(CXX) and $(CXXFLAGS) variables.

*$(CPPFLAGS) is meant for preprocessor flags, such as -MMD, -MP or -I.

*You need to include the rules GCC created in the dependency files.


text:
Q: How can i see my test logs in the console log of jenkins I'm running my junit test for my android app throw jenkins. In case a test fails I can only see the stacktrace  which sometimes doesn't help me to understand why My test was failed. I added some logs in my code so I can debug my test when I run them on my local machine but I want to be able to see those logs in the Jenkins console output so I can realize what went wrong when my test fails.

A: It is an old question, but I have found a solution.
I wrap Log class into a custom class (Logger).
Then I wrap the Log methods like:
public static void d(String tag, String message) {
    log(LOG.DEBUG, tag, message);
}

Then log looks like:
private static void log(LOG logLevel, Object message) {
        LOG_LINES.add(new LogLine(logLevel, tag, content));

        switch (logLevel) {
            case ERROR:
                Log.e(tag, content);
                break;
            case WARNING:
                Log.w(tag, content);
                break;
            case INFO:
                Log.i(tag, content);
                break;
            case DEBUG:
                Log.d(tag, content);
                break;
            case VERBOSE:
                Log.v(tag, content);
                break;
       }
    }

with LOG_LINES a CopyOnWriteArrayList
and LogLine a holder of the log data.
Finally, the logs are displayed in Jenkins (in the HTML Report) by using a custom test Runner. Simply add the Annotation @RunWith(MyLoggingTestRunner.class) to the test classes with :
public class MyLoggingTestRunner extends BlockJUnit4ClassRunner {

    public MyLoggingTestRunner(Class<?> klass) throws InitializationError {
        super(klass);
    }

    @Override
    protected void runChild(final FrameworkMethod method, RunNotifier notifier) {
        //override to override errors with logs
        Description description = describeChild(method);
        if (method.getAnnotation(Ignore.class) != null) {
            notifier.fireTestIgnored(description);
        } else {
            run(methodBlock(method), description, notifier);
        }
    }

    protected void run(Statement statement, Description description, RunNotifier notifier) {
        EachTestNotifier eachNotifier = new EachTestNotifier(notifier, description);
        eachNotifier.fireTestStarted();
        try {
            statement.evaluate();
        } catch (AssumptionViolatedException e) {
            eachNotifier.addFailedAssumption(e);
        } catch (Throwable e) {
            String throwableMessage = e.getMessage();
            String message = "\nLast logs :\n" + logsToString() + "\n\nStackTrace :\n" + e.getClass() + (TextUtils.isEmpty(throwableMessage) ? "" : ":" + throwableMessage);

            try {
                Field detailMessage = Throwable.class.getDeclaredField("detailMessage");
                detailMessage.setAccessible(true);
                detailMessage.set(e, message);
            } catch (Exception e1) {
            }
            eachNotifier.addFailure(e);
        } finally {
            eachNotifier.fireTestFinished();
        }
    }

    private static String logsToString() {
        List<LogLine> logs = Logger.getLogs();
        StringBuilder logBuilder = new StringBuilder();
        String sep = "";
        for (LogLine logLine : logs) {
            logBuilder.append(sep).append(logLine.toString());
            sep = "\n";
        }
        return logBuilder.toString();
    }
}

I hope it works since I adapted my code trying to explain it in a simple way.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android: How does one go about having the user click a button to create (not go to) a new activity What I'm trying to do is make an Android app that makes use of tabs, and when a user clicks a certain button I want a new tab to appear. I was wondering if this is possible, and if anyone could provide details or direction on this.
Basically:
One main activity where you can create new tabs.
This main activity has tabs, which the new one would be apart of.
Thanks

A: Here is one of solutions Android — Add new tab when button click like Google Chrome new button?.
I hope that will be enough for good start.


text:
Q: Issue in a time series ggplot I have a data like this:
df<-structure(list(Participant.ID = structure(c(1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "83528", class = "factor"),
    Response = c("2", "1", "0", "1", "3", "3", "5", "3", "5",
    "6", "3", "5", "7", "3", "6", "2", "3", "3", "3", "3", "5",
    "4", "3", "1", "4", "4", "3", "6", "3"), times = c(1, 2,
    3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
    19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29)), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -29L), groups = structure(list(
    Participant.ID = structure(1L, .Label = "1", class = "factor"),
    .rows = structure(list(1:29), ptype = integer(0), class = c("vctrs_list_of",
    "vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -1L), .drop = TRUE))

Using this code, I plotted a time series, but the outcome was not a time series, and the lines overlapped each other. Where is the problem? Thanks!
ggplot(df, aes(x = times, y = Response)) +
  geom_line(aes(color = Participant.ID), size = 1)  +
  theme_minimal()

A: The issue is that your Response column is a character. By default ggplot2 will group your data by a discrete columns. Hence you get a line for each category of Response.
To fix that you could convert your Response column to a numeric or override the default grouping by mapping Participant.ID on the group aes
library(ggplot2)

ggplot(df, aes(x = times, y = as.numeric(Response))) +
  geom_line(aes(color = Participant.ID), size = 1) +
  theme_minimal()

ggplot(df, aes(x = times, y = Response, group = Participant.ID)) +
  geom_line(aes(color = Participant.ID), size = 1) +
  theme_minimal()


text:
Q: Trouble installing Visual Foxpro 6 on Windows 8 I need to install Visual Foxpro 6 on my Windows 8 laptop.
I have the Visual Studio 6 CDs. I go through the installation and everything completes installing. However, after the progress bar completes and goes away, the green installation screen displays a message like "Configuring your setup" or "completing setup". But this screen never goes away. It just hangs until I "Close Program" it.
When I start VFP6, it opens but the Command window never displays. I do see the white VFP6 desktop, but it doesn't respond and I have to Close Program.
I tried copying the VFP6 files from the CD to the drive, but the same thing happens when I try to run VFP6, it doesn't respond and I have to Close Program.
I'm able to run VFP9 on this Win8 PC just fine. But I can't get VFP6 to install or run.
Is there a solution?

A: I would suspect that VFP 6 is not even CLOSELY supported for Windows 8.  Another person I help periodically was running VFP 8 on a Windows 8 machine and it fails.  Apparently that was his consensus finding across the board for others he has communicated with.  I wouldn't even bother trying VFP 6 on Windows 8.


text:
Q: Python MySQL not reading from database Python unable to read from MySql database. Connectivity works but no results returned
import mysql.connector
cnx = mysql.connector.connect(user='user', password='pwd',host='<host>', port='<port>',database='mydb')
cursor = cnx.cursor()
print("Connection success")
query = ("SELECT * from users")
cursor.execute(query)
for (row) in cursor:
    print(row)

print("Print complete")
cursor.close()
cnx.close()

I get below result
Connection success
Print complete

If I add below line
rows=cursor.fetchall()

I get below error
InterfaceError: No result set to fetch from.

I have checked from MySql workbench and I get results from above query.
EDIT: The question is not about fetchall, even without fetchall I don't see any results.
EDIT 2:
Few Observations:

*

*If I try with incorrect password, I get Access Denied error.

*If I try with incorrect table name (with correct password) I get
error that table doesn't exist.

*If I add below line before the for loop
print(len(cursor.description))
I get below error
TypeError: object of type 'NoneType' has no len()


text:
Q: Help for Binomial Distribution question I am having issues with understanding a question on an assignment:

A test for the presence of a certain disease has probability 0.05 of
  giving a false-positive reading and probability 0.04 of giving a
  false-negative result. Suppose that four individuals are tested, three
  of whom do not have the disease and one of whom does. Let X= the
  number of positive readings.

*

*Does X have a binomial distribution?

*Find the probability that only one of the four test results is
    positive.

Edit:
I'm not sure if this is correct, but I have the probability setup like this: P(A->P)P(B->N)P(C->N)P(D->N)+P(A->N)P(B->P)P(C->N)P(D->N)+P(A->N)P(B->N)P(C->P)P(D->N)+P(A->N)P(B->N)P(C->N)P(D->P)
Where A,B and C do not have the disease. D has the disease. (A->P means A tests positive)

A: What you are looking for is the probability generating function. This functions allows you to plug in the values given in your exercise and calculate the probabilities needed. A nice derivation of the probability generating function of the binomial distribution can be found under
http://economictheoryblog.com/2012/10/21/binomial-distribution/
If you are interested it will additionally provide you with the expected value and variance estimation.

A: *

*A binomial distribution models the number of positive outcomes in a number of independent true or false events (Bernoulli events) that each have the same probability of being true. You should ask yourself: for the four individuals being tested, does each person have the same probability of testing positive?

*If you have two independent events, the probability of any two events occurring is the probability of those two events occurring individually multiplied by each other, then multiplied by the number of permutations that it can occur in. Apply this to the case of four events. You should take note that this is exactly the principle that the binomial distribution is built off of. So if you only had two people, person A and person B, then
$$\begin{align*}
\mathbb{P}[&\text{exactly one person tests positive}] \\
&= \mathbb{P}[A \text{ tests positive}]\mathbb{P}[B \text{ tests negative}] + \mathbb{P}[A \text{ tests negative}]\mathbb{P}[B \text{ tests positive}]
\end{align*}$$


text:
Q: Gauge pressure vs. absolute pressure? What are the key differences between Gauge pressure and absolute pressure?
Are there any other forms of pressure?

A: It's just a matter of defining your 'zero point'.
In a real, actual gauge, pressure is measured relative to the atmospheric pressure. If  there was 1 atmosphere of pressure inside a container (so it's the same pressure inside the container as it is outside it), the gauge will not read 1 atm, but rather 0 atm, as the pressure inside the container would just be the same as the pressure outside. Relative to the outside world there would be no pressure in the container. This is gauge pressure.
Absolute pressure is technically what we think of when we say pressure - the force that the gas is applying per unit area of the container.
If the gas is applying 101,300 Newtons per square meter, then the absolute pressure would be 101.3 kPa. On the other hand, the gauge pressure would be 0 kPa, as 101.3 kPa also happens to be the pressure of the atmosphere outside the container.

A: Assuming you are in air at sea level and you have an open container the pressure inside and outside will be the same - so a pressure gauge will read zero. That's gauge pressure PSIG
But there is 1 atmosphere of pressure inside the container - so 1atm of absolute pressure.
Now pump the air out of the container to give a vacuum, you have zero absolute pressure and -1 atmosphere of gauge pressure. Although negative gauge pressures are rarely used as they are confusing

A: just wiki it. Anyways I will give you a oneliner from wiki itself-

*

*Absolute pressure is zero-referenced against a perfect vacuum, so it is equal to gauge pressure plus atmospheric pressure.

*Gauge pressure is zero-referenced against ambient air pressure, so it is equal to absolute pressure minus atmospheric pressure. Negative signs are usually omitted.

*Differential pressure is the difference in pressure between two points.

A: absolute pressure= pressure thats actually inside the vessel on which a gauge is fitted.
gauge pressure= pressure shown by gauge which will be <<1 atm>> lesser than actual pressure as atmosphere exerts 1 atm pressure on the gauge.
vacuum pressure= pressure less than atmospheric pressure.

A: Pressure above atmospheric pressure is gauge pressure.  If atmospheric pressure is 1 then gauge pressure will be 0. Vacuum pressure is pressure less than 1 atm.  absolute pressure=gauge pressure+atmospheric pressure while pressure absolute=atmospheric-vacuum pressure.


text:
Q: AVAudioPlayer crash in Xcode? When I run my app in from Xcode to my iPhone7, it crashes at this line:

audioNSURL    NSURL   "file:///private/var/containers/Bundle/Application/016483D7-D06F-4639-A026-CCD0B1F4B31F/Solo%20Mission.app/spaceMusic.mp3"  0x000000028217eac0

Something to do with the AVAudioPlayer inside of the GameViewController which gives me this error message:

Thread 1: EXC_BAD_ACCESS (code=1, address=0x48)

Please help with this issue I have already checked the build phases and the file is there. Below is all of the code.
import UIKit
import SpriteKit
import AVFoundation

class GameViewController: UIViewController {

var backingAudio = AVAudioPlayer()

 override func viewDidLoad() {
        super.viewDidLoad()

    let filePath = Bundle.main.path(forResource: "spaceMusic", ofType: "mp3")
    let audioNSURL = NSURL(fileURLWithPath: filePath!)

    do { backingAudio = try AVAudioPlayer(contentsOf: audioNSURL as URL) }
    catch { return print("Cannot Find The Audio") }

    backingAudio.numberOfLoops = -1
    backingAudio.volume = 1
    backingAudio.play()

A: SOLVED!
I tried so many different ways, but finally I solved the problem. I just needed to write the code differently. Here's what I wrote instead:
        var player: AVAudioPlayer?

        override func viewDidLoad() {
            super.viewDidLoad()

        func initializePlayer() -> AVAudioPlayer? {
            guard let path = Bundle.main.path(forResource: "spaceMusic", ofType: "mp3") else {
                return nil
            }

            return try? AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
        }
        player = initializePlayer()
        player?.play()

To be honest, I don't quite understand why this works. But, I would appreciate any explanation given.


text:
Q: Selecting subclass attributes with Class Table Inheritance (Table Per Type) I have an inheritance schema that follows the Table Per Type pattern:
Harvesters
harvester_id | description

Harvester_A
harvester_id | propertyA_1 | propertyA_2

Harvester_B
harvester_id | propertyB_1 | propertyB_2

where Harvester_A.harvester_id and Harvester_B.harvester_id are foreign keys referencing Harvesters.harvester_id.
I have a fourth table:
Equipment_Set
equipment_set_id | ... | harvester_id

Equipment_Set.harvester_id is a foreign key to Harvesters.harvester_id.
How do I get the attributes of the specific subclass without knowing in advance which subclass I want? I.e. I have some Equipment_Set and want to get specific Harvester_A or Harvester_B attributes about its harvester_id depending on which subclass it is, but do not know in advance which one it is.

A: Either put all tables together with outer joins (in the result, all the 'wrong' columns will be NULL):
CREATE VIEW Harversters_A_or_B AS
SELECT harvester_id,
       description,
       propertyA_1,
       propertyA_2,
       propertyB_1,
       propertyB_2
FROM Harvester
LEFT JOIN Harvester_A USING (harvester_id)
LEFT JOIN Harvester_B USING (harvester_id);

Or put all properties into the same columns using a compound query (all the 'wrong' joins will return no rows):
CREATE VIEW Harversters_A_or_B AS
SELECT harvester_id,
       description,
       propertyA_1 AS property1,
       propertyA_2 AS property2,
       'A' AS type
FROM Harvester
JOIN Harvester_A USING (harvester_id)
UNION ALL
SELECT harvester_id,
       description,
       propertyB_1,
       propertyB_2,
       'B'
FROM Harvester
JOIN Harvester_B USING (harvester_id);


text:
Q: Connect to byobu screen session and execute command? In a script I am building I'm experimenting with how to automate as much as possible. One of the more interesting challenges is to connect to a byobu screen session and execute a command.
So I started in the obvious place, looking on how many screen sessions there are (game has 3 windows in byobu and lordquackstar has 2. The users are in separate putty instances)
game@quackgame:~$ screen -ls
There is a screen on:
        2019.byobu      (01/05/2011 05:10:04 PM)        (Attached)
1 Socket in /var/run/screen/S-game.

Only one there, so I checked for the system
lordquackstar@quackgame:/home/game$ sudo ls -lAR /var/run/screen/
/var/run/screen/:
total 0
drwx------ 2 game          users         100 2011-01-06 09:18 S-game
drwx------ 2 lordquackstar lordquackstar 100 2011-01-06 09:17 S-lordquackstar

/var/run/screen/S-game:
total 4
prwx------ 1 game users 0 2011-01-08 07:55 2019.byobu
-rw------- 1 game users 0 2011-01-06 09:18 byobu-exchange
-rw-r--r-- 1 game users 3 2011-01-08 07:32 byobu.updates-available

/var/run/screen/S-lordquackstar:
total 4
prwx------ 1 lordquackstar lordquackstar 0 2011-01-08 07:42 1169.byobu
-rw------- 1 lordquackstar lordquackstar 0 2011-01-06 09:17 byobu-exchange
-rw-r--r-- 1 lordquackstar lordquackstar 3 2011-01-08 07:35 byobu.updates-available

Still no multiple screens
So for my question: How can I connect to a window in byobu from a script?

On a slightly related note, once I connect to it from a bash script, is there any way to send it a command then detatch?

A: You can directly attach to a previously detached byobu/screen session including the window:
byobu -r -p2

will reattach into window 2 (or a named one).
-X can send any command to a byobu/screen session and also works with the -p switch.
byobu -p2 -X stuff "uname -a $(echo -ne '\r')"

This will send a uname -a to the second (third actually) byobu window, the echo at the end sends a carriage return so the commands gets executed.

A: You can send a command to a particular screen window of a particular screen session without attaching to it.
screen -S sessionname -p windowname -X screencommand

The session name is set with the -S option when starting screen or the sessionname command; by default it's byobu with byobu. You can also use the screen PID after -S. You can set a window's name with the title command. You can also use the window number.
screen -S byobu -p 1 -X stuff 'ls
'


text:
Q: Qt interface class I want to use a main like this:
int main()
{
   if (param)
      QtDisp *disp = new QtDisp(); //no visual result
   else
      SDLDisp *disp = new SDLDisp();

   disp->init(param); //displays the window

   while (1)
   {
      disp->change_color(colour); //change background colour
      sleep(1);
   }
}

It works with SDLDisp, now I have to create QtDisp.
I don't know what to do with exec() which is blocking. First, I thought to use Qthread but the display must be in the first thread.

A: Qt is event based driven framework. All gui part won't work without event loop. Almost everything, except, maybe brute calculations in another thread need to be done in event loop. exec() method starts that event system. So until you call exec() you won't be able to do something useful. In easiest way you can do it like this:
int delay = 10; //msec
QTimer *colorChangeTimer() = new QTimer();
colorChangeTimer->setSingleshot(false);
connect(colorChageTimer, SIGNAL(timeout()), disp, SLOT(onTimerChageColor()));
colorChageTimer->start(delay);
int result = QApplication::exec();
delete colorChangeTimer;
return result;


text:
Q: What is the probability that these passengers will exceed the weight capacity? The weight of men in the United States is normally distributed with mean $E(X) = 185 $ pounds and standard deviation, $\sigma = 10$. If a boat containing $n=25$ total passengers of U.S. men has a weight capacity of 6,000 pounds. what is the probability that these passengers will exceed the weight capacity?
I am not really sure how to go about this problem. I'm guessing that you have to convert it into a z-score somehow, but I'm not sure how to apply the 25 men sample. I know that $Z = x-\frac{185}{10}$  or maybe $Z = x-\frac{185\sqrt{25}}{10}$. So what would I chose as my $X$? Would I divide 6000 by 25 to find the average weight it has to be to exceed the capacity? Just trying a few things, I got the probability that they will exceed the weight capacity to be basically zero. Not sure if that is correct, and could use some help.

A: You are correct that the answer is very nearly 0, but (even after @Drew's nice edit) it does not
seem you are at all clear on how to get the answer.
Here is an outline:
1) The total weight $T = X_1 + X_2 + \cdots + X_{25}$ is normally
distributed. Figure out its mean $\mu_T$ and its SD $\sigma_T.$
2) Standardize: $P(T > 6000) =
P\left(Z = \frac{T-\mu_T}{\sigma_T} > \frac{6000 - \mu_T}{\sigma_T}\right).$
3) Evaluate the quantity $\frac{6000 - \mu_T}{\sigma_T}$, and then the probability, using standard normal tables or software.
Below is a graph of the density function of the distribution of $T$,
Your answer is the area beneath the curve to the right of the
vertical red line.


text:
Q: Use regular expression to look for "%" I'm programming in Java and I want to use regex to look for any data with a percent sign, e.g. 10%, 20%,30%,etc. I've tried a.matches("%")but that only returns true if the string matches exactly the percent sign. What should be the correct regular expression to use? Thanks

A: If you're just looking for a '%', then String.indexOf('%') would probably be faster and simpler than any regular-expression-based solution.
Considering regular expressions, the matches() function attempts to match the entire string to the pattern, as you've discovered. Matcher.find() will look for substrings within the string that match the pattern, for example:
Pattern pp = Pattern.compile("%");
Matcher mm = pp.matcher(someString);
if (mm.find()) {
    // someString contains a '%'
    ...
}


text:
Q: Convert RQ decomposed matrix to QR decomposed matrix. I have a Matrix $M$ (in $\mathbb{R}^{3\times 3}$) given as its RQ-decomposed form $M=RQ$, where $R$ is an upper triangular matrix and $Q$ is an orthogonal matrix. I would like to find its QR-decomposition ($M=Q'R'$) and am wondering about the best way to do so.
Of course, I can reconstruct $M$ from the current decomposition and then decompose it anew, but I am wondering if this can be done more efficiently.


text:
Q: Echo Ordered List from Mysql database How do I make this code echo the data (4 questions) from mySQL database in an ordered fashion so for example.. 1. 2. 3. 4. etc. I basically want the 4 questions to have a question number!
This is my code:
<?php
$sql = mysql_query("SELECT * FROM NI ORDER BY RAND() LIMIT 4");

while($data = mysql_fetch_array($sql))
{
  echo '
' . '
' . $data['Question'] . ' (100)' . '
' . '
' . '
';
}

For some reason my code is echoing the number 1 beside each question!

A: Do this
your query here
    $i=0;

    echo '
';
    while(your given conditions){
    echo "
";
    echo $i++." ".$data["question"];
    echo "

";
    }
    echo '
';

A: You should put all items in the
...
:
$sql = mysql_query("SELECT * FROM NI ORDER BY RAND() LIMIT 4");

// Did we actually find anything?
if(mysql_num_rows($sql) > 0) {
  echo '
';
  while($data = mysql_fetch_array($sql))
  {
    echo '
' . $data['Question'] . ' (100)' . '
';
  }
  echo '
';
}

If you wrap each item in
...
 the enumeration will always start at 1.
A general note: Stop using mysql_*() functions. They are deprecated and outdated. Start using mysqli_*() instead.


text:
Q: The ultimate fate and influence of the HMS Bounty Is there canon information regarding the fate of the Klingon Bird-of-Prey that was re-christened "HMS Bounty"?

It was last seen floating in San Francisco Bay at the end of The Voyage Home, as a backdrop to Kirk and friends playing with whales in the water.
By some standards, it should be a famous ship.

*

*It was the last vessel to be nose-to-nose with the original USS Enterprise.

*It was the last ship to orbit the planet Genesis before its demise.

*It probably has the distinction of being the first Klingon Bird-of-Prey to be captained by a non-Klingon — for several months, for that matter.

*It's probably the only Klingon warship to have been to the surface of Vulcan (certainly true in pre-Khitomer Accord times, and likely even after the Accord).

*It's probably the only (full-blown) Klingon warship to have been to the surface of Earth — in multiple centuries, for that matter.

*It's probably the only K'Vort class warship to have been to the 20th Century.

*It's probably the only Klingon warship to ever have an aquarium installed in it.

*It's probably the only Klingon ship to have intimidated a whaling vessel.

*It managed to return the AWOL Enterprise crew, a recently resurrected Spock, a Terran marine biologist from the 1980s, and two humpback whales also from the 1980s to 23rd Century Earth.

*Finally, it saved Earth from certain destruction at the hands of a space probe that only speaks to whales.
Fame aside, the ship's grounding on Earth would probably represent an immense tactical advantage for Starfleet at the time.  Is there any canonical information about what was done with the ship by Starfleet?
Related enough to be part of this question: Did the capture of the Bounty influence any subsequent design decisions of Federation starships or of Birds-of-Prey?  (This should be treated as a sub-question of the main question, regarding the fate of the ship.)

A: The fate of the HMS Bounty was not officially addressed.
However it was part of an early storyboard draft for a scene in Star Trek VI: The Undiscovered Country in which the HMS Bounty was to be disassembled by Starfleet engineers.

Just not enough time/money it seems.


text:
Q: How to scroll vertically for specific view using nested scrollview in android This is my xml file
<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/nested_scroll_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">

                    <include layout="@layout/container_parent_child_graph" />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:background="#002649">

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:background="#001525"
                        android:orientation="vertical">

                        <LinearLayout
                            android:id="@+id/ln_application_used"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center"
                            android:background="#001525"
                            android:gravity="center"
                            android:orientation="horizontal">

                            <include layout="@layout/view_list_tab_view_layout" />

                        </LinearLayout>

                        <LinearLayout
                            android:id="@+id/ln_container_all_apps_wise"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:layout_marginStart="@dimen/dp_16"
                            android:layout_marginEnd="@dimen/dp_16"
                            android:background="@drawable/avatar_borders"
                            android:orientation="vertical"
                            android:visibility="gone">

                            <androidx.recyclerview.widget.RecyclerView
                                android:id="@+id/daily_monitor_list"
                                android:layout_width="match_parent"
                                android:layout_height="match_parent"
                                android:nestedScrollingEnabled="false" />

                            <androidx.recyclerview.widget.RecyclerView
                                android:id="@+id/weekly_monitor_list"
                                android:layout_width="match_parent"
                                android:layout_height="match_parent"
                                android:layout_marginStart="@dimen/dp_8"
                                android:layout_marginEnd="@dimen/dp_8"
                                android:nestedScrollingEnabled="false" />
                        </LinearLayout>

                        <LinearLayout
                            android:id="@+id/ln_container_category_wise"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:layout_marginStart="@dimen/dp_16"
                            android:layout_marginEnd="@dimen/dp_16"
                            android:background="@drawable/avatar_borders"
                            android:visibility="visible">

                            <androidx.recyclerview.widget.RecyclerView
                                android:id="@+id/categoryListRv"
                                app:layout_constraintBottom_toBottomOf="parent"
                                app:layout_constraintEnd_toEndOf="parent"
                                app:layout_constraintStart_toStartOf="parent"
                                app:layout_constraintTop_toTopOf="parent"
                                android:layout_width="match_parent"
                                android:layout_height="match_parent" />
                        </LinearLayout>

                    </LinearLayout>
                </LinearLayout>
            </LinearLayout>
        </LinearLayout>
    </androidx.core.widget.NestedScrollView>

using this xml i want scroll vertically  till view at top ln_application_used i.e view whose it is ln_application_used should visibile it should scroll before ln_application_used . i am trying using this code
nested_scroll_view.setOnScrollChangeListener(NestedScrollView.OnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->{
      nested_scroll_view.smoothScrollTo(ln_application_used)
}

fun NestedScrollView.smoothScrollTo(view: View) {
        var distance = view.top
        var viewParent = view.parent
        //traverses 10 times
        for (i in 0..9) {
            if ((viewParent as View) === this) break
            distance += (viewParent as View).top
            viewParent = viewParent.getParent()
        }
        smoothScrollTo(0, distance)
    }

but unable to scroll before ln_application_used it always scrolling full view please help me what i am doing wrong or how to achieve this .


text:
Q: A question about time dilation So I have failed to understand something in time dilation. Motion is relative right? So how do you chose for which observer the time runs slower? For example, when an astronaut spends time in a rocket that moves close to the speed of light (relative to earth) when he comes back to earth, everyone aged more than he did. But why is that? Why wouldn't it be the other way, I mean relative to him earth moved at the same speed, that he did relative to earth...

A: This question looks like the Twin Paradox, but it isn't really the that. It can be answered without apparent contradiction in Minkowski Space ($M^4$): the proper time of a word line is a Lorentz invariant, and it is given by:
$$\Delta\tau = \int\frac 1 c \sqrt{\eta_{\mu\nu}dx^{\mu}dx^{\nu}}=\int\frac{dt}{\gamma(t)}$$
which you can evaluate in any frame and find that the traveling twin's is shorter.
Special relativity is self-consistent (no contradictions), and when evaluated in $M^4$, it has no apparent contradictions (aka: paradoxes).

A: motion is relative to a very very VERY small scale. In he 1960's hey tried to prove experiment for time dilation they synchronized two atomic clocks and put on stationary and one on a Boeing 747 and flew it around the world, there was a discrepancy in time albeit mere nanoseconds observed. Time is relative to speed/motion. It's not until you start approach sublight speed time dilation becomes more observed


text:
Q: how to set textview from left if imageview disappear in android <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <com.lociiapp.utils.RoundedImageView
        android:id="@+id/notificationuserimage"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_margin="20dp"
        android:layout_marginBottom="10dip" />

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/notificationuserimage"
        android:layout_toEndOf="@+id/notificationuserimage"
        android:layout_toRightOf="@+id/notificationuserimage"
        android:paddingBottom="10dp"
        android:text="Request for traveling"
        android:textColor="#282e36"
        android:textSize="23px"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/desc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/title"
        android:layout_alignStart="@+id/title"
        android:layout_below="@+id/title"
        android:text="asd has requested to travel with you"
        android:textColor="#282e36"
        android:textSize="23px" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="25dip"
        android:layout_alignBottom="@+id/notificationuserimage"
        android:layout_toEndOf="@+id/notificationuserimage"
        android:layout_toRightOf="@+id/notificationuserimage"
        android:src="@drawable/accepticon" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="25dip"
        android:layout_alignTop="@+id/imageView1"
        android:layout_toEndOf="@+id/imageView1"
        android:layout_toRightOf="@+id/imageView1"
        android:src="@drawable/rejecticon" />

    <TextView
        android:id="@+id/rejectedrequest"
        android:layout_width="wrap_content"
        android:layout_height="40dip"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/revresetime"
        android:singleLine="true"
        android:text="Rejected"
        android:visibility="invisible" />

    <ImageView
        android:id="@+id/runnimage"
        android:layout_width="wrap_content"
        android:layout_height="25dip"
        android:layout_alignTop="@+id/revresetime"
        android:layout_toLeftOf="@+id/rejectedrequest"
        android:layout_toStartOf="@+id/rejectedrequest"
        android:src="@drawable/drive"
        android:visibility="invisible" />

    <TextView
        android:id="@+id/revresetime"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/imageView2"
        android:layout_alignTop="@+id/imageView2"
        android:layout_toEndOf="@+id/imageView2"
        android:layout_toRightOf="@+id/imageView2"
        android:gravity="center_vertical"
        android:text="Just 5 Minute Ago"
        android:textColor="#8f939b"
        android:textSize="23px" />

</RelativeLayout>

This is code of Notification List item Xml :
public class Notifcationadapter extends BaseAdapter {
    private static ArrayList<Notify> values;
    Context context;
    String senderid;
    String imagepath;
    String member_id;
    String recevr_id;
    String jsonResp;

    // List<RowItem> rowItems;
    ViewHolder holder = null;
    LinearLayout linear2;
    DataBaseManager dbManager = new DataBaseManager(context);
    ArrayList<Notify> notifies;

    public Notifcationadapter(Context context, ArrayList<Notify> notifies) {
        super();
        this.context = context;
        this.notifies = notifies;

    }

    /* private view holder class */
    private class ViewHolder {

        TextView txtTitle;
        TextView txtDesc;
        ImageView yesimage;
        ImageView noimage;
        TextView revresetime;
        TextView rejected;
        ImageView runnimage;
        ImageView notificationuserimage;
        LinearLayout linear2;

    }

    public View getView(int position, View convertView, ViewGroup parent) {

        LayoutInflater mInflater = (LayoutInflater) context
                .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.notifcationlistitem,
                    parent, false);
            holder = new ViewHolder();
            // holder.linear2 = (LinearLayout) convertView
            // .findViewById(R.id.linear2);
            holder.txtDesc = (TextView) convertView.findViewById(R.id.desc);

            holder.txtTitle = (TextView) convertView.findViewById(R.id.title);
            holder.yesimage = (ImageView) convertView
                    .findViewById(R.id.imageView1);
            holder.noimage = (ImageView) convertView
                    .findViewById(R.id.imageView2);
            holder.revresetime = (TextView) convertView
                    .findViewById(R.id.revresetime);
            holder.rejected = (TextView) convertView
                    .findViewById(R.id.rejectedrequest);
            holder.notificationuserimage = (ImageView) convertView
                    .findViewById(R.id.notificationuserimage);

            holder.runnimage = (ImageView) convertView
                    .findViewById(R.id.runnimage);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        // holder.txtTitle.setText("Title");
        String statustype = notifies.get(position).getNotificationType();

        if (statustype.equals("1")) {
            holder.txtTitle.setText("Request For travelling");
            holder.txtDesc.setText(notifies.get(position)
                    .getNotificationDescrpiton());

            holder.revresetime.setText(Functions
                    .setLastSeenNotifcationTime(notifies.get(position)
                            .getNotificationDatetime()));

            senderid = notifies.get(position).getNotificationSenderID();
            imagepath = "http://api.lociiapp.com/TransientStorage/"

            + senderid + ".jpg";
            AQuery aq = new AQuery(context);

            aq.id(holder.notificationuserimage).image(imagepath);

            holder.yesimage.setVisibility(View.VISIBLE);
            holder.noimage.setVisibility(View.VISIBLE);

            holder.yesimage.setTag(convertView);
            holder.yesimage.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    View parentView = (View) arg0.getTag();
                    View view = parentView.findViewById(R.id.imageView1);
                    view.setVisibility(View.GONE);
                    view = parentView.findViewById(R.id.imageView2);
                    view.setVisibility(View.GONE);
                    // view = parentView.findViewById(R.id.linear2);
                    view.setVisibility(View.INVISIBLE);
                    view = parentView.findViewById(R.id.runnimage);
                    view.setVisibility(View.INVISIBLE);

                    new sendMesgTask().execute("Acepted");
                    Toast.makeText(context, "Yes", 10000).show();

                }
            });
            holder.noimage.setTag(convertView);
            holder.noimage.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    View parentView = (View) v.getTag();
                    View view = parentView.findViewById(R.id.imageView1);
                    view.setVisibility(View.GONE);
                    view = parentView.findViewById(R.id.imageView2);
                    view.setVisibility(View.GONE);
                    view = parentView.findViewById(R.id.rejectedrequest);
                    view.setVisibility(View.VISIBLE);
                    Toast.makeText(context, "NO", 10000).show();
                    // holder.linear2.setVisibility(View.INVISIBLE);

                    new sendMesgTask().execute("Rjected");
                    holder.yesimage.setVisibility(View.GONE);
                    holder.noimage.setVisibility(View.GONE);
                    holder.rejected.setVisibility(View.VISIBLE);
                }
            });

        }

        else if (statustype.equals("2")) {

            holder.txtDesc.setText(notifies.get(position)
                    .getNotificationDescrpiton());
            holder.txtTitle.setText("Post");
            holder.revresetime.setText(Functions
                    .setLastSeenNotifcationTime(notifies.get(position)
                            .getNotificationDatetime()));

            holder.runnimage.setVisibility(View.VISIBLE);

            senderid = notifies.get(position).getNotificationSenderID();
            imagepath = "http://api.lociiapp.com/TransientStorage/"

            + senderid + ".jpg";
            AQuery aq = new AQuery(context);
            aq.id(holder.notificationuserimage).image(imagepath);

            holder.yesimage.setVisibility(View.GONE);
            holder.noimage.setVisibility(View.GONE);
        }

        else {
            holder.txtDesc.setText(notifies.get(position)
                    .getNotificationDescrpiton());
            holder.txtTitle.setText("Accept/ Reject ");
            holder.txtDesc.setTextColor(Color.RED);
            holder.yesimage.setVisibility(View.GONE);
            holder.noimage.setVisibility(View.GONE);
            holder.revresetime.setText(Functions
                    .setLastSeenNotifcationTime(notifies.get(position)
                            .getNotificationDatetime()));
            senderid = notifies.get(position).getNotificationSenderID();
            imagepath = "http://api.lociiapp.com/TransientStorage/" + senderid
                    + ".jpg";
            AQuery aq = new AQuery(context);
            aq.id(holder.notificationuserimage).image(imagepath);

        }
        String notifcationsenderid = notifies.get(position)
                .getNotificationSenderID();
        String notisread = notifies.get(position).getNotificationStatus();
        if (notisread.equals("false")) {

            convertView.setBackgroundColor(Color.parseColor("#f5f6f1"));
        } else {
            convertView.setBackgroundColor(Color.parseColor("#ffffff"));
        }

        return convertView;
    }

    @Override
    public int getCount() {
        return notifies.size();
    }

    @Override
    public Object getItem(int position) {
        return notifies.get(position).getNotificationType();
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    }
}

In given Screen item which has a like and dislike Button  , date is coming right of image like dislike but when ImageView is hidden date and time goes to top even you can see In Post item that date and time are appearing on the top . I need suggestions how to achieve this.

A: Too many layouts which are not needed for your situation i think, i'd suggest to try and reduce that first.
For now, replace the
    android:layout_alignBottom="@+id/imageView2"
    android:layout_alignTop="@+id/imageView2"
    android:layout_toEndOf="@+id/imageView2"
    android:layout_toRightOf="@+id/imageView2"

in
 <TextView
        android:id="@+id/revresetime"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/imageView2"
        android:layout_alignTop="@+id/imageView2"
        android:layout_toEndOf="@+id/imageView2"
        android:layout_toRightOf="@+id/imageView2"
        android:gravity="center_vertical"
        android:text="Just 5 Minute Ago"
        android:textColor="#8f939b"
        android:textSize="23px" />

with
android:layout_toRightOf="@+id/notificationuserimage"
android:layout_above="@+id/thelayoutwithtext"Post"inyourimage"

A: <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#fff"
    android:orientation="horizontal" >
     <com.lociiapp.utils.RoundedImageView
        android:id="@+id/notificationuserimage"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_margin="20dp"
        android:layout_marginBottom="10dip" />

    <LinearLayout
            android:id="@+id/motherLayout"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"

        android:orientation="vertical" >

         <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/notificationuserimage"
        android:layout_toEndOf="@+id/notificationuserimage"
        android:layout_toRightOf="@+id/notificationuserimage"
        android:paddingBottom="10dp"
        android:text="Request for traveling"
        android:textColor="#282e36"
        android:textSize="23px"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/desc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/title"
        android:layout_alignStart="@+id/title"
        android:layout_below="@+id/title"
        android:text="asd has requested to travel with you"
        android:textColor="#282e36"
        android:textSize="23px" />

          <LinearLayout
            android:id="@+id/motherLayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:orientation="horizontal" >
        <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="25dip"
        android:layout_alignBottom="@+id/notificationuserimage"
        android:layout_toEndOf="@+id/notificationuserimage"
        android:layout_toRightOf="@+id/notificationuserimage"
        android:src="@drawable/accepticon" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="25dip"
        android:layout_alignTop="@+id/imageView1"
        android:layout_toEndOf="@+id/imageView1"
        android:layout_toRightOf="@+id/imageView1"
        android:src="@drawable/rejecticon" />

    <TextView
        android:id="@+id/rejectedrequest"
        android:layout_width="wrap_content"
        android:layout_height="40dip"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/revresetime"
        android:singleLine="true"
        android:text="Rejected"
        android:visibility="invisible" />

    <ImageView
        android:id="@+id/runnimage"
        android:layout_width="wrap_content"
        android:layout_height="25dip"
        android:layout_alignTop="@+id/revresetime"
        android:layout_toLeftOf="@+id/rejectedrequest"
        android:layout_toStartOf="@+id/rejectedrequest"
        android:src="@drawable/drive"
        android:visibility="invisible" />

    <TextView
        android:id="@+id/revresetime"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/imageView2"
        android:layout_alignTop="@+id/imageView2"
        android:layout_toEndOf="@+id/imageView2"
        android:layout_toRightOf="@+id/imageView2"
        android:gravity="center_vertical"
        android:text="Just 5 Minute Ago"
        android:textColor="#8f939b"
        android:textSize="23px" />

 </LinearLayout>

 </LinearLayout>
</LinearLayout>


text:
Q: Unqualified Class Name Collides with New .NET Class in System Namespace I have (a lot) of legacy code that references one of my static classes, called AppContext.  Sadly, references to this class have all been resolved in this legacy code by a namespace using declaration throughout.  For the sake of argument, let's say the namespace is "MyNamespace" (it isn't, but it's just as bad)
Therefore, I have many, many modules that start off looking like this:
using System;
using MyNamespace;

My problem now is that Microsoft, in their .NET Framework 4.6, has introduced a new System.AppContext class.  Obviously, all of my code uses System.
Now whenever I get to a line of code that looks something like this:
if (AppContext.MyProperty == "some value")

... I will get an error telling me that MyProperty is not a recognized member of AppContext.
Now as my users roll out Windows updates containing .NET 4.6 (or .NET 4.6.1) I find my distributed code is breaking all over the place.
I know that my brute force solution to this is to go to every place where I reference my class and apply an unambiguous namespace.  This is a sensible thing to do and I will do it going forward.  My problem is that I have a big installed base and fixing this everywhere for everyone will take a lot of time and a lot of work (especially considering regression testing/moving to production, etc.)
Is there any way to resolve the name conflict, short of adding an unambiguous namespace to each reference of my class?
I'd really like to know if there is a quick/short term solution that I can use to keep my users from breaking my system with Windows updates until I can get a proper solution rolled out everywhere.

A: Add using AppContext = MyNamespace.AppContext to the top of every file.


text:
Q: Eclipse CDT Cygwin error i have a problem with eclipse CDT and cygwin, when i try to build a simple hello world project i have this error:
 make all
Building file: ../src/test.cpp
Invoking: Cygwin C++ Compiler
g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/test.d" -MT"src/test.d" -o "src/test.o" "../src/test.cpp"
C:\shell.w32-ix86\make.exe: *** [src/test.o] Error 1

14:37:48 Build Finished (took 178ms)

Cygwin is in the path and commands like 'g++' or 'make' works fine.
Thank in advance for your help.

A: Follow this tutorial to properly set up cygwin with Eclipse CDI. After completing all the steps, add one more path dependency on: Project Properties -> C/C++ General -> Paths and Symbols -> Includes GNU C++ with the value to : ${CYGWIN_HOME}/usr/i686-pc-cygwin/sys-root/usr/bin. This solved all the issues arising on Eclipse CDT with CYGWIN.


text:
Q: Multiple data frames - Wide to long using pandas I have two data frames like as shown below
df1 = pd.DataFrame({'person_id': [11, 21, 31, 41, 51],
                        'date_1': ['12/30/1961', '05/29/1967', '02/03/1957', '7/27/1959', '01/13/1971'],
                        'date_2': ['07/23/2017','05/29/2017','02/03/2015',np.nan,np.nan]})

df2 = pd.DataFrame({'person_id': [11,11,11,21,31],
                    'visit_id':['A1','A2','A3','B1','B2'],
                    'date_start': ['01/01/2012', '02/25/2017', '02/03/2015', '07/27/2016', '01/13/2011'],
                    'date_end': ['05/03/2012','05/29/2017','03/03/2015','08/15/2016','02/13/2011']})

I tried the below. I want only the date columns in a long format
df = pd.merge(df1, df2, on='person_id',how='outer')
df = pd.wide_to_long(df, stubnames=['date'], i='person_id', j='grp').sort_index(level=0)
df = df.reset_index(level=1, drop=True).reset_index()
df

But this gives an empty data frame.
I would like to get all the dates of each subject as shown below (sample output for 2 subjects)

A: This is just melt and concat:
(pd.concat([df1.melt('person_id', value_name='dates'),
            df2.melt('person_id',value_vars=['date_start','date_end'], value_name='dates')
          ])
   .drop('variable', axis=1)
   .sort_values('person_id')
)


text:
Q: Python implicit nested for loop I want to iterate over each line read from a file, split them, and then convert each splitted element into floats to create a 2d list of floats.
I have the following code so far:
f = open('coordinates.dat')
contents = map(str.strip, f.readlines())
f.close()

For each element (line) in contents, I want to do line.split(), and then for each element in line.split(), convert them to floats. Is it possible to do this with implicit loops? The output would look something like this:
[[float1, float2, float3], [float4, float5, float6], ... , [floatX, floatY, floatZ]]

(There are three numbers on each line of the file)
I tried the following:
a = [ line for line in contents for float(i) in line.split()]

which gives a sytax error: SyntaxError: can't assign to function call

A: Rearranging your attempt yields the correct code:
a = [[float(i) for i in line.split()] for line in contents]

A: You can use a nested list comprehension:
a = [[float(i) for i in line.split()] for line in contents]

A: If you wanted to use map:
with open("coordinates.dat") as f:
    out = [list(map(float, sub)) for sub in map(str.split, f)]

Or:
with open("coordinates.dat") as f:
    out = [list(map(float, sub.split())) for sub in f]
    print(out)

Or considering you have numerical data numpy would be useful:
import numpy as np

arr = np.loadtxt("coordinates.dat")

You also don't need to call readlines or str.strip to cast to float.


text:
Q: PHP __LINE__ equivalent for twig There is a way to get PHP __LINE__ equivalent for Twig?
It's almost impossible to search __LINE__ on Google as exact word...
The purpose is purely for debugging a long twig file containing nested twig code inside a complex Js code, to console.log it.
The version of twig I'm using is 2.12.5.
Thanks

A: First things first:
As seen in the PHP documentation the (magic) constant will return the current line number of the file.The "problem" here is that twig converts templates to PHP in order to render them.
This means if you were actually were to be able to use __LINE__ inside a template, it would report back the line number from either a temporary PHP file or a cached PHP file, wether you have caching enabled or not.
TLDR: Using __LINE__ inside a template is going to report back "false"/useless information.

However, you can easily extend twig and even introduce new tags which you then can use inside templates. These customs tags allow you to modify/alter the compilation of the template's PHP file.
The interesting part here is that the "compiler" is able to provide your custom tag on which specific line the tag was called.
We can even create a custom tag, register it with twig and let the tag report back the line number in the parsed template.
Step 1 - Create a TokenParser
The TokenParser is responsible for parsing the template and allows you to choose a name for your tag. The code below will be responsible to create a simple, empty tag named line
<?php
    namespace MyProject\Base\Twig\TokenParser;

    use \MyProject\Base\Twig\Node\Line as LineNode;

    class Line extends \Twig_TokenParser {

        public function parse(\Twig_Token $token)
        {
            $this->parser->getStream()->expect(\Twig_Token::BLOCK_END_TYPE);
            return new LineNode(new \Twig_Node(), $token->getLine(), $this->getTag());
        }

        public function getTag()
        {
            return 'line';
        }
}

Step 2 - Create a Node
The Node is responsible for converting the template code to actual PHP code
<?php
    namespace MyProject\Base\Twig\Node;

    class Line extends \Twig_Node {
        public function __construct(\Twig_NodeInterface $body, $lineno, $tag = null) {
            parent::__construct(['body' => $body,], array(), $lineno, $tag);
        }

        public function compile(\Twig_Compiler $compiler) {
            $compiler->write('echo '.$this->getLine().';')
                     ->write(PHP_EOL);
        }
    }

Step 3 - Register the tag with twig
<?php
    namespace MyProject\Base\Twig;

    class MyProjectTwigExtension extends Twig_Extension {
        public function getTokenParsers() {
            return [
                new \CMS4U\Base\Twig\TokenParser\Line(),
            ];
        }

        public function getName() {
            return 'MyProjectTwigExtension';
        }
    }

<?php
    $twig->addExtension(new \MyProject\Base\Twig\MyProjectTwigExtension());

If everything is good, you can now use the custom tag {% line %} wherever you like in any template
Foo
Bar
FooBar
Current line number is {% line %} {# 4 #}


text:
Q: converting MySQL query to Codeigniter syntax I have some problem converting a MYSQL query to CI syntax.
This my MySQL syntax:
select a.pbj_name as 'NAMA PERUSAHAAN', count(a.id_pbj) as 'JUMLAH PAKET', group_concat(c.paket_kode) as 'PILIHAN PAKET'
from jed_pbj a
left join jed_paket_pbj b
       on a.id_pbj=b.id_pbj
left join jed_paket c
       on b.id_paket=c.id_paket
group by a.id_pbj

A: Check out this Active Record class in Codeigniter,
$this->db->select("a.pbj_name as 'NAMA PERUSAHAAN', count(a.id_pbj) as 'JUMLAH PAKET', group_concat(c.paket_kode) as 'PILIHAN PAKET'");
$this->db->from('jed_pbj a');
$this->db->join('jed_paket_pbj b', 'a.id_pbj=b.id_pbj', 'left');
$this->db->join('jed_paket c', 'b.id_paket=c.id_paket', 'left');
$this->db->group_by("a.id_pbj");
$this->db->get();


text:
Q: DashDB sync with Cloudant doesn't work I had a setup to sync data from Cloudant database into DashDB. Initially the setup and processes were working well. I keep the sync processes running after the setup. A few days later, I inserted a record into my Cloudant database, then I were expecting it being populated at DashDB automatically. But that didn't happen.
When I checked the sync process after above issue, I want to turn my sync process to 'Pause' and then 'Resume' it, a popup window shows me "Initialization in Progress" which blocks me to do anything about it.
Now, my sync processes are hanging in there, and data not being synced at all.
Any suggestions for solving the issue?
Best Regards

A: Cloudant does a continous transformation to dashdb if warehouse is created, may be the transformation hit an error, you can check if there is an error in the warehouser docs
Take a look inside the document inside the _warehouser database, and look for the warehouser_error_message to see if there is issue with transformation occurred.


text:
Q: "I capitalised this letter" How do you say, "I capitalised this letter"?
How would a native English speaker phrase the following sentences?

*

*i wrote it with a lower case letter

*i wrote it with a capital letter

*i have replaced upper case letter on lower case letter.

By "letter", I do not mean a letter (e.g. mail), I mean the characters used to make words.

A: Depending on exactly how something is actually written, I would lean toward:

*

*I wrote it in lowercase.  ("thing")

*I wrote it in uppercase. -or- I wrote it in all-caps.  ("THING")

*I capitalized it.  (writing "Thing", or converting "thing" -> "Thing")

*I lowercased it. -or- I un-capitalized it.  (converting "Thing" or "THING" -> "thing")

*I uppercased it.  (converting "thing" -> "THING")

A: 1) I wrote it with a lowercase letter.
2) I wrote it with a capital letter.
3) I have replaced an/the uppercase letter with a/the lowercase letter.

A: 1) I wrote it with a lowercase letter.
2) I wrote it with a capital letter.
3) I replaced the uppercase letter with a lowercase letter.


text:
Q: Does primary index in mysql table automatically have a value when new row is added? So, assuming I have a table, with 20 columns, and I want to insert data to them, and the first column is just a primary index, which will automatically have a numerical value if I don't assign one to it. Primary index has auto increment on.
So my question is, do I always have to do it like this (which is pretty annoying and slow)
INSERT INTO table (col1,col2,col3,col4,col5,col6) VALUES (col1value,col2value,col3value,col4,value,col5value,col6value)

or, could I just specify the values (assuming that I'm filling every column except the primary index) like this
INSERT INTO table VALUES (col1values,col2values,col3values,col4values,col5values,col6values)

or will it break the table?

A: No, you can't use your second solution, unless you provide as many values as field count. You can still provide primary key value with NULL. MySQL will then replace it by an auto-incremented value (assuming your column is PRIMARY KEY + AUTO_INCREMENT).
Nevertheless, the first solution is perfectly fine.

A: tldr; You need to define the columns you are inserting into.
Mysql assumes that when you don't put in the column names like below
INSERT INTO table (column_name1, column_name2, column_name3)

that you are going to define all the columns in your value definition later. Without defining the column names, it wouldn't know which row to skip for the primary key.
An example of this would be if you had the primary key as column_name2 in the above example.

A: The first one is correct.
In the second one you can specify the primary key attribute as null or using INSERT INTO table VALUES('',col2values,col3values,col4values,col5values,col6values) assuming that the first field is primary key.


text:
Q: C# byte array conversion to VB.NET As per my last question I'm borrowing some code from the Opus project to integrate into VB.NET software.
Consider
byte[] buff = _encoder.Encode(segment, segment.Length, out len);

which I've translated to:
Dim buff(wavEnc.Encode(segment, segment.Length, len)) As Byte

It is throwing a:

Value of type '1-dimensional array of Byte' cannot be converted to 'Integer' error...

How can I fix this problem?

A: Try this:
Dim buff = wavEnc.Encode(segment, segment.Length, len)

Of course you can do a direct translation of the c#:
Dim buff As Byte() = wavEnc.Encode(segment, segment.Length, len)

No need for a type at all - let the compiler figure it out.

A: _encoder.Encode() is the right-hand side of an assignment.  The left-hand side is a byte array.
The way you are using it in your VB sample is as an array dimensioner: an Integer.


text:
Q: JQuery mobile hiding a dynamically generated button I have written some code that generates a set of buttons when the page loads using a loop, each iteration of the loop increments an ID value to assign to the new button.
I originally wrote it using standard JQuery but because of the way JQuery Mobile works, I am having to rewrite it.
<a id = "<?php echo $button_id_add_to_cookbook ?>"onclick="update_button('<?php echo $button_id_add_to_cookbook ?>')" data-role="button">Send

the function update button is below, at least the test trial version.
function update_button(id)
{
$(id).click(function(){
    $(id).toggle();
});
}

I'm having a hard time finding 2 accounts that say how to do this the same way so don't think this is correct.
The goal it to dynamically generate a set of buttons and when a button is clicked, it will call some code to alter a mysql database and on success hide the button that called the function. For this example I just want to hide the button when t was clicked.
Can anyone help me with the correct way to do this, the page should not refresh, just update the button element.

A: I think it was a spacing issue causing problems, for dynamic id content this seemed to work as a replacement function.
function update_button(id)
{
$('#' + id).closest('.ui-btn').hide();
}

if this will lead to any issues in the long term please let me know!


text:
Q: The performance in relation to the interval I have made an intermittent bar, the problem is that I am afraid, that something so insignificant requires so much, with this I mean that in 1 minute more than 120 intervals were made, is there a more efficient way to do this?

window.addEventListener("DOMContentLoaded", () => {
var e = document.getElementById("bar"), flag = true;
setInterval(()=>{
if(flag) {
e.style.display = "none";
flag = !flag;
}
else {
e.style.display = "block";
flag = !flag;
}
},400);
});
#barText {
font-family: monospace; color: purple; font-size: 25px;
font-weight: 600;
position: absolute;
}
#bar {
width: 2.2px;
height: 29px;
background-color: purple;
margin: 0 0 0 22%;
}

Overflow

A: You could just use a CSS animation and not use JS at all.

#barText {
    font-family: monospace; color: purple; font-size: 25px;
    font-weight: 600;
    position: absolute;
}
#bar {
    width: 2.2px;
    height: 29px;
    background-color: purple;
    margin: 0 0 0 22%;
    animation: blink-animation .6s steps(2, start) infinite;
    -webkit-animation: blink-animation .6s steps(2, start) infinite;
}
@keyframes blink-animation {
  to {
    visibility: hidden;
  }
}
@-webkit-keyframes blink-animation {
  to {
    visibility: hidden;
  }
}

Overflow


text:
Q: Django: add ManyToMany between two apps I cannot modify I have two apps:

*

*trains provides the Train model, and

*railroad the Rail model.

Since I totally love trains, I want to ensure that Train can only drive over the compatible Rail, therefore I implement a TrainRailCompatibility. However, I cannot modify neither Train nor Rail model to add a field ManyToMany(through=TrainRailCompatibility) (I am not a maintainer of those apps). I would still like to be able to do in my project something like my_train.compatible_rails.all() or filter(foo__trains__compatible_rails__in=[...]).
Is there a way / what would be the best way to achieve it?

A: You couls simply add this class to your desired App
class TrailRailCompatibility(models.Model):
    train = models.ForeignKey('app1.Train')
    rail = models.ForeignKey('app2.Rail')

and now the TrailRailCompatibility - class will be available on both of the referenced models via
from app1.models import Train
from app2.models import Rail

Trail.trailrailcompatibility_set.all()
Rail.trailrailcompatibility_set.all()

A: Looks like it is management issue because you can't do something in a proper way. Workaround is ugly and slower because it uses subquery instead of join.
class Compatibility(models.Model):
    train = models.ForeignKey('trains.Train', related_name='compatibilities')
    rail = models.ForeignKey('railroad.Rail', related_name='compatibilities')

    class Meta:
        unique_together = ('train', 'rail')

def get_trains(rails):
    return Train.objects.filter(compatibilities__rail__in=rails)

def get_rails(train):
    return Rail.objects.filter(compatibilities__train_id=train.id)

A: I don't think this can be done without adding the ManyToMany fields on the Train and Rail models. You could create a regular TrainRailCompatibility model with foreign keys to Train and Rail and set unique_together = ('train', 'rail') and then add entries manually. You just won't be able to access them from the Train and Rail models.


text:
Q: Handling Errors with RESTSerializer Using ember and ember-data 2.6 versions, I'm trying to get error handling working but running into issues. I'm using the RESTSerializer and I'm sending the following payload to my server:
{
    "brand": {
        "name": null,
        "description": null,
    }
}]

Since name cannot be null, this is what I'm sending back as my response:
{
    "errors": [{
        "code": null,
        "detail": "may not be null",
        "status": null,
        "title": null,
        "source": {
            "pointer": "brand/name",
            "parameter": null
        }
    }]
}

In my route, I am doing the following in the save promise on failure:
console.log(savedBrand.get('isValid')); // logs false
console.log(savedBrand.get('errors').toArray()); // logs [ ]

There doesn't seem to be a lot of detailed documentation on how this all works so I'm using this article as a starting point. I'm unsure as to why toArray() returns an empty array instead of my error that I'm returning in the JSON.

A: even though I'm not passing in the data per the json-api, the pointer still had to be set as if I were:
{
    "errors": [{
        "code": null,
        "detail": "may not be null",
        "status": null,
        "title": null,
        "source": {
            "pointer": "/data/attributes/name",
            "parameter": null
        }
    }]
}


text:
Q: ¿Como insertar una variable dentro de un resultado en mongoose? Mi duda es esa. Por ejemplo, tengo dos schema, libros y categorías. Entonces desde la administración me gustaría saber cuantos libros tiene cada categoría.
return Category.find({}, async function( err, data ){

    const result = [];

    await data.map(d => {
        d.booktotal = 10;
        console.log( d );
    })

    /**
     *
     */

    // return res.status(200).json({
    //  categories: result
    // });
});

Como ven obtengo las categorías e intento iterar cada categoría y agregar la variable totalbook con un valor "10" pero si le doy console.log a la variable d entonces este solo muestra el nombre de la categoría mas no muestra la variable booktotal. ¿Como inserto en un resultado una variable personalizada que contenga un valor estático o un resultado de otra consulta en mongoose?

A: Primero buscas en la tabla Category.
const categories = await Category.find({}).lean();
El lean sirve para que te devuelva solo el objecto de las categorías, si no haces el lean te devuelve un objecto Mongoose.
Una vez tienes las categorías ya puedes añadir el valor que quieras.
Debería quedarte así el código:
const categories = await Category.find({}).lean();
const result = categories.map(category => {
    category.booktotal = 10;
    return category;
});
return res.status(200).json(result);


text:
Q: Convert hours and minutes to minutes using PHP I am using Google Maps API to get the duration in between two points. That API gives the duration in hours and mins. So I want it to convert only to minutes using PHP code. Are there any solutions?
Ex: 2 hours 10 mins (Should give 130 mins as the output)

A: Try something like this
    // Transform hours like "1:45" into the total number of minutes, "105".
function hoursToMinutes($hours)
{
    $minutes = 0;
    if (strpos($hours, ':') !== false)
    {
        // Split hours and minutes.
        list($hours, $minutes) = explode(':', $hours);
    }
    return $hours * 60 + $minutes;
}

// Transform minutes like "105" into hours like "1:45".
function minutesToHours($minutes)
{
    $hours = (int)($minutes / 60);
    $minutes -= $hours * 60;
    return sprintf("%d:%02.0f", $hours, $minutes);
}

Src : laserlight -> http://board.phpbuilder.com/showthread.php?10342598-quot-Convert-quot-hours-minutes-quot-to-quot-total_minutes-quot-and-back-quot

A: Thanks for the help guys, I found another solution...This works for me
$duration = "What Ever the time (2 hours 10 mins)"

$split = preg_split("/[^\w]*([\s]+[^\w]*|$)/", $duration, -1, PREG_SPLIT_NO_EMPTY);

    if ($split[0] >= 1 && $split[0] < 60 && $split[1] == 'min'){
        $duration = $split[0];
    }
    elseif ($split[0] >= 1 && $split[0] < 60 && $split[1] == 'mins'){
        $duration = $split[0];
    }
    else{
        $durationHours = $split[0]*60;
        $durationMin = $split[2];

        $duration = $durationHours + $durationMin;
        echo $duration;
    }


text:
Q: mapper [user_agent.version] cannot be changed from type [text] to [keyword]" How to disable this mapper? I'm newbie to elasticsearch. What I want to do is to gather logs with filebeat from kubernetes cluster and send them to elasticsearch. My filebeat config file looks like this:
filebeat.yml: |
  filebeat.inputs:
  - type: container
    paths:
      - /var/log/containers/*.log
    processors:
    - add_kubernetes_metadata:
        host: ${NODE_NAME}
        matchers:
        - logs_path:
            logs_path: "/var/log/containers/"

I am outputting to elasticsearch,but I cant show the config. I don't have access to elasticsearch instance I only have access to kibana where I can add index pattern to match logs from elasticsearch.
I see logs from file beat where it's written that:

"Failed to parse mapping [_doc]: mapper [user_agent.version] cannot be
changed from type [text] to
[keyword]","caused_by":{"type":"illegal_argument_exception","reason":"mapper
[user_agent.version] cannot be changed from type [text] to
[keyword]"}}

What I found in docs is this: https://www.elastic.co/guide/en/elasticsearch/reference/7.17/user-agent-processor.html
, but I can't find how to disable this processor or even better how to omit this one field which is causing the error.
I would highly appreciate any help.


text:
Q: Syntax error in Postgres using if statement Using the DBeaver tool to run PostgreSQL, and getting error SQL Error [42601]: ERROR: syntax error at or near "if"
query -
DO $$
if (1<2) then select 1
end if;
end $$;

A: https://www.postgresql.org/docs/current/errcodes-appendix.html
=>> 42601  syntax_error means syntax error.
Google search "postgresql do block" will link you to https://www.postgresql.org/docs/current/sql-do.html
By imitate manual example. You can rewrite the following way.
DO $$
begin
if (1<2) then raise info '1';
end if;
end $$;


text: Q: exporting query result to multitab excel workbook I want to export 4 query result set to a single multi-tab workbook in excel.  My environment is 64-bit sql server 2008. None of the examples I have seen work.


text:
Q: First time installation of Fedora from bootable USB fails to boot After the bootloader, the last thing I see before systemd fills my screen, and then it goes blank, is the following:

I am trying to install Fedora 37 to replace my current Windows 10. Mo matter if I choose UEFI or the one without it, the top message is always as in the picture:
[timestamp] dracut-pre-udev[618]: sh: line 1: /sbin/sysctl: no such file or directory`

The screenshot below is not of my machine, as my machine presents GRUB, but has the same choices (except for minor things like versions).

The messages about disk checks only come up if I choose "test this media & start fedora workstation KDE live 37".
In either case, once systemd has finished starting services, the screen goes blank, and doesn't proceed. What can I do to bring up the actual install screen?

A: The /sbin/sysctl: no such file or directory error is probably a harmless minor bug.
Note that "Fedora workstation KDE live 37" is not just an installer: it is a "live" system, i.e. it will allow you to try Fedora with KDE desktop environment before you actually install it, and then run the installer from the KDE desktop.
Also, note that there is a third item in the boot menu, labeled Troubleshooting. Have you tried it?
Your hardware configuration, particularly the make and model of your GPU, would probably be important to know in this case. Please add this information to your question.

A: Use the third option. I literally solved it while I was reading the answer above. Use the troubleshooting option, then choose start fedora live in basic graphic mode and it will start. Some problem with Nvidia graphics I suppose


text:
Q: Summation of a constant using sigma notation Apologies if this is a silly question, but is it possible to prove that $$\sum_{n=1}^{N}c=N\cdot c$$ or does this simply follow from the definition of sigma notation?
I am fairly sure it's the latter, but for some reason I've managed to get myself thrown by the absence of a summation index (intuitively of course it makes sense that summing a constant $N$-times should equal $N\cdot c$).

A: It is possible to prove it. If you define $\sum$ notation recursively then it's something you can prove by induction. Specifically, given a sequence $a_1, a_2, \dots$ of numbers, you can define $\displaystyle\sum_{i=1}^n a_i$ recursively by:
$$\displaystyle\sum_{i=1}^1 a_i = a_1 \quad \text{and} \quad \displaystyle\sum_{i=1}^{n+1} a_i = \left( \sum_{i=1}^n a_i \right) + a_{n+1} \text{ for all } n \in \mathbb{N}$$
An inductive proof that $\displaystyle\sum_{i=1}^n c = nc$ then proceeds as follows:

*

*(Base case) $\displaystyle\sum_{i=1}^1 c = c$;

*(Induction step) Fix $n$ and suppose $\displaystyle\sum_{i=1}^n c = nc$. Then
$$\sum_{i=1}^{n+1} c = \left( \sum_{i=1}^n c \right) + c = nc + c = (n+1)c$$

So we're done. Here, the sequence was just the constant sequence $c,c,c,\dots$.

A: You can write it as $c\sum_{i=1}^N 1$ and then say that the sum of $N$ $1's$ is $N$, but that doesn't actually shed much light on the matter.
The thing to remember, ultimately, is that $\sum$ isn't some abstruse function. It's just a more compact way of writing addition. Writing $\sum_{x=1}^N f(x)$ means writing $f(1)+f(2)+\cdots f(N)$, and anything that you can do with addition you can do with it, because it is exactly addition.

A: The formal definition of that sigma notation is recursive:
$$\sum_{j=1}^1a_j=a_1,$$
$$\sum_{j=1}^{n+1}a_j=\sum_{j=1}^na_j+a_{n+1}.$$
Since the formal definition is recursive, anything you prove about it is going to involve induction at some point. Proving $\sum_{j=1}^Nc=Nc$ by induction is not hard.


text:
Q: get data from object in firestore using AngulaFire I have a nested object in a firestore collection and I want to get data from this object.
this is how i created my function, which mail_campaign is the collection and drops is a an object that contains it's own data.
const drops = collection(this.firestoreDB, 'mail_campaign/drops');
return from(collectionData(drops, { idField: 'id' }) as Observable<Drop[]>);

I got an error saying :
ERROR Error: Uncaught (in promise): FirebaseError: [code=invalid-argument]: Invalid collection reference. Collection references must have an odd number of segments, but mail_campaign/drops has 2.
FirebaseError: Invalid collection reference. Collection references must have an odd number of segments, but mail_campaign/drops has 2.


text:
Q: Javascript array modify value I have an array as following.
var vehicle = new Array();
vehicle.push( { "name": "honda", "value": "civic" } );
vehicle.push( { "name": "toyota", "value": "camry" } );

How can I modify this array to change civic to accord?

A: Try this
vehicle[0].value = 'accord';

And for the array entirely
vehicle.map(function (vehicle) {
   if (vehicle.value === 'civic') {
       vehicle.value = 'accord';
   }
});

A: If you don't know the position of the object in the array, then you can simply loop through the array. When you find the value, replace it and exit the loop. If there could be more than one value of "civic" in the array, then leave out the break; statement and the loop will change all instances of "civic" to "accord".
for(var a = 0, len = vehicle.length; a < len; a++) {
    if(vehicle[a].value === "civic") {
        vehicle[a].value = "accord";
        break;
    }
}

A: Try vehicle[0].value = "accord"

A: Just do this:
vehicle[0].value = 'accord';

A: for (var i = 0, len = vehicle.length; i < len; i++) {
    if (vehicle[i].value === "civic") {
        vehicle[i].value = "accord";
    }
}

A: see JS Fiddle
vehicle[0]['value']='accord';


text:
Q: Joomla 3 - use category title as Browser Page Title with the menu item title I'm using Joomla 3.4.8, and I have all of my pages linked to menu items. I can't figure out how to get the menu item title to show in the <title> tag of the page, rather than only the article title.
For eg. My Menu item title is 'test', when I press the button it shows test but in that menu item there are many articles. when i click on the article in the test page. It only shows the article name and not the menu item. What i want is that it shows the article name + the menu item.
I know that I can change each 'Browser Page Title' setting for each menu item and individually override the menu item title. But I'm worried this will create confusion in the future when trying to update page titles.
something like this source but with the menu item.
<?php $document=& JFactory::getDocument();
$document->setTitle( $this->item->title ); ?>

A: You can retrieve current active menu item and use the parameters that you need with JApplication with this code:
$active_menu = JFactory::getApplication()->getMenu()->getActive();

Then set the title as you need:
JFactory::getDocument()->setTitle($active_menu->title." - ".$this->item->title);


text:
Q: How to get maximum value from two tables where only IDs overlapping? I have two different tables with headers (shortened)
table a
supplier_id, company_name

table b
product_id, product_name, supplier_id, unit_price

I have to produce a table with only maximum unit price products of each company. The header of the resulting table is: company_name, product_name, unit_ price.
My code is actually selecting each product.
SELECT suppliers.company_name AS company, products.product_name AS product, MAX(products.unit_price) AS price FROM suppliers
JOIN products
    ON products.supplier_id = suppliers.supplier_id
GROUP BY company_name, product_name, unit_price
ORDER BY price DESC;

Company     Product     Max unit price
company a   product x      value 1
company b   product y      value 2

A: demo:db<>fiddle
It seems that you are searching for DISTINCT ON. This gives out the first record of an ordered group. In your case the groups are the company_name and the order within them is the price (in descending order to get the highest value first):
SELECT DISTINCT ON (suppliers.company_name)
    suppliers.company_name AS company,
    products.product_name AS product,
    products.unit_price AS price
FROM suppliers
JOIN products
    ON products.supplier_id = suppliers.supplier_id
ORDER BY suppliers.company_name, products.unit_price DESC;

A: You can use distinct on, but you don't need group by:
SELECT DISTINCT ON (s.company_name) s.company_name AS company, p.product_name AS product, p.unit_price
FROM suppliers s JOIN
     products p
     ON p.supplier_id = s.supplier_id
ORDER BY s.company_name, unit_price DESC;

You can do this with aggregation, but you need a bit of a trick to get the product.  Here is a way using arrays:
SELECT s.company_name AS company,
       (ARRAY_AGG(p.product_name ORDER BY p.unit_price DESC))[1] AS product,
      MAX(p.unit_price) as max_price
FROM suppliers s JOIN
     products p
     ON p.supplier_id = s.supplier_id
GROUP BY s.company_name;

I would expect the DISTINCT ON (without GROUP BY) to have the better performance.


text:
Q: AJAX Submit with no redirect I'm trying to have some data send to submit.php. The data does submit but it redirects me to the submit.php page. How can I submit this with out changing page?
JS
function submitq() {
if (window.XMLHttpRequest) {
  xmlhttp=new XMLHttpRequest();
  }
else
  {
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("submitdata").value=xmlhttp.responseText;
    }
  }
xmlhttp.open("POST",submit.php,true);
xmlhttp.send();
}

A: Just figured it out.
The form can't have an action of a method because that will redirect it after it is posted.


text:
Q: Magento 1 - how to set a single product for free shipping? I want to give the specific product for free shipping and I tried "Attribute" rules and it doesn't work.

A: You need use next article /how-to-set-up-free-shipping-rules-in-magento-2
don't forget about global configuration

A: You can add yes/no variable for free shipping and set yes for Price Rule Conditions then create rules with that attribute. Please check below images.
[1]: https://i.stack.imgur.com/tadFH.png
[2]: https://i.stack.imgur.com/rl2Lc.png


text:
Q: Wondering how to get my ENV variables into supervisor In my ~/.bashrc I set the below variables...they work fine in my python script when I launch it but when I use supervisor it can't fine
FAILURE
[supervisor]

environment=ORACLE_HOME="%(ORACLE_HOME)s",LD_LIBRARY_PATH="%(LD_LIBRARY_PATH)s"

SUCCESS
[supervisor]

environment=ORACLE_HOME="/path/to/it",LD_LIBRARY_PATH="/path/to/it"

Basically I don't want to go back into the config file every time I want to update the oracle instant client.
Thanks

A: Try this executing these commands and then start supervisor
>> sudo export ORACLE_HOME="/path/to/it"
>> sudo export LD_LIBRARY_PATH="/path/to/it"
>> . ~/.bashrc


text:
Q: When using Queries.Add: How do I reference to a custom function inside the formula argument of Queries.Add? In General: I'm trying to create a sub that runs multiple queries. All of these queries are exactly similar except for one word: Column1. Therefore I'd like to use a loop and replace Column1 with a function GetColumnAct(x). The function should return Column1 when running the loop the first time, Column2 when running it the second time and so on...
Here's the code:
Sub ColumnLoop()

For x = 1 To 5

ActiveWorkbook.Queries.Add Name:=GetColumnAct(x), Formula:= _
        "let" & Chr(13) & "" & Chr(10) & "    Quelle = Excel.Workbook(File.Contents(""C:\Users\felix\OneDrive\Dokumente\GIZ Consultancy\Technisch\Teststruktur\FV_MA_Abfragen\Aktuelle Abfrage NEU\MA_Daten_AktuelleAbfrageNEU.xlsx""), null, true)," & Chr(13) & "" & Chr(10) & "    Tabelle1_Sheet = Quelle{[Item=""Tabelle1"",Kind=""Sheet""]}[Data]," & Chr(13) & "" & Chr(10) & "    #""Höher gestufte Header"" = Table.PromoteHeaders(Tabelle1_Sheet, [PromoteAllScalars=true]" & _
        ")," & Chr(13) & "" & Chr(10) & "    #""Spalte nach Trennzeichen teilen"" = Table.SplitColumn(#""Höher gestufte Header"", ""Mitarbeiter (eMail) TN-Projekt"", Splitter.SplitTextByDelimiter("","", QuoteStyle.Csv), {""MA.1"", ""MA.2"", ""MA.3""})," & Chr(13) & "" & Chr(10) & "    #""Zusammengeführte Abfragen"" = Table.NestedJoin(#""Spalte nach Trennzeichen teilen"", {""TN Projekt""}, Tabelle1, {""TN Projekt""}, ""Tabelle1"", JoinKind.FullOuter)," & Chr(13) & "" & Chr(10) & "    #""Erweiterte Tabelle1"" = Table.ExpandTableColumn(#""Zusammengeführte Abfragen"", ""Tabelle1"", {""TN Projekt"", ""Fachverbunds Nr."", ""TN Bezeichnung"", ""Fachverbundsbezeichnung"", ""MA.1"", ""MA.2"", ""MA.3""}, {""Tabelle1.TN Projekt"", ""Tabelle1.Fachverbunds Nr."", ""Tabelle1.TN Bezeichnung"", ""Tabelle1.Fachverbundsbezeichnung"", ""Tabelle1.MA.1"", ""Tabelle1.MA.2"", ""Tabelle1.MA.3""})," & Chr(13) & "" & Chr(10) & "    #""Entfernte Spalten"" = Table.RemoveColumns(#""Erweiterte Tabelle1"",{""Tabelle1.TN Projekt"", ""Tabelle1.Fachverbunds Nr."", ""Tabelle1.TN Bezeichnung"", ""Tabelle1.Fachverbundsbezeichnung""})," & Chr(13) & "" & Chr(10) & "    #""Tiefer gestufte Header"" = Table.Demote" & _
        "Headers(#""Entfernte Spalten"")," & Chr(13) & "" & Chr(10) & "    #""Transponierte Tabelle"" = Table.Transpose(#""Tiefer gestufte Header"")," & Chr(13) & "" & Chr(10) & "    ColumnNext = #""Transponierte Tabelle"" [GetColumnAct(x)]," & Chr(13) & "" & Chr(10) & "    #""In Tabelle konvertiert"" = Table.FromList(ColumnNext, Splitter.SplitByNothing(), null, null, ExtraValues.Error)," & Chr(13) & "" & Chr(10) & "    #""Entfernte Duplikate"" = Table.Distinct(#""In Tabelle konvertiert"")," & Chr(13) & "" & Chr(10) & "    #""" & _
        "Entfernte leere Zeilen"" = Table.SelectRows(#""Entfernte Duplikate"", each not List.IsEmpty(List.RemoveMatchingItems(Record.FieldValues(_), {"""", null})))," & Chr(13) & "" & Chr(10) & "    #""Transponierte Tabelle1"" = Table.Transpose(#""Entfernte leere Zeilen"")" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & "    #""Transponierte Tabelle1"""

Next x

End Sub

And the function is this:
Public Function GetColumnAct(ColNumber) As String

Dim ColumnAct As String

ColumnAct = "Column" & ColNumber

GetColumnAct = ColumnAct

End Function

The only problem is the inclusion of the function GetColumnAct(x) in the formula. While it works for the Argument Name:=GetColumnAct(x), (at the beginning) it doesn't work when included in Formula:=... (at the end).
Does anybody know why this is so? Maybe I'm just getting the syntax wrong? I'm super thankful for any help provided as I'm stuck on this mini thing the whole day now...
Here's the error message I get in advanced editor (power query):
invalid identifier

A: Try this:
Public Function GetColumnAct(ColNumber as Integer) As String

    Dim ColumnAct As String

    ColumnAct = "Column" & str(ColNumber)

    GetColumnAct = ColumnAct

End Function

A: thanks again to everybody who looked into this!
I've now found the answer!
Instead of
#""Transponierte Tabelle"" [GetColumnAct(x)]," & Chr(13) & ""

I needed to write
#""Transponierte Tabelle"" [" & GetColumnAct(x) & "]," & Chr(13) & ""

Somebody told me at another website, so glad I've got it now!


text:
Q: SQL Server Indexes of DateTime Parts such as YEAR, MONTH Is it possible to have indexes on DateTime parts such as DATEPART(YEAR, bp.[CreatedOn]) and DATEPART(MONTH, bp.[CreatedOn])? For example, I have the following T-SQL query:
DECLARE @year AS INT = 2012;
DECLARE @month AS INT = 8;

SELECT bp.Title, bp.CreatedOn FROM BlogPosts bp
WHERE (DATEPART(YEAR, bp.[CreatedOn]) = @year) AND (DATEPART(MONTH, bp.[CreatedOn]) = @month)
ORDER BY bp.CreatedOn;

And this is the execution plan I have: https://gist.github.com/3551450
Currently, there are not many records so it is not a big problem in terms of perf but the records will grow over the time.

A: You'd better construct criterion using datetime field:
declare @startMonth datetime = '20120801'

SELECT bp.Title, bp.CreatedOn
  FROM BlogPosts bp
 WHERE bp.[CreatedOn] >= @startMonth
   AND bp.[CreatedOn] < dateadd (month, 1, @startMonth)
ORDER BY bp.CreatedOn;

This way query executor will be able to use index on CreatedOn.

A: Yes is it possible to put index on year and month. Here is an example:
create table testt(d datetime)
alter table testt add year as year(d) PERSISTED -- after marc_s advise. Thx
alter table testt add month as month(d) PERSISTED --

create index idx_year on testt(year)
create index idx_month on testt(month)

However I would always use a variation of Nikola's solution, so +1 to Nikola.
This is how you can rewrite month and year into a date:
DECLARE @year AS INT = 2012;
DECLARE @month AS INT = 8;
DECLARE @from DATE = dateadd(month, (@year-1900)*12 + @month - 1, 0)

A: I suggest you store date parts on different fields. Clearly this is a requirement which exist in your domain as such needs to be part of your model.
What you lose is that you have to construct the datetime for every model you load or you set the value but that would be a few CPU cycles.