text:
Q: Select columns based on the current column selected (SQL) QUERY 1
WITH CUST1 AS
(SELECT CUSTOMER_ID, TYPE FROM CUSTOMERS WHERE CONDITION),
    CARS1 AS
(SELECT * FROM CARS INNER JOIN CUST1 ON
    CUST1.CUSTOMER_ID = CARS.CUSTOMER_ID AND
    CUST1.TYPE = CARS.TYPE) select * from CARS1;

CUSTOMERE TABLE
    CUSTOMER_ID ||    TYPE
    ------------||  -------
    1           ||     5
    2           ||     5
    3           ||     2
    4           ||     2

CARS TABLE
CAR_ID  ||  CUSTOMER_ID  ||   TYPE   ||   SN   ||  DATE
------- ||  ------------ ||   ------ ||  ----- || -------
1       ||  1            ||    5     ||  0123  ||  02/06/1999
2       ||  1            ||    2     ||  2365  ||  03/08/1999
3       ||  1            ||    3     ||  5156  ||  03/02/1999
4       ||  3            ||    1     ||  8651  ||  03/03/1999
5       ||  2            ||    5     ||  2555  ||  03/09/1999
6       ||  2            ||    2     ||  8562  ||  03/18/1999

QUERY 1 result
CAR_ID  ||  CUSTOMER_ID  ||   TYPE   || SN    ||  DATE
------- ||  ------------ ||  ------  || ----- || --------
1       ||    1          ||     5    || 0123  || 02/06/1999
5       ||    2          ||     5    || 2555  || 03/09/1999

The above query joins the temp table "CUST1" with an actual table "CARS" on the columns CUSTOMER_ID and TYPE.
Now, what I am hoping to achieve is to select the DATE AS DATE2 and SN AS SN2 from CARS which belong to the customer where
the CARS.TYPE = 2 for CUSTOMER_IDs resulted from the JOIN condition.
However, the dilemma is that I don't want to rejoin/use a sub-query since the CARS table is very big.
Please ignore the temp table approach as it's used in the rest of the code for other reasons.
The current column would be CUSTOMER_ID and the other two columns based on that CUSTOMER_ID will be SN and TYPE.
Expected results
CAR_ID  ||   CUSTOMER_ID  ||   TYPE  || SN    ||  DATE      || DATE2       ||  SN2
------- ||   ------------ ||  ------ || ----- || --------   || -------     || -----
1       ||      1         ||     5   || 0123  || 02/06/1999 || 03/08/1999  ||  2365
5       ||      2         ||     5   || 2555  || 03/09/1999 || 03/18/1999  ||  8562

A: I think conditional aggregation will do what you want.  I'm not sure what the actually logic is, but it seems to be along these lines:
SELECT CAR_ID, CUSTOMER_ID, 5 as TYPE,
       MAX(CASE WHEN TYPE = 5 THEN SN END) as SN,
       MAX(CASE WHEN TYPE = 5 THEN DATE END) as DATE,
       MAX(CASE WHEN TYPE = 2 THEN SN END) as SN2,
       MAX(CASE WHEN TYPE = 2 THEN DATE END) as DATE2,
 CARS c INNER JOIN CUST1 cu
     ON cu.CUSTOMER_ID = c.CUSTOMER_ID AND
        cu.TYPE = c.TYPE
WHERE CONDITION
GROUP BY CAR_ID, CUSTOMER_ID;

A: I'm not sure you can without a join back to cars. How big is you cars table? Using my simple test, I found that I was creating a bloom filter which might be efficient enough to make the query perform. Why not try it an see if you really have a problem? Perhaps post the execution plan. For example:
 select c.car_id, c.customer_id, c.type, c.sn, c.car_date, c2.sn, c2.car_date, c2.sn
from cars c
join cust cu
on c.customer_id = cu.customer_id
and c.type = cu.type
join cars c2
on c2.customer_id = cu.customer_id
where c2.type = 2

gives
    CAR_ID CUSTOMER_ID       TYPE SN   CAR_DATE  SN   CAR_DATE  SN
---------- ----------- ---------- ---- --------- ---- --------- ----
         1           1          5 0123 06-FEB-99 2365 08-MAR-99 2365
         5           2          5 2555 09-MAR-99 8652 18-MAR-99 8652

.
select * from table( dbms_xplan.display_cursor( null, null, 'TYPICAL' ) );

----------------------------------------------------------------
| Id  | Operation                    | Name    | Rows  | Bytes |
----------------------------------------------------------------
|   0 | SELECT STATEMENT             |         |       |       |
|*  1 |  HASH JOIN                   |         |     2 |   234 |
|   2 |   JOIN FILTER CREATE         | :BF0000 |     2 |   130 |
|*  3 |    HASH JOIN                 |         |     2 |   130 |
|*  4 |     TABLE ACCESS STORAGE FULL| CARS    |     2 |    78 |
|   5 |     TABLE ACCESS STORAGE FULL| CUST    |     4 |   104 |
|   6 |   JOIN FILTER USE            | :BF0000 |     6 |   312 |
|*  7 |    TABLE ACCESS STORAGE FULL | CARS    |     6 |   312 |
----------------------------------------------------------------


text:
Q: class or static method - python I want to understand in my case if I should use static or class method.
The idea: I'm not editing any class variable, but I'm using this variable.
example 1:
class RandClass():
   static_variable = "some rand value to static variable"

   @classmethod
   def func_that_return_string_contain_static_variable(cls):
       return "some rand string" + cls.static_variable

example2:
class RandClass():
   static_variable = "some rand value to static variable"

   @staticmethod
   def func_that_return_string_contain_static_variable():
       return "some rand string" + RandClass.static_variable

What is the best practice?

A: The best practice is most likely using example1, or an @classmethod.
In general, class methods are used when methods are specific to a class (and therefore use values from the class) without needing instantiation (and therefore a self parameter).
Static methods are generally used simply to group methods structurally - not to access attributes of the class they're in (and use them in any way).
The cls parameter when using an @classmethod will be a reference to the class it was called on, or simply RandClass when called as RandClass.func_that_return_string_contain_static_variable(). Therefore, both code blocks do the exact same thing - it's simply that using an @classmethod is preferred for this purpose, and using an @staticmethod is more of a workaround.
Hope this helps!

A: Its a question of inheritance in subclasses. Suppose I create class Rand2(RandClass):. Should it be able to override the class variable? In the classmethod case, methods on the parent class will use the variable on the subclass (if redefined in the subclass), not the parent. This is polymorphism at work - I can change what a base method does by changing a variable on the class.
class RandClass():
    static_variable = "some rand value to static variable"

    @classmethod
    def func_that_return_string_contain_static_variable(cls):
        return "some rand string" + cls.static_variable

class Rand2(RandClass):
    static_variable = "and now for something completely different"

print(RandClass().func_that_return_string_contain_static_variable())
print(Rand2().func_that_return_string_contain_static_variable())

Outputs
some rand stringsome rand value to static variable
some rand stringand now for something completely different

In the staticmethod case, the parent variable is used regardless of what the subclass tries to do.
if its important that a method always use the variable defined on the base class, then use example 2. The other 99% of the time, if you use variables on the class, use a class method and access it via cls.

redpajama_set_name: RedPajamaStackExchange


text:
Q: extract nested dataframes from complex JSON efficiently using purrr functions and %>% I'm trying to build a table similar to this (this is just a couple rows, but I'm trying to get all of the hits from a list of games):
game_pk   atBatIndex  pitchNumber   hardness launchAngle  launchSpeed  location  totalDistance  trajectory   coordX   coordY
565711    4           3             medium   2.74         76.62        9         188.03         ground_ball  177.88   145.11
565711    5           3             hard     15.42        101.26       8         328.08         line_drive   144.79   62.25

Most of what I want to extract can be found in hitData, which is in some, but not all, of 80 elements in the list playEvents, which is itself in the dataframe allPlays. You can use jsonData$allPlays$playEvents[[80]]$hitData to see an example.
Here is the code I'm using:
library(jsonlite)
library(purrr)
library(dplyr)

url <- "http://statsapi-prod-alt-968618993.us-east-1.elb.amazonaws.com/api/v1/game/565711/playByPlay"

jsonData <- fromJSON(url)

hitDataDF <- data.frame(jsonData %>%
                       map("playEvents") %>%
                       map("hitData") %>%
                       map_df(bind_rows))

Unfortunately, it returns the error:

Error: Argument 7 can't be a list containing data frames

I'm having difficulty coming up with way to to deal with the collections of lists, dataframes, nested dataframes, and vectors that are found in the JSON.
Beyond hitData, I also want data from atBatIndex, a numeric vector found in jsonData$allPlays$about (also in jsonData$allPlays), and pitchNumber, which can be found at the same level as hitData.
I'm grabbing the game_pk number 565711 from the URL and adding it to the data frame using this code:
hitDataDF$game_pk = str_match(url, '([^/]+)(?:/[^/]+){1}$')[,2]

I'm newish to R would like to write the code using %>% and map. This is my first try at at it and I'm not sure I fully understand this method. If you have a solution, could you please try to explain so I can better understand what is happening and hopefully apply it to other code if I have pulling similar data?
Any help is greatly appreciated!!
Thanks!!

A: You picked a challenging problem for your first steps with the magrittr pipe and the map functions! I'll do my best to give you a helpful answer, but I would also recommend that you find some easier data to work with as you practice. A good place to learn about the pipe %>% is with the "Pipes" chapter in Hadley Wickham's book. The chapter on iteration also offers a good intro into the map_* functions. You can return to more complex problems once you have a firmer conceptual understanding. I think Hadley explains these tools better than I ever could, so I won't go into great detail about them here, and instead focus on explaining why your code doesn't work, and why mine does.
An analysis of your code
Map functions allow a couple of useful shortcuts, one of which you've already discovered - namely, if you pass in vectors or lists as the function argument, they are automatically converted into extractor functions. So, you're on the right track!
The thing to remember is that map functions return a vector that is the same length, and has the same names, as the input vector. Your input vector is jsonData, which has 5 elements with names [1] "copyright"     "allPlays"      "currentPlay"   "scoringPlays"  "playsByInning". When you run jsonData %>% map("playEvents") %>% map("hitData"), data is being extracted, but R still returns a vector with five elements and the same names as the original vector. If you take a look at the following code, you'll see that your code is, indeed, peeling away the uppermost layers, but the length remains the same, which isn't very helpful:
> unlist(map(jsonData, class))
    copyright      allPlays   currentPlay  scoringPlays playsByInning
  "character"  "data.frame"        "list"     "integer"  "data.frame"

> unlist(map(jsonData %>% map("playEvents"), class))
    copyright      allPlays   currentPlay  scoringPlays playsByInning
       "NULL"        "list"  "data.frame"        "NULL"        "NULL"

> unlist(map(jsonData %>% map("playEvents") %>% map("hitData"), class))
    copyright      allPlays   currentPlay  scoringPlays playsByInning
       "NULL"        "NULL"  "data.frame"        "NULL"        "NULL"

The final output, and what you are trying to combine with your call to bind_rows above, is this:
> jsonData %>% map("playEvents") %>% map("hitData")
$copyright
NULL

$allPlays
NULL

$currentPlay
  launchSpeed launchAngle totalDistance trajectory hardness location coordinates.coordX coordinates.coordY
1          NA          NA            NA       <NA>     <NA>     <NA>                 NA                 NA
2        81.3       61.92         187.5      popup   medium        6              75.78             167.97

$scoringPlays
NULL

