Warning: filter_input(): INPUT_REQUEST is not yet implemented

Question: I am trying to modify this line.
Originally, it was
$cmd = $_REQUEST["cmd"];

Then, I changed to this by reading this post a link at Stackoverflow.
$cmd = filter_input(INPUT_REQUEST, "cmd");

But, I am still getting bottom error:
Warning: filter_input(): INPUT_REQUEST is not yet implemented

When I read other article a link, it says "INPUT_REQUEST is not a valid type."
What is solution here?
Answer: Per the documentation (and your error message, and the answer to the SitePoint Q&A you reference), it's not a valid parameter. The documentation says:

One of INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV.

There is no such thing as INPUT_REQUEST for this function.

What is solution here?

Use one of the parameters that actually exists.
Comment: Does it matter which one to use? I was leaning toward using INPUT_GET.
Answer: TL;DR
If you want to use filter_input()'s filter option then choose POST, GET, or COOKIE as your request type. But there are ways to get REQUEST style behaviour.
note: GET is conventionally used for sending details of a request for retrieving data, while POST is used for submitting data to be stored on the server.
You have a few options:
Indeed, so far (as of PHP 7.2) only INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV have been implemented. But you can still get INPUT_REQUEST style behaviour, or other options might actually fulfill your needs.
Implement INPUT_REQUEST Yourself: (I don't recommend this) you can use INPUT_GET, INPUT_POST and INPUT_COOKIE to implement the behaviour you would expect from the currently non-extant INPUT_REQUEST by running one, and if that didn't get anything running the next and so on, as follows.
`$test_filter = filter_input(INPUT_COOKIE, 'test') ?? filter_input(INPUT_POST, 'test') ?? filter_input(INPUT_GET, 'test');`

Use INPUT_GET or INPUT_POST: if you know which of PUSH or GET will be used to send the request then use the corresponding option. Data sent in the query string of the url will be retrieved using INPUT_GET for example.
Suppress the Superglobal Warning: you can choose which warnings netbeans shows you by going to Windows: Tools -> Options -> Editor -> Hints Mac: NetBeans -> Preferences -> Editor -> Hints and deselecting Superglobals or whatever subset of that you don't want.
Final Note: filter_input() has a third argument that is the actual filter part; if you're using filter_input anyway then you might as well actually use the filter. If you omit the argument then:

If omitted, FILTER_DEFAULT will be used, which is equivalent to FILTER_UNSAFE_RAW. This will result in no filtering taking place by default.
Comment: Thanks. This is not the accepted answer but the description is much better and it also explains the question of @Java in the first comment of the accepted answer.
Answer: You can use filter_var() if you still need to access $_REQUESTS in a similar manner.
There are a couple differences you need to be aware of though.
filter_var()

Returns "" (empty string).
(Recommended) Has an isset() wrap.

filter_input()

Returns Null.

Example
$cmd = '';
if ( isset( $_REQUEST["cmd"] ) ) {
    $cmd = filter_var( $_REQUEST["cmd"], FILTER_SANITIZE_STRING );
}

Answer: Please note that according to this ticket: https://bugs.php.net/bug.php?id=54672, INPUT_REQUEST will never be implemented.
INPUT_REQUEST and INPUT_SESSION have been removed altogether in PHP 8.0
Answer: If what you want achieve is to filter both POST and GET values using filter_input, a good way could be this one:
$cmd = filter_input(INPUT_POST, "cmd");
if ($cmd){
    $cmd = filter_input(INPUT_GET, "cmd");
}

you can even do something more accurate knowing that the return values of filter_input are:

false: if the filter fails
null: if the var_name variable is not set
the variable itself: if everything is ok
Answer: Although the answer is already accepted, here is another solution that I use when I do not know or POST or GET is used.
function getRequestValue($fieldName, $filter = FILTER_DEFAULT, $options = 0)
{
    if (filter_input(INPUT_SERVER, "REQUEST_METHOD") == "POST") {
        return filter_input(INPUT_POST, $fieldName, $filter, $options);
    } else {
        return filter_input(INPUT_GET, $fieldName, $filter, $options);
    }
}

Use it like this:
$cmd = getRequestValue("cmd");

Additional optionals are similar to https://www.php.net/manual/de/function.filter-input.php


What are the "Big Three" Gestures in Mobile Development?

Question: last week, our project manager mentioned that we needed to incorporate more of the "big 3" gestures in our mobile software. unfortunately, she's off on vacation now and none of us know what exactly this means.
what are the "big 3"?
Comment: I sympathise deeply with anyone who works with a project manager who drops vague ideas from on high, doesn't explain, and then goes on vacation :)
Answer: The big three gestures are tap, swipe/flick and pinch/reverse pinch.

These are the rudimentary motions that are inherent to the end-user for mobile devices. This is due to the early adopters of mobile technology incorporating these gestures in their proprietary software, conditioning consumers to use these motions throughout their devices. Thus, many application developers have chosen to incorporate these motions to better aid usability. The other two more popular gestures, pan and rotate, are derivatives of pinch and swipe respectively and are more situational in terms of their use-cases.
Citations:
http://appdeveloper.intel.com/en-us/article/porting-gesture-recognizers-apple-ios-meego-using-photo-viewer-example/

Includes tutorials on tap/swipe/pinch functionality and mentions the
  similarities between rotating/swiping.

http://en.wikipedia.org/wiki/IOS

Interaction with the OS includes gestures such as swipe, tap, pinch,
  and reverse pinch, all of which have specific definitions within the
  context of the iOS operating system and its multi-touch interface.

http://www.foraker.com/introducing-ux-recorder-screen-recording-software-for-ios/

It also captures touch screen navigation, including gestures like
  swipes, pinches, and taps.

http://www.fastpdfkit.com/

The interface: tap, double-tap, swipe, pinch – everything you would
  expect from Apple's iOS.
Comment: Android also has long-press, which is fairly distinct from "tap".  Don't know about iOS/others
Comment: (Sufficient?) citations added. I will look for more evidence if required.
Comment: Are you sure these are *specifically* the Big 3? How do you know that, for instance, two-finger scrolling doesn't count as one of the big 3? Basically I'm asking; can you cite your sources here?
Comment: Excellent, yes. Thanks for adding those, it's an ideal answer now.
Comment: Dragging is another big one, technically distinct from swipe, but this is generally automatically done by the OS, not the app (as a scroll action)


Running gunicorn on Ubuntu in a conda environment

Question: I'm trying to deploy a Flask app on an EC2 instance running Ubuntu.  I have my WSGI file set up, but I'm having some issues running gunicorn.  At first, I installed gunicorn with sudo apt-get install gunicorn.  However, it ran with the wrong version of python, and it threw import errors for each of the modules my Flask app uses.  I ascertained that this was due to the fact that I use conda as an environment manager, and because installing with apt-get placed gunicorn outside of the purview virtual environment.  So, I uninstalled gunicorn (sudo apt-get purge gunicorn) and reinstalled it through conda (conda install gunicorn).  Now, when I run gunicorn (gunicorn --bind 0.0.0.0:8000 wsgi:app), I don't get a 50 line traceback.  I do, however, get the following error: -bash: /usr/bin/gunicorn: No such file or directory.  I tried uninstalling gunicorn and reinstalling with pip, but I still get the same error.  I've tried searching Google and StackOverflow for solutions, but all I've discovered is that I should be installing gunicorn within a virtual environment to overcome this error (which, I beleive, I'm already doing).  I'm guessing there's an easy fix to this, and that the problem is related to my ineptitude, as opposed to conda or something else.  Any suggestions would be much appreciated.  Thanks.
Answer: So, I was right - the problem is entirely related to my own ineptitude.  Rather than deleting this question, though, I'm going to answer it myself and leave it here in case any future fledgling developers run into the same problem.  The issue, as it turns out, is that I was running gunicorn --bind 0.0.0.0:8000 wsgi:app in the wrong directory.  After I cd into the directory containing wsgi.py, gunicorn works just fine.  The takeaway: gunicorn must be run from within the directory containing wsgi.py.


DT transformation in data.table

Question: I have a data table similar to the one shown below that I would like to modify using data.table in RStudio.
library(data.table)
set.seed(57)
DT <- data.table(ITEM = c("car", "cars", "Car ",
                          "Tire", "tyre", " breaks",
                          "brake  pads ", " Steering  wheel ",
                          "steering wheel", "door window", "door/window",
                          "bike", "Bicycle", "chain", "chains "),
                 METRIC_1 = sample(15:100, size = 15, replace = TRUE),
                 METRIC_1_CLASS = c("A", "B", "C"),
                 METRIC_2 = rnorm(15, 38.50, sd = 3),
                 METRIC_2_CLASS = c("I", "II", "III"))

# DT
#
# > DT
#                 ITEM METRIC_1 METRIC_1_CLASS METRIC_2 METRIC_2_CLASS
# 1:               car       35              A 38.87161              I
# 2:              cars       59              B 34.12781             II
# 3:              Car        18              C 40.32863            III
# 4:              Tire       29              A 38.78030              I
# 5:              tyre       78              B 34.12089             II
# 6:            breaks       72              C 36.40179            III
# 7:      brake  pads        99              A 39.32594              I
# 8:  Steering  wheel        47              B 45.04061             II
# 9:    steering wheel       62              C 44.60871            III
# 10:       door window       42              A 44.53798              I
# 11:       door/window       96              B 40.25646             II
# 12:              bike       49              C 39.59810            III
# 13:           Bicycle       93              A 41.07434              I
# 14:             chain       56              B 36.93384             II
# 15:           chains        31              C 40.13403            III

For the 'ITEM' column I would like to
  1 -- change the case from lower to upper case
  2 -- remove leading or trailing spaces, and replace center spaces with an underscore
  3 -- combine data for car, cars, and Car; combine Tire and tyre
  4 -- handle data from the first ten rows together because they are part of one larger group, and do the same for the last 4 columns. For combinations, METRIC_1 is additive and METRIC_2 is additive for the corresponding grouping.
  5 -- replace in METRIC_1_CLASS with A = 100, B = 1000, C = 10000, METRIC_2_CLASS will be similarly substituted.
I would also like to setkeys to ITEM and METRIC_1_CLASS, but I'm not sure if I should do that before or after transforming DT.
This part of the code appears to implement some of the changes
DT[, .(ITEM=toupper(trimws(ITEM)))]

# > DT[, .(ITEM=toupper(trimws(ITEM)))]
#               ITEM
# 1:             CAR
# 2:            CARS
# 3:             CAR
# 4:            TIRE
# 5:            TYRE
# 6:          BREAKS
# 7:     BRAKE  PADS
# 8: STEERING  WHEEL
# 9:  STEERING WHEEL
# 10:     DOOR WINDOW
# 11:     DOOR/WINDOW
# 12:            BIKE
# 13:         BICYCLE
# 14:           CHAIN
# 15:          CHAINS

The final DT should look something like the following:
set.seed(57)
metric.2 <- DT$METRIC_2
DT <- data.table(ITEM = c("CAR", "TIRE", "BREAKS", "STEERING_WHEEL", "DOOR_WINDOW", "BIKE", "CHAIN"),
                 METRIC_1 = c(35+59+18, 29+78, 72+99, 47+62, 42+96, 49+93, 56+31),
                 METRIC_1_CLASS = c(11100, 1100, 10100, 11000, 1100, 10100, 11000),
                 METRIC_2 = c(sum(metric.2[1:3]), sum(metric.2[4:5]), sum(metric.2[6:7]), sum(metric.2[8:9]), sum(metric.2[10:11]),
                              sum(metric.2[12:13]), sum(metric.2[14:15])))