$playsByInning
NULL

Obviously that's not what you want. After some tinkering I came up with the following solution.
My own strategy
The libraries:
library(jsonlite)
library(purrr)
library(dplyr)
library(readr)
library(stringr)
library(magrittr)

I use a slightly different method to download and parse the JSON because I need to see the structure. I'll include it just in case you might find it useful:
url <- paste0("http://statsapi-prod-alt-968618993.us-east-1.elb.amazonaws",
              ".com/api/v1/game/565711/playByPlay")

url %>% read_file() %>% prettify() %>% write_file("bball.json")

jsonData <- fromJSON("bball.json")

I first extract and clean the hitData dataframes. I know they can all be found in playEvents, so I can skip a few steps by using the $ syntax. The first call to map extracts hitData from each element of the list playEvents. The hitData dataframes are nested (they contain other dataframes), so the second call to map with jsonlite::flatten flattens them. The function safely ensures that R doesn't throw an error when something other than a dataframe is encountered (only 46 elements contain hitData). Many of the hitData dataframes contain rows full of NAs, so the third call to map uses an anonymous function (again in safely) to get rid of those. The fourth call to map then extracts the dataframe from each element's result variable, which was created by safely (along with an error variable that we don't need):
hitdata_list <- jsonData$allPlays$playEvents %>%
    map("hitData") %>%
    map(safely(jsonlite::flatten)) %>%
    map(safely(~.$result[complete.cases(.$result),])) %>%
    map("result")

Now I have a list of hitData dataframes. As I mentioned above, only 46 of 80 entries contain hitData, so I need a way to get the corresponding values from atBatIndex. I can do that by generating a logical vector with TRUE when an element in hitdata_list contains a dataframe, and FALSE otherwise. I use map_lgl to return a logical vector instead of a list:
lgl_index <- map_lgl(hitdata_list, ~ !is.null(.))
atbatindex_vec <- jsonData$allPlays$atBatIndex[lgl_index]

I then use a stringr function to get game_pk from the URL. I'm not sure if it would work with every URL, but it works fine in this case:
game_pk_vec <- str_match(url, "/(\\d+)/")[2] %>%
    as.integer()

Finally, I combine atBatIndex and game_pk in a tibble, then combine that tibble with with the hitData data using bind_cols. The hitData dataframes are still in a list, so I'll need to combine those first with bind_rows. The set_colnames function is from the magrittr package and does just what it says. I need to set the column names because some compound names were created when I flattened the hitData dataframes:
hitdata_df <- tibble(game_pk = game_pk_vec, atBatIndex = atbatindex_vec) %>%
    bind_cols(bind_rows(hitdata_list)) %>%
    set_colnames(str_extract(names(.), "\\w+$"))

The only thing I didn't do was extract pitchNumber. Calling jsonData$allPlays$playEvents %>% map("pitchNumber") returns a list of sequences 1 through n, where each vector has length > 1. I assume you only need the final number in each sequence, but I'm not sure so I'll spare myself the effort. You can do what I did with atBatIndex to get the relevant elements, and then extract what you need. Here's the final dataframe:
# A tibble: 46 x 10
   game_pk atBatIndex launchSpeed launchAngle totalDistance trajectory  hardness location coordX coordY
   <chr>        <int>       <dbl>       <dbl>         <dbl> <chr>       <chr>    <chr>     <dbl>  <dbl>
 1 565711           4        76.6        2.74        188.   ground_ball medium   9         178.   145.
 2 565711           5       101.        15.4         328.   line_drive  hard     8         145.    62.2
 3 565711           6       103.        29.4         382.   line_drive  medium   9         237.    79.4
 4 565711           8       109.        15.6         319.   line_drive  hard     9         181.   102.
 5 565711           9        75.8       47.8         239.   fly_ball    medium   7          99.8  103.
 6 565711          10        91.6       44.1         311.   fly_ball    medium   8         140.    69.3
 7 565711          12        79.1       23.4         246.   line_drive  medium   7          52.3  126.
 8 565711          13        67.3      -21.3         124.   ground_ball medium   6         108.   156.
 9 565711          14        89.9      -21.6           7.41 ground_ball medium   6         108.   152.
10 565711          15       110.        27.7         420.   fly_ball    medium   9         250.    69.0
# … with 36 more rows

A: Try a cheecky bit of 'unlist'. I've managed to get a nameless data frame - getting the names out of a list seems complicated. Hope this helps:
hitData = jsonData %>%
      map("playEvents") %>%
      map("hitData") %>%
      unlist(recursive = F)

numRows = lapply(hitData,length) %>% unique %>% unlist

hitDataFrame = unlist(hitData) %>% matrix(nrow = numRows) %>% as.data.frame


text:
Q: File renaming and deleting error I am trying to modify the data in the file. while checking whether it has successfully deleted and renamed the file,it always prints "Not Successfully changed".
public void transfer()
{

    File temp=new File("temp.dat");
    File supply=new File("supply.dat");
    boolean rename=temp.renameTo(supply);
    boolean delete=supply.delete();

    if(delete && rename)
        Sopln("Successfully Changed");
    else
        Sopln("Not Successfully Changed");
}//transfer end

here is the switch-case block where i am invoking this method.
    Sopln("Modify :-");
    Sopln("1)Preffered Period");
    Sopln("2)Preffered Class");
    Sopln("3)Exit");
    int option;
    do
    {
        option=Check_Int("Enter Your Choice");
        int ctr=0;
        switch(option)
        {
            case 1: Sopln("______________________________");
                    String name=Check_String("Enter The Name Of The Teacher Whose Details You Want To Change");
                    String record;
                    while((record=fr.readLine())!=null)
                    {
                        String token[]=record.split("-");
                        if(name.equalsIgnoreCase(token[0]))
                        {
                            Sopln("Your Current Info:");
                            Sopln("Name : "+token[0]);
                            Sopln("Preffered Period : "+token[3]);
                            Sopln("Enter Your New Preffered Period");
                            token[3]=br.readLine();
                            pw.println(token[0]+"-"+token[1]+"-"+token[2]+"-"+token[3]+"-"+token[4]);
                            ctr++;
                        }//if block end
                        else
                        {pw.println(record);}
                    }//while loop end
                    if(ctr==0)
                    {Sopln("Not Found");
                    submenu();
                    }
                    else
                    {
                        ctr=0;
                        transfer();
                    }
                    fr.close();
                    pw.close();
                    break;
            case 2: Sopln("______________________________");
                    String name_class=Check_String("Enter The Name Of The Teacher Whose Details You Want To Change");
                    String record_class;
                    int cnt=0;
                    while((record_class=fr.readLine())!=null)
                    {
                        String token[]=record_class.split("-");
                        if(name_class.equalsIgnoreCase(token[0]))
                        {
                            Sopln("Your Current Information:-");
                            Sopln("Name : "+token[0]);
                            Sopln("Preffered Class : "+token[4]);
                            Sopln("Enter Your New Preffered Class");
                            token[4]=br.readLine();
                            pw.println(token[0]+"-"+token[1]+"-"+token[2]+"-"+token[3]+"-"+token[4]);
                            cnt++;
                        }//if block end
                        else
                        {pw.println(record_class);}//else block end
                        }//while loop end
                        if(cnt==0)
                        {Sopln("Name Not Found!");
                        submenu();}
                        else
                        {
                            cnt=0;
                            transfer();
                        }//else block end
                        fr.close();
                        pw.close();
                        break;
            case 3: main_menu mm=new main_menu();
                    mm.menu();
                    break;
        }
    }while(option<0 || option>2);
}//change method end

so, when I check my documents,the temp file is created with the the necessary modifications but, But the file is not being renamed nor the original Supply file being deleted.
Plz Help!!

A: You 1st to rename and then create a new file variable & then delete. Simple solution.
public void transfer()

{
    //rename file
    File temp=new File("temp.dat");
    File supply=new File("supply.dat");
    boolean rename=temp.renameTo(supply);
//delete file
File f = new File("supply.dat");
boolean delete=supply.delete();

if(delete && rename)
    Sopln("Successfully Changed");
else
    Sopln("Not Successfully Changed");

}//transfer end


text:
Q: Syntax error while updating state in React.js the following code show me an syntax error while updating the state in React.js.
import { FETCH_POSTS } from '../actions/index';
const INITIAL_STATE = { all:[], post: null};

export default (state=INITIAL_STATE,action) => {
  switch(action.type){
    case FETCH_POSTS:
    return { ...state, all: action.payload.data };
    default:
    return state;
  }
}

it show me an error on return { ...state,all:action.payload.data };

A: According to the ES6 specification, the spread operator can be applied only to iterable objects (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Spread_operator). You can use Object.assign or consider something like https://github.com/sebmarkbage/ecmascript-rest-spread with your transpiler.

A: Make use of Object.assign() to update and return the state
export default (state=INITIAL_STATE,action) => {
  switch(action.type){
    case FETCH_POSTS:
    return Object.assign({}, state, {all: action.payload.data});
    default:
    return state;
  }
}

A: I had the same issue with the same code as yours when I started my own project after finishing this course https://www.udemy.com/react-redux
I figured out that I forgot to install preset-1 https://www.npmjs.com/package/webpack-preset-babel-stage-1
and include it in webpack.config.js
module.exports = {
  entry: [
    './src/index.js'
  ],
  output: {
    path: __dirname,
    publicPath: '/',
    filename: 'bundle.js'
  },
  module: {
    loaders: [{
      exclude: /node_modules/,
      loader: 'babel',
      query: {
        presets: ['react', 'es2015', 'stage-1']
      }
    }]
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  devServer: {
    historyApiFallback: true,
    contentBase: './'
  }
};

A: Well, I came across the same problem.
Do remember to install "babel-preset-stage-1" in your npm packages and use it as "stage-1" while setting presets for babel.
It will work.


text:
Q: HTML Compressor | Line breaks needed? I'm minifying my html using:
http://htmlcompressor.com/compressor.html
It leaves return characters in so instead of one single line...I get a bunch of individual lines.
Any reason why?(JS and CSS minifiers do not do this)  Any experience with this for html minification?  Is this a solid tool?

A: Newlines can affect the output, so they can't really be safely stripped from every HTML document.
For example:

Hello
World

HelloWorld

This gets rendered as:
Hello World
HelloWorld

Demo: http://jsfiddle.net/UTy2f/


text:
Q: Dimension of the dual of a finite-dimensional vector space My book defines the dual space $V^\ast$ of a vector space $V$ as the set of the linear application in $V$. Then it says ...

Theorem: If $V$ is a vector space of limited dimension on the $K$ field, so the dual space $V^\ast$ have limited dimension and ...
... $\dim V^\ast = \dim V$.

Now, if the dimension of a space is the number of vectors needed to generate the entire space, how is it possible to generate an infinite number of possible linear applications by a limited basis?
Is it possible because the linear applications can be summed and multiplicated by constants? Im just not sure...


text:
Q: How can I communicate between adjacent elements in ReactJS? I'm trying to construct a table in ReactJS that generates two rows for each element in an array. The problem I'm having trouble solving is generating them in such a way where row(n) can send a message to row(n+1).
The application of this is opening a detail view if one of the rows is clicked.
Right now my approach is to generate the rows and pass row(n+1) as a prop of row.
const orders = [
  // this is just some example data
  {
   "name": "lorem",
   "number": "20.00",
   "price": "20.00",
   "image": "http://localhost/path/to/image1.jpg"
  },
  {
   "name": "lorem",
   "number": "20.00",
   "price": "20.00",
   "image": "http://localhost/path/to/image1.jpg"
  },
];

const Orders = React.createClass({

  renderAllRows(order) {
    // this function would generate all the rows of the table
    const rows = [];
    orders.map(function (order, index) {
      const OrderDetailInstance = <OrderDetail display={false}  item={order} />
      // OrderDetailInstance is passed as a prop of OrderItemInstance
      const OrderItemInstance = <OrderItem detail={OrderDetailInstance} item={order}/>;
      rows.push(OrderItemInstance, OrderDetailInstance);
    });
    return rows;
  },

  render() {
    const { state } = this;
    const { orders } = state;
    const { isLastPage } = state;

    return (

            {this.renderAllRows(orders).map(function(row) {
               return row;
            })}

    );
  },
});

However this doesn't work, because while the prop is successfully passes, I do not know how to access methods on a react element. So I'm obviously going about this wrong.
Currently this is my unsuccessful approach to calling a method on a react element.
const OrderItem = React.createClass({
  render() {
    const item = this.props.item;

    return (

        {item.number}
        {item.number}

          open detail

    );
  },

  openOrderDetail() {
    // This is where I'm trying to call the prop's method.
    this.props.detail.open();
  }
});

const OrderDetail = React.createClass({
  render() {
    const display = this.props.display;
    const classes = display ? classNames('') : classNames('hidden');
    return (

            This is the detail of the previous row

    );
  },

  open() {
    // This should IDEALLY be exposed to any react element that has
    // OrderDetail as a prop.
    console.log("open");
  }
});

I'm open to the idea of using the state of the Orders class but I can't help feel that would be overkill.

A: What if you just used CSS to show/not show the detail row unless it was preceded by a row with a certain class.
So, your DOM could look like

And your CSS could be something like
.detail-row { display: none}
.show-detail + .detail-row { display: block }

So a detail-row is not shown, unless it immediately follows a show-detail item.
Then, your OrderItem component is only worried about toggling a class on itself, rather than talking to it's sibling.

A: Wrap OrderItem and OrderDetail in a container component, say: OrderView. Keep the state of whether to show the detail or not in the new OrderView. In your OrderView.render(), choose to show the detail row or not based on the state. Instead of trying to call open(), just set the OrderView.state as required.
This tutorial really helped me a lot.


text:
Q: Linear transformation calculation don't understand. I am new to linear algebra, today I came across a solution sample as follow:
The sample solution deduces $T(1) = x+3,\ T(x) = 3x+4$ from a transformation: $T(ax+b) = (3a+b)x+a+3$.
I cannot understand this, can somebody please explain this to me? Thanks.

A: When $a=0$ and $b=1$ we have $T(0x+1)=T(1)=x+3.$
For $a=1$ and $b=0$ we have $T(1x+0)=T(x)=3x+4$ by substituting into the transformation.

A: The transformation is defined by specifying how a first degree binomial is transformed,
$$f(ax+b)=\cdots$$
Now it suffces to make the connections between
$$ax+b\leftrightarrow 1$$
and
$$ax+b\leftrightarrow x,$$ then apply the definition.


text:
Q: Mount NAS Ubuntu 20.04 I'm trying to mount a NAS that is on my local network.
This website tells me to use
$ mount <NAS Ethernet Interface IP>:/share/<Shared Folder Name> <Directory to Mount>
I'm a little unsure what I should provide for shared folder name as well as directory to mount.
Furthermore this mentions to first use $ smbclient -L //<IP> to see the NAS which in my case gives me do_connect: Connection to 192.168.178.54 failed (Error NT_STATUS_CONNECTION_REFUSED)

A: Typically the shared folder name is the name of the folder on the NAS that you want to have available on the Ubuntu machine.
Like Movies or TV.
The directory to mount to is the directory under mnt that you have created as the mount point. You need to create this directory.
The line about SMB requires you to have installed and setup SMB on the Ubuntu machine assuming your NAS supports SMB.


text:
Q: Canvas animated line over border so i have a canvas element that displays some values, i use window.requestAnimationFrame to update the canvas. Now i would like to add an animated line that would loop over the canvas. This is how my canvas looks and this is the code for the line so far:
this.ctx.lineWidth = 1;
this.ctx.strokeStyle = 'rgba(47, 48, 63, 0.3)';
this.ctx.setLineDash([]);

this.ctx.beginPath()
this.ctx.rect(0, 0, this.canvasWidth, this.canvasHeight)
this.ctx.beginPath()
this.ctx.lineWidth = 5 * this.ratio;
this.ctx.strokeStyle = this._gradient

let topEdge = this._loaderX + this._loaderWidth;
this.ctx.moveTo(this._loaderX, 0);
this.ctx.lineTo(topEdge, 0);

let bottomLeftEdge = topEdge > this.canvasWidth ? topEdge - this.canvasWidth : -this._loaderWidth;
this.ctx.moveTo(this.canvasWidth, bottomLeftEdge)
this.ctx.lineTo(this.canvasWidth, bottomLeftEdge + this._loaderWidth)
this.ctx.stroke()

this._loaderX += 5;

But the problem occurs when the line gets to the edge, it doesn't make a seamless transition, not sure how should i proceed.

A: property vector2d firstPoint: Qt.vector2d(lineWidth / 2, 0)
property vector2d secondPoint: Qt.vector2d(width, lineWidth / 2)
property int lineWidth: 5 * width / height
property int _loaderWidth: width / 2

onPaint:
{
    var ctx = getContext("2d")
    ctx.reset()

    ctx.beginPath()
    ctx.lineWidth = lineWidth
    ctx.strokeStyle = "green"

    var topEdge = this.firstPoint.x + _loaderWidth;
    ctx.moveTo(this.firstPoint.x, lineWidth / 2);
    ctx.lineTo(topEdge, lineWidth / 2);

    var bottomLeftEdge = topEdge > this.width ? topEdge - width : -_loaderWidth;
    ctx.moveTo(this.width - lineWidth / 2, bottomLeftEdge - lineWidth / 2)
    ctx.lineTo(this.width - lineWidth / 2, bottomLeftEdge - _loaderWidth)
    ctx.stroke()

    this.firstPoint.x += 5;
}


text:
Q: How to make a negative flank to a negative pulse from normal state not connected? I have a reset signal which should be triggered by a falling flank from 5V to 0 volt.
This flank should generate a low pulse (5V -> 0V -> 5V). This can be done by just adding a capacitor and a pull-up. However since I also use the RESET pin for debug wire I can not have a capacitor. So what I need:
Input: falling flank from 5V to 0 volt
Output: not conected -> 0V -> not conected
Outside this circuit I will have a 20k pull-up to the RESET pin. The important part is that there may be no low pass filtering by caps on the reset pin since that will afect the debug wire.
How do a low cost circuit look for this?

A: Use an AND (assuming negative RESET!) or OR (for positive RESET) gate to combine the signal used for the debugging interface with the one used to for the usual RESET function.
Or use open-drain buffers with wired-AND connections.
For better control of the RESET pulse, use a one-shot like SN74LVC1G123 instead of just an RC circuit for the reset function.
None of these chips should cost more than a few dimes in volume, or a dollar or so onesy-twosy.


text:
Q: Qt using images for buttons I have been developing in Qt for a little over half a year now, and I've been mostly using stylesheets to give my GUI a better look and feel. I have gotten it to the point where it looks good, but not extremely professional. i.e. my GUI looks a little bit amateurish. What I'm wondering is, should I be using images for buttons and other widgets to make them look more professional? or should I focus on learning how to do everything using stylesheets. For example..I know some photoshop designers which can make some great images for me, is that a valid practice for GUI development in Qt?
Thanks.


text:
Q: Extract Json elements from string I'm getting data from an API as a python dict and appending it to a list, which is then dumped onto a txt file.
I am trying to read the huge string in the txt file and load into Json objects but am finding issues.
I take the dictionary and make it Json applicable, i.e.
jsonStr = json.dumps(d)

Where d is the dictionary returned by the API.
This jsonStr is then appended to a list.
As its a string, when put into a txt file the ' is still there../. e.g.
['{"md1": {"id": 422, "h": "bla"}}', '{"md2": {"id": 42211, "h": "bla2"}}']

I need to get rid of the ' from each element. Can't figure out the best how to tackle this.

A: Can you elaborate on the other elements of the list? If the list contains no items that include single quotation marks, you can use replace("'", "") on the text in the file. This will replace all single quotation marks with nothing. A better way to do this, I believe, is to dump the JSON after it has been added to the list, like so:
the_list_to_which_you_append = [...]

the_list_to_which_you_append(d)
jsonStr = json.dumps(the_list_to_which_you_append)

A: https://docs.python.org/3/library/json.html
To convert a json into a string you do json.dumps()
To convert a string into a json you do json.loads()
So in your situation. Before you append it to a list you should convert the string to a json first. Then append it to the list. Then you can save your list to a textfile.


text:
Q: What is default color of TextBlock.Foreground? Is default value of TextBlock's Foreground one of the SystemColors? If so, which one is it?

A: This is rather theme-dependent, if there is no override from the applying theme the DP-system uses the default value of the respective DependencyProperty, which is Brushes.Black.
There are however many possibly overrides, in the Aero theme inheritance changes the value in some cases. While the TextBlock style does not set the Foreground directly (which would be a stronger override), the Foreground of Windows is set to {DynamicResource {x:Static SystemColors.WindowTextBrushKey}} so if the TextBlock is in a Window the brush associated with that key will be applied unless the inheritance is overridden by another value of even higher precedence.

A: Foreground="{ThemeResource DefaultTextForegroundThemeBrush}"

A: Textblock's foreground hex value is #FF000000


text:
Q: how read pdf layers and add to another page using itextsharp? How can I read PDF layers and add them to another page using iTextSharp?
I want to copy layers from one PDF page and move them to another PDF page in C#.
I've tried reading from a PDF layer from one page, but I am unable to copy that layer.
var document = new Document();

FileStream outfile = new FileStream(outPutFilePath, FileMode.Create);

var writer = new PdfCopy(document, outfile);

document.Open();

foreach (var fileName in filesPath)
{
    var reader = new PdfReader(fileName);
    PdfStamper stamper = new PdfStamper(reader, outfile);

    Dictionary<String, PdfLayer> layers = stamper.GetPdfLayers();
    //PdfLayer layer = layers.get("Nested layer 1");
    //layer.setOn(false);

    for (var i = 1; i <= reader.NumberOfPages; i++)
    {
        var page = writer.GetImportedPage(reader, i);
        page.ContentTagged = true;
        writer.AddPage(page);

    }
    stamper.Close();

    reader.Close();
}
writer.Close();

document.Close();


text:
Q: Examples of technical (or science in general) magazines using LaTeX I have been looking for resources related to (beautifully) typesetting technical and science magazines with LaTeX. I am aware of the Showcase of beautiful typography done in TeX & friends question and it is a wonderful source of inspiration.
However, not many of those examples come with the associated source.
Some of the examples I have been looking for would include:

*

*Two-column magazines with modern fonts and styling, complex caption positioning for figures and high-resolution graphics and charts, besides illustrations.

*Journals with complex editorial pages, prologues, sections like classifieds or miscellaneous tidbits, etc.

I understand this might be a too broad question but I would like to update this with answers from people out there and make it a valuable resource for anyone thinking (or already working on) typesetting a great looking LaTeX magazine.
Some questions for would-be contributors:

*

*What styles and classes do you use mostly?

*How do you handle the independent submissions and articles comprising the magazine, and how do you choose to render these into the final compiled PDF/output?

*What makes your job easier as an editor to have a ready-set, standard library of styles and commands that allow easily typesetting formulae, code, captions, figures, Tikz pots, etc.


text:
Q: Flow Notation over Interval Given a section of the flow $\Phi^t(x_0)$ (for finite $t$), I'd like to denote a subsection of this flow from times $\tau^{i-1}$ to time $\tau^{i}$ using similar notation.
I was considering using something like: $\phi_i = \Phi^\tau(\Phi^{\tau^{i-1}}(x_0)), \forall\tau\in[\tau^{i-1},\tau^{i}]$
However I thought that this seemed a bit hacky, and sadly after much searching online I've not found anything more beautiful or concise.
If you need more details on my motivation behind wanting to do this before you can advise me, then I'll gladly update my post with such information.
Thanks in advance!


text:
Q: How to import iPhone videos into Instagram without distortion? Whenever I take a video with the standard camera app and then import it into Instagram on my iPhone 5S, the video ends up distorted.
A still from the original video:

A screengrab showing distortion:

I suspect this occurs due to the different aspect ratios of the two formats.
Is there any way to either:

*

*Take video in the default camera app in Instagram's 1:1 ratio, or

*Crop video in the Instagram app so that it doesn't distort

A: I know that Instagram doesn't allow video cropping at the moment. Nor can you change the Camera app's aspect ratio. I suggest either recording inside Instagram or changing your phone's recording position to landscape.

A: In case someone still has this problem, I found a way to avoid the distortion on videos caused by Instagram. Instead of opening the instagram app and selecting your video in the app, go to your phone gallery and click on the "Share" button, share to instagram and the distortion goes away! Worked this way for me!
PS: Android user... might work for Iphones as well!


text:
Q: Cannot run the job on hadoop cluster. only runs using LocalJobRunner I have submitted a MR job using hadoop jar command with the following command on CDH5 Beta 2
hadoop jar ./hadoop-examples-0.0.1-SNAPSHOT.jar com.aravind.learning.hadoop.mapred.join.ReduceSideJoinDriver tech_talks/users.csv tech_talks/ratings.csv tech_talks/output/ReduceSideJoinDriver/

I've also tried providing the fs name and job tracker url explicitly as below without any success
hadoop jar ./hadoop-examples-0.0.1-SNAPSHOT.jar com.aravind.learning.hadoop.mapred.join.ReduceSideJoinDriver -Dfs.default.name=hdfs://abc.com:8020 -Dmapreduce.job.tracker=x.x.x.x:8021 tech_talks/users.csv tech_talks/ratings.csv tech_talks/output/ReduceSideJoinDriver/

The job runs successfully but is using the LocalJobRunner instead of submitting to the cluster. The output is written to HDFS and is correct. Not sure what I am doing wrong here so appreciate your input. I've also tried explicitly specifying the fs and job tracker as below but have the same result
14/04/16 20:35:44 INFO Configuration.deprecation: session.id is deprecated. Instead, use dfs.metrics.session-id
14/04/16 20:35:44 INFO jvm.JvmMetrics: Initializing JVM Metrics with processName=JobTracker, sessionId=
14/04/16 20:35:45 WARN mapreduce.JobSubmitter: No job jar file set.  User classes may not be found. See Job or Job#setJar(String).
14/04/16 20:35:45 INFO input.FileInputFormat: Total input paths to process : 2
14/04/16 20:35:45 INFO mapreduce.JobSubmitter: number of splits:2
14/04/16 20:35:46 INFO mapreduce.JobSubmitter: Submitting tokens for job: job_local1427968352_0001
14/04/16 20:35:46 WARN conf.Configuration: file:/tmp/hadoop-ird2/mapred/staging/ird21427968352/.staging/job_local1427968352_0001/job.xml:an attempt to override final parameter: mapreduce.job.end-notification.max.retry.interval;  Ignoring.
14/04/16 20:35:46 WARN conf.Configuration: file:/tmp/hadoop-ird2/mapred/staging/ird21427968352/.staging/job_local1427968352_0001/job.xml:an attempt to override final parameter: mapreduce.job.end-notification.max.attempts;  Ignoring.
14/04/16 20:35:46 WARN conf.Configuration: file:/tmp/hadoop-ird2/mapred/local/localRunner/ird2/job_local1427968352_0001/job_local1427968352_0001.xml:an attempt to override final parameter: mapreduce.job.end-notification.max.retry.interval;  Ignoring.
14/04/16 20:35:46 WARN conf.Configuration: file:/tmp/hadoop-ird2/mapred/local/localRunner/ird2/job_local1427968352_0001/job_local1427968352_0001.xml:an attempt to override final parameter: mapreduce.job.end-notification.max.attempts;  Ignoring.
14/04/16 20:35:46 INFO mapreduce.Job: The url to track the job: http://localhost:8080/
14/04/16 20:35:46 INFO mapreduce.Job: Running job: job_local1427968352_0001
14/04/16 20:35:46 INFO mapred.LocalJobRunner: OutputCommitter set in config null
14/04/16 20:35:46 INFO mapred.LocalJobRunner: OutputCommitter is org.apache.hadoop.mapreduce.lib.output.FileOutputCommitter
14/04/16 20:35:46 INFO mapred.LocalJobRunner: Waiting for map tasks
14/04/16 20:35:46 INFO mapred.LocalJobRunner: Starting task: attempt_local1427968352_0001_m_000000_0
14/04/16 20:35:46 INFO mapred.Task:  Using ResourceCalculatorProcessTree : [ ]
14/04/16 20:35:46 INFO mapred.MapTask: Processing split: hdfs://...:8020/user/ird2/tech_talks/ratings.csv:0+4388258
14/04/16 20:35:46 INFO mapred.MapTask: Map output collector class = org.apache.hadoop.mapred.MapTask$MapOutputBuffer
14/04/16 20:35:46 INFO mapred.MapTask: (EQUATOR) 0 kvi 26214396(104857584)
14/04/16 20:35:46 INFO mapred.MapTask: mapreduce.task.io.sort.mb: 100
14/04/16 20:35:46 INFO mapred.MapTask: soft limit at 83886080
14/04/16 20:35:46 INFO mapred.MapTask: bufstart = 0; bufvoid = 104857600
14/04/16 20:35:46 INFO mapred.MapTask: kvstart = 26214396; length = 6553600
14/04/16 20:35:47 INFO mapreduce.Job: Job job_local1427968352_0001 running in uber mode : false
14/04/16 20:35:47 INFO mapreduce.Job:  map 0% reduce 0%
14/04/16 20:35:48 INFO mapred.LocalJobRunner:
14/04/16 20:35:48 INFO mapred.MapTask: Starting flush of map output
14/04/16 20:35:48 INFO mapred.MapTask: Spilling map output
14/04/16 20:35:48 INFO mapred.MapTask: bufstart = 0; bufend = 6485388; bufvoid = 104857600
14/04/16 20:35:48 INFO mapred.MapTask: kvstart = 26214396(104857584); kvend = 24860980(99443920); length = 1353417/6553600
14/04/16 20:35:49 INFO mapred.MapTask: Finished spill 0
14/04/16 20:35:49 INFO mapred.Task: Task:attempt_local1427968352_0001_m_000000_0 is done. And is in the process of committing
14/04/16 20:35:49 INFO mapred.LocalJobRunner: map
14/04/16 20:35:49 INFO mapred.Task: Task 'attempt_local1427968352_0001_m_000000_0' done.
14/04/16 20:35:49 INFO mapred.LocalJobRunner: Finishing task: attempt_local1427968352_0001_m_000000_0
14/04/16 20:35:49 INFO mapred.LocalJobRunner: Starting task: attempt_local1427968352_0001_m_000001_0
14/04/16 20:35:49 INFO mapred.Task:  Using ResourceCalculatorProcessTree : [ ]
14/04/16 20:35:49 INFO mapred.MapTask: Processing split: hdfs://...:8020/user/ird2/tech_talks/users.csv:0+186304
14/04/16 20:35:49 INFO mapred.MapTask: Map output collector class = org.apache.hadoop.mapred.MapTask$MapOutputBuffer
14/04/16 20:35:49 INFO mapred.MapTask: (EQUATOR) 0 kvi 26214396(104857584)
14/04/16 20:35:49 INFO mapred.MapTask: mapreduce.task.io.sort.mb: 100
14/04/16 20:35:49 INFO mapred.MapTask: soft limit at 83886080
14/04/16 20:35:49 INFO mapred.MapTask: bufstart = 0; bufvoid = 104857600
14/04/16 20:35:49 INFO mapred.MapTask: kvstart = 26214396; length = 6553600
14/04/16 20:35:49 INFO mapred.LocalJobRunner:
14/04/16 20:35:49 INFO mapred.MapTask: Starting flush of map output
14/04/16 20:35:49 INFO mapred.MapTask: Spilling map output
14/04/16 20:35:49 INFO mapred.MapTask: bufstart = 0; bufend = 209667; bufvoid = 104857600
14/04/16 20:35:49 INFO mapred.MapTask: kvstart = 26214396(104857584); kvend = 26192144(104768576); length = 22253/6553600
14/04/16 20:35:49 INFO mapred.MapTask: Finished spill 0
14/04/16 20:35:49 INFO mapred.Task: Task:attempt_local1427968352_0001_m_000001_0 is done. And is in the process of committing
14/04/16 20:35:49 INFO mapred.LocalJobRunner: map
14/04/16 20:35:49 INFO mapred.Task: Task 'attempt_local1427968352_0001_m_000001_0' done.
14/04/16 20:35:49 INFO mapred.LocalJobRunner: Finishing task: attempt_local1427968352_0001_m_000001_0
14/04/16 20:35:49 INFO mapred.LocalJobRunner: map task executor complete.
14/04/16 20:35:49 INFO mapred.LocalJobRunner: Waiting for reduce tasks
14/04/16 20:35:49 INFO mapred.LocalJobRunner: Starting task: attempt_local1427968352_0001_r_000000_0
14/04/16 20:35:49 INFO mapred.Task:  Using ResourceCalculatorProcessTree : [ ]
14/04/16 20:35:49 INFO mapred.ReduceTask: Using ShuffleConsumerPlugin: org.apache.hadoop.mapreduce.task.reduce.Shuffle@5116331d
14/04/16 20:35:49 INFO reduce.MergeManagerImpl: MergerManager: memoryLimit=652528832, maxSingleShuffleLimit=163132208, mergeThreshold=430669056, ioSortFactor=10, memToMemMergeOutputsThreshold=10
14/04/16 20:35:49 INFO reduce.EventFetcher: attempt_local1427968352_0001_r_000000_0 Thread started: EventFetcher for fetching Map Completion Events
14/04/16 20:35:49 INFO reduce.LocalFetcher: localfetcher#1 about to shuffle output of map attempt_local1427968352_0001_m_000001_0 decomp: 220797 len: 220801 to MEMORY
14/04/16 20:35:49 INFO reduce.InMemoryMapOutput: Read 220797 bytes from map-output for attempt_local1427968352_0001_m_000001_0
14/04/16 20:35:49 INFO reduce.MergeManagerImpl: closeInMemoryFile -> map-output of size: 220797, inMemoryMapOutputs.size() -> 1, commitMemory -> 0, usedMemory ->220797
14/04/16 20:35:49 INFO reduce.LocalFetcher: localfetcher#1 about to shuffle output of map attempt_local1427968352_0001_m_000000_0 decomp: 7162100 len: 7162104 to MEMORY
14/04/16 20:35:49 INFO reduce.InMemoryMapOutput: Read 7162100 bytes from map-output for attempt_local1427968352_0001_m_000000_0
14/04/16 20:35:49 INFO reduce.MergeManagerImpl: closeInMemoryFile -> map-output of size: 7162100, inMemoryMapOutputs.size() -> 2, commitMemory -> 220797, usedMemory ->7382897
14/04/16 20:35:49 INFO reduce.EventFetcher: EventFetcher is interrupted.. Returning
14/04/16 20:35:49 INFO mapred.LocalJobRunner: 2 / 2 copied.
14/04/16 20:35:49 INFO reduce.MergeManagerImpl: finalMerge called with 2 in-memory map-outputs and 0 on-disk map-outputs
14/04/16 20:35:49 INFO mapred.Merger: Merging 2 sorted segments
14/04/16 20:35:49 INFO mapred.Merger: Down to the last merge-pass, with 2 segments left of total size: 7382885 bytes
14/04/16 20:35:50 INFO reduce.MergeManagerImpl: Merged 2 segments, 7382897 bytes to disk to satisfy reduce memory limit
14/04/16 20:35:50 INFO reduce.MergeManagerImpl: Merging 1 files, 7382899 bytes from disk
14/04/16 20:35:50 INFO reduce.MergeManagerImpl: Merging 0 segments, 0 bytes from memory into reduce
14/04/16 20:35:50 INFO mapred.Merger: Merging 1 sorted segments
14/04/16 20:35:50 INFO mapred.Merger: Down to the last merge-pass, with 1 segments left of total size: 7382889 bytes
14/04/16 20:35:50 INFO mapred.LocalJobRunner: 2 / 2 copied.
14/04/16 20:35:50 INFO Configuration.deprecation: mapred.skip.on is deprecated. Instead, use mapreduce.job.skiprecords
14/04/16 20:35:50 INFO mapreduce.Job:  map 100% reduce 0%
14/04/16 20:35:51 INFO mapred.Task: Task:attempt_local1427968352_0001_r_000000_0 is done. And is in the process of committing
14/04/16 20:35:51 INFO mapred.LocalJobRunner: 2 / 2 copied.
14/04/16 20:35:51 INFO mapred.Task: Task attempt_local1427968352_0001_r_000000_0 is allowed to commit now
14/04/16 20:35:51 INFO output.FileOutputCommitter: Saved output of task 'attempt_local1427968352_0001_r_000000_0' to hdfs://...:8020/user/ird2/tech_talks/output/ReduceSideJoinDriver/_temporary/0/task_local1427968352_0001_r_000000
14/04/16 20:35:51 INFO mapred.LocalJobRunner: reduce > reduce
14/04/16 20:35:51 INFO mapred.Task: Task 'attempt_local1427968352_0001_r_000000_0' done.
14/04/16 20:35:51 INFO mapred.LocalJobRunner: Finishing task: attempt_local1427968352_0001_r_000000_0
14/04/16 20:35:51 INFO mapred.LocalJobRunner: reduce task executor complete.
14/04/16 20:35:52 INFO mapreduce.Job:  map 100% reduce 100%
14/04/16 20:35:52 INFO mapreduce.Job: Job job_local1427968352_0001 completed successfully
14/04/16 20:35:52 INFO mapreduce.Job: Counters: 38
        File System Counters
                FILE: Number of bytes read=14767932
                FILE: Number of bytes written=29952985
                FILE: Number of read operations=0
                FILE: Number of large read operations=0
                FILE: Number of write operations=0
                HDFS: Number of bytes read=13537382
                HDFS: Number of bytes written=2949787
                HDFS: Number of read operations=28
                HDFS: Number of large read operations=0
                HDFS: Number of write operations=5
        Map-Reduce Framework
                Map input records=343919
                Map output records=343919
                Map output bytes=6695055
                Map output materialized bytes=7382905
                Input split bytes=272
                Combine input records=0
                Combine output records=0
                Reduce input groups=5564
                Reduce shuffle bytes=7382905
                Reduce input records=343919
                Reduce output records=5564
                Spilled Records=687838
                Shuffled Maps =2
                Failed Shuffles=0
                Merged Map outputs=2
                GC time elapsed (ms)=92
                CPU time spent (ms)=0
                Physical memory (bytes) snapshot=0
                Virtual memory (bytes) snapshot=0
                Total committed heap usage (bytes)=1416101888
        Shuffle Errors
                BAD_ID=0
                CONNECTION=0
                IO_ERROR=0
                WRONG_LENGTH=0
                WRONG_MAP=0
                WRONG_REDUCE=0
        File Input Format Counters
                Bytes Read=4574562
        File Output Format Counters
                Bytes Written=2949787

Driver code
public class ReduceSideJoinDriver extends Configured implements Tool
{
    @Override
    public int run(String[] args) throws Exception
    {
        if (args.length != 3)
        {
            System.err.printf("Usage: %s [generic options] <input> <output>\n", getClass().getSimpleName());
            ToolRunner.printGenericCommandUsage(System.err);
            return -1;
        }

        Path usersFile = new Path(args[0]);
        Path ratingsFile = new Path(args[1]);

        Job job = Job.getInstance(getConf(), "Aravind - Reduce Side Join");

        job.getConfiguration().setStrings(usersFile.getName(), "user");
        job.getConfiguration().setStrings(ratingsFile.getName(), "rating");

        job.setInputFormatClass(TextInputFormat.class);
        job.setOutputFormatClass(TextOutputFormat.class);
        job.setMapOutputKeyClass(IntWritable.class);
        job.setMapOutputValueClass(TagAndRecord.class);

        TextInputFormat.addInputPath(job, usersFile);
        TextInputFormat.addInputPath(job, ratingsFile);

        TextOutputFormat.setOutputPath(job, new Path(args[2]));

        job.setMapperClass(ReduceSideJoinMapper.class);
        job.setReducerClass(ReduceSideJoinReducer.class);
        job.setOutputKeyClass(IntWritable.class);
        job.setOutputValueClass(Text.class);

        return job.waitForCompletion(true) ? 0 : 1;
    }

    public static void main(String args[]) throws Exception
    {
        int exitCode = ToolRunner.run(new Configuration(), new ReduceSideJoinDriver(), args);
        System.exit(exitCode);
    }
}

A: Make sure you have valid following configuration files in hadoop classpath. By default configuration files are taken from the directory /etc/hadoop/conf. This activity should be performed a part of hadoop client node setup.
mapred-site.xml
yarn-site.xml
core-site.xml

If the above mentioned configuration files are empty. You got to pupulate the above files with right properties. Population can be achieved in two ways
In Cloudera Manager when click on service yarn, in action portion, there is an option Deploy client configuration along with start,stop etc. Use that option to deploy the client configuration.
Sometimes above option maynot work if the node is not managed by CM and yarn gateway is not configured on the node. use the option Download client configuration instead of deploy client Configuration. Extract the downloaded zip configuration file(above files) and copy those files to the location /etc/hadoop/conf manually.
For executing the jar either hadoop or yarn can be used.

A: Apparently, you can only submit a hadoop job from the node designated as the gateway node. Everything is working once I submitted the job from the gateway node.


text:
Q: What does "a golden fruit" mean?
Patience bears a golden fruit!

In the above sentence, what does "a golden fruit" mean?

A: The phrase "to bear fruit" means to create something of value, or have a positive result.  For instance, someone might ask if an investigation has born fruit as a poetic way to ask if new information has been found.  It is used fairly often in religious texts, but is otherwise rare in common use.  Anyone who uses that phrase is either trying to sound like religious scripture or being overly colorful.
In this phrase, "Patience bears a golden fruit!", the source sounds like religious scripture.  The phrase has nearly the same meaning without "golden" - "Patience bears fruit!" would also mean you can expect a positive result from patience.  However, by specifying a golden fruit, the source is trying to reinforce that this is an exceptionally valuable and desirable result.

A: Golden fruit may be an allusion to the Golden Apples that Hercules stole. One of the major goals of alchemy was to turn base metals into gold (because gold was so desirable). There is also the fable of Midas who was cursed with turning anything he touched into gold. This last is noteworthy because having the "golden touch" and being able to create any number of golden objects would be believed to be very desirable. You should familiarize yourself with those stories. In this case, "fruit" is being used to mean "product" or "result" (metaphorically) and "golden" means "very valuable" or " very desirable". Hence 'golden fruit' means "very desirable reward".

A: I have never heard this saying before. However, from context, I would assume that it means "a great reward."
The overall sentence is just saying that if you exercise patience, you will be rewarded.

A: I am not sure about "golden fruit" but golden apples come up in mythology as, for example, "food of the gods". See here. There are also stories of golden eggs - e.g. the expression

the goose that lays the golden egg.

I wonder if partly the idea is that if you had a tree that produced golden apples (or golden fruit of any kind) then you would become immensely wealthy.
So in context here the expression implies that patience brings a very valuable reward.


text:
Q: TypeScript - obtaining generic type information after a type has been erased Since TypeScript uses type erasure for generics, I'm working on an alternative solution for gathering type information at runtime.
The solution I've come up with is similar to that in Java, using a Class<T>.
It works, but it doesn't feel...complete
type Class<T> = { prototype: T }

function passMeAClass<T>(cls: Class<T>): void {
    console.log(cls);
}

passMeAClass(String)

*

*Is type Class<T> = { prototype: T } complete enough?

*Is there a better approach to do this?

A: The way to accomplish this usually is to use a constructor signature (similar with a function signature but with new in front of it):
type Constructor<T> = new (... args: any[]) => T;

function passMeAClass<T>(cls: Constructor<T>): void {
    console.log(cls);
}
passMeAClass(String)

This has the advantage of also being able to new up objects in the function. (so new cls() works for example).
Also for mixin scenarios you can use cls as a base type (your version would not work):
function extendTheClass<T extends Constructor<{}>>(cls: T) {
    return  class X extends cls {

    };
}


text:
Q: Copy/paste produces wrong codepage characters When I copy/paste text into nano on a console window (Ctrl+Alt+F2), the braces and brackets are converted to German Umlaut characters. It's fine in a terminal running on the graphical Desktop.
That's probably because a German keyboard was detected during installation and I want a German keyboard.
How to make Copy/Paste work?
Output of locale:
LANG=en_US.UTF-8
LANGUAGE=en_US
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC=de_DE.UTF-8
LC_TIME=de_DE.UTF-8
LC_COLLATE="en_US.UTF-8"
LC_MONETARY=de_DE.UTF-8
LC_MESSAGES="en_US.UTF-8"
LC_PAPER=de_DE.UTF-8
LC_NAME=de_DE.UTF-8
LC_ADDRESS=de_DE.UTF-8
LC_TELEPHONE=de_DE.UTF-8
LC_MEASUREMENT=de_DE.UTF-8
LC_IDENTIFICATION=de_DE.UTF-8
LC_ALL=

Output of update-locale LANG=de-DE.UTF-8:
*** update-locale: Error: invalid locale settings:  LC_TELEPHONE="de_DE.UTF-8" LC_MONETARY="de_DE.UTF-8" LC_ADDRESS="de_DE.UTF-8" LC_PAPER="de_DE.UTF-8" LC_NAME="de_DE.UTF-8" LC_NUMERIC="de_DE.UTF-8" LC_MEASUREMENT="de_DE.UTF-8" LC_TIME="de_DE.UTF-8" LANG=de-DE.UTF-8 LC_IDENTIFICATION="de_DE.UTF-8"

VMWare Workstation 10.0, VMWare Tools installed
  Ubuntu 13.10 Desktop 32 bit, almost clean installation, 1 day ago


text:
Q: How can I display newline in playframework template? I am new to playframework. I was trying to use a form -where the textarea field receives multi-line string.

After processing the taxtarea form field, data
is stored in postgresql database.

But when I try to display the string pulling from database the newLine is not displayed in template.

Here is the template code -- contactUs.message is carrying the string data

           @contactUs.message

How can I display newline in play template?

A: After you read from db or before you write to db replace new line (\r) with HTML br tag.

A: Ops! It was my mistake, I should have used pre tag.

@contactUs.message


text:
Q: How to get ids from divs that were dragged into a drop zone on button click javascript I'm trying to find a way to get the ids from dragged divs after they are in the drop zone.
All the drag components have an id from drag1 - drag8 and the drop zone is div drop zone. Because there are no divs in the drop zone when the page loads I want to gather the ids on a save button for now with a text box entry and drop down menu select.
I have tried the code below:
$(document).ready(function() {
    $("#dropzone div").click(function() {
        var index = $("#dropzone div").index(this);
        $("#dropzone_drag").html("Index " + drag + " was clicked");
    });
});

And I use jQuery for the text box, which works nicely:
$(document).ready(function() {
    $('#save').click(function() {
        alert($('#name').val());
    });
});

How do I find the ids from dragged divs after they are in the drop zone?

A: In my comprehension .index(this) returns the index of the element relative to the list "#dropzone div"., which may or may not contain the elements in the order you want. But if all your elements have a common class, say ".foo_bar" it probably would be easier to know the id given an clicked element.
Otherwise, as you're using this on the function, if this is one of your "drags" it is probably easier to pick the id from this than to try the indexes.
Try doing it like that and maybe it'll word better.
ids = {};
$("#dropzone>div").each(function(){
    ids[$(this).prop('id')] = $(this).prop('id').replace(/[^0-9]/g, '');
});

the code .replace() means that we are removing characters (in this case anything that isn't a number) from the string so we end up with it's true number. Instead of it's place in the DOM.
If i didn't comprehend well your problem, correct my comprehension errors and i will edit the answer. And an html of the zones would be nice ;)

A: After playing around i came up with the following:
var ids = {};
$("#dropzone>div").each(function(i){
    ids[i] = $(this).prop('id');
});

which at the moment says undefined, but i did manage to put it on the save button so it no longer pops up when i open the page.
Any suggests please?

A: The following code worked for me:
  <script>
  var div = document.getElementById('dropzone')
  </script>

and on the button i added:
alert( div.innerHTML )

The result gave me all of the div information from it's html page so i could select the information i wanted to push to the database.
Thank you all for you input and advice.
Matthew


text:
Q: Ubuntu Mate 18.04 32bit on MD E1210: Power management shall not invoce sleep mode when tasks are running I have Ubuntu Mate 18.04 32-bit running on an old Medion E1210 netbook. I set the power management to go to sleep mode after 1 hour of idle time when connectet to the power grid.
But what I get: when the computer is idle, it will take much longer than 1 hour until it goes to sleep mode - on the other hand, when it's executing some heavyload tasks it will go to sleep mode after some time even when those task are still running.
I thought there must be something wrong with idleness detection, I didn't know that it only refers to user interaction. Now is there a way to bypass sleep mode automatically while the system is idle but heavy tasks are running? Of course I could change the settings to never sleep and invoke it manually, but those tasks are running during the night so I won't be there when things are finished.


text:
Q: Bi directional communications between two view controllers in Objective-C I have a main Container View controller which has a table view controller and another view controller. In table view I am displaying certain items which can be selected and grouped. This group details are shown on the view controller(like a summary). once grouped these items will no longer be in table view. If needed I can even ungroup them and add it back to table view.
So these two view controllers need to have a communication channel between them. What would be the best approach here ? Protocols or blocks ? Notifications are a strict no.

A: The business logic of your application should be handled separately from the code that glues things into views — you're conflating model and controller.
So the items and the groupings would be maintained by a third class. Both view controllers would talk to it. They would nit talk to one another beyond transient UI information like, say, one saying "this was the specific item selected".

A: A good way to think about it is to start with the goal of no direct communication.  Instead, both VCs have access to the application's model (usually a form of a singleton), and configure their state based on the state of the model.  In other words, the view controllers are stateful with respect to the app's model, stateless with respect to each other.
But sometimes vcs in the same container must communicate, like in a navigation controller when a selection is made.  That's typically done in prepare for segue.  The selection is conveyed to the vc being pushed, and then it carries on.  To the extent that vc needs to communicate back down the stack, I try to go by the first principal:  can it just change the model state and get popped, counting on its parent to notice the changes in viewDidAppear?
If I need further communication still, I begin to worry about my design, but the next place I go is KVO.  There again, view controllers are passive with respect to each other, watching the app's model for changes they care about.  I classify NSNotification in this category.  Even though it sounds like you want to rule it out, it's my third favorite idea after nothing.
While I'm editing here, I notice @Tommy has provided concise advice that I agree with (and consistent with my opinion here).  I'll leave the answer since it adds a little nuance.


text:
Q: Error in data validation on firebase database I'm trying to validate a date in my app with firebase database. The situation is:
I have a CalendarView, when I select a date, this date go to textview and when user click in button, I want to do the following validation if the date is in the database show a negative message, if the date isn't in the database save the date selected.
Here is the snippet of my code that is experiencing the error, the database and the error that appears.
On the android monitor, the error is
public class AgendarRecursoActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

    String TAG = "AgendarRecursoActivity";
    String nomeRecurso;

    TextView txtData;
    CalendarView calendario;

    Recurso recurso;

    TextView txtNome;
    Button btnAgendarRecurso;
    Spinner recursoSpinner;

    FirebaseDatabase firebaseDatabase;
    DatabaseReference databaseReference;

    private FirebaseAuth mAuth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_agendar_recurso);

        mAuth = FirebaseAuth.getInstance();

        FirebaseUser user = mAuth.getCurrentUser();

        //databaseReference = FirebaseDatabase.getInstance().getReference()
        //.child("recursos").child(user.getUid()).child("");

        calendario = (CalendarView) findViewById(R.id.calendarioRecurso);
        txtData = (TextView) findViewById(R.id.txtDataCalendario);
        txtNome = (TextView) findViewById(R.id.txtEmailUsuarioRecurso);
        btnAgendarRecurso = (Button) findViewById(R.id.btnAgendarRecurso);
        recursoSpinner = (Spinner) findViewById(R.id.spinner);

        txtNome.setText(user.getEmail());
        //txtData.setText("Data");

        databaseReference = FirebaseDatabase.getInstance().getReference();

        databaseReference.child("recursos").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                final List<String> recursoNome = new ArrayList<String>();

                for (DataSnapshot recursoSnapshot : dataSnapshot.getChildren()) {
                    //Pega título do nó
                    String recursoSnap = recursoSnapshot.getKey();

                    //Adiciona na lista
                    recursoNome.add(recursoSnap);
                }

                //Pega lista e poe no spinner
                ArrayAdapter<String> recursosAdapter = new ArrayAdapter<String>(AgendarRecursoActivity.this, android.R.layout.simple_spinner_item, recursoNome);
                recursosAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                recursoSpinner.setAdapter(recursosAdapter);

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        calendario.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
            @Override
            public void onSelectedDayChange(@NonNull CalendarView view, int year, int month, int dayOfMonth) {
                String date = dayOfMonth + "/" + (month + 1) + "/" + year;
                Log.d(TAG, "onSelectedDayChange: " + date);

                txtData.setText(date);
            }
        });

        btnAgendarRecurso.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                recurso = new Recurso();
                recurso.setNomeUsuario(txtNome.getText().toString());
                recurso.setDataRecurso(txtData.getText().toString());
                recurso.setNomeRecurso(recursoSpinner.getSelectedItem().toString());

                DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
                FirebaseUser user = mAuth.getCurrentUser();

                databaseReference.child("recursos").child(recursoSpinner.getSelectedItem().toString()).addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {

                        for(DataSnapshot snapshot: dataSnapshot.getChildren()) {

                            if(snapshot.child("dataRecurso").getValue().toString().equals(recurso.getDataRecurso())){  //error in android monitor is here

                                Toast.makeText(AgendarRecursoActivity.this, "Data indisponível", Toast.LENGTH_SHORT).show();

                            }

                            else{

                                reservarRecurso();

                            }

                        }

                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });

            }
        });
    }

    public void reservarRecurso(){

        databaseReference.child("recursos").child(recursoSpinner.getSelectedItem().toString()).push().setValue(firebaseDatabase, new DatabaseReference.CompletionListener() {
            @Override
            public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
                //Problem with saving the data
                if (databaseError != null) {
                    Toast.makeText(AgendarRecursoActivity.this, "Erro ao agendar recurso! Data não disponível", Toast.LENGTH_LONG).show();
                } else {
                    //Data uploaded successfully on the server
                    databaseReference.child("nomeUsuario").setValue(txtNome.getText().toString());
                    databaseReference.child("dataRecurso").setValue(txtData.getText().toString());
                    Toast.makeText(AgendarRecursoActivity.this, "Recurso agendado com sucesso!", Toast.LENGTH_LONG).show();
                    retornaTela();
                }
            }
        });

    }

    public void agendar(View v) {
        calendario = (CalendarView) findViewById(R.id.calendarioRecurso);
        SimpleDateFormat formatoData = new SimpleDateFormat("dd/MM/yyyy");
        String dataRecurso = formatoData.format(new Date(calendario.getDate()));

    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        nomeRecurso = parent.getItemAtPosition(position).toString();
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    public void retornaTela(){
        Intent intent = new Intent(this,MenuActivity.class);
        startActivity(intent);
    }

}