DT

# > DT
#              ITEM METRIC_1 METRIC_1_CLASS  METRIC_2
# 1:            CAR      112          11100 113.32805
# 2:           TIRE      107          11100  72.90119
# 3:         BREAKS      171          11100  75.72772
# 4: STEERING_WHEEL      109          11100  89.64932
# 5:    DOOR_WINDOW      138          11100  84.79444
# 6:           BIKE      142          11100  80.67244
# 7:          CHAIN       87          11100  77.06786

If I start with this DT instead:
set.seed(57)
DT <- data.table(ITEM = c('CAR', 'CAR', 'CAR',
                        'TIRE', 'TIRE', 'BREAKS',
                        'BREAKS', 'STEERING_WHEEL', 'STEERING_WHEEL', 'DOOR_WINDOW',
                        'DOOR_WINDOW', 'BIKE', 'BIKE', 'CHAIN', 'CHAIN'),
                 METRIC_1 = sample(15:100, size = 15, replace = TRUE),
                 METRIC_1_CLASS = c(100, 1000, 10000),
                 METRIC_2 = rnorm(15, 38.50, sd = 3),
                 METRIC_2_CLASS = c("I", "II", "III")
               )
DT

# > DT
#              ITEM METRIC_1 METRIC_1_CLASS METRIC_2 METRIC_2_CLASS
# 1:            CAR       35            100 38.87161              I
# 2:            CAR       59           1000 34.12781             II
# 3:            CAR       18          10000 40.32863            III
# 4:           TIRE       29            100 38.78030              I
# 5:           TIRE       78           1000 34.12089             II
# 6:         BREAKS       72          10000 36.40179            III
# 7:         BREAKS       99            100 39.32594              I
# 8: STEERING_WHEEL       47           1000 45.04061             II
# 9: STEERING_WHEEL       62          10000 44.60871            III
# 10:    DOOR_WINDOW       42            100 44.53798              I
# 11:    DOOR_WINDOW       96           1000 40.25646             II
# 12:           BIKE       49          10000 39.59810            III
# 13:           BIKE       93            100 41.07434              I
# 14:          CHAIN       56           1000 36.93384             II
# 15:          CHAIN       31          10000 40.13403            III

I could do this:
DT[, lapply(.SD, sum), by = "ITEM", .SDcols = c("METRIC_1", "METRIC_1_CLASS", "METRIC_2")]

# > DT[, lapply(.SD, sum), by = "ITEM", .SDcols = c("METRIC_1", "METRIC_1_CLASS", "METRIC_2")]
#              ITEM METRIC_1 METRIC_1_CLASS  METRIC_2
# 1:            CAR      112          11100 113.32805
# 2:           TIRE      107           1100  72.90119
# 3:         BREAKS      171          10100  75.72772
# 4: STEERING_WHEEL      109          11000  89.64932
# 5:    DOOR_WINDOW      138           1100  84.79444
# 6:           BIKE      142          10100  80.67244
# 7:          CHAIN       87          11000  77.06786

Comment: "handle data from the first ten columns together" -- you mean rows? By the way, if you're going to give two example data sets, you might want to give them different names.
Comment: @Frank, I do mean rows and not columns.
Answer: Heavily manual, but it does the job:
# Remove leading spaces
DT[, ITEM := gsub("^\\s*([^\\s].*)$", "\\1", ITEM, perl = TRUE)]
# Remove trailing spaces
DT[, ITEM := gsub("^(.*[^\\s])\\s*$", "\\1", ITEM, perl = TRUE)]
# Substitute center spaces and slash with underscore
DT[, ITEM := gsub("\\s+|/", "_", ITEM, perl = TRUE)]
# UPPER Case
DT[, ITEM := toupper(ITEM)]

# Text cleanup
DT["CARS" == ITEM, ITEM := "CAR"]
DT["TYRE" == ITEM, ITEM := "TIRE"]
DT["BRAKE_PADS" == ITEM, ITEM := "BREAKS"]
DT["CHAINS" == ITEM, ITEM := "CHAIN"]
DT["BICYCLE" == ITEM, ITEM := "BIKE"]

# Numeric substitutions
DT[,
   METRIC_1_CLASS :=
     ifelse(
       "A" == METRIC_1_CLASS
       , 100
       , ifelse(
         "B" == METRIC_1_CLASS
         , 1000
         , ifelse(
           "C" == METRIC_1_CLASS
           , 10000
           , NA
         )))]

DT transformation in data.table


Build expression trees to represent if-else

Question: Deserializing of Expression tree using ExpressionSerialization on a full conditional expression i.e ternary operator is giving error . If i am using ternary operator it causes FullConditionExpression (System Not Supported Exception)
Using code from following links:
http://archive.msdn.microsoft.com/exprserialization
Are there any latest version available for the above link?
http://metalinq.codeplex.com/
Tried this afterwards
public Expression<Func<object, string>> LabelCriteria { get; set; }

LabelCriteria = x =>
    {
      if (true)
          return "Cash";
      else
          return " ";
    }

Expression doesn't support if - else block . It gives error as " A lambda expression with a statement body cannot be converted to expression tree . Is there any other way to do it.
Comment: Its just a code snippet. I want to actually use if else-if else-if else .
Answer: You must use the conditional operator:
LabelCriteria = x => true ? "Cash" : " ";

It may be that the compiler is modifying the expression because of constant folding, however, since the condition is a constant expression (true).  Try using a variable there and see what happens.
Comment: True is just used for code snippet. It basically checks multiple things to evaluate to true or false. I also wanted to add that i wanna use if else-if else-if else loop.
Comment: @user1650470 you cannot use if-else in an expression lambda.  You can use the conditional operator.  If you have multiple conditions, then use multiple conditional operators: `x => condition1 ? result1 : condition2 ? result2 : condition3 ? result3 : result4;`.  A statement lambda (such as `x => { if (condition1) return result1; else return result2; }`) cannot be converted to an expression tree.
Answer: You could use a method like here:
string myFunction(Object obj){
     //here your if-else...
}

LabelCriteria = x => myFunction(x);

Answer: you could construct an expression tree explicitly with Expression API, refer to https://msdn.microsoft.com/en-us/library/bb397951.aspx
here's the code for your problem:
        ParameterExpression x = Expression.Parameter(typeof (object), "x");
        ConditionalExpression body = Expression.IfThenElse(
            Expression.Constant(true),
            Expression.Constant("Cash"),
            Expression.Constant(" ")
            );

        LabelCriteria = Expression.Lambda<Func<object, string>>(body, x);

Comment: Your code throws 'System.ArgumentException : Expression of type 'System.Void' cannot be used for return type 'System.String'. You should use Expression.Condition instead of Expression.IfThenElse.
Answer: I found the solution.
Ad i was using this particular piece of code
Using code from following links:
http://archive.msdn.microsoft.com/exprserialization
It didn't handle full conditional expression but it handle conditional expression. I just added FullConditionalExpression into the switch case in deserialization and it worked. It was same as ConditionalExpression in the switch.


Need help picking up and moving a file with a dynamic name

Question: I am trying to move a backup file that is created every morning from its current location to a shared network location but can not figure out how to code for dynamic dates in SQL.
Ex: The file is called my.file03232017130.bak and every day a new file will be saved with the same name except the 03232017130 will be changed to that days date.
I would like to utilize SSIS and SQL to set up a process that will move the file every morning from where it is saved by default to a different location.
Any help is appreciated.
Comment: I see MMDDYYYY that part isn't a big deal really. That is pretty simple string manipulation. What part(s) do you need help with? As posted this is pretty broad.
Answer: Make a package variable and then set the value to the string using code depending on the current date in a Script Task, then use that variable in your File System Task.
Answer: Setup a File Watcher on the backup folder and utelize a File Transfer Task to send each file to the destination you want. You can do it without the 3rd party tools but it will take much longer to setup and usually runs into many windows related issues


Hellinger-Toeplitz theorem use principle of uniform boundedness

Question:
Suppose $T$ is an everywhere defined linear map from a Hilbert space $\mathcal{H}$ to itself. Suppose $T$ is also symmetric so that $\langle Tx,y\rangle=\langle x,Ty\rangle$ for all $x,y\in\mathcal{H}$. Prove that $T$ is a bounded directly from the uniform boundedness principle and not the closed graph theorem.

This is problem III.13 in the Reed-Simon volume 1. Hints are welcome.
Comment: For a solution that *does* use the closed graph theorem, see http://math.stackexchange.com/questions/255763/graph-of-symmetric-linear-map-is-closed?rq=1
Answer: Hint: Consider the family of linear functionals $f_x$ defined by $f_x(y) = \langle Tx,y \rangle$, as $x$ ranges over the unit ball of $\mathcal{H}$.
Answer: Both proofs are valid for a linear operator $T : X \to X'$ on a Banach space $X$, that is symmetric in the sense that $\langle T x, y \rangle = \langle T y, x \rangle$, $x, y \in X$, where $\langle \cdot, \cdot \rangle$ is the duality pairing.


Are presheaf categories well-copowered?