JSON Exported database
{
  "recursos" : {
    "Churrasqueira" : {
      "-KvyL-Lqbk_2laoU6dHZ" : {
        "dataRecurso" : "11/10/2017",
        "nomeRecurso" : "Churrasqueira",
        "nomeUsuario" : "d@d.com"
      },
      "-KvyQ1a0gkG-OYO4ru1-" : {
        "dataRecurso" : "19/10/2017",
        "nomeUsuario" : "d@d.com"
      },
      "-KvyZDPRNWOX4AJS3t2U" : {
        "dataRecurso" : "26/10/2017",
        "nomeUsuario" : "d@d.com"
      },
      "-Kw3HlJJGZeilpKZBhr8" : {
        "dataRecurso" : "11/10/2017",
        "nomeUsuario" : "d@d.com"
      }
    },
    "Escada" : {
      "-KvyMACClT8TnSU53NnT" : {
        "dataRecurso" : "12/10/2017",
        "nomeRecurso" : "Escada",
        "nomeUsuario" : "d@d.com"
      },
      "-Kw016X_JxFzzZ9lSzS2" : {
        "dataRecurso" : "17/10/2017",
        "nomeUsuario" : "sthomazdasilva@gmail.com"
      }
    },
    "Salão de festas" : {
      "-KvyMDjHdL314aki28EI" : {
        "dataRecurso" : "27/10/2017",
        "nomeRecurso" : "Salão de festas",
        "nomeUsuario" : "d@d.com"
      }
    }
  }
}

Can help me, please?


text:
Q: AWS API Gateway 403:Forbidden I am trying to call API of AWS through c#. It is getting me exception as

"The remote server returned an error: (403) Forbidden" .

But when I call same API from postman it works. I am creating signature as mentioned in answer by Vasil Indzhev
AWS API Gateway Signature

A: The error could be returned from CORS rejection at the API path during preflight request. Since Postman does not do the preflight request, this could be the reason why you are seeing the request works in Postman.


text:
Q: PostgreSQL: SELECT MAX numeric value for entire table from multiple columns I have a table similar to this (3 rows, 4 columns: id, name, gradeA, gradeB):
id    name    gradeA    gradeB
------------------------------
1     David   59        78
2     Anna    66        92
3     David   22        89

I'm looking for a query that will give me 1 numeric property for the highest grade by in the whole table by condition.
for example:

What is the highest grade for any student named David?

The answer should be  { maxGrade: 89 }
Note: grades are stored as varchar values and should be cast to numeric values for comparison

A: You need to combine max() with greatest()
select max(greatest(gradea::int, gradeb::int)) as max_grade
from the_table
where name = 'David';

If you need a JSON result (because you wrote: result should be {maxGrade: 89}), you can wrap that query and convert the row to JSON:
select to_jsonb(t)
from (
  select max(greatest(gradea::int, gradeb::int)) as "maxGrade"
  from the_table
  where name = 'David'
) t;