Question: I am trying to proof the existence of a right adjoint to the functor $F_*\colon \mathrm{Set}^D \to \mathrm{Set}^C$ given by precomposing with a functor $F\colon C \to D$, where $C$ and $D$ are small categories, using the dual version of the special adjoint functor theorem.
One of the ingredients for this is that $\mathrm{Set}^C$ is well-copowered (in the sense that $(\mathrm{Set}^C)^{\mathrm{op}}$ is well powered), which means--assuming I got my dualization right--that the collection of isomorphism classes of epimorphisms $F \to G$ in $(F \downarrow \mathrm{Set}^C)$ is (isomorphic to) a set.
This seems like a well known fact, but I couldn't find any proof of it and also failed to think of one by myself. Any hints or references to why this should be true?
Comment: An overkill answer is to appeal to Theorem 1.58 in Adamek and Rosicky's _Locally Presentable and Accessible Categories_, which says that any [locally presentable category](https://ncatlab.org/nlab/show/locally+presentable+category) is well-copowered. Zhen Lin's answer is obviously better here. The general result does tell you e.g. that the category of commutative rings is well-copowered, which is not obvious (though it can [also be proven directly](https://stacks.math.columbia.edu/tag/04VM).
Answer: If $\mathcal{S}$ is a category with cokernel pairs and $\mathcal{C}$ is a non-empty small category, then $\mathcal{S}$ is well-copowered if and only if $[\mathcal{C}, \mathcal{S}]$ is. The key observation is this: a morphism in $[\mathcal{C}, \mathcal{S}]$ is an epimorphism if and only if all its components are, because being an epimorphism is something that can be detected by cokernel pairs, and cokernel pairs in $[\mathcal{C}, \mathcal{S}]$ are computed componentwise if $\mathcal{S}$ has them.
The point is that the epimorphisms in $\mathbf{Set}$ are surjections, so there is an obvious cardinality bound on the quotients of any given set.
Comment: I did already work out the connection between epimorphisms in $[\mathcal{C}, \mathcal{S}]$ and $\mathcal{S}$; however, I fail to see how the well-copoweredness of $\mathcal{S}$ transfers to that of $[\mathcal{C}, \mathcal{S}]$. Can you elaborate on that?
Comment: Two quotients in $[\mathcal{C}, \mathcal{S}]$ are isomorphic if and only if their components are isomorphic as quotients in $\mathcal{S}$.
Comment: Just to make sure that I get this right, since I am a bit insecure in such size matters: For each $F \in [\mathcal{C}, \mathcal{S}]$ and for each $C \in \mathcal{C}$ there is a set of isomorphism classes of quotients of $F( C )$ in $\mathcal{S}$. Since $\mathcal{C}$ is small, we can construct there product $\Pi_{C \in \mathcal{C}} \mathrm{Quot}(F( C ))$. Then $\mathrm{Quot}(F)$ should be in bijection with this set where $\mathrm{Quot}$ means collection of isomorphism classes of quotients. Is this correct? Is this too complicated?
Comment: That's not quite correct. Rather, there is an _injection_ from the set of isomorphism classes of quotients of $F$ to the set of tuples of isomorphism classes of quotients of etc.
Comment: Right, sorry. I think I get it now, thanks!

Are presheaf categories well-copowered?


Compiling a DLL in C++ mingw 64

Question: I want to compile a DLL in C++ and then call the Library from VBA. I have done this on windows32 bits. But I wanted to replicate such exercise since I use Windows 64 bit at work. Given this fact I downdloaded mingw 64.
My example:
main.h
#ifndef __MAIN_H__
#define __MAIN_H__

#ifdef BUILD_DLL
#define DLL_EXPORT __declspec(dllexport)
#else
#define DLL_EXPORT __declspec(dllimport)
#endif

extern "C"
{
int DLL_EXPORT __stdcall add2(int num);
int DLL_EXPORT __stdcall mult(int num1, int num2);
}

#endif // __MAIN_H__

main.cpp
#include "main.h"

int DLL_EXPORT __stdcall add2(int num)
{
return num + 2;
}

int DLL_EXPORT __stdcall mult(int num1, int num2)
 {
 int product;
 product = num1 * num2;
 return product;
 }

When I compile the dll I pass this linker options:
Wl,--add-stdcall-alias

and/or
Wl,--kill-at

I also generate the .def file, which looks like this:
EXPORTS
   add2 @1
   mult @2

I expected a .def file which looks like this (as in my 32bit PC):
EXPORTS
   add2 @1
   mult @2
   add2 = add2 @1
   mult = mult @2

Then I call the dll and the functions from VBA like this:
Public Declare PtrSafe Function add2 _
Lib "C:\MyPath\dll.dll" _
(ByVal num As Long) As Long

The problem is: The functions can be called from VBA editor and gives right results, but when called from an Excel sheet they throw some other number (address of the passed argument??). If I try to call the function from VBA AFTER I tried inside Excel, then VBA throws an error (out of stack Space).
This problem is not present when I use mingw4.7 32bit. The problem is when I compile using mingw 4.6.3 64bit (I had installed mingw4.7 64bit but I found on internet People saying that 4.6.3 is more stable)
I have also noticed that the .def file looks identicall to the one above even if i dont pass my linker options.
Can anybody help? whats happening? is mingw64 or vba/Excel feiling? or is my mingw64 configuration?
UPDATE....
ok I found this site :https://sites.google.com/site/jrlhost/links/excelcdll#array and as explain there by using and itermediate function in VBA, my function add2 Works from the worksheet.
Public function fromWorksheetAdd2 ( dim x as Long) as Long
   fromWorksheetAdd2 = add2(x)
end function

then I can use fromWorksheetAdd2 at worksheets and Add2 at VBA. However this approach is kind of tedious. Hope someone can help With an elegant approach.
Answer: Look at your parameters.
A Long in VBA is 64 bits (8 bytes).  On the C++ side, the size of an int is whatever sizeof(int) is, which is more than likely 4 bytes in the environment you're using.
You must guarantee that the types you're sending and returning between VBA and C++ are exactly the same size, otherwise you can wind up with stack corruption.
Comment: When you create DLL's from C or C++ to be used by other languages, it is preferred that you use the Windows API defined types such as LONG, DWORD, as parameters or return types in your exported functions instead of the C++ int, long, etc.  This way, you don't get into the mess of having types not match up.
Comment: I have tried to used long long variables in C++ and VBA both should by 8 bytes. I also used LONG in C++ and Long in VBA. But none of these approaches fixed my problem. I am still wondering on the effect of Wl,--add-stdcall-alias

Compiling a DLL in C++ mingw 64


Trying to print the number 12 but it only prints the number 1

Question: def computes(text):
    file=open(text)
    line=file.readlines()
    for i in range(0,len(line)):
        print(str(line[i][1]))

Output
[4, 4, 3, 4, 0]
[9, 7, 6, 8, 0]
[6, 6, 4, 2, 2]
[9, 10, 6, 8, 6]
[12, 9, 6, 9, 2]
[12, 12, 2, 4, 1]
[5, 6, 3, 4, 16]
[24, 21, 14, 16, 0]
[3, 2, 2, 5, 0]
[10, 10, 10, 0, 9]
4
9
6
9
1
1
5
2
3
1

What I'm trying to do, is loop through a text that has an array of lists inside and I am trying to print the number 12 but is only printing the first number, I am not sure where to go from here. How can I correct this?
Comment: `line[i]` is a string, not a list, so `line[i][1]` is the 2nd character of each line.
Comment: Why does the output include the whole lines from the file? Your function doesn't print the input anywhere.
Comment: I had to stare at this question for 3 minutes with a confused look on my face until I finally realized that the content of the text file is included with the output of the text for whatever reason, and then it took me another minute to figure out why the expected output is 12 instead of 1.
Comment: what I'm trying to do, is try to print the first number from every list. In one of the list, the first number is 12 but when i print, the only number that is output is the number 1 and I'm trying to output the whole number 12
Comment: @Laura Check my answer below, if that helps, [don't forget to accept and upvote](https://stackoverflow.com/help/someone-answers) :)
Answer: Your data in the file is stored as text, which means the lists are just string representation and not actual Python objects. So you need to convert them into Python lists for printing the whole number. You can do this by doing a ast.literal_eval on each of the list:
import ast

def computes(text):
    file=open(text)
    line=file.readlines()
    for i in range(0,len(line)):
        print(ast.literal_eval(line[i])[0])

Answer: if you file is in this format, separated number for one space:

4 4 3 4 0
9 7 6 8 0
10 11 12 13

you can use this code:
def computes(text):
    file=open(text)
    for line in file:
        numbers = line.split(" ")
        for number in numbers:
            print(number)
computes("text.txt")

Answer:     print(str(line[i][1]))

You are printing only the second character of each line - using [1] index, which corresponds to the second element.
If you want to print the whole line, do:
print(str(line[i]))

I'm not sure if that's what you meant, though.
Comment: what I'm trying to do, is try to print the first number from every list. In one of the list, the first number is 12 but when i print, the only number that is output is the number 1 and I'm trying to output the whole number 12


.NET C# async await. whenall does not wait for tasks

Question: I have problem with multi threading in .NET Framework 4.5 with await/async/whenall.
I called thousands of threads by calling in loop.
List<Task<string>> t = new List<Task<string>>();
for (Row = 0; Row < lines.Count; Row++)
{
    t.Add(AccessPaymentVault(Row, credentials, cts.Token));
}
string[] str_list = await Task.WhenAll(t.ToArray());

AccessPaymentVault Function is used for connecting vault web service and retrieve credit card information.
async Task<string> AccessPaymentVault(int row, Credentials credentials, CancellationToken ct){
    var data = await Task.Run(() =>
    {
      return Tokenization.Retrieve(credentials, lines[row][CCColumnToken]);
    }, ct);

    return Encryptor.Decrypt(data);
}

Tokenization.Retrieve is the most waited function and it connects to webservice.
WhenAll seems to be not waiting all tasks because some records in the result are randomly missing.
When I first run, it retrieves all records.
In second run, some records in the middle are missing.
In third run, the missing records in second run was there but other records are missing.
I guess the problem is in WhenAll but not sure about it.
Any form of help is very appreciated.
Thank you.
Comment: in terms of using async/await everything looks fine. Just a couple of ideas:
1. there is a shared state in Tokenization.Retrieve which might be broken because of multithreading
2. you might swallow some exceptions inside the Tokenization.Retrieve
Comment: Max, you solved the problem! There was an exception raising because too many connections to the server. In catch section, I tried connecting again and it was solved. Write an answer and I will accept yours as answer. You saved me. thanks a lot!
Comment: So TRUE! I swallowed an exception in Retrieve function when returning.
Comment: This sounds a lot like http://stackoverflow.com/q/23936521/120955. Does `Tokenization.Retrieve()` act asynchronously by itself?
Comment: No it doesn't. That's why I used Task.Factory.StartNew for this function.
Comment: When you say "some records in the middle are missing," what do you mean? What code are you using to see which records are there?
Comment: It is populating csv file. So I can see the records missing easily.
Comment: I mean rather than missing records, missing fields would be more correct expression. AccessPaymentVault function is used for retrieving credit card details, but some of them doesn't return. I tried debugging. When I debug the code, everything is there( I can see every records. perhaps it is because of delay in step by step debugging?). But when I execute, some cc details are missing.
Answer: Nowadays the suggested way of starting a new task is Task.Run instead of Task.Factory.StartNew, unless you need a higher level of the control over the Task.
In your case, the main problem is that the result type will be Task, cause some nesting here.
But luckily there is a way - Task.Unwrap.
So if you call the Task.Run - underneath Task.Factory.StartNew and the Task.Unwrap are called automatically.
Check out this link:
http://blogs.msdn.com/b/pfxteam/archive/2011/10/24/10229468.aspx
And another good article: StartNew is Dangerous
Update from comments
In terms of using async/await everything looks fine.
Just a couple of ideas:

there is a shared state in Tokenization.Retrieve which might be broken because of multithreading
you might swallow some exceptions inside the Tokenization.Retrieve
Comment: Max, I appreciate your answer. I changed the startNew into Task.Run but it had same problem. I am editing the question into Task.Run for no more confusion.
Comment: the link to msdn blogs seems broken. here is the web archive version:
https://web.archive.org/web/20150221140040/http://blogs.msdn.com/b/pfxteam/archive/2011/10/24/10229468.aspx


Has the handling of the /etc/issue file changed from 18.04 to 20.04

Question: I have bionic systems that display the lines in /etc/issue on login and re-display if I press ENTER.
But, on my focal systems I only get the /etc/issue contents once, it does not display when I press ENTER.
How do I get the 18.04 behavior in 20.04?
Comment: @guiverc - my question is specific to moving from 18.04 to 20.04
Comment: I don't understand. Are you saying you get the contents of `/etc/issue` displayed twice after you login on 18.04? Immediately after logging in and again after the first prompt?
Comment: @muru - on bionic the console displays /etc/issue and every press of the enter key displays it again.  on focal it only displays it once, the enter key just displays a login prompt (no /etc/issue)

this is important because there is system information displayed there that is relevant to the user.
Comment: I'd consider it a bug if the system decided to dump the contents of issue every time I pressed enter (and probably others did too, which is why it's not the behaviour now - though I don't recall this ever happening to me)
Comment: @muru - be that as it may, that's the way it worked up through bionic
Comment: I've been using it since 9.04, and I certainly don't remember anything like that.
Answer: This behavior has changed in 20.04, the ENTER key only displays a login message but....
Pressing CTRL-C will display the contents of /etc/issue.


Ubuntu Nvidia GTX 960M

Question: I promise that I've tried to find the answer for days and days.
I've come accross of dozens and dozens of indications, explanations, opinions and so on.
And... nothing.
I am tired of rebooting my notebook.
MSI PE60 6QE  Nvidia GTX 960M
Fresh installation
Well-known error while trying to install
Try to set nomodeset but There Is No nomodeset in my Ubuntu DVD.
Help will be sincerely appreciated.
I've forgot to say that I am absolutely new to Linux. New. Never tried it.
I am tired of Windows but if installing Ubuntu is so complicated I think I will offer my notebook and forget just about everything. Back to the pencil and the paper.
Answer: There is no need for being frustrated.
Boot from Ubuntu installation media.
Highlight Try Ubuntu without installing and press the E key.
Add nouveau.modeset=0 to the end of the linux line.
Press the F10 key to boot into the Ubuntu Live desktop.
Click on Install Ubuntu and start the system installation.
When finished, reboot into the installed Ubuntu system.
Highlight the Ubuntu menu entry and  press the E key.
Add nouveau.modeset=0 to the end of the linux line.
Press the F10 key to boot into the Ubuntu system.
First of all install the NVIDIA drivers and reboot the system.
Now you don't have to add nouveau.modeset=0 anymore ...
Comment: Thnks for your answer but it hasn't work maybe because I am not writting the command where I should.
Comment: Thnks for your answer but it hasn't work maybe because I am not writting the command where I should. I've placed it at the end of the Linux line: ...quiet splash -- nouveau.modeset=0, didn't work; then at the end of the Linux line: ...quiet splash nouveau.modeset=0 --, didn't work; and finally between Linux and the third and last line, didn't work. Still the same error.
Comment: @user513831 : You have to write it without "--" ! Please try again and in case it still does not work, use the parameter nomodeset instead of  nouveau.modeset=0 - and important : put a space before the parameter.
Comment: I haven't used any quotes. My doubt was about where in the line should I place the parameter assuming that the Linux line finishes like this: ...quiet splash --
Comment: As I told you in my first comment I've already tried all those three combinations. I've just tried with nomodeset and as I say in my first post,doesn't work neither. Thank you very much for time anyway.
Comment: @user513831 : Maybe you have to disable the NVIDIA graphics card in BIOS and re-enable it afterwards - otherwise I am running out of ideas ... the instructions I gave you have worked fine in nearly every case. :)
Comment: Unfortunately no option to disable or enable graphic card in BIOS.
Comment: @user513831 : Some last ideas : What about the installation media ? Did you download the recommended 64 bit Ubuntu edition - is the installation media configured properly -did you disable Secure Boot in BIOS ?
Comment: Yes 64 bit edition downloaded from Ubuntu org; Secure Boot, Fast Boot disabled. Just for the record for future readers the error message says: [0,176607] ACPI : EC : Fail in evaluating the _REG object of EC device. Broken bios is suspected.     I've found that this error is related to GTX 960M graphic card. Anyway, big thanks cl-netbox for your time and patience.
Comment: @user513831 : You're welcome ! This might be a hint for a hardware failure, maybe a BIOS flash can fix it ... you should contact the hardware vendor. :)
Comment: I've also reflashed my BIOS. This is why I started saying that I tried all I could try (for the moment) :)

Ubuntu Nvidia GTX 960M


Wifi connected but internet not working

Question: There is problem with my wifi connection. Its shows as connected but still internet is not working. I tried making my mobile as hotspot then try to connect my laptop to it, it worked. So problem is only when I connect to my wifi router.
Answer: Solved by referring to instructions given here: https://sites.google.com/site/easylinuxtipsproject/internet#TOC-Disable-power-management-for-the-wireless-card
<code>sudo apt-get purge bcmwl-kernel-source broadcom-sta-common broadcom-sta-source
sudo apt-get install b43-fwcutter firmware-b43-installer
</code>
This solved my issue.

Wifi connected but internet not working


DB2/AS400 SQL Pivot

Question: I have a problem with pivot tables ....
I don't understand what to do ...
My table is as follows:
<code>|CODART|MONTH|QT  |
|------|-----|----|
|ART1  |1    |100 |
|ART2  |1    |30  |
|ART3  |1    |30  |
|ART1  |2    |10  |
|ART4  |2    |40  |
|ART3  |4    |50  |
|ART5  |4    |60  |
</code>
I would like to get a summary table by month:
<code>|CODART|1  |2  |3  |4  |5  |6  |7  |8  |9  |10 |11 |12 |
|------|---|---|---|---|---|---|---|---|---|---|---|---|
|ART1  |100|10 |   |   |   |   |   |   |   |   |   |   |
|ART2  |30 |   |   |   |   |   |   |   |   |   |   |   |
|ART3  |30 |   |   |50 |   |   |   |   |   |   |   |   |
|ART4  |   |2  |   |   |   |   |   |   |   |   |   |   |
|ART5  |   |   |   |60 |   |   |   |   |   |   |   |   |
|TOTAL |160|12 |   |110|   |   |   |   |   |   |   |   |
</code>
Too many requests? :-)
Thanks for the support
Comment: Does this answer your question? [DB2 Pivot equivalent](https://stackoverflow.com/questions/66053075/db2-pivot-equivalent)
Comment: the last row of totals is missing
I can't figure out how to do it
Answer: <code>WITH MYTAB (CODART, MONTH, QT) AS
(
VALUES
  ('ART1', 1, 100)
, ('ART2', 1,  30)
, ('ART3', 1,  30)
, ('ART1', 2,  10)
, ('ART4', 2,  40)
, ('ART3', 4,  50)
, ('ART5', 4,  60)
)
SELECT
  CASE GROUPING (CODART) WHEN 0 THEN CODART ELSE 'TOTAL' END AS CODART
, SUM (CASE MONTH WHEN  1 THEN QT END) AS "1"
, SUM (CASE MONTH WHEN  2 THEN QT END) AS "2"
, SUM (CASE MONTH WHEN  3 THEN QT END) AS "3"
, SUM (CASE MONTH WHEN  4 THEN QT END) AS "4"
---
, SUM (CASE MONTH WHEN 12 THEN QT END) AS "12"
FROM MYTAB T
GROUP BY ROLLUP (T.CODART)
ORDER BY GROUPING (T.CODART), T.CODART
</code>

CODART
1
2
3
4
12

ART1
100
10

ART2
30

ART3
30

50

ART4

40

ART5

60

TOTAL
160
50

110

DB2/AS400 SQL Pivot


Visual Studio Version 17.6.1 breaks Blazor .NET 6 Project with (false?) Errors

Question: I am working on a ASP.NET Blazor Server Project, .NET 6 (LTS).
Everything worked fine in the previous VS 2022 Version (even before 17.4.4 through 17.5.*) but the new Update to 17.6.1 breaks the code: The Project won't compile anymore. I have copied and tested the exact same code across different Computers and VS2022 Versions.

It seems like that:
The first Bug is created by MyParent=this, which makes the Parent give its own instance as Parameter to the Child. (This trick is often used in examples and used to work in previous versions.) This will create the first two lines of error (CS0400 and CS1503).
When wrapping the Child component into the Wrapper, this will create the CS1662 Error.
Removing all in-going parameters lets the project compile.
@*this compiles*@
<Wrapper>
    <Child></Child>
</Wrapper>

I have also successfully recreated the (two) Bugs within the default Blazor Server Template.

Parent.razor:
@page "/parent"

Parent

This will create both bugs:

"namespace bug" (CS0400 and CS1503)

"lambda expression bug"(CS1662)

    <Wrapper>
        <Child MyParent=this></Child>
    </Wrapper>
    @*
    alt version (longer)
    <Wrapper Context="MyContext">
        <Child MyParent=this MyObj=MyContext.MyData></Child>
    </Wrapper>
    *@

@*

This will create only the first ("namespace") bug:

"namespace bug" (CS0400 and CS1503)

    <Child MyParent=this></Child>

*@

@code {
    public string MyName { get; set; } = "I am the parent.";
}

Wrapper.razor:
@using VS17._6._1BUG_Test.Data;

Wrapper

@code {
    [Parameter]
    public RenderFragment<MyClass> ChildContent { get; set; }
}

Child.razor:

Child2

my text:

    @MyObj.ToString()

parent data:

@MyParent.MyName

@code {
    [Parameter]
    public object MyObj { get; set; }
    [Parameter]
    public Parent MyParent { get; set; }
}

MyClass.cs:
namespace VS17._6._1BUG_Test.Data
{
    public class MyClass
    {
        public object MyData { get; set; } = "default data";
    }
}

I am hoping on a timely Bugfix from Microsoft. If anybody has any other suggestions, they are welcome also. If this problem persits I would probably think of downgrading VS 2022 to 17.5, although that seems to be my last resort and also probably kind of difficult. Even a complete re-install to an earlier Version if probably a bit more complicated, since I don't think that can be easily done with the VS-installer.
Update:
I have noticed, that the VS-installer actually now provides an option to rollback to previous version. So I'm hesitant to update to 17.6.2 to test if its fixed (then I would only be able to roll back to 17.6.1), but I will probably roll back to 17.5 for now.
Update:
It seems that in the preview version 17.7.0 preview 1 this bug is not longer surfacing, although I have not found a specific fix for it in the release notes (did not search too deep).
Comment: This seems more appropriate as a report to the Visual Studio team at Microsoft via the Send Feedback button in the corner.
Comment: NameSpace manipulation is cause one of your issues. The other is the Wrapper is not outputting the ChildContent.
Comment: It is not it is the cause of the Lamda error. I actually downloaded your code the errors are real the ide is not at fault!.
Comment: Thanks, I have done that. I will then post any results here and close the question if solved.
Comment: @Brian sorry, I don't understand, how that would cause v 17.5.5 to work, 17.6.1 not to compile and 17.7.0 preview 1 to work again. Additionally, the namespace in the example is a bit unlucky, but that is unrelated, it was auto generated from the project name. The result is the very same if simply using the standard template project name "BlazorApp1" and the according namespace. No further "manipulation" of namespace are done. All files have the default ns from folder structure.
Comment: @Brian "outputting" the ChildContent or not is irrelevant to the problem. As explained the problem is, that in the specific VS version the exact same code won't compile. The actual content doesn't matter. Adding ```@ChildContent``` to the Wrapper's BuildRenderTree doesn't change a thing.
Comment: Well, No! one can simply start plain CMD and type ````dotnet run``` in the project's folder, and voila the project actually runs. So I claim it IS the IDE's fault, if the runtime can compile and run it directly but the IDE fails at it at this specific version (and previous and later version also are able to run it). Also there is no error in any lambda statement. but even if you think so, please make a code example.
Answer: I've run into the same problem with Visual Studio - my code works on 15.X, and doesn't work on 16.X. I managed to track it down to a razor base class with generic parameters:
ElementBase.razor
@typeparam TElementType where TElementType : Element

@code {
    [Parameter]
    public TElementType Model { get; set; } = default!;

    public void Foo()
    {
        // ...
    }

    public void Bar()
    {
        // ...
    }
}

Since this is a base class, it doesn't define any markup - anything it defines would be overridden by child classes anyway. I changed it to be a plain C# class instead, and the error went away:
public abstract class ElementBase<TElementType> : ComponentBase
{
    [Parameter]
    public TElementType Model { get; set; } = default!;

    public void Foo()
    {
        // ...
    }

    public void Bar()
    {
        // ...
    }
}

Answer: As of Release Version 17.6.3 the bug seems to be resolved. (VS is able to build again and the "errors" are no longer shown.)
As a workaround Preview 17.7.0 (preview 1 and 2) also seem to work.


Problems displaying array results in table using CodeIgniter

Question: I am in need of some help displaying the correct values from an array within an html table. I am writing a scheduling engine of sorts that will allow the user to schedule classes based on preferred dates/times and check the availability of educators.
The code below properly outputs a table with 8 weeks (in rows) and also displays my available educators (in columns). My dates are incremented 1 week at a time correctly, but the problem I am having is displaying the correct availability based on the Educator_Id. My view does not seem to be looping through the educators properly, as the same status is displayed for each educator. Reviewing the mysql logs, shows that the correct queries were executed (I can see that multiple id's were passed).
Here is what my table looks like. Week 4 should only show a personal day for Jane Doe.
Thanks for any help you can give.

My view:

   Week #
   Date
   Time
   <?php foreach($educators as $educator): ?>
    <?php echo $educator->First_Name.' '.$educator->Last_Name; ?>
   <?php endforeach; ?>

 <?php
 $i = 0;
 foreach($weeks as $key => $week):
 $class_date= $class_dates[$key];
 $week = $weeks[$key];
 $master_schedule = $master_schedules[$key];
 $educator_schedule = $educator_schedules[$key];
 $educator_availability = $educator_availabilities[$key];
 $week_day_id = $i + 1;
 ?>

   Week <?php echo $week_day_id; ?>
   <?php echo $class_date; ?>
   <?php echo $opportunity->First_Preferred_Start_Time.' - '.$opportunity->First_Preferred_End_Time; ?>

   <?php foreach($educators as $educator): ?>

    <?php if($week->Count == 1): echo 'Class Conflict'; endif; ?>
    <?php if($master_schedule->Count == 1): echo $master_schedule->Title; endif; ?>
    <?php if($educator_schedule->Count == 1): echo $educator_schedule->Title; endif; ?>
    <?php if($educator_availability->Count == 1): echo 'Not Scheduled'; endif; ?>

   <?php endforeach; ?>

  <?php if($i ++ == 7) break; endforeach; ?>

My controller:
function schedule_opportunity($Opportunity_Id) {
    //retrieve opportunity details
    $this->data['opportunity'] = $this->ion_auth_model->get_opportunity($Opportunity_Id)->row();
    $opportunity = $this->ion_auth_model->get_opportunity($Opportunity_Id)->row();

    $Curricula_Id = $opportunity->Curricula_Id;
    $Preferred_Start_Time = $opportunity->First_Preferred_Start_Time;
    $Preferred_End_Time = $opportunity->First_Preferred_End_Time;
    $Preferred_Start_Date = $opportunity->First_Preferred_Start_Date;

    //find available educators
    $this->data['educators'] = $this->ion_auth_model->available_educators($Curricula_Id);
    $educators = $this->ion_auth_model->available_educators($Curricula_Id);

    foreach($educators as $educator):
        $Educator_Id = $educator->Educator_Id;

        for($i=0; $i < 8; $i++):
            $Date = strtotime("+$i week", strtotime($Preferred_Start_Date));
            $Class_Date = date("Y-m-d", $Date);

            $this->data['class_dates'][] = date("Y-m-d", $Date);
            $this->data['weeks'][] = $this->ion_auth_model->week($Educator_Id, $Class_Date, $Preferred_Start_Time, $Preferred_End_Time)->row();
            $this->data['master_schedules'][] = $this->ion_auth_model->master_schedule_check($Class_Date, $Preferred_Start_Time, $Preferred_End_Time)->row();
            $this->data['educator_schedules'][] = $this->ion_auth_model->educator_schedule_check($Educator_Id, $Class_Date, $Preferred_Start_Time, $Preferred_End_Time)->row();
            $this->data['educator_availabilities'][] = $this->ion_auth_model->educator_availability_check($Educator_Id, $Class_Date, $Preferred_Start_Time, $Preferred_End_Time)->row();
        endfor;
    endforeach;

    $this->data['main_content'] = 'schedule_opportunity';
    $this->load->view('./_blocks/template', $this->data);
}

My model:
function educator_schedule_check($Educator_Id, $Class_Date, $Preferred_Start_Time, $Preferred_End_Time) {
    $Date = "('$Class_Date' BETWEEN Start_Date AND End_Date AND All_Day = 1 AND Educator_Id = '$Educator_Id' OR '$Class_Date' BETWEEN Start_Date AND End_Date AND (Start_Time BETWEEN '$Preferred_Start_Time' AND '$Preferred_End_Time' OR End_Time BETWEEN '$Preferred_Start_Time' AND '$Preferred_End_Time'))";

    $this->db->select("Count(*) AS Count, Title")->from('Educators_Schedule')->where($Date)->where('Educator_Id', $Educator_Id);
    return $this->db->get();
}

Answer: Something about the following for loop does not seem quite right although it is difficult for me to say for certain without using a debugger.
<?php foreach($educators as $educator):

    <?php if($week->Count == 1): echo 'Class Conflict'; endif; ?>
    <?php if($master_schedule->Count == 1): echo $master_schedule->Title; endif; ?>
    <?php if($educator_schedule->Count == 1): echo $educator_schedule->Title; endif; ?>
    <?php if($educator_availability->Count == 1): echo 'Not Scheduled'; endif; ?>

<?php endforeach; ?>

I see that you are looping over the educators, but what I don't see is the current educator actually changing within the iteration.  You do not appear to be moving through the $week, $master, $educator_schedule, and $educator_availability arrays.  Instead you may be accessing the same element in each of those arrays.
In other words, consider two arrays.  You loop over one array as such:
 <?php
     foreach($foos as $foo):
         echo $bar;
     endforeach;
 ?>

All that you would do in that loop is print out the value for $bar for each element of $foos.
Instead you need to access the elements of your $week, $master, $educator_schedule, and $educator_availability according to the educator being referenced in a particular iteration of the for loop so something that functions as:
<?php foreach($educators as $educator):

    <?php if($week[$educator]->Count == 1): echo 'Class Conflict'; endif; ?>
    <?php if($master_schedule[$educator]->Count == 1): echo $master_schedule->Title; endif; ?>
    <?php if($educator_schedule[$educator]->Count == 1): echo $educator_schedule->Title; endif; ?>
    <?php if($educator_availability[$educator]->Count == 1): echo 'Not Scheduled'; endif; ?>

<?php endforeach; ?>

Which will not work with the code in its current state, but may point you in the right direction.
Lastly, I am a little concerned with how you are controlling the order of elements returned from your database queries.  Most of the time, your results will come back in the same order, but it might help for clarity and sanity if you add an order_by clause to some of your queries so that you can be sure that your results are properly correlated.
Comment: Thanks for the response Joel. I agree, that is what is happening. Within my controller, the educator id gets passed correctly. I will have to work on correcting this in my view. Also, thanks for the advice on the order_by clause. Good idea.


How to set environment variable in .NET systemd service?

Question: I have virtual machine of Linux with Ubuntu 18. When I am running this command
sudo systemctl start myservice.service

Getting error
● myservice.service - dummyservice in .NET Loaded: loaded (/lib/systemd/system/myservice.service; disabled; vendor preset: enabled) Active: failed (Result: exit-code) since Tue 2020-05-26 23:53:20 IST; 10min ago Process: 3634 ExecStart=/usr/bin/dotnet /home/linux/bin/Downloads/myservice.dll (code=exited, status=1/FAILURE)

May 26 23:53:19 arvind systemd[1]: Starting myservice in .NET... May 26 23:53:20 arvind dotnet[3634]: The user's home directory could not be determined. Set the 'DOTNET_CLI_HOME' environment variable to spec May 26 23:53:20 arvind systemd[1]: myservice.service: Control process exited, code=exited status=1 May 26 23:53:20 arvind systemd[1]: myservice.service: Failed with result 'exit-code'. May 26 23:53:20 arvind systemd[1]: Failed to start myservice in .NET.

How can I set environment variable 'DOTNET_CLI_HOME' environment variable to spec ?
Comment: Might help -- https://blog.jongallant.com/2018/09/solution-users-home-directory-could-not-be-determined/
Comment: @Liso - In that workaround, they didnt mention where to do that. In Windows OS or in Virtual Linux machine or in .Net project?
Comment: You need to set the env of the user running the 'myservice.service' process.
Comment: @AndreasF - How can I do that?
Comment: https://help.ubuntu.com/community/EnvironmentVariables
Comment: @AndreasF - If you can edit your answer and add like how to env to user and to /temp path. That will be very nice. I am very new to Ubuntu.
Comment: You may find the information here useful: [How to run a .NET Core console app as a service using Systemd on Linux](https://swimburger.net/blog/dotnet/how-to-run-a-dotnet-core-console-app-as-a-service-using-systemd-on-linux) and also [How do I make my systemd service run via specific user and start on boot?](https://askubuntu.com/questions/676007/how-do-i-make-my-systemd-service-run-via-specific-user-and-start-on-boot). However I can't help feeling that this is something you should be running as a [systemd user service](https://wiki.archlinux.org/index.php/Systemd/User)
Comment: @AndreasF won't work for SystemD units, the envs need to be defined by the app running OR by `Environment=` declaration with all the env vars available.
Comment: @steeldriver - Thank you. That issue has been solved.
Answer: When using SystemD, you can define environment variables inside your unit. (this is per the SystemD docs on service files and declarations and configurations.)
Example syntax:
[Service]
...
Environment=VARNAME=VARCONTENTS

So in this case, try adding Environment=DOTNET_CLI_HOME=/temp to your Service declaration in your service file.  Then run your typical:
sudo systemctl daemon-reload
sudo systemctl start myservice.service

which should then utilize the newer setup/environment variable as defined in SystemD.
Answer: There is couple ways to set an environment variables in Linux, and you can apply for Ubuntu.
1) Using export
export NAME=VALUE

2) Editing bashrc file in $USER folder
[... Other environments variables]
NAME=VALUE

If you want to know more and go deep the difference between then, please take a minute to read https://www.geeksforgeeks.org/environment-variables-in-linux-unix/
Comment: This may work for *normal* environment variables, etc. but this will NOT apply for SystemD units which are all run independently AND can be run as separate users in chroots, etc.  For this, you have to go the SystemD route of defining environment variables for the service - see https://www.freedesktop.org/software/systemd/man/systemd.service.html


Is Bluetooth smart supported? If so, how; if not yet, when?

Question: I've seen a couple of questions relating to users wanting to use their Logitech MX Anywhere 2 Bluetooth mouse with Ubuntu. I am in the same boat. I eagerly awaited the release of Ubuntu 15.10 because there had been some advice that our mouse would be supported in this release. Unfortunately I can't find that it is. Perhaps I'm doing something wrong -- any suggestions? Perhaps it's coming later? If that's the case, which release are we looking to now.
Thanks very much,
Dave
Answer: BlueZ 4 (ubuntu bluetooth manager) version on earlier versions of Ubuntu didn't have support for Bluetooth Smart and therefore Logitech MX Anywhere 2 mouse couldn't work but Ubuntu 15.10 comes with BlueZ 5.35 version that supports Bluetooth Smart and Logitech MX Anywhere 2 mouse should work on Ubuntu 15.10.
Comment: On my new install of Ubuntu 15.10, my new Logitech MX Anywhere 2 mouse is not even found during Bluetooth search. Under version 15.04 the mouse was found and prperly identified; but as you say, not supported under 15.04. Please if you canhelp me figure out how to make this work, I'd be grateful -- for me, it doesn't "just work out-of-the-box."  Thanks for any constructive suggestions.
Comment: You can try and install `sudo apt-get install blueman`, (Blueman Bluetooth interface) an app that manages bluetooth and try with it or try using terminal.
Comment: Type `bluetoothctl` in to the terminal where you'll get an interface to interact with Bluetooth devices. Type `help` to get a list of commands and what they do. The command that you'll want to use first for pairing the MX Anywhere 2 is the `scan` command. If you type `scan on`, your computer will start searching for Bluetooth devices.
Comment: While in this mode, put your MX Anywhere 2 in to pairing mode and wait for it to show up in the console. It will show up something like this: `[NEW] Device XX:XX:XX:XX:XX:XX MX Anywhere 2 (The name may not be accurate)
` The "XX:XX:XX:XX:XX:XX" string is the MAC address of your MX Anywhere 2. To pair it and connect it, type: `pair XX:XX:XX:XX:XX:XX` `connect XX:XX:XX:XX:XX:XX` Make sure to change all the "XX:XX:XX:XX:XX:XX" to the MAC address you got when scanning.
Comment: The answer and guide is taken from this post http://askubuntu.com/questions/636712/logitech-mx-anywhere-2-mouse-pairs-but-doesnt-do-anything
Comment: All well and good. Now the mouse is recognized and paired. But when I try to connect Bluetooth crashes. If I get Bluetooth up the mouse disconnects. So, bottom line is the mouse still doesn't work with Ubuntu. If I can figure out how to uninstall Ubuntu, I'll give fedora a try. After that, Apple . . .?
Comment: You can download Fedora from the official site `https://getfedora.org/en/workstation/`. Create installation USB using Startup Disk Creator app or write it on CD in Ubuntu and choose to install alongside or delete Ubuntu. I've seen posts  of other people using Logitech MX Anywhere 2 and it's working for them on Fedora. It's on you to try it out.
Comment: You can search for installation guides or videos online,ask in another post or ask me over chat and I'll reply as soon as i can.


Glassfish v3 + SOAP, Existing WebService not launching

Question: I didn't make the code, I'm just being asked to help find the problem. I know nothing of SOAP.
A WebService, generated from a WSDL, is running on an old Glassfish v2.
No problem, the service is exposed on both the portName and serviceName endpoints.
Then that application is moved to Glassfish v3.
Now only the portName endpoint is accessible. The serviceName is not.
Does anyone have a 5-6 step guide on fixing this.
I am not in the mood to wade thorough another 50 page Oracle document, promising to help fix problems, and then ... doesn't. I've waded through the net, in wain for too long, and are quite frankly at my wits end.
Answer: In the implementing SOAP class, add wsdlLocation to the @WebService annotation.
Remove the sun-web.xml and sun-jaxws.xml, as well as removing the listener com.sun.xml.ws.transport.http.servlet.WSServletContextListener from the web.xml.
Finally adding a basic glassfish-web.xml
<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE glassfish-web-app PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Servlet 3.0//EN" "http://glassfish.org/dtds/glassfish-web-app_3_0-1.dtd">
<glassfish-web-app error-url="">
  <context-root>/</context-root>
  <class-loader delegate="true"/>
  <jsp-config>
    <property name="keepgenerated" value="true">
      <description>Keep a copy of the generated servlet class' java code.</description>
    </property>
  </jsp-config>
</glassfish-web-app>
</code>
After that, the server now locates the services itself, and places them where the WebService annotation specifies it.


Why is my simpleDateFormat screwing up the day of the week?

Question: I am trying to parse a date. When I use the following date format:
SimpleDateFormat sdf = new SimpleDateFormat("EEEE, MMM d");

With the string "Monday, May 19", doing
cal.setTime(sdf.parse(dateString));

and pulling out the day of week in short format, I'm getting "Tue"! Cal's day of week seems to be set to 3. Any idea why? It's coming up with May for month and 19 for day, but it wants to say Tuesday for day of week, and May 19 is definitely a Monday in my locale.
Comment: Its `Tue May 19 00:00:00 GMT 1970` Try with `sdf.parse("Monday, May 19")`
Answer: The parse method's Javadocs state:

All of the calendar's date-time fields are cleared before parsing, and the calendar's default values of the date-time fields are used for any missing date-time information. For example, the year value of the parsed Date is 1970 with GregorianCalendar if no year value is given from the parsing operation.

You don't supply a year, so it defaults to 1970, and the day of the week follows.
Answer: Because May 19, 1970 was a Tuesday, and it's defaulting the year for some reason.


Download videos from youtube playlist or user based on date

Question: Can I do a date-wise download of youtube videos of particular user or playlist using youtube-dl ?
For example - download all videos uploaded by User X in this week.
Looking for provision of downloading youtube videos from a channel/user/playlist with start-date and end-date.
Comment: No its not. Do not miss the "date-wise" part.
Comment: Downloading a date range with youtube-dl is a little bit more complicated, but there is an answer about that too in a different question: http://askubuntu.com/questions/334081/youtube-dl-multiple-files-downloading/334097#334097 This answer is actually the way I usually do it myself, because I usually don't want to download some of the videos in a playlist, so I have to make a list of all the downloadable video links and then delete the links that I don't want.
Comment: This isn't a duplicate, how do I remove that ?
Can I get the video info like date of upload before triggering download?
Comment: Alright, I get it that you want to scrape the videos' date data from the YouTube website automatically, so I retracted my "possible duplicate of...". There is a package for scraping website data in the default Ubuntu repositories, so it should be possible to do it automatically.
Answer: Yes.  From the youtube-dl man page:
--date DATE
          Download only videos uploaded in this date

--datebefore DATE
          Download only videos uploaded on or before this date (i.e.  inclusive)

--dateafter DATE
          Download only videos uploaded on or after this date (i.e.  inclusive)

Not stated there, but only hidden in the code, is that DATE is in the format YYYYMMDD or
    (now|today)[+-][0-9](day|week|month|year)(s)?, so for example the 17th August 2016 would be 20160817, and seven days ago would be now-7days or now-1week.
You can specify a range by using --datebefore and --dateafter together, so:
youtube-dl -i --dateafter 20160808 --datebefore 20160810 https://www.youtube.com/channel/CHANNEL

will download all videos from a channel uploaded between and including August 8th and August 10th 2016, and:
youtube-dl -i --dateafter now-1week https://www.youtube.com/playlist?list=PLAYLIST

will download all videos from a playlist uploaded in the past week.
The -i option prevents youtube-dl from exiting prematurely if some videos are unavailable.
Note youtube-dl will still say it is downloading each video even when it doesn't. For example:
[download] Downloading video 1 of 123
[youtube] xxxxxxxxxxx: Downloading webpage
[youtube] xxxxxxxxxxx: Downloading video info webpage
[youtube] xxxxxxxxxxx: Extracting video information
[youtube] xxxxxxxxxxx: Downloading MPD manifest
[download] 2016-08-07 upload date is not in range 2016-08-08 - 2016-08-10
[download] Downloading video 2 of 123
...

Answer: Maybe your looking for this solution to sync a playlist or channel.
youtube-dl -o "%(title)s.%(ext)s" -x --audio-format mp3 --audio-quality 0 --download-archive Filename.txt https://www.youtube.com/playlist?list=PLAYLIST


Error: The system is running in low-graphics mode in Ubuntu 14.04 Samsung np270e4e-k05mx

Question: I'm trying the distribution Ubuntu 14.04 and when I start sometimes appears the error 'The System is running in low graphics mode', so I reboot and if I am lucky it will start normally but is annoying be doing that, so what I can do?.
My computer is a Samsung np270e4e-k05mx
http://www.samsung.com/mx/consumer/monitor-peripherals-printer/ultra-mobile-pc/ativ-book-performance/NP270E4E-K05MX
Screen:
LED HD de 14" (1,366 x 768), antirreflejante
Graphics:
Intel® HD 4000
I put the features of the screen because I think is in it the problem.
I'm a beginner on Ubuntu, so i don't know what the problem is, but I tried some of the solutions in other questions, how to reinstall the ubuntu-desktop or sudo apt-get install fglrx, but it didn't work.
Comment: yes, I have read it, but I hadn't tried all the responses, I find the solution doing this:

ctrl + alt + f1
sudo apt-get install gdm
choose gdm
sudo reboot

and I got login without the error :D

but  I miss lightdm graphic ambiance :( nah finally it doesn't matter.

thanks it was very usefull to me.
Comment: Did you read this http://askubuntu.com/questions/141606/how-to-fix-the-system-is-running-in-low-graphics-mode-error or this http://askubuntu.com/questions/196382/system-in-low-graphics-mode ?
Answer: OP's own answer:
I found the solution doing this: ctrl+alt+f1
sudo apt-get install gdm

choose gdm
sudo reboot

and I got login without the error


iOS - top cells moved up away from the screen when keyboard shows

Question: Here is before the keyboard shows:

Here is after the keyboard shows:

Here is what I want:
If there are enough messages, when move all of them up. If not, like shown in these two images above, then do not move the messages up.
What should I do?
By the way, I use Swift.
Thank you so much!
Comment: how much have you tried?
Comment: use `contentInset`
Comment: I used the IQKeyboardManager and that's all I had done.
Comment: Can you provide us your code/storyboard so we can see how you declare your interface?
I think that you need to remove the constraint to the bottom but I don't know what is your implementation
Answer: Because i can't add a comment. so i had to help you in this way.

You can provide us more information about table view's constraint. because if you listening keyboard notification and change constraint, maybe will become like this
If you use frame property to build this, the same point with first
You can run project and use xcode's Debug view hierarchy tool, to check tableview's state. check it's because table view's frame change and be clipped or you change table view's contentInset or other properties to made it ,like this


What is the algorithm used for phong shading normal interpolation?

Question: Let's suppose we have an object consisting of only 3d points, and triangle faces that each take a subset of these 3d points. How can I interpolate the normal vectors to get that Phong smooth shading? The actual algorithm seems impossible to find yet everybody is doing it.
There is one post on here, but I still have no idea how to implement it: Normal Interpolation for Phong shading
Also, it seems wrong to me that this supposed formula only takes in account two normals. What if you have a triangle surrounded by 3 other triangles? Then how do you blend the normals?
Comment: Refer to: "Weights for Computing Vertex Normals from Facet Normals". Generally you walk over all triangles that share a vertex and use all of the adjacent triangle  normals to compute the normal at that vertex. To achieve this you can walk over all triangles and add their normals to their 3 adjacent vertices (with a weight). More generally you can create a structure which for each vertex lets you iterate over the triangles that share it.
Comment: Also worth pointing out the interpolated normals need renormalising per pixel.
Comment: @lightxbulb exactly what I was looking for, thank you! I can't upvote comments yet but otherwise I would have.
Answer: I am going to assume that you have the normals available for each point and that your vertex pass don't do this for you. For every pixel you will have an intersection point $p$ that exists on the nearest triangle surface defined by 3 points $p_i$, $p_j$ and $p_k$ with corresponding normals $n_i$, $n_j$ and $n_k$. Phong shading is the normalized interpolated normal, which can be found by:

Computing the barycentric coordinates of $p$, (look at (https://github.com/Jojendersie/gpugi/blob/5d18526c864bbf09baca02bfab6bcec97b7e1210/gpugi/shader/intersectiontests.glsl#L63) in the function "IntersectTriangle"). Note that the order is important such that your coordinate values $u$, $v$ and $w$ has the same order as your points.

Interpolating and normalizing: $\frac{un_i + vn_j + wn_k}{|| un_i + vn_j + wn_k ||}$.

???

Profit!
Answer: EDIT: I misunderstood your question, so please disregard this answer.
The Phong shading model assumes a surface normal $\mathbf{n}$ at the shading point $\mathbf{x}$ but it is independent of its type, so either the shading normal or the geometric normal will work. Moreover, this reflectance model requires an incoming and outgoing directions. In that sense, you can't just "interpolate the normals" to get the desired effect since you need to take into account the positions of the camera and the light, as well as the roughness parameters.
The (normalized) Phong BRDF is a sum of a diffuse and specular term:
$$
f_r(\mathbf{x},\omega_i,\omega_o) = \frac{\rho_d}{\pi} + \rho_s \frac{n+2}{2\pi}\max(0,\cos^n\alpha),
$$
where

$\rho_d$ is the diffuse albedo, i.e. the fraction of the incoming energy that is reflected diffusely,
$\rho_s$ is the specular albedo, i.e. the fraction of the incoming energy that is reflected specularly,
$n$ is the Phong exponent; higher values yield more mirror-like specular reflection, and
$\alpha$ is the angle between the perfect specular reflection direction $\omega_r$ and the outgoing direction $\omega_o$.

You can compute $\omega_r$ from the surface normal $\mathbf{n}$ and the lighting direction $\omega_i$, which is just
$$
\omega_r = 2\mathbf{n}(\mathbf{n}\cdot\omega_i) - \omega_i.
$$
Typically you pick the albedos such that $\rho_d + \rho_s \leqslant 1$ to conserve energy.
Comment: He is talking about Phon shading, not the Phong brdf: https://en.m.wikipedia.org/wiki/Phong_shading
Consider editing your answer as it is currently misleading.
Comment: I don't see how this formula makes creased edges appear to smoothly blend into its neighbours, aka phong normal interpolation (I'm not confused with gouraud interpolation)
Answer: A possible way is using bilinear interpolation. Assuming you know the normals at the triangle vertices, when doing a raster-scan conversion, you intersect the triangle projection with horizontals and each time obtain two intersection points. Then you fill the segment between them with further interpolated data.
So interpolation takes place first between triangle vertices, then between intersection, and in both cases a linear interpolation can be used. Anyway, the resulting vector should be normalized to unit norm in order to apply Phong's model.

Note that as the first interpolation is done between two vertices, the continuity of the normal vectors is implicitly guaranteed along edges common to two faces.


Does mirror like wallpaper suitable for a mini dance studio at home exist?

Question: I live on my own and because I'm a dancer I want to use one of my spare rooms as a good rehearsal space. What I want to do is cover at least one of my walls there in a mirror-like wallpaper or something so that I can see my reflection really well. I can't afford a lot at the moment. I cant buy a huge mirror because they're expensive so I was thinking about a huge mirror sticker.
Answer: You can get chrome mirror finish vinyl (with a self adhesive backing). To get an effective mirror effect on a wall though, the wall would need to be very smooth, or it would easily show distortion - think a "hall of mirrors" type effect.
Signwriter suppliers would be the place to look for it.


Windbg !address command result

Question: Using Windbg, we can find some info about an !address. One of the info us Usage.
What is the difference between: RegionUsageIsVAD, or RegionUsageHeap.
Answer: Please check out this article which describes those stats. Basically, RegionUsageIsVAD is details about virtual memory allocations. Whilst RegionUsageHeap is information about allocations in the heap.
Comment: Concluding, RegionUsageIsVAD stands for virtual allocs and  RegionUsageHeap for heap allocs.

Windbg !address command result


Morph Targets Normal adding math

Question: I am trying to verify that if I have my inNormal and some N amount of morph normals that I would want to do something such as
outNormal = vec3(inNormal);
outNormal += morphNormal0 * morphWeight0;
outNormal += morphNormal1 * morphWeight1;
...
outNormal += morphNormalN * morphWeightN;

This seems to work for me (don't have a ground truth to compare) so I wanted to test it in Three.js knowing it would have an established method and I see they use
objectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];
objectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];
objectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];
objectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];

So now I am wondering how that math works out as it doesn't work for me. Both methods end up multiplying it by a normalMatrixso not sure what would be different.
edit: Assuming both are loading in glTF 2.0 models
Comment: In your method, is morphNormalN a delta or the actual normal to morph towards?
Comment: @bram0101 the spec says "deviations in the Morph Target" and looking at the data it looks like morphNormal0 a delta, not the "new normal" of the morph target position
Comment: Actually I realized I never checked if they altered the morphNormals prior to this
Answer: It would seem that, in the second example, the morphNormals are targets while in in the first they are deltas.
This explains the difference in math used between the two pieces of code.

Morph Targets Normal adding math


React native inaccurate device width division question

Question: i've come across a problem trying to create a grid by dividing the device width.
When trying to make 7 Views next to each other in a row by doing Dimensions.get('window').width / 7, it calculates only 6 in a row and because the parent container has flex: wrap, it drops the 7th View in a second row. This only happens on iPhone devices specifically iPhone X (12.1), it calculates it perfectly on iPad. Am i missing something in the calculations or is it a known issue?
Comment: Please add your .js code
Answer: i'think doesn't use width/7 use this
<View style={{flex : 1}}>
        <View style={{ flex: 1 }} /> //7x
      </View>

or use react-native-grid and
<Grid><Row/></Grid>


start MooTools Events Calendar next month

Question: i'm using this calendar http://dansnetwork.com/mootools/events-calendar/usage/. I can't understand how can i start this calendar for next month, if current month is august, i want to start it for september.
What i've tried:
    var date = new Date();
    var d = date.getDate();
    var m = new Date(date.getMonth() +1 );
    var y = date.getFullYear();

 $('#calendar1').fullCalendar({
      editable: true,
      events: [
        {
          title: 'All Day Event',
          start: new Date(y, m, 1)

but it does not work.
Thanks.
Answer: Looking at the source it doesn't seem like there is an option to explicitly set which month to show initially. There is however the newDate option which allows you to set the initial selected date, which I'm guessing would work as far as showing the month you want.
http://dansnetwork.com/mootools/events-calendar/source/  (line 22)


Boolean operation initiation in a Matrix application

Question: Given a function taking input matrix $A$ and $B$. The function only returns True if $A$ and $B$ are both vectors (either coulomb or row vector.) Is the following right?

if (numRow(A)!=1 and numCoulomb(AB)!=1) or (numRow(B)!=1 and numCoulomb(B)!=1):
return False
else: return True.

I felt the above somewhat non-intuitive, do the above logic seems intuitive to you? Or you need to use certain methods to figure them out or take some time doing trial-error to figure it out. Very confused.... Appreciate any help!
Answer: Assuming the $AB$ in your first clause is meant to be $A$, this is correct and a natural way to express this. You're just saying "if $A$ is not a vector and $B$ is not a vector" and expanding "not a vector" into "has neither one row nor one column." Regarding the methodology, what I just did is all I ever do: express the statement in natural language and break it into pieces small enough to translate into formal logic. If this isn't easy for you, then of course trial and error usually works for small Boolean problems.
Comment: Thank you. I just have troubles doing this even in natural language... Maybe its because English is not my first language, or maybe it is because of my OCD.... Thank you:-)


how do you copy a directory and its contents to a new location under a new directory name?

Question: I'm new to the Linux command line and am trying to get to grips with the copy command at the moment.
Can anyone please tell me if it's possible to copy a directory with its subdirectories and associated files to a new directory with a new name, e.g. directory_backup?
Thanks for any and all help in advance.
Answer: You can use cp with the -r (copy recursively) flag and specify the new directory name:
cp -r /path/to/directory /path/to/location/new-name

In the above command replace the given paths with the real ones.
For example, to copy stuff from my home directory to an existing directory named backup and name the new directory stuff-backup (if this directory already exists, note that stuff will be copied into it, not overwrite it), you run:
cp -r ~/stuff ~/backup/stuff-backup

~ is a shortcut for your home directory /home/$USER or /home/zanna in my case. You can omit it if the current working directory is your home directory - you can see this from your prompt
zanna@monster:~$
              ^--the ~ here is where I am - home!

You can add the -v (verbose) flag to make cp report each copy being performed:
$ cp -vr stuff backup/stuff-backup
'stuff/thing1' -> 'backup/stuff-backup/thing1'
'stuff/thing2' -> 'backup/stuff-backup/thing2
...

Comment: Sorry Zanna. I'll put your advice into practice and see how I go. Like the idea of the verbose flag . assume this will also work as a report while other command are being worked.. Cheers.
Comment: @Edmuntu sorry for what? Yes, lots of commands have a `-v` or `--verbose` flag :)
Comment: sorry for initial short" thank you"....hit return key in error.
Answer: The command you need is simply cp which stands for "copy".
You can use it for example with one of these syntaxes:
cp SOURCEFILE TARGETFILE
cp SOURCEFILE TARGETDIRECTORY

The first variant allows you to specify a new file name for the target file, while the second variant creates a copy with the same name in the target directory. You must of course substitute the place holders in capital letters with valid paths first.
However, cp by default operates on files only, not on directories. To get it to copy a complete directory with all its content recursively, you must add the -r option:
cp -r SOURCEDIRECTORY TARGETDIRECTORY

You can learn more about the cp command by typing man cp in your terminal.
Comment: Not used to this comment section Byte Commander...keep hitting return to change line but post instead. Very clear outline in your answer . Look forward to sorting out those directories now that I've been given good instruction on the correct usage of the available tools. Excellent.
Comment: @Edmuntu In the future, use SHIFT+ENTER while commenting to go down a line.
Comment: @OwenHines Just that comments strip any linebreak and additional whitespace and having them in the editor doesn't change anything in the result.
Comment: @ByteCommander Oh right, nevermind. Well, now he knows.
Answer: You can use the below command to copy directory from one place to another sub directory.
cp -Rvp /home/edmuntu/data /home/edmuntu/mydata/

Explanation of command:

-R = copy directories recursively
v = explain what is being done
p = It will help your to preserve your permission and ownership with timestamps
Comment: Thank you @Rakesh Chauhan."preserve your permission and ownership with timestamps" ??? Wow....I need to get to it!!!! Yet another aspect of line commands to be explored. Thank you for your reply.
Answer: As an alternative to the generally useful cp command you can use rsync which has the added benefit of replicating the permissions/timestamps of the original directory structure:
rsync -av dir/ newdir

-a archive
-v verbose
note the slash after the source dir.
Comment: This is much better than copy as it also copied the permissions
Comment: Had huge issues with rsync. cp -Rvp with a . after the directory to copy is working well for me (the . will copy hidden files/foders).  And @HelloUniverse - if you use the p command with cp, it preserves permissions, ownership, timestamps
Answer: cp is the command that does the function that you're looking for. It stands for copy and it does just that. The command that would work for you in this situation is
cp -R source/ destination/
This would copy the source/ folder and all of its sub-directories to destination/.
If destination/ doesn't exist, it will be created.
The -R flag stands for recursive, which tells cp to copy all sub-directories.
Comment: @Edmuntu Glad I could help, if you found the solution to your issue, can you please mark the answer that worked for you as the correct one by clicking the check mark under it? This will help alert others who view the page of the question being solved.
Comment: Thank You@Owen Hines. Sound like this is definitely the command for my task.Cheers
Answer: I find it easier to change to the directory I'm copying from first. For this example change to a directory everyone has called /boot. Anyone can copy and paste the commands below into their Terminal.
cd /boot
sudo mkdir /boot_backup
sudo cp -r . /boot_backup
du /boot_backup -h

752K    /boot_backup/extlinux/themes/debian-wheezy
756K    /boot_backup/extlinux/themes
832K    /boot_backup/extlinux
2.5M    /boot_backup/grub/i386-pc
20K     /boot_backup/grub/locale
2.3M    /boot_backup/grub/fonts
7.2M    /boot_backup/grub
565M    /boot_backup

For the cp command the current directory is identified as . which is the /boot directory we changed to. The -r option makes it recursive to include all sub-directories.
To ensure it worked run du to list all sub-directories and total file sizes in the new directory /boot_backup in this case.
After finishing this walk-through, use: sudo rm -r /boot_backup to remove the new directory and it's sub-directories.
Comment: While this does explain how to copy all files from your current dir to another dir, it doesn't fully answer OPs question on how to copy a dir (and its contents) to a different name dir. There are shorter commands (such as `cp -r`) which will take care of creating a new directory and copying all files into it
Comment: It does explain how to copy and dir and it's contents--the difference is it changes to the source directory first as a precautionary habit. `cp -r` as you recommend is already on the third command line. The tutorial is based on the fact everyone has a `/boot` directory and can try this on their own machine. Had I used `cp -r /home/GroundZero/Documents /home/GroundZero/Documents_backup` readers could not copy and paste into their terminal--they would have change `GroundZero` creating more work and chances for error. I hope you appreciate the KISS of this answer with an embedded tutorial.
Comment: @GroundZero doing a `cd ~/Documents/SomeObsucreFolder/2016/Nov/` to set current directory as source directory will change the Terminal prompt to ensure it is spelled correctly and then using `cp -r .` as the source eliminates retyping the source directory. It is simply what I consider a good habit. Additionally once changing to source directory it's easy to do `ls FIleName1`,  `ls FileName2`, etc. to esnure the files you want to backup are there without having to repeat the source directory name for the `ls` command.
Answer: You generally want to keep the file permissions the same when making a copy, not a new set of default creation permissions. That means use -a flag for cp.
cp -a file filenew

Comment: I think this is the best answer. From the manual: `-a` is the same as `-dR --preserve=all`


How can I install this programmable switch where a neutral is not present?

Question: I'm trying install this programmable switch but the instructions do not match reality. The instructions refer to the existence of a black (load) cable and a white (neutral) cable supposedly coming out of the wall, but instead I have two black cables and a naked wire. Is the naked wire the equivalent of the white in the diagram?
Comment: Possible duplicate http://diy.stackexchange.com/questions/24926
Comment: Is there a unfurnished space above the wall where the switch is located?
Answer: The naked wire is the ground (sometimes colored green) and is not the same as the neutral.
Your particular installation requires a neutral so that the switch can be powered without sending power to the load.  If there is no neutral in your electrical box it means that the power source (line) does not come into that box and instead you are just switching the hot from another source.  A traditional single-pole single-throw switch only switches the hot so it does not need the neutral.  There might be one behind the switch, it will have a wire nut on it and be connected to all the other neutral wires coming into the box. If present you should use this and not the ground.
If there is no neutral then unfortunately, you cannot install this type of switch in this location without running a new cable.
Comment: On a side note. NEC 2011 added section 404.2(C) to article 404, which requires a neutral at each switch outlet unless there is the possibility of *easily* adding one in the future.
Comment: As the instructions cited in the question noted, the neutral wire(s) should always be white.  The neutral wires that Steven suggested might be behind the switch would be white.


LESS variable changes depending on context?

Question: I'm trying to set the shorthand font value (related question), but the variable I'm using for line-height is behaving weirdly; as if the variable is re-interpreted each time.
This is in LESS version 1.4.2
<code>.info {
    @infoHeight: 22px;
    @infoTopPadding: 2px;
    @infoLineHeight: @infoHeight - @infoTopPadding;
    margin: @infoLineHeight;
    font: bold 13px~'/'@infoLineHeight Arial, sans-serif;
}
</code>
Results in:
<code>.info {
    margin: 20px;
    font: bold 13px / 22px - 2px Arial, sans-serif;
}
</code>
So the same variable results in two different values depending on context. Is this intended behavior or could this be a bug?
Answer: in Less >= 1.4.0 you need to use math operations in brackets by default (thats's by design, but can be changed in the Less settings). Your code would work perfectly fine in older versions of Less.
So if you write in Less:
<code>.info {
    @infoHeight: 22px;
    @infoTopPadding: 2px;
    @infoLineHeight: (@infoHeight - @infoTopPadding);
    margin: @infoLineHeight;
    font: bold 13px~'/'@infoLineHeight Arial, sans-serif;
}
</code>
the CSS output becomes:
<code>.info {
  margin: 20px;
  font: bold 13px / 20px Arial, sans-serif;
}
</code>
I hope this is your desired/expected outcome.


Files are listed as wrong size in 12.04

Question: Hi all got a weird situation here.  The other day I noticed when I wanted to seed a file for an older torrent, that the file size was wrong on my computer.  The torrent said the file was say 450 mb, but when I went to look for the file, it was listed as say 480 mb! Bigger by maybe 10%.
This was just weird, but turned out to be a big pain in the butt because I made a vdi file for virtualbox at a fixed size of 15.8 gigs, and now it is listed as 17 gigs on Ubuntu!  Which means I can't put it on the 16 gig memory stick I have!
(And yes, the memory stick has enough room for 15.8 gigs on it, in case anyone is wondering)
So, this is not the end of the world, I just have to buy a 32 gig stick now, but I am like WTF you know??  What gives as the kids say.
All other sources of information are consistent, and therefore Ubuntu is wrong. The website says the file is 450, the torrent file and the torrent client all say the file is 450. Virtualbox says the file is actually 15.8 gigs, it even handily provides an "actual size" value which says...15.8 gigs!
Only Ubuntu is giving these larger numbers. Therefore Ubuntu is wrong.
Why, dear goddess why??
Answer: You need to be careful with dealing with file/disk sizes. Some systems/applications/advertisements use a base-10 measurement (so 1 K bytes is 1000 bytes) whereas others use a base-2 like system (so 1 K bytes is 1024 bytes) and some use a weird mixture ( 1 K is 1024 bytes but 1 M is 1024000).
See http://en.wikipedia.org/wiki/Mebibyte
Comment: yeah I noticed a discussion about that.  But it doesn't help me here. Ubuntu is apparently not using the same system as *everyone else*.
Comment: That is true. But this has been a problem for decades. I was once asked to set up a drive into 512MB partitions (circa 1994). I later learned the user was very frustrated because he could not completely backup the partitions onto his 512MB tapes. Part of the problem was they used different measurements.The other problem is that overhead of file system layout was not accounted for. [Think of 1.44MB Floppy Disk iff using MS-DOS, but 1.4MB iff using Mac, 2.0MB iff unformatted] Trying to size things for a perfect fit is very difficult.
Comment: Ok you are right, I thought about it and the increase is basically right.  Frustrating for sure, and I could have sworn my work ubuntu, also 12.04, doesn't do this. I will check that soon, is it possible that two different installs would have different results?
Comment: First, here is a longer post on the subject: http://askubuntu.com/questions/465/is-it-true-that-ubuntu-will-no-longer-measure-file-size-unit-as-byte-megabyte
Comment: Wow. So all ubuntu over a certain vintage...actually this might make sense, at work we have two comps with 10.04 and I think on those computers the number for that vdi file are "right". So 12.04 already does this but 10.04 perhaps does not.

Files are listed as wrong size in 12.04


How to decide the level of multiple level paging

Question: Given a computer system with a 64 bit virtual address and 8 byte per page entry, let the physical address be of 48 bits, and the system is "byte-addressable". Assume that every page is of 4KB. Then:
I known the maximum number of frames = 2^48/2^12 = 2^36.
But suppose that we have multi-level paging. How many levels do we have in multi-level paging?
Thanks in advance!
Answer: There's not enough information to decide that. You could theoretically have one single level table with 2^36 entries. You could also have a 36-level setup with each table only containing 2 entries. Current designs typically use between 2-4 levels...
Comment: Ya. That's what bothers me. I found this question from my OSC past final exam and it didn't have answer. So according to your answer, there is no clue in the question to decide how many levels...No matter what, I really appreciate your response.
Comment: If that's the extent of the information, yes, it's underspecified. However, it's entirely possible that they're looking for "propose a specific solution and prove that you are capable of thinking through the details and evaluating the tradeoffs" - a question that would have several "right" answers, as long as you prove you have mastery of the concepts involved....
Comment: Got it. For multi-level paging, I know that it is to reduce the page table size in memory. Think about it if there are 2^36 entries and one for 8 bytes, then we may need extremely large memory space. But it also has disadvantage that we need more than one time memory access which will reduce the performance of effective memory access time. Finally, thanks again for your information and help. ^^


ObjectDataSource Update method with dynamic parameters

Question: I have this DataTable that has a varying set of columns except for a sequence number.
| Sequence | Value | Tax | Duty | Total |
Any number of columns should be accepted with unique column names.
To display that table, I need to use an ObjectDataSource mapped to a presenter class with a Select method.
class Presenter {
    [DataObjectMethod(DataObjectMethodType.Select)]
    public DataView GetDutyAndTax() { ... }
}

The ObjectDataSource is then bound to a GridView with AutoGenerateColumns set to true. Sequence is the data key.
So far, that works for selecting the table. The problem comes when I need to update the table. The ObjectDataSource keeps nagging me to have an update method with the exact same parameters with that of the columns in the table.
public void EditDutyAndTax(string Value, string Tax, string Duty, string original_Sequence) { ... }

But I can not create a method like that because I don't know the set of columns needed.
I tried using a method with variable parameter list but it doesn't want to use it.
public void EditDutyAndTax(params object[] values) { ... }

On idea I have now is to create a set of update methods like this in Presenter:
public void EditDutyAndTax(string value1, string original_Sequence) { ... }
public void EditDutyAndTax(string value1, string value2, string original_Sequence) { ... }
public void EditDutyAndTax(string value1, string value2, string value3, string original_Sequence) { ... }
//an so on...

But I neither think that's gonna get through code review nor like the idea.
The other idea I have is to create a dynamic method and attach that (if possible) to the Presenter class or wherever at runtime, but I'm not really sure if that would work.
So if you guys have any solution, please help. Thanks so much!
Carlos
Answer: It sounds to me like you're going to have to scrap using the ObjectDataSource declarative model, and go to the "old-school" setting of the datasource & binding the grid manually in postback (or load, as the case may be), and then handling edit/update manually as well.
The DataSource objects are very particular about how you use them - and don't work well, if at all, if you try to go outside the lines.


Alone Amidst the Stars - Finding the original star system after warping to 10+ star systems?

Question: How do I figure out how to find the original star system (or even if that is necessary) to continue one of the main quests, Alone Amidst the Stars?
The game says my next objective is Triangulate your position: place second space beacon.
Comment: Quests can be reset, all explored stars can be seen in Journal/Map and if you find something exceptional - mark it with the base.
Answer:
Press Escape to make sure the quest is selected.
While in flying in space, press m for the star map.
The star system will have a red and white icon on it.

I don't know how this would work for someone who has gone considerably more than my 37 light years however.
As a reminder press z and use the signal booster to get the triangulate position option.
Comment: Would also add that a quest can be reset is the destination is too far away. i had the Cadmium quest reset because the selected Red Star was too far away and the First Traveller mission where you search a crashed freighter can lead to an already visited one making the mission impossible to complete, i've read that if you go into a Black Hole you can end up far enough away to give you the option to reset