A: Try the below:
We shall achieve with GREATEST and MAX:

*

*We can make use of GREATEST to return the large value between the columns grade A and grade B for every user record

*And use MAX to return the maximum grade if more than user matches with the same name.

SELECT
  MAX(GREATEST(gradeA::integer, gradeB::integer)) as maxGrade
FROM
  "table_name"
WHERE
  "table_name"."name" = 'David';

A: I would recommend a lateral join:
select max(grade::int) as max_grade
from t cross join lateral
     (values (gradea), (gradeb)) v(grade)
where name = 'David';

In particular, this works if any of the grades are NULL.
It can also easily be tweaked to get which grade is the maximum:
select v.*
from t cross join lateral
     (values ('a', gradea), ('b', gradeb)) v(which, grade)
where name = 'David'
order by grade::int desc
limit 1


text:
Q: Git Rebasing issue I'm basically brand new to Git and am having some trouble rebasing. I had 9 commits on my branch - and I wanted to squash some of them together. So, in IntelliJ I did
git rebase -I

and went into the file and successfully altered my commits so that there are now only 7 commits. However, I then went to push to GitHub, and now, instead of altering the previous commits, it added the 7 commits as new and so there are 16 commits sitting on my branch.
How do I get my rebase to alter and not re-add?

A: Following a rebase, which by the way you would typically never want to do on your repository's main branches (i.e. develop or master) you would need to do a force push, i.e. git push -f.  This is due to the fact that the history of the repository has been changed, and as a result, you have to "overwrite" the history that is stored in the GitHub version of the repository.  When you pushed your changes, did you do a force push?


text:
Q: Yii2: Writing to database the date/time of the current record via expression There is table with some columns. One of it date_of_record. Means the date when current row is inserted in database. In current version i just calculate this field in PHP code before save().
How it should be correctly done via expression? Example by opportunity

A: Use Timestamp Behaviors In Controller :
use yii\db\Expression;

public function behaviors()
{
  return [
    [
        'class' => TimestampBehavior::className(),
        'createdAtAttribute' => 'date_of_record',
        'value' => new Expression('NOW()'),
    ],
  ];
}

References
1) Timestamp Behaviors
2) Concept Behaviors


text:
Q: Select all rows of all user logins, where user had logged in from more than 3 ip address within the past month Our SQL Server UserLogins table has these columns: UserID, DateTime, IpAddress.
How can I select rows of users who have logged in from more than three different ip addresses within a specified time period (e.g., one month), ordered by User ID

A: We can actually do this in one scan of the table, by using window functions. Unfortunately, we cannot use COUNT(DISTINCT... as a window aggregate, so we must hack it with DENSE_RANK and MAX
SELECT UserID, [DateTime], IpAddress
FROM (
    SELECT UserID, [DateTime], IpAddress,
        distinctIps = MAX(rn) OVER (PARTITION BY UserID)
    FROM (
        SELECT UserID, [DateTime], IpAddress,
            rn = DENSE_RANK() OVER (PARTITION BY UserID ORDER BY IpAddress)
            -- row-number distinct ip addresses
        FROM UserLogins
        WHERE [DateTime] >= DATEADD(month, -1, GETDATE())
    ) ul
) ul
WHERE distinctIps > 3;

A: You can use the DISTINCT clause inside of a COUNT() aggregate function in your HAVING clause after applying a GROUP BY on the UserId like so:
WITH CTE_Users_MoreThan3IpAddresses AS
(
    SELECT UserID
    FROM UserLogins
    WHERE [DateTime] >= '01/01/2021' AND [DateTime] < '02/01/2021' -- Sets the date range for logins (1 month example)
    GROUP BY UserID -- Groups all rows of the same UserID up
    HAVING COUNT(DISTINCT IpAddress) > 3 -- Filters out everything except User's with more than 3 unique IP Addresses
)

SELECT U.UserID, U.[DateTime], U.IpAddress
FROM UserLogins AS U
INNER JOIN CTE_Users_MoreThan3IpAddresses AS C
    ON U.UserID = C.UserID
ORDER BY U.UserID

Note you should be careful what names you use for your columns. DateTime is a reserved keyword in the SQL language to represent a data type, which is why I put the square brackets around it in this example (which tells SQL to actually treat it as a column name).


text:
Q: How can image effects be applied to text (TextObject) in Corona SDK? I'd like to apply image effects like blurring, wiping and masking to text displayed in my Corona SDK app.  If the text to be displayed were static, I could store it in an image file.  A DisplayObject based on that image could be instantiated using display.newImage() and the effects applied by setting the object's fill property. (This is explained in the section on image effects in the Corona Developer Guide to Graphics/Audio/Animation.)
However, the text I need to display changes every time the user launches the app.  It is based on a combination of phrases selected at random from a list and is displayed in a font and font size that depend on user preferences.  So the image asset approach cannot be used in this case.
Is there a way to apply image effects to TextObjects created using display.newText()?  These objects have no fill property, so it's not clear that these effects can be used.

A: It is true that TextObjects have no fill property and, to the best of my knowledge, there is no way to apply image effects directly to them. I tried various image effects and even simpler fills like gradients.  No dice.
I realized, however, that TextObjects (like all DisplayObjects) can be inserted into the GroupObject of a SnapshotObject which does have a fill property. From the Snapshots section of the Graphics dev guide:

Snapshots inherit all functionality of rectangles. For example, all 2.5D effects are available to snapshot objects.

By inserting only the TextObject into the snapshot and applying image effects to the latter, you effectively apply the effects to the text.
This code snippet demonstrates this solution.  The effect I'm implementing makes the text, which is initially hidden, appear through a circular keyhole with a blurry edge. (The transition is done in three phases to preserve the blurry region between the inner and outer radius.)
local textString = "This is some string generated at Runtime."
local textObj = display.newText({
    text = textString,
    font = myFavoriteFont,
    fontSize = myFavoriteFontSize})
textObj:setFillColor( 0 )

local snapshot = display.newSnapshot( textObj.contentWidth, textObj.contentHeight )
snapshot.group:insert( textObj )

snapshot.fill.effect = "filter.vignetteMask"
snapshot.fill.effect.innerRadius = 0.01
snapshot.fill.effect.outerRadius = 0

sceneGroup:insert( snapshot )

local totalTimeForTextToAppear = 2000 -- duration of transition in milliseconds
local timeStep = totalTimeForTextToAppear / 3 -- duration of each phase of the transition
transition.to( snapshot.fill.effect, {delay = 0, time = timeStep , innerRadius=0.5})
transition.to( snapshot.fill.effect, {delay = timeStep, time = timeStep, innerRadius=1} )
transition.to( snapshot.fill.effect, {delay = timeStep, time = timeStep, outerRadius=.5} )
transition.to( snapshot.fill.effect, {delay = 2 * timeStep, time = timeStep, outerRadius=.99} )

(When using this approach, all the usual "gotchas" regarding snapshots on Android devices apply.  These are discussed here.)
This is the solution I found to my question.  I would love to see any other workarounds I may have missed.


text:
Q: Arraylist in C# i have created a class named employees to hold the employee information. the class looks as follows.
class Employee
{
    private int employeeID;
    private string firstName;
    private string lastName;
    private bool eligibleOT;
    private int positionID;
    private string positionName;
    private ArrayList arrPhone;
    private ArrayList arrSector;

as you can see i have created an array named arrSector. it takes the name of the sectors which the employee is associated. now i also want to take in the sector id along with the sector name.
my question is how do i implement the sector id as well as the sector name in a single arraylist variable.
i want to store the value of sector id as wel as the sector name together.
any help is appreciated.

A: First of all: Don't use ArrayList if you can help it, at least if you're using .NET 2 or later. You can use the generic List<T> which is specific to the type you put in it, which saves you a lot of casting.
As for your problem, you probably want a Hashtable or Dictionary<TKey, TValue>. Hashtables are collections that store associations of one value (the key) to another value (the value). In your case you'd probably have an integer or a GUID as key and a string as value.
But as others have noted, you can also create a Sector class which essentially consists of the ID and a name and put instances of that class into your list.
What you gain here when using a Hashtable/Dictionary is that you have quick lookup by ID. When you search for a specific ID in a list you would have to iterate through the list (well, if it's sorted you can use a binary search) while a hashtable requires just a single lookup usually.

A: You might want to use a Dictionary instead of an ArrayList, but if you have to use an ArrayList, I would create a class or struct that holds both the SectorId and the SectorName.
With a Dictionary:
Dictionary<int, string> dictSector = new Dictionary<int, string>();
dictSector.Add(1,"MySectorName");
dictSector.Add(2,"Foo");
dictSector.Add(3,"Bar");

With an ArrayList:
class Sector {
  public int Id {set; get;}
  public string Name {set; get;}
}

ArrayList arrSectors = new ArrayList();
arrSectors.Add(new Sector() {Id = 1, Name = "MySectorName"});
arrSectors.Add(new Sector() {Id = 2, Name = "Foo"});
arrSectors.Add(new Sector() {Id = 3, Name = "Bar"});

A: Create an object to hold both pieces of information.
public class Sector
{
    public string Name { get; set; }
    public int Id { get; set; }
}

Then use a generic List instead of an ArrayList.
class Employee
{
    private int employeeID;
    private string firstName;
    private string lastName;
    private bool eligibleOT;
    private int positionID;
    private string positionName;
    private ArrayList arrPhone;
    private List<Sector> arrSector;
}

A: Not really sure what you mean. I think you should implement a Sector class and probably also use generic lists.
class Employee
{
    // field
    private List<Sector> sectors;
    // property to get the sectors
    public List<Sector> Sectors { get { return this.sector; }
}

// sector class
class Sector
{
  int Id { get; set; }
  string Name { get; set; }
}

A: class Sector
{
    int id;
    string name;
}

class Employee
{
   ...
   List<Sector> sectors;
}

A: Define a new Sector class:
public class Sector
{
    public int Id { get; set; }

    public string Name { get; set; }
}

Then define the list as a List<Sector> like this:
private List<Sector> sectors;

A: If your sector has 2 values (ID and name), guess you (sh)could:

*

*Create a class (inner, public, your call) to hold those values.

*Create a struct, see it here

*Use a KeyValuePair, it will hold both info, but this is lame.

And all other answers are good as well, specially when advising you to use generic lists.


text:
Q: Multiple UISwitch on the view controller I have two UISwitch, both call the same method on the click event, so in that methodi need to distinguish between the two switch to know who send the event. For that i assigned tag only for one of them:
switch1.tag=0;

In the method that gets fired when one of these UISwitch gets clicked, i make that test:
-(void)switchValueGetsChanged:(UISwitch*)sender{

    if (sender.tag==0) {
        NSLog(@"It's switch 1");
    }else{

        NSLog(@"It's switch 2");
    }

Now, when i run the code, what i noticed is that i get always the first message:
    NSLog(@"It's switch 1");

Even when i click on the second UISwitch. I solved the issue by assigning a tag for the second UISwitch as well:
switch1.tag=0;
switch2.tag=1;

Now, the problem is solved, so my question is: if you get more than one UISwitch, and you want to judge on the tag value, is it mandatory to assign tag property for all your UISwitchobjects ? Thanx in advance.

A: You asked:

if you get more than one UISwitch, and you want to judge on the tag value, is it mandatory to assign tag property for all your UISwitch objects?

If you want to differentiate any view based on its tag property then yes, you must set its tag property. How else could you check the tag if you don't set the tag?
BTW - don't use 0 as one of your tag values. This is the default for all views so setting it to 0 doesn't really help any.


text:
Q: Split a string after a specific character in BigQuery I have a field that contains street name, state, and zip code that I need to pull just the state abbreviation from. I tried using SUBSTR but the challenge is that sometimes the zip codes are the full 9 digit zipcodes (and not just the 5 digit zips). I'm sure there is an easy way to do this with maybe REGEX but I can't figure out the correct syntax.
Example:
123 Street ABC, NY 12345
1234 Street, NY 12345-1234
Need to return:  NY

A: Below works backward and looks for first 2 chars, so it does not matter how zip cod is represented or if it missed at all
select reverse(regexp_extract(reverse(address), r'[A-Z]{2}')) state
from `project.datatset.table`


text:
Q: Why can't I see my database when creating File DSN for Azure SQL? I am trying to set up a File DSN in order to export data from a local Access database to a cloud Azure SQL database.
I have followed the instructions here to create the DSN.
It "works" in so far as when I test the connection to the database it connects successfully.
However, it defaults the database to "master", whereas I want to use "mydatabase". The Change Default Database dropdown only has master, mydatabase doesn't appear so I can't change it.
So if I use the default settings I get the error that CREATE TABLE is denied in master.
I edited the File DSN via notepad in to include the line "DATABASE=mydatabase", but then I get the error: "Reference to database and/or server name in 'master...sysdatabases' is not supported in this version of SQL Server.
How can I set this up to specify the correct database and have it work properly?

A: You don't reveal your connection string, but Server requires an extended syntax with AzureSQL, as does Uid, like:
"ODBC;Driver=SQL Server Native Client 13.0;Server=tcp:b8uroj8q5d.database.windows.net;Database=YourDatabase;Uid=username@b8uroj8q5d;Pwd=YourPassword;Encrypt=yes"

A: As described in my comment on @Gustav's answer, the resolution to this should anyone have a similar problem is actually to create the File DSN direct from the Access Export wizard and not using the Administrative Tools wizard per the link in my question.
The Access Export wizard allows you to select the driver: ODBC Driver 13 for SQL Server and not the driver SQL Server.
(The reason I knew this was the driver to use is because on the Azure portal under Connection Strings > ODBC it shows that driver.)
Some other points: don't copy your server name from the azure portal, again use what it says in the connection string. (i.e. rather than {yourserver}.database.windows.net you use tcp:{yourserver}.database.windows.net,1433 and the username is also {username]@{yourserver} and not just {username}
The Access Wizard will then allow you to change the default database away from master.


text:
Q: What does it mean for a parameterised path to be spherically symmetric? This question seems embarrassingly simple, but I was wondering what it means for an object to be spherically symmetric? I've been working through some questions where I'm told to use this fact to help simplify working with paths in space.
I understand what this means intuitively (maybe), but am having difficulty expressing this condition mathematically. Say we have a parameterised path given by:
$\sigma(s)=(r(s), \theta(s), \phi(s))$
What does it mean for this to be spherically symmetric? Some people have suggested this means $\frac{d\theta}{ds}=\frac{d\phi}{ds}=0$
Thinking about this, I initially thought about a circle which is (I think?) is a spherically symmetric path, i.e. the path in polar coordinates $(r, \theta, \phi)$ given by:
$x(s)=(R, 2\pi s, 0)$,
where $R$ is fixed and $s\in[0, 1]$
This doesn't have $\frac{d\theta}{ds}=0$, which makes me think the condition must be something else? Or is the circle not a spherically symmetric path because it isn't the same in ALL directions (eg. $\phi\ne 0$). In this case, any idea what could my books be referring to when they talk about using spherical symmetry to simplify working with paths?

A: My answer might not be truly correct by "definition", but I'm going to attack it from a different viewpoint. I am inspired by the action $J$ of a functional
$$ J = \int_{x_1}^{x_2} f(x,y,\dot y)dx $$
as in Lagrangian mechanics. You can solve this problem to solve the geodesics of physical geometries. For example in Euclidean space, the functional is $ds = \sqrt{dx^2 + dy^2} = \sqrt{1+{\dot y}^2}dx$, which minimizes to a linear solution $y-y_0 = m(x-x_0)$ in applying Lagrange's equations.
Here $ds$ is a function of $x$ and $y$, which are all of the independent coordinates belong to that that 2D space. Now let's go to your example of the circle: in polar coordinates, we write a general displacement as
$$ dr = \sqrt{dr^2 + (rd\theta)^2} $$
But in the case of a circle, the radius does not change over the movement, so
$$ ds = rd\theta.$$
Here, I would say the circle has spherical symmetry because the displacement - or from my inspiration, the functional minimized to uncover its geodesic - maintains a constant radial distance $r$ with respect to the other variables.
Properly I believe you should write $$d\vec{x} = dr{\hat r} + rd\theta \mathbf{\hat{\theta}},$$
which collapses to a circular displacement in the limit of $r \rightarrow 0$. The real condition I think for spherical symmetry resulting of this is
$$ \frac{dr}{d\theta} = \frac{dr}{d\phi} = 0 $$
which is to say that $r$ remains constant under changes of $\theta$ and $\phi$.
Now for your position vector $\vec{x}(s) = (R, 2\pi s,0)$. Differentiate with respect to your parameter $s$:
$$ \frac{d\vec x}{ds} = (0, 2\pi, 0),$$
which is a circular path of $2\pi$ radians. Here we needed to satisfy $\frac{dR}{ds} = 0$ for the circle, which is certainly does.
Here $ds = \frac{1}{2\pi}d\theta$ so we have the condition that $\frac{dr}{d\theta} = 0$ hidden there.


text:
Q: Make SVG height smaller in size & full-width? I have SVG & it is of size 1326 x 745.
SVG looks like:
import React from 'react'

export const Wave = (props: React.SVGProps<SVGSVGElement>) => {
    return (
        <svg viewBox="0 0 16 9" {...props}>
            <path
                d="M0 8L0.2 7.8C0.3 7.7 0.7 7.3 1 7.2C1.3 7 1.7 7 2 6.8C2.3 6.7 2.7 6.3 3 6C3.3 5.7 3.7 5.3 4 5.7C4.3 6 4.7 7 5 7.5C5.3 8 5.7 8 6 7.5C6.3 7 6.7 6 7 5.7C7.3 5.3 7.7 5.7 8 5.8C8.3 6 8.7 6 9 6.2C9.3 6.3 9.7 6.7 10 6.8C10.3 7 10.7 7 11 6.7C11.3 6.3 11.7 5.7 12 5.7C12.3 5.7 12.7 6.3 13 6.5C13.3 6.7 13.7 6.3 14 6.3C14.3 6.3 14.7 6.7 15 6.8C15.3 7 15.7 7 15.8 7L16 7L16 10L15.8 10C15.7 10 15.3 10 15 10C14.7 10 14.3 10 14 10C13.7 10 13.3 10 13 10C12.7 10 12.3 10 12 10C11.7 10 11.3 10 11 10C10.7 10 10.3 10 10 10C9.7 10 9.3 10 9 10C8.7 10 8.3 10 8 10C7.7 10 7.3 10 7 10C6.7 10 6.3 10 6 10C5.7 10 5.3 10 5 10C4.7 10 4.3 10 4 10C3.7 10 3.3 10 3 10C2.7 10 2.3 10 2 10C1.7 10 1.3 10 1 10C0.7 10 0.3 10 0.2 10L0 10Z"
                strokeLinecap="round"
                strokeLinejoin="miter"
                fill="currentColor"
            ></path>
        </svg>
    )
}

It takes so much space. I want it to be really small. Only take up wave space.

I made this Wave SVG on https://app.haikei.app/
I tried all configurations but I can't get it to be small.
All I want is width to be 100% no matter which device I'm on & it should have a proportional height. What do I need to do to change it?


text:
Q: How can we update/concatenate whereHas condition in Laravel Hi everyone Could someone let me know how can we update/concatenate  whereHas condition in Laravel
Example#1.
$posts = Post::whereHas('comments', function (Builder $query) {
    $query->where('content', 'like', 'code%');
});

if($request->has('user_id') && $request->user_id >0){
   $posts = Post::whereHas('comments', function (Builder $query) use($request) {
    $query->where('user_id', $request->user_id);
   });
}

$posts->get();

I know I can combine both whereHas quires in one like this
Example#2
$posts = Post::whereHas('comments', function (Builder $query) use($request) {
    $query->where('content', 'like', 'code%');
    if($request->has('user_id') && $request->user_id >0){
       $query->where('user_id', $request->user_id);
    }
});

But I dont want this way I want to adopt first example in my project. Could you please let me know if this possible

A: I guess you want to operate on the same query. You can keep adding conditions to your query, by saving the query builder as an variable, like $query = Post::where('title', 'something');.
The query builder also has a method called when(), that is conditional syntactic sugar for the if statement you have made.
$posts = Post::whereHas('comments', function (Builder $query) {
    $query->where('content', 'like', 'code%');
})->when($request->has('user_id') && $request->user_id > 0, function ($query) use ($request) {
    $query->whereHas('comments', function (Builder $query) use ($request) {
         $query->where('user_id', $request->user_id);
    });
})->get();


text:
Q: Thompson Router and public IP address I have a Thompson ST546 Router and I want to give it a public ip address and give two servers behind it public ip addresses as well.
Now I am having great trouble getting this set in the web interface.
My router IP address is 91.85.232.65 with .66 and .67 will be the two servers. What is the subnet for these ips? Is it 255.255.255.248?
I have assigned my server the public address but if I try to ping it I am getting no response as if the ip is only a local address. My server is windows server 2008, is there a setting to turn ping on/off that I might have missed? I know the server is pingable internally.
Just to make it clear my ISP has assigned me IPs x.65 to x.70 for my use

A: The usual configuration would be that your WAN side should still be set to use DHCP unless they gave you a static IP specifically for your side of the link to them. The LAN IP of your router should be set to 91.85.232.65. You are correct, the subnet should be 255.255.255.248.
Your server should have an IP address of 91.85.232.66 or .67, the subnet mask should be 255.255.255.248 and the default gateway should be 91.86.232.65.
Before you test if you can reach your servers, test if your servers can traceroute out past the router. Also, you'll need to configure static DNS IP addresses in the servers.