text:
Q: How can I discriminate a union of interfaces using an object map without switch statement? I'm fairly new to advanced typescripts concepts so bear with me.
I have a number of projects that use objects to map out react components by some common prop (e.g _type).
What I want to do is automatically return the correct type for the component resolved using these object maps, however I just receive a type of any when I try this.
Many posts online recommend using switch statement (example below). Our company uses the object map pattern so I'd like to avoid using the switch statements if possible. Thanks.
For added context, this is our first react project using typescript (moving from javascript).
// types
type AnimalType = 'cat' | 'dog'

interface Cat {
  _type: AnimalType
  name: string
  onMeow: () => void
}

interface Dog {
  _type: AnimalType
  name: string
  onBark: () => void
}
type Animal = Cat | Dog

type AnimalMap = {
  [property in Animal['_type']]
}

// THIS WORKS BUT WE DON'T WANT TO USE THIS
// resolving animal type via switch
const CatComponent = ({ _type, name, onMeow }: Cat) =>
I'm a cat!

const DogComponent = ({ _type, name, onBark }: Dog) =>
I'm a dog!

function resolveAnimal(_type: AnimalType): React.Component<Animal> {

  switch(_type) {
    case "dog": return DogComponent
    case "cat": return CatComponent
  }
  return animalMap[_type]
}

// THIS DOESN'T WORK, WE'D LOVE TO USE THIS!
// resolving animal type via object map

const animalMap: AnimalMap = {
  cat: CatComponent,
  dog: DogComponent,
}

function resolveAnimal(_type: AnimalType): React.Component<Animal> {
  return animalMap[_type]
}

function App() {
  const ResolvedAnimalComponent = resolveAnimal('dog')
  return <ResolvedAnimalComponent onBark={() => console.log('HE BARKED')} />
}

A: Remove the explicit notation of : AnimalMap so that the object declaration values are not widened - you want TypeScript to see
const animalMap: {
  cat: CatComponent,
  dog: DogComponent,
}

not
const animalMap: AnimalMap

(not only because your AnimalMap doesn't note the values - the components - but also because it doesn't tie the properties to their components)
Use
const animalMap = {
    cat: CatComponent,
    dog: DogComponent,
}

function resolveAnimal<T extends keyof typeof animalMap>(_type: T) {
    return animalMap[_type]
}


text:
Q: How to implement pure client side pagination without requests to the server in react, using react-table and react-paginate components? I am using an array of objects that comes from the server in componentDidMount method and then I save it into the state.
If I change page size from select component everything is ok, but the page number clicks don't work.
For example,  I set the page size to 20. My data array length equal to 29, so I have 2 pages. In the react table, there are 20 rows, and selected page - number 1. When I select page 2, nothing happens. It should have shown the remaining 9 rows but nothing occurs.
I know that in general the amount of data corresponding to the page size must come from the server when click to another page occurs. But I was given the task that I should implement everything without requests to the server.
How I can implement this? Any of your help will be useful, great thanks in advance! Here is my code:
constructor:
    perPage: JSON.parse(localStorage.getItem('detailsTablePerPageOrderEdit')) || 20,
    pageRanges: [20, 50, 100, 200, 300, 500, 1000],

                 <CustomReactTable
                    columns={columnsDetails}
                    tableHeight={_.isEmpty(this.state.details) ? '25vh' : '80%'}
                    data={this.state.details}
                    onTrClick={(data) => this.handleDetailSelect(data)}
                    pageSize={this.state.perPage}
                  />
                  <PaginationRow
                    changePerPage={(pageSize) => this.onPageSizeChange(pageSize)}
                    count={this.state.details.length}
                    handlePageChange={(page) => this.handlePageChange(page)}
                    page={this.state.page}
                    perPage={this.state.perPage}
                    pageRanges={this.state.pageRanges}
                  />

        handlePageChange = (page) => {
       this.setState({ page: page.selected + 1 });
          //I think, here should be some code to implement pagination
       };
onPageSizeChange = pageSize => {
    console.log(typeof pageSize);
    localStorage.setItem('detailsTablePerPageOrderEdit', pageSize);
    this.setState({
      page: 1,
      perPage: pageSize
    });
  };

paginationRow component:
import React from 'react';
import {Row, Col} from 'react-bootstrap';
import ReactPaginate from 'react-paginate';
import PaginationCount from './PaginationCount';
import i18n from '../../i18n';

export default (props) => {

  if(props.count <= 0 || props.page < 0 || props.perPage < 0){
    return null;
  }

  const fromItem = (props.page - 1) * props.perPage + 1;
  let toItem = props.page * props.perPage;

  toItem = toItem > props.count ? props.count : toItem;

  const handlePageSizeChange = e => {
    props.changePerPage && props.changePerPage(e.target.value);
  };

  const pageRanges = props.pageRanges || [50, 100, 200, 300, 500, 1000];

  return(
    <Row>

        <ReactPaginate
          activeClassName="active"
          breakLabel={...}
          containerClassName="pagination"
          disableInitialCallback
          forcePage={props.page - 1}
          initialPage={props.page - 1}
          marginPagesDisplayed={5}
          nextLabel={i18n.t('PaginationRow.next_label')}
          onPageChange={props.handlePageChange}
          pageCount={props.count/props.perPage}
          pageRangeDisplayed={5}
          previousLabel={i18n.t('PaginationRow.previous_label')}
          subContainerClassName="pages pagination"
        />

      {props.perPage ?

            <select
              className="form-control paginationSelect" id="exampleFormControlSelect1"
              name="perPage"
              onChange={handlePageSizeChange}
              value={props.perPage}
            >
              {pageRanges.map(r => (<option key={r} value={r}>{r}</option>))}
            </select>

  : null
      }

          <PaginationCount
            itemFrom={fromItem}
            itemTo={toItem}
            totalCount={props.count}
          />

    </Row>
  );
};

A: It looks like you have to modify your array of results based on page state (current pagination page).
With F.E array.slice func:
function paginate (array, page_size, page_number) {
  return array.slice((page_number-1) * page_size, (page_number) * page_size);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why additional options for JSLint in Notepad++ are ignored? I Installed the JSLint plugin at Notepad++ with choosing JSLint in Plugins/Plugin Manager.
My Additional options at Plugins/JSLint/JSLint Options are ignored.
I added: /* jslint nomen: true,  vars: true, plusplus: true */ in the Additional options field.
var _this = this; is still causing the Error Unexpected dangling '_' in '_this'
Some Options can be set by clicking on it. This works. Unfortunately not all options are available as a click option.
I also included in the Predefined field: "$","window","document","Image". This is also ignored:
var i = new Image(); => 'Image' was used before it was defined.
How can I define additional options for JSLint in Notepad++?

A: I found out:
Write only the options in the field Plugins/JSLint/JSLint Options/Additional options, without the starting /*jslint and ending */.
Write the names in the field Plugins/JSLint/JSLint Options/Predifined without ".
Klick at Assume a browser, than only $ is needed in the Predifined field for jQuery.
If options are used in the source code, space between /* and jslint is not allowed. Use /*jslint and NOT /* jslint.


text:
Q: Query & Sort Comments by custom comment meta I added a basic "favorite/recommend" functionality for posts and comments to a wordpress site I'm working on.
I'm storing the total numbers of comment "likes" in  a custom comment meta field (update_comment_meta). Now I would like to query and sort comments based on this custom meta key and the corresponding values in order to display popular comments.
Ideally I would like to be able to use parameters like "meta_key" and "order_by=meta_value_num" similar to WP_Query, but apparently comment queries don't support those.
Do I have to use a custom written query to the database? If so, could anybody give me an initial push as to how to approach this?

A: Unfortunately it's unsupported by the applicable WordPress functions for querying comments, which is primarily due to(i feel) not enough people(or anyone) yet asking for it.
I want to highlight a couple of core files here to help understand the issue.

*

*First up comments-template.php, the comment_template function, it's this function that queries for comments and then adds them to the WP_Query object.

*

*See Line 882

*No filters or actions there to intercept the query before it happens, or change it.

*

*Next up comments.php and the get_comments function, this time you'll find no support for custom sorts, eg. meta sorting.

*

*See Line 262

*The array_intersect looks for matches only, if it's not in that array of values you see there then it's not considered a valid order.

There is one filter in the comment template function though that will pass on the whole array of comments called comments_array (you'll see that hook in the first file i linked to on line 892).
You could loop over the array of comments that have been fetched and build a new array that's sorted based on your meta data(though you'd probably need a custom query to go fetch the meta data if you want to be as efficient as possible).
I can add an example of array juggling later if you need one.


text:
Q: Python: Why does split do not work correctly for numbers I thing split() function do not work correctly if I want split number as string which one I converted from float.
Main question is how to fix my code.?
To show you my problem I wrote short script in python. You can copy and run.
#!/usr/bin/env python3
# coding=utf-8

def f_test(number):
    print(f"I will split {number}")
    if isinstance(number, float):
        print('This number is float')
        number = str(number)
        print(f'I changed type to str: {type(number)}')
    else:
        print('This number is string')
    l1 = number.split('.')
    print(l1)
    print()

f_test(2.12)
f_test('2.12')

f_test(0.1)
f_test('0.1')

f_test(0.000000001)
f_test('0.000000001')

f_test(0.000107)
f_test('0.000107')

f_test(0.0000107)
f_test('0.0000107')

Because i do not know the type of this number, I have to check is that float or string.
If is float I convert it to str.
In my opinion is something wrong with conversion float to string, because after conversion python show type as string, but print show the following form significand *(base)^exponent for float
For test i used numbers as float and str. That what i got you can see bellow.
Strange behavior for 0.000000001 and 0.0000107.
Generally split doesn't work correctly for all numbers as float converted to string In situation when after conversion print show float representation like this 1.07e-5
I will split 2.12
This number is float
I changed type to str: <class 'str'>
['2', '12']

I will split 2.12
This number is string
['2', '12']

I will split 0.1
This number is float
I changed type to str: <class 'str'>
['0', '1']

I will split 0.1
This number is string
['0', '1']

I will split 1e-09
This number is float
I changed type to str: <class 'str'>
['1e-09']

I will split 0.000000001
This number is string
['0', '000000001']

I will split 0.000107
This number is float
I changed type to str: <class 'str'>
['0', '000107']

I will split 0.000107
This number is string
['0', '000107']

I will split 1.07e-05
This number is float
I changed type to str: <class 'str'>
['1', '07e-05']

I will split 0.0000107
This number is string
['0', '0000107']

I am using Python 3.8.6


text:
Q: Limits in two variables What is the value of the following limit? $$L=\lim_{(x,y)\rightarrow (\alpha,0)}\left (1+\frac{x}{y} \right )^{y}$$
I rewrite the expression as$$\lim_{(x,y)\rightarrow (\alpha,0)}\left ( \left (1+\frac{x}{y} \right )^\frac{y}{x} \right )^\alpha$$ (as x tends to $\alpha$)
Setting $t=\frac{y}{x}$ the expression reduces to $M^{\alpha}$ where $$M= \lim_{t\rightarrow 0}\left ( 1+\frac{1}{t} \right )^{t}$$
Now the limit of M exists and is equal to 1, I have two questions in this regard

*

*If t approaches zero from the negative side, finding limit by taking natural logarithms would not be justified, while t, approaching from positive side, gives a limit of 1, so how does the limit exist and is equal to 1?

*Assuming M=1, the value of L should be 1, however the textbook I am referring to shows the answer as $e^{\alpha}$


text:
Q: I want to avoid id duplication and add values using push controller
$scope.items = [
      {"id" : 1 , "itemname" : "name_1", "comment" : "dsdsd", "price" : 5000},
      {"id" : 1 , "itemname" : "name_2", "comment" : "dddd", "price": 3000},
      {"id" : 3 , "itemname" : "name_3", "comment" : "sdasd", "price" : 2000},
      {"id" : 4 , "itemname" : "name_4", "comment" : "asdasd", "price" : 3000},
      {"id" : 5 , "itemname" : "name_5", "comment" : "asdasd", "price" : 2000}
    ]
$scope.addToCart=function(item){
cart.add(item);
}
service
    cartObj.cart.add=function(item){
      cartObj.cart.push(item);
    };

id: {{item.id}}

itemname: {{item.itemname}}

top code cart.html

[ addcart ]

top code index.html
Example OUTPUT
id   1
   name_1    5000
   name_2    3000
id   3
   name_3    2000
id   4
   name_4    3000
id   5
   name_5    2000

A: You can check if it's safe to push to an array before pushing on to it.
if ($scope.items.indexOf(item) == -1) {
   $scope.items.push(item);
}

A: You can check wether there's already an item with that id, before pushing.
let oldItem = $scope.items.find(elm => elm.id === item.id);
if(oldItem){
    //you can assign the properties of `item` to the one in the list
    Object.assign(oldItem, item);
}else{
    $scope.items.push(item);
}


text:
Q: Why is Ebean ORM throwing java.sql.SQLException: IJ031021: You cannot rollback during a managed transaction I have a Jax-RS Rest service that uses Ebean to query the database. On any query I make this exception is thrown.
For example.
User currentUser = new QUser().where().id.eq(currentUserID)).findUnique();

Logs

ERROR [io.ebeaninternal.server.transaction.JdbcTransaction] (default task-10) Error when ending a query only transaction via ROLLBACK: java.sql.SQLException: IJ031021: You cannot rollback during a managed transaction

Now the query returns the appropriate user and doesn't interfere with the Jax-RS.
But I can't ignore the large code-smell
And the huge log that is created because it gets thrown on every query.
My Configuration
ServerConfig config = new ServerConfig();
        config.setDataSource(ds);
        config.setName("db");
        config.setAutoCommitMode(false);
        config.setDatabasePlatform(new PostgresPlatform());
        config.setRegister(true);
        config.setDefaultServer(true);
        config.setTransactionRollbackOnChecked(true);
        config.addPackage(User.class.getPackage().getName());
        EbeanServer es = EbeanServerFactory.create(config);

A: When using ebean inside Java EE you need to configure the EbeanServer before it is used. A typical place to do it is in a @PostConstruct method in a @Startup @Singleton bean-managed transaction ejb. And you need to configure it to use the JTA transaction manager so it doesn't try to begin/commit the transactions on its own.
@Singleton
@Startup
@TransactionManagement(TransactionManagementType.BEAN)
public class AtStartup {

    @Resource(mappedName = "java:jboss/datasources/EbeanTestDS")
    private DataSource ds;

    @SneakyThrows
    @PostConstruct
    public void startup() {
        new MigrationRunner(new MigrationConfig()).run(ds); // begin/commits transaction for the migration...

        ServerConfig config = new ServerConfig();
        config.setDataSource(ds);
        config.addPackage(Customer.class.getPackage().getName());
        config.setUseJtaTransactionManager(true); // This is important !
        config.setAutoCommitMode(false);
        EbeanServerFactory.create(config);
    }


text:
Q: SSIS Error - ODBC Source I am using ODBC connection to connect to MYSQL in SSIS - the connection is successful, but when the SSIS package is executed, I get the below error.
[ODBC Source [30]] Error: SQLSTATE: 22018, Message: [MySQL][ODBC 8.0(a) Driver][mysqld-5.7.30-0ubuntu0.16.04.1];  [ODBC Source [30]] Error: SSIS Error Code DTS_E_INDUCEDTRANSFORMFAILUREONERROR.  The "ODBC Source.Outputs[ODBC Source Output]" failed because error code 0xC020F450 occurred, and the error row disposition on "ODBC Source" specifies failure on error. An error occurred on the specified object of the specified component.  There may be error messages posted before this with more information about the failure.
[SSIS.Pipeline] Error: SSIS Error Code DTS_E_PRIMEOUTPUTFAILED.  The PrimeOutput method on ODBC Source returned error code 0xC0209029.  The component returned a failure code when the pipeline engine called PrimeOutput(). The meaning of the failure code is defined by the component, but the error is fatal and the pipeline stopped executing.  There may be error messages posted before this with more information about the failure.
I looked online for the solutions, but nothing worked. I have done enoough investigation but no use.
Thanks in advance.

A: I am not sure why I got this error, But the error resolved -- In the source --> Error output, I selected Ignore Failure for the columns


text:
Q: How to fetch stock exchange data with Python I am writing a small program to fetch stock exchange data using Python. The sample code below makes a request to a URL and it should return the appropriate data. Here is the resource that I am using:
https://python.plainenglish.io/4-python-libraries-to-help-you-make-money-from-webscraping-57ba6d8ce56d
from xml.dom.minidom import Element
from selenium import webdriver
from bs4 import BeautifulSoup
import logging
from selenium.webdriver.common.by import By
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

url = "http://eoddata.com/stocklist/NASDAQ/A.htm"
driver = webdriver.Chrome(executable_path="C:\Program Files\Chrome\chromedriver")
page = driver.get(url)
# TODO: find element by CSS selector
stock_symbol = driver.find_elements(by=By.CSS_SELECTOR, value='#ctl00_cph1_divSymbols')
soup = BeautifulSoup(driver.page_source, features="html.parser")
elements = []
table    = soup.find('div', {'id','ct100_cph1_divSymbols'})
logging.info(f"{table}")

I've added a todo for getting the element that I am trying to retrieve from the program.
Expected:
The proper data should be returned.
Actual:
Nothing is returned.

A: It is most common practice to scrape tables with pandas.read_html() to get its texts, so I would also recommend it.
But to answer your question and follow your approach, select <div> and <table> more specific:
soup.select('#ctl00_cph1_divSymbols table')`

To get and store the data you could iterat the rows and append results to a list:
data = []
for row in soup.select('#ctl00_cph1_divSymbols table tr:has(td)'):
    d = dict(zip(soup.select_one('#ctl00_cph1_divSymbols table tr:has(th)').stripped_strings,row.stripped_strings))
    d.update({'url': 'https://eoddata.com'+row.a.get('href')})
    data.append(d)

Example
from bs4 import BeautifulSoup
import requests
import pandas as pd

url = "https://eoddata.com/stocklist/NASDAQ/A.htm"
res = requests.get(url)
soup = BeautifulSoup(res.text)

data = []
for row in soup.select('#ctl00_cph1_divSymbols table tr:has(td)'):
    d = dict(zip(soup.select_one('#ctl00_cph1_divSymbols table tr:has(th)').stripped_strings,row.stripped_strings))
    d.update({'url': 'https://eoddata.com'+row.a.get('href')})
    data.append(d)
pd.DataFrame(data)

Output

Code
Name
High
Low
Close
Volume
Change
url

0
AACG
Ata Creativity Global ADR
1.390
1.360
1.380
8,900
0
https://eoddata.com/stockquote/NASDAQ/AACG.htm

1
AACI
Armada Acquisition Corp I
9.895
9.880
9.880
5,400
-0.001
https://eoddata.com/stockquote/NASDAQ/AACI.htm

2
AACIU
Armada Acquisition Corp I
9.960
9.960
9.960
300
-0.01
https://eoddata.com/stockquote/NASDAQ/AACIU.htm

3
AACIW
Armada Acquisition Corp I WT
0.1900
0.1699
0.1700
36,400
-0.0193
https://eoddata.com/stockquote/NASDAQ/AACIW.htm

4
AADI
Aadi Biosciences Inc
13.40
12.66
12.90
98,500
-0.05
https://eoddata.com/stockquote/NASDAQ/AADI.htm

5
AADR
Advisorshares Dorsey Wright ETF
47.49
46.82
47.49
1,100
0.3
https://eoddata.com/stockquote/NASDAQ/AADR.htm

6
AAL
American Airlines Gp
14.44
13.70
14.31
45,193,100
-0.46
https://eoddata.com/stockquote/NASDAQ/AAL.htm

...


text:
Q: lists:map(lists:sum,[[1,2,3,4],[1,2,3]) is not allowed. Instead of list:sum there must be a fun? Why is the following not allowed:
156> lists:map(lists:sum,[[1,2,3,4],[1,2,3]).
* 1: illegal expression

, and when I make a fun around lists:sum, it is allowed:
162> lists:map(fun (L)->lists:sum(L)end,[[1,2,3,4],[1,2,3]]).
[10,6]

?

A: @spkhaira answer is correct, reasoning behind this syntax decision is that in Erlang functions and variables occupies different namespaces, it is similar to Lisps 2. This is mostly because of 2 reasons:

*

*Erlang is dynamically typed language

*Functions in Erlang are defined by 2 values: it's name and arity (amount of arguments)

With these 2 properties we cannot deduce what "version" of the function you want to call, that is why you need to use /N. What about fun prefix? It is just needed for parser to differentiate between erlang:'/' (aka division) and /N that is used for defining arity.

A: Try this -
lists:map(fun lists:sum/1,[[1,2,3,4],[1,2,3]]).


text:
Q: C: Read Binary and Write as encoded text I wish to read a jar in binary mode and write the binary as string(encoded if need be) to a file.
This string would be included in code to be read and converted back into binary and written as a jar file.
I'm trying to replicate what get-pip.py has done to distribute pip.
What would be the best way to do this in C?

A: You can use base64 encoding for this.  Base64 is a standard, and you can use the encoder from one implementation, and the decoder from another, and you'd get back the original string on the other side.  The typical straightforward implementation is a table driven one, as in this answer here:  https://stackoverflow.com/a/6782480/1212725


text:
Q: How to display an image when a button is pressed in JavaFX I'm having trouble figuring out how to display an image when a button is pressed. Here's what I have so far:

public class Flags extends Application {
@Override
public void start(Stage primaryStage) {
   //Create a label to display a prompt
    Label promptLabel = new Label("Select Button to Display a Flag");

   //Create buttons to display the flags
    Button americanButton = new Button("American Flag");
    Button canadianButton = new Button("Canadian Flag");
    Button frenchButton = new Button("French Flag");
    Button germanButton = new Button("German Flag");
    Button mexicanButton = new Button("Mexican Flag");

    //Creating an HBox
    HBox hbox = new HBox(10, promptLabel);
    HBox hbox1 = new HBox(10, americanButton);
    HBox hbox2 = new HBox(10, canadianButton);
    HBox hbox3 = new HBox(10, frenchButton);
    HBox hbox4 = new HBox(10, germanButton);
    HBox hbox5 = new HBox(10, mexicanButton);

    americanButton.setOnAction(new AmericanButtonHandler());

    //Creating a VBox
    VBox vbox = new VBox(10, hbox, hbox1, hbox2, hbox3, hbox4, hbox5);

    //set vbox padding
    vbox.setPadding(new Insets(10));

    //set vbox alignment
    hbox.setAlignment(Pos.CENTER);
    //gridpane.setAlignment(Pos.CENTER);
    hbox1.setAlignment(Pos.CENTER);
    hbox2.setAlignment(Pos.CENTER);
    hbox3.setAlignment(Pos.CENTER);
    hbox4.setAlignment(Pos.CENTER);
    hbox5.setAlignment(Pos.CENTER);

    //Create a scene
    Scene scene = new Scene(vbox);

    primaryStage.setTitle("Flags");
    primaryStage.setScene(scene);
    primaryStage.show();
}

class AmericanButtonHandler implements EventHandler<ActionEvent>{
    @Override
    public void handle(ActionEvent event){
        Pane aPane = new HBox(10);

        //Create new image
        Image americanImage = new Image("file:America.png");

        //Create new imageView
        ImageView aImageView = new ImageView(americanImage);

        aImageView.setImage(americanImage);
    }
}

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    launch(args);
}

}

So what I want to happen, is when the americanButton is pressed, the event handler is invoked allowing for the image to display. I've gotten to this point and can't seem to get passed it. Someone help!

A: I would try something like the bottom function(Note:I modified some code to my liking it won't affect anything on your end its just how I prefer to look at it) I see you are not creating a scene stage or showing the stage if you look at the bottom function that should give you a good idea of what you should be doing the only thing I pass is a file path so it should be fairly easy to implement and understand
public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        //Create a label to display a prompt
        Label promptLabel = new Label("Select Button to Display a Flag");

        //Create buttons to display the flags
        Button americanButton = new Button("American Flag");
        americanButton.setOnAction(event -> {
            showFlagAction(getClass().getResource("/TestImage.png").toExternalForm());
        });

        Button canadianButton = new Button("Canadian Flag");
        Button frenchButton = new Button("French Flag");
        Button germanButton = new Button("German Flag");
        Button mexicanButton = new Button("Mexican Flag");

        //Creating an HBox
        HBox hbox = new HBox(10, promptLabel);
        hbox.setAlignment(Pos.CENTER);

        HBox hbox1 = new HBox(10, americanButton);
        hbox1.setAlignment(Pos.CENTER);

        HBox hbox2 = new HBox(10, canadianButton);
        hbox2.setAlignment(Pos.CENTER);

        HBox hbox3 = new HBox(10, frenchButton);
        hbox3.setAlignment(Pos.CENTER);

        HBox hbox4 = new HBox(10, germanButton);
        hbox4.setAlignment(Pos.CENTER);

        HBox hbox5 = new HBox(10, mexicanButton);
        hbox5.setAlignment(Pos.CENTER);

        //Creating a VBox
        VBox vbox = new VBox(10, hbox, hbox1, hbox2, hbox3, hbox4, hbox5);
        vbox.setPadding(new Insets(10));

        primaryStage.setTitle("Flags");
        primaryStage.setScene(new Scene(vbox));
        primaryStage.show();
    }

    private void showFlagAction(String filePath){
        ImageView imageView = new ImageView(new Image(filePath));

        VBox vBox = new VBox();
        vBox.setAlignment(Pos.CENTER);
        vBox.getChildren().add(imageView);

        Stage stage = new Stage();
        stage.setScene(new Scene(vBox));
        stage.show();
    }

}


text:
Q: Last outgoing call details after call ends Hi I searched a lot on this forum for correct result but unable to find. I need details of last outgoing call once call is ended. For this I am using BroadcasteReceiver here is code for my receiver
  public class CallStateBroadcaster extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub

    ((TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE)).listen(new CustomPhoneStateListener(context), PhoneStateListener.LISTEN_CALL_STATE);

}}

Here is code for PhoneStateListener
    public class CustomPhoneStateListener extends PhoneStateListener{

private Context context;

  public CustomPhoneStateListener(Context paramContext)
  {
    this.context = paramContext;
  }

@Override
public void onCallStateChanged(int state, String incomingNumber) {
    // TODO Auto-generated method stub
    super.onCallStateChanged(state, incomingNumber);
    ((TelephonyManager)this.context.getSystemService("phone")).listen(this, PhoneStateListener.LISTEN_NONE);
    if(TelephonyManager.CALL_STATE_IDLE == state)
    {
    try {
        Thread.sleep(1500L);
        Intent intent = new Intent(this.context,LastCallInfoActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        this.context.startActivity(intent);

    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    }
}

Here is code for my activity which fetch call details for call log
    public class LastCallInfoActivity extends Activity{

String addtolist;
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    Cursor callDetailCursor = getContentResolver().query(CallLog.Calls.CONTENT_URI, null,null,null,android.provider.CallLog.Calls.DATE + " DESC limit 1");
    int phoneNumber= callDetailCursor.getColumnIndex(CallLog.Calls.NUMBER);
    int callType=callDetailCursor.getColumnIndex(CallLog.Calls.TYPE);
    int callDate=callDetailCursor.getColumnIndex(CallLog.Calls.DATE);
    int callDuration=callDetailCursor.getColumnIndex(CallLog.Calls.DURATION);

    Log.i(">>CAllDetails", "getsCallLogs" );

    if(callDetailCursor.getCount()>0)
    {
        while(callDetailCursor.moveToNext())
        {
            String phoneNumberString=callDetailCursor.getString(phoneNumber);
            String  contactName= getContactName(this, phoneNumberString);
            String callTypeString =callDetailCursor.getString(callType);
            String callDateString=callDetailCursor.getString(callDate);
            String callDurationString=callDetailCursor.getString(callDuration);
            Date callDayTime=new Date(Long.valueOf(callDateString));

            int callCode = Integer.parseInt(callTypeString);
            int calldur=Integer.parseInt(callDurationString);
            if (callCode==2 && calldur>=1)
            {
                Double callCost=Double.parseDouble(callDurationString);

                String callCostString= String.valueOf( callCost);
                Log.i(">>CAllDetails", "getsLocation" );

                addtolist= "Name :"+contactName+"\n"+
                        "Phone Number: "+phoneNumberString+"\n"+"Call Duration :"+
                        callDurationString+" Seconds\n"+"Call Date: "+callDayTime+"\n"+
                callCostString;

            }
        }
    }callDetailCursor.close();

    Toast.makeText(this, addtolist, Toast.LENGTH_LONG).show();
}

public String getContactName(Context context, String phoneNumber) {
    ContentResolver cr = context.getContentResolver();
    Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
    Cursor cursor = cr.query(uri, new String[]{PhoneLookup.DISPLAY_NAME}, null, null, null);
    if (cursor == null) {
        return null;
    }
    String contactName = null;
    if(cursor.moveToFirst()) {
        contactName = cursor.getString(cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME));
    }

    if(cursor != null && !cursor.isClosed()) {
        cursor.close();
    }

    return contactName;
}

}

My this program show toast even before my call got disconnected and start my activity. Please help me and correct my code so that it will get executed after call ends
thanks

A: just try this add an additional if statement for checking previous sate was off hook.
 boolean wasoffhook=false;

  if(TelephonyManager.CALL_STATE_OFFHOOK == state)

   {
      wasoffhook=true;
    }
  if(TelephonyManager.CALL_STATE_IDLE == state&&wasoffhook)
     {
    try {
    Thread.sleep(1500L);
    Intent intent = new Intent(this.context,LastCallInfoActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    this.context.startActivity(intent);

} catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
}

A: In your onreceive method of Callstatebroadcaster add this code and it would work fine.I just solved it.
  @Override
public void onReceive(Context context, Intent intent)
{

    try
    {
        if (intent.getAction().equals("android.intent.action.NEW_OUTGOING_CALL"))
        {
            savedNumber = intent.getExtras().getString("android.intent.extra.PHONE_NUMBER");
            Toast.makeText(context,"the no. is"+savedNumber,Toast.LENGTH_LONG).show();
           // onOutgoingCallStarted(context,"",callStartTime);

        }
        else
        {
            String stateStr = intent.getExtras().getString(TelephonyManager.EXTRA_STATE);
            String number = intent.getExtras().getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
            int state = 0;

            if(stateStr.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
                switch (state) {
                    case TelephonyManager.CALL_STATE_IDLE:
                        Log.d("Testing", "Outgoing call has been disconnect");
                        intent = new Intent(context, MyCustomDialog.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                        context.startActivity(intent);
                        System.out.println("CAll has been disconnect...............");
        //                            Toast.makeText(this, "CAll has been disconnect", Toast.LENGTH_LONG).show();
                        break;
                }
            }
            else if(stateStr.equals(TelephonyManager.EXTRA_STATE_OFFHOOK))
            {
                state = TelephonyManager.CALL_STATE_OFFHOOK;
            }
            else if(stateStr.equals(TelephonyManager.EXTRA_STATE_RINGING))
            {
                state = TelephonyManager.CALL_STATE_RINGING;
            }

            onCallStateChanged(context, state, number);
        }
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

And in Callstatechanged method add this code.
  public void onCallStateChanged(Context context, int state, String number)
{
    if(lastState == state)
    {
        //No change, debounce extras
        return;
    }
    switch (state)
    {
        case TelephonyManager.CALL_STATE_RINGING:
            isIncoming = true;
            callStartTime = new Date();
            savedNumber = number;
           // onIncomingCallStarted(context, number, callStartTime);
           // onIncomingCallEnded(context, savedNumber, callStartTime, new Date());
           // onOutgoingCallEnded(context, savedNumber, callStartTime, new Date());
          //  wasRinging = true;
            break;

        case TelephonyManager.CALL_STATE_OFFHOOK:

            if (!wasRinging) {
                // Start your new activity
                onIncomingCallEnded(context,savedNumber,callStartTime,new Date());
                onOutgoingCallEnded(context,savedNumber,callStartTime,new Date());
            } else {
                onIncomingCallStarted(context,savedNumber,callStartTime);
                // Cancel your old activity
            }

            // this should be the last piece of code before the break

            break;

        case TelephonyManager.CALL_STATE_IDLE:
            if(isIncoming)
            {
               onIncomingCallEnded(context, savedNumber, callStartTime, new Date());
            }
    }
    lastState = state;
}

This would work.


text:
Q: Changing Password of a user in asp mvc I'm making an intranet website in which there is a functionality of change password.
When the user enters the old and new password, it checks the old password with the current password and if both matches then it updates the new password in the database.
When i look at the database then the value in password column is changed but if I try to login with the new password then it doesn't happen but it logins with the old password.
Now If I stop the application and Build/Run again then it takes the updated password.
Why is it happening like this?
 public JsonResult ChangePwd(string OldPwd, string NewPwd)
     {
         string username = User.Identity.Name.ToUpper();
         USER_DET temp = objUser.getUserByName(username);
         if (temp.Password.ToString() == OldPwd.ToUpper())
         {

             temp.Password = NewPwd.ToUpper();
             objUser.Update(temp);
             var data2 = new[] {
      new { Text="True", Value="1" }//Password Changed

         };
             return Json(data2, JsonRequestBehavior.AllowGet);
         }
         else
         {
             var data2 = new[] {
               new { Text="False", Value="1" }//Password didnt match... no changes

                 };
             return Json(data2, JsonRequestBehavior.AllowGet);
         }
     }

A: Somehow I have managed to get it working. I was using a function in Membership provider class which was not getting the updated values from the database. So Instead of using that I created a separate function which is getting the updated values.


text:
Q: how can I show the date and time a user has used a textarea (saved with local storage onclick)? I am working on a textarea that saves to local storage on a button press. It also displays a pop up alert when something is saved or the textarea is visited. I also want it to display the date it was last updated or modified. How do I do that?
Here is the code :
<textarea id="box" style="margin-    bottom: 4px; width: 250px; height:     20px">
</textarea>
<br />
<button id="save">Save</button>

<script type="text/javascript">//  check if "user" is in localStorage

if (localStorage["box"])
{
var user = localStorage["box"] ;
document.getElementById("box").    value = user ;
alert("Welcome Back.")
}
else
{
document.getElementById("box").    placeholder = "Type here..." ;
    console.log("user not found in    localStorage") }

//save entered gmail address
document.   getElementById("save").  addEventListener("click", function ()
{
    var user = document.    getElementById("box").value ;
    //localStorage["box"] = user ;
    localStorage.setItem("box",    box) ;
    alert("The text has been saved.   ") ;
    console.log("The text has been    saved")
    } , false);</script>

I've found how to display the last modified date using timestamp. Here :
            <script type="text/javascript">
               (function() {

try {

    (window.localStorage.getItem) /   / will throw in Firefox under some settings
} catch (e) {

    return; // quit because dom.   storage.enabled is false
    }

    var area = document.    querySelector('#ta');

  // place content from previous     edit
  if (!area.value) {

      area.value = window.  localStorage.getItem('value');

  }

  updateLog(false);

  // your content will be saved   locally
   document.querySelector('#ta').   addEventListener('keyup',   function() {

      window.localStorage.  setItem('value', area.value);

      window.localStorage.  setItem('timestamp', (new Date()).  getTime());

    updateLog(true);

  }, false);

  function updateLog(new_save) {

      var log = document.  querySelector("#ta-log");

      var delta = 0;

      if (window.localStorage.  getItem('value')) {

          delta = ((new Date()).  getTime() - (new Date()).  setTime(window.localStorage.getItem('timestamp'))) / 1000;

          if (new_save) {

              log.textContent = 'Saved.   ';

              setTimeout(function() {

                  log.textContent = '';

              }, 3000);

          } else {

              log.textContent = 'last   saved: ' + delta + 's ago';

          }

      }

   } })();

But instead of  minutes, seconds, and nanoseconds I want to show the actual date and time.
Ex. Turn 5:30:20 to Sun, September 22, 2013 5:59PM.
Any help?
Is it understandable?

A: Try to save stringify object inside the localstorage.
var obj = { 'content': 'Textarea content is held here', 'time': Date.now() };

localStorage.setItem('box', JSON.stringify(obj));

To get it:
var box = localStorage.getItem('box');

box = JSON.parse(box);

// to get content: box.content
// to get time: box.time

A: Create a 2nd localstorage variable to hold the date/time of the last update.


text:
Q: How can we use redux-react-session to maintain session in react js I have tried to use redux-react-session npm package in my react application , but didn't got much success in that .
If anyone used these package to maintain session in react then it would be great if you provide a working example of it .


text:
Q: Create folder/file and set permissions How to in XP from command line create folder/file and after that allow everything to everyone permissions ? I tried from properties, I deselect readonly but when I open properties again for that folder/file it is always READONLY.

A: You have to use "CACLS".
Use CACLS /help to have the documentation.
Here 2 exemples:
To give the full right to the user "user1" to the directory
CACLS c:\directory /E /T /C /G "user1":F

To give the full right to the user "user1" to the content of the directory
CACLS c:\directory\*.* /E /T /C /G "user1":F

A: CACLS /help:
NOTE: Cacls is now deprecated, please use Icacls.

To give the full right to the user "user1" to the directory (Nicolas' example converted):
Icacls c:\directory /T /C /grant "user1":F


text:
Q: Backbone.js nested views, general ideas I'm hoping to get your general ideas about how to use nested models and views with backbone.js.
Say you have a bunch of dialogs and each dialog has a bunch of tabs.  A particular tab may get reused in more than one dialog.  Each tab is very different and you may want to add a new tab to the dialog dynamically.
It seems logical to me to have different views for each tab.  Also, the dialog should be a view.  I'm just a little unclear about how the models and views all fit together.
This is my main question:
If a parent view wants to render child views, it probably needs to actually do something like:
var childView = new ChildView();

And then, use jQuery to
this.$("#listOfChildViews").append(childView.el);

To ensure that the list is cleared before we add, we need to
this.$("#listOfChildViews").html("");

Is this the preferred way of doing this?  Seems a little bad to me because of ripping out the whole list and then creating all new objects and adding them in there all at once.  Would be perhaps nicer if there was not a 'render' function per se, but rather a 'renderInitially' and then simply 'add' (for adding new childviews).
Sorry this isn't too coherent!

A: Nick,
I think you should throw in the power of Backbone Models.
Have a Dialog model (or maybe a TabContainer, as Dialog sounds more like a view concept). Each dialog has a collection of Tabs (tab again is from the view universe).
In the initial render, in the DialogView, you show the entire dialog.tabs collection, each one in a TabView.
Then, in the DialogView, you can listen on the events from the tabs collection of the dialog model (add, remove, reset) and add/remove only the views that correspond to the elements that changed.
You have to create the functions that add/remove views yourself. The add function would create and render a view for the added tab, and add it to this.$("#listOfChildViews").
Hope that helps.


text:
Q: "Taylor series" is to "Volterra series" as "Padé approximant" is to _________? Padé approximants are often better than Taylor series at representing a function. Given a Taylor series, one can use Wynn's epsilon algorithm to easily produce the Padé approximants to it.
Volterra series are a generalization of Taylor series that can also model "memory" phenomena. Does there exist a similar generalization of Padé approximants that can model these phenomena, or an algorithm like Wynn's to compute them from the Volterra series?
I would be at least happy to know the answer for the discrete Volterra series, which (I think) would be equivalent to something like a multivariate Padé approximant.
Originally asked at MSE, but seems too advanced for that site.

A:
"I would be at least happy to know the answer for the discrete Volterra series, which (I think) would be equivalent to something like a multivariate Padé approximant."

Multi-variate versions of Padé approximants got attention in the 1970s, for example a generalization to functions of two variables was published by J.S.R. Chisolm in 1973 (see "Rational Approximates Defined from
Double Power Series") and a generalization to functions of  countably more variables was studied at around the same time by P.R. Graves-Morris and D.E. Roberts who were both at the University of Kent in Canterbury, leading to this generalization being called the "Canterbury approximant" (see "Calculation of Canterbury approximants").
The original papers about Canterbury approximants never seemed to get many citations, so it's easy to look through the entire list of papers that cited them to find further generalizations (for example, to functions of an uncountably infinite number of variables). Some of the most significant post-Canterbury papers on multivariate versions of Padé approximants that can be found in this list are:

*

*Annie Cuyt "How well can the concept of Padé approximant be generalized to the multivariate case?" (May 1999)

*Philippe Guillaume and Alain Huard. "Multivariate Padé approximation" (September 2000)
Finally, one of the original authors of the Canterbury approximant co-wrote a book with George Baker Jr. called "Padé Approximants" (first edition: 1982, second edition: 1996) which provides you with any developments which they considered significant between the aforementioned papers from the 1970s and about the time of the aforementioned papers from 1999-2000.
Finally, some steps towards a generalization to functions of complex variables can be found in my analogous question: "Taylor series" is to "Volterra series" as "Laurent series" is to _________?


text:
Q: Scapy encapsulation example I'm trying to define a new layer in scapy that contains an encapsulated IP packet.  Are there any examples or documentation for creating such a layer?  I imagine there would be a particular method to do this, such that the packet dissection is recursively applied to the encapsulated packet.
Currently I'm just creating the encapsulation header and sending like so:
send( IP( ... )/
      UDP( ... )/
      NEW_HEADER( ... )/
      IP( ... )/
      TCP( ... ))

A: You will have to define your own layer according to the scapy documentation on adding new layers.
Here's a basic example, taken from the documentation:
class Disney(Packet):
    name = "DisneyPacket "
    fields_desc=[ ShortField("mickey",5),
                  XByteField("minnie",3) ,
                  IntEnumField("donald" , 1 ,
                              { 1: "happy", 2: "cool" , 3: "angry" } ) ]

Layers will automatically dissect and build based on the field descriptions.
I'd be best to also have a look at the existing layers in the scapy.layers package as there'll be most likely already a layer that is similar to the one you'd like to create as well as having a look at existing fields that you could reuse from scapy.fields


text:
Q: How to create Google signup button in android using kotlin I am using jetcompose android with kotlin and i am trying to create a google signup/signin button.
I could only create the SignInButton object. But i didnt find anyway on how to render it.
val signupButton = SignInButton(LocalContext.current)
Package from where i imported SigninButton
com.google.android.gms.common.SignInButton
I am trying to render the signupbutton but unable to render using the above code

A: The com.google.android.gms.common.SignInButton is a View,  not a Composable so it won't be rendered inside of a Composable context. To render Views that are commonly used in XML layouts you should use AndroidView into a Composable context and put the View inside it.
AndroidView(
            factory = { ctx ->
                SignInButton(ctx).apply {
                    setOnClickListener {
                        //Handle on click
                        Toast.makeText(ctx, "On SignInButton clicked!", Toast.LENGTH_SHORT)
                            .show()
                    }
                }
            },
            modifier = Modifier.fillMaxWidth()
        )


text:
Q: Yes & No answer in C I am trying to make a C program where I can ask the following user yes or no questions:
Do you like beer? Y or N

Are you old enough? Y or N

How old are you?

if the user said over 18 print the message: let's go for some beers
but if one of the 2 first questions or the age is N, print: sorry maybe next time
I think the issue is with the If statement , perhaps I am not encapsulating the conditions.
#include <stdio.h>

int main(){

    char answer;
    int age = 0 ;

    printf("Do you like beers Enter Y or N: \n");
    scanf(" %c", &answer);
    printf("\n so your answer is %c\n", answer);

    printf("Are you old enough to have a beer?\n");
    scanf(" %c", &answer);
    printf("\n so your answer is %c\n", answer);

    if (answer == 'Y') {

        printf("how old are you?\n");
        scanf(" %d", &age);

        if (age >= 18)
            printf("\n Let's go for some beers , I will pay the first round \n");

    }if else  (age < 18 && answer == 'N')
        printf("\n sorry my friend , maybe next time \n");

       // printf("You may NOT ");

  return 0;

}

A: From your code snippet above, it looks like your else statement is formatted incorrectly (if else instead of else if). Also, since you are testing whether or not either question was false, you should use the || operand. So you would want to do something like:
else if  (age < 18 || answer == 'N')

A: The issue is your last if statement is only true if the user is under 18 AND said No. you want it to be either or.
Change the last if statement from
if else  (age < 18 && answer == 'N')

To:
  if else  (age < 18 || answer == 'N')

A: You are using the same variable "answer". So, when you enter the answer to the second question it replace the first answer.
    int main(){

        char answer;
        char answer2;
        int age = 0 ;

        printf("Do you like beers Enter Y or N: \n");
        scanf(" %c", &answer);
        printf("\n so you answer is %c\n", answer);

        printf("Are you older enough to have a beer?\n");
        scanf(" %c", &answer2);
        printf("\n so you answer is also %c\n", answer2);

        if (answer == 'Y' && answer2 == 'Y') {

            printf("how old are yo.\n");
            scanf(" %d", &age);

            if (age >= 18)
                printf("\n lets go for some beers , I will paid the first round \n");

        }

        else if  (answer == 'N' || answer2 == 'N')
            printf("\n sorry my friend , maybe next time \n");

           // printf("You may NOT ");

      return 0;

    }

Hope this is what you needed. Cheers.

A: I think that you can think that the structure of your program is roughly as follows.
REPLY = PROMPT(Q1_MESSAGE)
IF(REPLY == YES){
    //Narrow down the conditions
    REPLY = PROMPT(Q2_MESSAGE)
    IF(REPLY == YES){
        //Narrow down the conditions
        REPLY = PROMPT(Q3_MESSAGE)
        IF(REPLY >= 18){
            DISPLAY(GOOD_MESSAGE)
        } ELSE {
            DISPLAY(NO_GOOD_MESSAGE)
        }
    } ELSE {
        DISPLAY(NO_GOOD_MESSAGE)
    }
} ELSE {
    DISPLAY(NO_GOOD_MESSAGE)
}

A nested IF can be considered as AND condition as a condition.
So by summarizing the question message and its response part into a function, it is possible to write as follows.
IF(FUNC1() == TRUE AND FUNC2() == TRUE AND FUNC3() == TRUE){//Function call proceeds from left to right (Shortcut evaluated)
    DISPLAY(GOOD_MESSAGE)
} ELSE {
    DISPLAY(NO_GOOD_MESSAGE)
}

As an example, you can write concretely as follows.
#include <stdio.h>

int main(void){
    char YN(const char *prompt);
    int enter_age(const char *prompt);

    if(YN("Do you like beers Enter Y or N: \n") == 'Y' &&
       YN("Are you old enough to have a beer?\n") == 'Y' &&
       enter_age("How old are you?\n") >= 20){
        printf("\nLet's go for some beers, I will take the first round.\n");
    } else {
        printf("\nSorry my friend, maybe next time.\n");
    }

    return 0;
}

char YN(const char *prompt){
    char ans[2], ret, ch;
    int ret_scnf;

    while(1){
        fputs(prompt, stdout);
        if((ret_scnf = scanf(" %1[YNyn]%c", ans, &ch)) == 2 && ch == '\n'){
            if(*ans == 'Y' || *ans == 'y'){
                ret = 'Y';
                break;
            } else if(*ans == 'N' || *ans == 'n'){
                ret = 'N';
                break;
            }
        } else if(ret_scnf == EOF){
                ret = 'N';
                break;
        }
        scanf("%*[^\n]");scanf("%*c");//clear input
    }
    return ret;
}
int enter_age(const char *prompt){
    int ret_scnf, age;
    char ch;

    while(1){
        fputs(prompt, stdout);
        if((ret_scnf = scanf("%d%c", &age, &ch)) == 2 && ch == '\n'){
            if(age < 0)//Can I enter years old at the age of 0?
                continue;
            return age;
        } else if(ret_scnf == EOF){
                age = -1;
                break;
        }
        scanf("%*[^\n]");scanf("%*c");
    }
    return age;
}


text:
Q: Extract row based on a particular column value using opencsv I have a huge CSV file which I have read each row and compared against a database table using hash of each row, now I would want to extract certain rows depending on id value from the csv file again. I cannot save the rows initially as I have around 20 columns and and > 500k rows. Thus would there exist a lookup function by column value?
 id price year comments
 1   23.5  2014  XYZ
 2   25    2016  XYZ
 3   22.5  2014  XYZ

A: *

*Library used: OpenCSV

*You can use following method to get the value from specific columns

*csvData: has all the data from csv using readAll() from OpenCSV lib;

*colName: for which column you want to extract the data.

private void getCsvColumnData(String colName) {

    int counter = 0;
    String[] col = csvData.get(0);
    for (String c1 : col) {
        if (c1.equalsIgnoreCase(colName)) {
            break;
        }
        counter++;
    }
    System.out.println("size:- " + counter);

    for (int i = 1; i < csvData.size(); i++) {
        String[] label = csvData.get(i);
        for (int j = 0; j < label.length; j++) {
            if (j == counter) {
                System.out.println(label[j]);
            }

        }
    }

}

A: Use the CsvToBeanFilter.  In the opencsv api there is an excellent example that you can use to create your own filter.


text:
Q: How to overwrite EngineIO method in SocketIO NestJS gateway class I need to use custom client ID, here - stackoverflow.com/questions/7702461/socket-io-custom-client-id is answer for express.js apps:
const io = require('socket.io')(http)

io.engine.generateId = function (req) {
    // generate a new custom id here
    return 1
}

and some other answers
But in classes it's doesn't work
@WebSocketGateway(8080)
export class AppGateway {
    @WebSocketServer()
        server: Server
    this.server.engine.generateId = req => {  // Unexpected token.
        // generate a new custom id here      // A constructor, method,
        return 1                              // accessor, or property was expected.
    }

}


text:
Q: thread should have started running after i created an object with start() in constructor There are 2 classes i used
1st class: Counter
public class Counter {
int val = 0;
void inc() { val++;}
void dcr() { val--;}
}

2nd class: threadTesting
public class ThreadTesting extends Thread {

/**
 * @param args the command line arguments
 */
Counter c;
ThreadTesting(Counter c){
    this.c = c;
    start();
}

public void run(){
    for(int i=0;i<10000;i++)
        c.dcr();
}
public static void main(String[] args) throws Exception {
    // TODO code application logic here
    Counter c = new Counter();
    ThreadTesting rc = new ThreadTesting(c);
    Boolean stateOfThread = rc.isAlive();
    System.out.println(stateOfThread);
    for(int i=0;i<10000;i++)
       c.inc();
    rc.join();

    System.out.println("Final value of c.val: "+c.val);
}

}

if I commented these code
 Boolean stateOfThread = rc.isAlive();
    System.out.println(stateOfThread);
    for(int i=0;i<10000;i++)
       c.inc();
    rc.join();

The result i get would be 0, but the child thread should be started once i created the object rc but it didn't. Why ?

A: If you comment the mentioned statements, the constructor would still start the second thread, but System.out.println("Final value of c.val: "+c.val); is executed on the main thread before the second thread's run() method starts. Therefore c.val is still 0 when the output is printed.
Add a Thread.sleep(1000) prior to that print statement and you'll see the second thread does run.
You'll most likely get an output of:
Final value of c.val: -10000


text:
Q: Corollary 2.4.11. from Analysis Now by Pedersen - bad proof? Here is a small excerpt from Analysis Now by Pedersen:

2.4.10. Proposition. Let $\mathfrak{X}$ be a normed space and $\mathfrak{Z}$ be a w*-closed subspace of $\mathfrak{X}^\ast$. For every $\psi$ in $\mathfrak{X}^\ast\backslash\mathfrak{Z}$ there is an $x$ in $\mathfrak{Z}^\perp$ such that $\langle x,\psi \rangle \neq 0$.
Proof. (...)
2.4.11. Corollary. Every w*-closed subspace of $\mathfrak{X}^\ast$ has the form $\mathfrak{Y}^\perp$ for some norm closed subspace $\mathfrak{Y}$ of $\mathfrak{X}$.

Why does the corollary follow? Here is my attempt:

For $\mathfrak{S}$ w*-closed in $\mathfrak{X}^\ast$ then take $S\subseteq \mathfrak{X}$  as $\mathfrak{S}^\perp\triangleq \{x|\forall\phi \in \mathfrak{S},\ \langle x, \phi \rangle=0\}$ Considering that each of these $\phi$ is continuous, $S$ is clearly a norm-closed subspace of $\mathfrak{X}$. Using the contrapositive of 2.4.10 on $S$, then we have that if some $\psi$ is $0$ along all $S$ then $\psi$ must be in $\mathfrak{S}.$

I am scared I have used a tautology somewhere and assumed the claim. Are there any gaps?

A: It's correct. ${}{}{}{}{}{}{}{}{}{}{}{}$


text:
Q: What is the proper way to design a database for a website that has multiple instances of the same table/collection for each table/collection? So I have a website that is separated into 5 different modes / sections / modules / compartments / etcs...
The user would be able to switch to each separate mode by clicking on an icon / link.
Each of the modes are basically a different instance of the website. In other words, they all have the same UI components and backend tables / collections.
And the data in the modes will NEVER have to communicate with tables of other modes. In other words, no joins between the tables of the different modes.
Suppose that all of the modes need to have a table called TABLE_A.
Designed option 1:
Each of the 5 modes to have their own version of TABLE_A:

*

*MODE_1_TABLE_A

*MODE_1_TABLE_A

*MODE_2_TABLE_A

*MODE_3_TABLE_A

*MODE_4_TABLE_A

*MODE_5_TABLE_A
Designed option 2:
Have only one TABLE_A with an extra column to record which mode the records belong to
TABLE_A { Column_ID, ..., Column_Mode }
Which design is the correct design in terms of speed of queries, etc.?
I have chosen to use no noSQL database which is MongoDB.
There will be a page on each mode that will display a list of items from TABLE_A.

A: I don't believe either option would have a significant impact on query performance. The real questions are more around flexibility and supportability.
It is obviously easier to maintain a single table rather than 5 identical copies of the same table.
If the 5 modes ever diverged from a single, common model then having the data for all 5 modes in a single table will become more and more difficult to support and splitting them into 5 separate tables at some point in the future is unlikely to be simple.
Up to you whether supportability or flexibility are more important/relevant to you


text:
Q: Wald's Equation 3.3.6 I have an issue with Eq. 3.3.6 of Wald's General Relativity. There he would like to prove that for Gaussian normal coordinates, the geodesic tangent field remains orthogonal to all coordinate basis fields which generate hypersurfaces indexed by parameter $t$ (page 43).
The step is as follows: Let $n^a$ be tangent vector to the geodesic and $X^a$ be any one of the coordinate basis fields. Then
\begin{equation}
\begin{aligned}
n^b\nabla_b(n_aX^a)&=n_an^b\nabla_bX^a\\&=n_aX^b\nabla_bn^a\\&=\frac{1}{2}X^b\nabla_b(n^an_a)\\&=0
\end{aligned}
\end{equation}
First equality is due to product rule and also the definition of geodesics (parallel transport its own tangent vector). Third equality follows by reversing product rule. Fourth equality follows because $n_an^a$ is a constant (norm of $n^a$). But I do not quite get second equality. Wald mentioned that it follows because as coordinate basis for the tangent space at $p$, $[n^a,X^b]=0$. But I cannot see how that enters the second equality.

A: The commutator of two vector fields $n^a$ and $X^b$ is $[n,X]^a = n^b \nabla_b X^a - X^b \nabla_b n^a$.  Since this vanishes, it follows that $n^b \nabla_b X^a = X^b \nabla_b n^a$, and the second step follows from there.
I don't have my copy of Wald in front of me, but I'm 99% sure that the commutator of two vector fields is defined in terms of the covariant derivative (or vice versa) somewhere in Chapter 3.


text:
Q: Compute $\lim_{n\to\infty} \left(\int_0^{\pi} \frac{\sin^2 n x}{\sin x} \ dx-\sum_{k=1}^n \frac{1}{k}\right)$ Compute the limit
$$\lim_{n\to\infty} \left(\int_0^{\pi} \frac{\sin^2 n x}{\sin x} \ dx-\sum_{k=1}^n \frac{1}{k}\right)$$

A: The point is that you can write $\sum_{k=1}^nsin(2k-1)x=\frac{cos(2nx)-1}{-2sinx}=\frac{sin^2(nx)}{sinx}$, so the integral is equal to $I=lim_{n\to\infty}\sum_{k=1}^n(\int_{0}^\pi(sin(2k-1)xdx-\frac{1}{k})=lim_{n\to\infty}\sum_{k=1}^n(\frac{2}{2k-1}-\frac{1}{k})$, then using $\sum_{k=1}^{n}\frac{1}{k}\sim log(n)+c$, $c$ is the Euler constant, so $I=lim_{n\to\infty}2[\sum_{k=1}^{2n}\frac{1}{k}-\sum_{k=1}^n\frac{1}{2k}]-\sum_{k=1}^n\frac{1}{k}=lim_{n\to\infty}(2log2n+2c-logn-c-logn-c)=2log2$.

A: Let's suppose that $\ \displaystyle f(n):=\int_0^{\pi} \frac{\sin^2 n x}{\sin x} \ dx\ $ then :
\begin{align}
f(n+1)-f(n)&=\int_0^{\pi} \frac{\sin^2((n+1) x)-\sin^2(n x)}{\sin x} \ dx\\
&=\int_0^{\pi} \frac{\cos(2n x)-\cos(2(n+1) x)}{2\sin x} \ dx\\
&=\int_0^{\pi} \frac{\cos(2n x)(1-\cos(2x))+\sin(2nx)\sin(2x)}{2\sin x}dx\\ &=\int_0^{\pi} \frac{\cos(2n x)2\sin(x)^2)+\sin(2nx)2\sin(x)\cos(x)}{2\sin x} dx\\
&=\int_0^{\pi} \cos(2n x)\sin(x)+\sin(2nx)\cos(x)\;dx\\
&=\int_0^{\pi} \sin((2n+1) x)\;dx\\
&=\frac 2{2n+1} \\
\end{align}
So that your limit (as $\ (n+1)\to +\infty$) is the series :
$$f(0)+\sum_{n=0}^\infty \left(\frac 2{2n+1}-\frac 1{n+1}\right)=2\sum_{n=0}^\infty \left(\frac 1{2n+1}-\frac 1{2n+2}\right)=2\,\log(1+1)=\log(4)$$
(using the expansion of $\;\log(1+x)\,$ at $\,x=1$)

A: Lemma: $\int_{0}^{\pi} e^{(2n+1)ix} dx = \frac{-2}{i}(2n+1)$.
Now let $t=e^{ix}$. We'll simplify the integrand:
$$\frac{\sin^2(nx)}{\sin x} = (\frac{t^{n}-t^{-n}}{2i})^2 (\frac{t-t^{-1}}{2i})^{-1}$$
$$=\frac{i}{-2} \frac{t^{2n+1}+t^{1-2n}-2t}{t^2-1} = \frac{i}{-2} t \frac{t^{2n}-1}{t^2-1}(1-t^{-2n})$$
$$=\frac{i}{-2} \sum_{i=0}^{n-1} (t^{2i+1} - t^{2(i-n)+1})$$
Now, by applying the lemma, we find that the integral is
$$\frac{i}{-2}\frac{-2}{i} \sum_{i=0}^{n-1} \frac{1}{2i+1} - \frac{1}{2(i-n)+1}=$$
$$=2 \sum_{i=0}^{n-1} \frac{1}{2i+1} =2(H_{2n}-\frac{1}{2}H_n)$$
So the limit in question is $\lim_{n \to \infty} 2(H_{2n}-\frac{1}{2}H_n) - H_{n} = \lim 2H_{2n}-2H_{n}$. Now we can either use $H_{n} \sim \log n + \gamma + O(n^{-1})$ or compare $H_{2n}-H_{n}$ to the integral $\int_{n}^{2n} \frac{dt}{t} = \ln 2$ to conclude that the limit is $\ln 4$.


text:
Q: unable to extract day and month from date using R I have a dataframe like as shown below
test_df <- data.frame("subject_id" = c(1, 1, 1, 2),
                      "date_1" = c("8/6/2009 11:54", "28/3/2009 19:54", "18/2/2009 1:54", "11/3/2009 2:54"))

I would like to extract the month and day from the date_1 field. So, I tried the below
test_df %>%
  mutate(date_1 = lubridate::dmy_hm(date_1),
         without_year = format(date_1, "%d/%m"))

However, this throws an error like as shown below
Error in format.default(date_1, "%d/%m") :
  invalid 'trim' argument

I expect my output to be like as shown below

A: Also you can try with dplyr and base R:
test_df %>% mutate(date_1=as.Date(test_df$date_1,format = '%d/%m/%Y %H:%M'),
                   daymonth=format(date_1,'%d/%m'))

  subject_id     date_1 daymonth
1          1 2009-06-08    08/06
2          1 2009-03-28    28/03
3          1 2009-02-18    18/02
4          2 2009-03-11    11/03

A: test_df %>%
  mutate(
    asDate=lubridate::dmy_hm(date_1),
    justDayMonth=paste0(lubridate::day(asDate), "/", lubridate::month(asDate)
  )
)
  subject_id          date_1              asDate justDayMonth
1          1  8/6/2009 11:54 2009-06-08 11:54:00          8/6
2          1 28/3/2009 19:54 2009-03-28 19:54:00         28/3
3          1  18/2/2009 1:54 2009-02-18 01:54:00         18/2
4          2  11/3/2009 2:54 2009-03-11 02:54:00         11/3

A: using base-R
format( as.POSIXct(test_df$date_1, format= "%d/%m/%Y %H:%M"), "%d/%m")
[1] "08/06" "28/03" "18/02" "11/03"


text:
Q: How to use Jetstream authentication in SPA powered by Vue without using inertia and laravel router? I am creating a Single Page Application using Laravel 8, Vue and Sanctum for API.
If I use Jetstream for authentication, there is compulsory to use another js Inertia and according to documentation it's saying "you will use Laravel's router instead of Vue router."
Can I use Jetstream without the inertia or without laravel router?


text: Q: w2ui popup body is not populating I am new to w2ui and have dowloaded the w2ui-starter-es6 repo. I want to code something similar to W2UI Demo / Combo / Popup & Grid. I know how to code layout, grid and form in conf.js and have got popup working with an empty body. Not clear how to code main.js to populate layout, grid and form in the body.


text:
Q: Using bound argument name inside python function My current hackish manner of printing multiple arrays in columns uses keyword arguments to label the output:
def table(**data_dict):
    n=([len(x) for x in data_dict.values()]) # # data for each var
    N=max(n)
    # prep data & print headings
    prntstr=''
    for i,var in enumerate(data_dict):
        # convert lists to str for printing, padding as needed
        data_dict[var] = ['{:.5g}'.format(x) for x in data_dict[var]] + ['']*(N-n[i])
        prntstr=prntstr+f'| {var:^8} |'
    print(prntstr,'-'*12*len(data_dict),sep='\n'); # print heading
    # print data
    for i in range(0,N):
        prntstr=' '.join(f'{data_dict[var][i]:>11}' for var in data_dict)
        print(prntstr)

and used
rho=[1.5,0.11]
Fx=[-14.2]
table(rho=rho,T=[665,240],Fx=Fx)

producing
|   rho    ||    T     ||    Fx    |
------------------------------------
        1.5         665       -14.2
       0.11         240

Is there another way to do this that can use the bound argument name (e.g rho) and avoid the repetition (e.g. rho=rho) for non-keyword arguments so that one could type simply table(rho,T=[665,240],Fx)?  Thank you in advance.

A: Use RHO=rho where RHO is the heading in the output.
Replace
table(rho=rho,T=[665,240],Fx=Fx)

with
table(RHO=rho,T=[665,240],Fx=Fx)

If this is not acceptable you will have to accept the first argument
Replace
def table(**data_dict)

with
def table(RHO, **data_dict):
    data_dict['rho'] = RHO

and call as follows:
Replace
table(rho=rho,T=[665,240],Fx=Fx)

with
table(rho,T=[665,240],Fx=Fx)


text:
Q: Insert text inside of a single word. Unique circumstance I have a very strange out-of-the-box question but there's a good reason for it.
If I have a variable such as:
var myText = "Select an option, and we'll update you.";

I need to change it to:
"Se~lect an option, and we'll up~date you.";

Now the symbol is irrelevant. I just need to use a special character of any kind for words that are database related. Select, Update, Count, etc. But I also want to pick a character that isn't used often by the typical person when typing.
I'm hoping there's a way to insert these characters into a list of specified words IF they exist within a variable.
Process:
User enters a comment in a form which the val() is captured in a variable.
Then take the variable and insert a special character inside of those words.
It's on a SQL level that I parse out these characters using replace before they're inserted into the database.
Thank you so much...

A: If you absolutely cannot fix this, you could encode the comment as JSON and represent each character with its unicode escape sequence:
function unicode_stringify(s) {
    var result = [];

    for (var i = 0; i < s.length; i++) {
        result.push('\\u' + ('0000' + s.charCodeAt(i).toString(16)).slice(-4));
    }

    return '"' + result.join('') + '"';
}

Decode it on your server and it should work just fine:
> unicode_stringify('SELECT * FROM comments')
""\u0053\u0045\u004c\u0045\u0043\u0054\u0020\u002a\u0020\u0046\u0052\u004f\u004d\u0020\u0063\u006f\u006d\u006d\u0065\u006e\u0074\u0073""
> JSON.parse(unicode_stringify('SELECT * FROM comments'))
"SELECT * FROM comments"

Please use this only as a last resort.

A: Perhaps something like this should give you a start (if you really must).
Javascript
var words = ["select", "update", "count"];

function modify(text) {
    words.forEach(function (word) {
        text = text.replace(new RegExp("\\b" + word + "\\b", "gi"), function(match) {
            var insertAt = Math.floor(match.length / 2);

            return match.slice(0, insertAt) + "~" + match.slice(insertAt);
        });
    });

    return text;
}

console.log(modify("Select an option, and we'll update you. Count. Select an option, and we'll update you."));

Output
Sel~ect an option, and we'll upd~ate you. Co~unt. Sel~ect an option, and we'll upd~ate you.

On jsfiddle
Update: Optimisation
Javascript
var words = ["select", "update", "count"],
    regexs = words.map(function (word) {
        return new RegExp("\\b" + word + "\\b", "gi");
    });

function modify(text) {
    regexs.forEach(function (regex) {
        text = text.replace(regex, function (match) {
            var insertAt = Math.floor(match.length / 2);

            return match.slice(0, insertAt) + "~" + match.slice(insertAt);
        });
    });

    return text;
}

console.log(modify("Select an option, and we'll update you. Count. Select an option, and we'll update you."));

On jsfiddle


text:
Q: Get request outside a controller in .netcore Is there a way I can get the response from a method without using a controller. I mean, in order to get the tenants from the database I use attribute binding and I get it from: "http://localhost:5000/api/tenants". Is there a way I can retrieve values without using a controller, like a service? For example in angular I use httpclient to get the response. Is there anything similar in .netcore 2 webapi? Thank, you!

A: For Controller, it uses UseMvc middleware to route the request to controller.
If you would not use controller, you could try custom middleware to return the data directly based on the request path.
    public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        //your config
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
       //your config
        app.Map("/tenants", map => {
            map.Run(async context => {
                var dbContext = context.RequestServices.GetRequiredService<MVCProContext>();
                var tenants = await dbContext.Users.ToListAsync();
                await context.Response.WriteAsync(JsonConvert.SerializeObject(tenants));
            });
        });
        app.Run(async context => {
            await context.Response.WriteAsync($"Default response");
        });
    }
}


text:
Q: How to log Queue name in SimpleMessageListenerContainer.java We're having issues with one of the consumers, and need to debug the code. SimpleRabbitListenerContainerFactory allows to set a ConsumerTagStrategy, which should add tags during logging.
@Bean
public SimpleRabbitListenerContainerFactory analyzeTransactionListenerContainerFactory(ConnectionFactory connectionFactory, AsyncTaskExecutor asyncTaskExecutor) {
    connectionFactory.getVirtualHost());
    SimpleRabbitListenerContainerFactory factory = new  SimpleRabbitListenerContainerFactory();
    factory.setConnectionFactory(connectionFactory);
    factory.setConcurrentConsumers(2);
    factory.setMaxConcurrentConsumers(4);
    factory.setTaskExecutor(asyncTaskExecutor);
    ConsumerTagStrategy consumerTagStrategy = new ConsumerTagStrategy() {
        @Override
        public String createConsumerTag(String queue) {
            return queue;
        }
     };
     factory.setConsumerTagStrategy(consumerTagStrategy);
     return factory;
}

However, the logs still do not have the tag. So there is no way to find what queue/consumer this message is for.
LogLevel=DEBUG; category=org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer; msg=Cancelling Consumer: tags=[{}], channel=Cached Rabbit Channel: AMQChannel(amqp://guest@10.17.1.13:5672/,47), acknowledgeMode=AUTO local queue size=0;

LogLevel=DEBUG; category=org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer; msg=Idle consumer terminating: Consumer: tags=[{}], channel=Cached Rabbit Channel: AMQChannel(amqp://guest@10.17.1.13:5672/,47), acknowledgeMode=AUTO local queue size=0;

How does one add some tags to SimpleMessageListenerContainer logging?

A: Well, looks like you misunderstood the Consumer Key a bit. From the RabbitMQ docs:

consumer-tag consumer-tag
Specifies the identifier for the consumer. The consumer tag is local to a channel, so two clients can use the same consumer tags. If this field is empty the server will generate a unique tag.
The client MUST NOT specify a tag that refers to an existing consumer. Error code: not-allowed
The consumer tag is valid only within the channel from which the consumer was created. I.e. a client MUST NOT create a consumer in one channel and then use it in another. Error code: not-allowed

The SimpleMessageListenerContainer populates its internal map for the consumerTags when it starts to listen to provided queues. If we are listening (consuming) there we can see them from the:
public String toString() {
    return "Consumer: tags=[" + (this.consumerTags.toString()) + "], channel=" + channel
            + ", acknowledgeMode=" + acknowledgeMode + " local queue size=" + queue.size();
}

as you expecting, of course.
But if we don't consumer any more, in case of Channel#basicCancel, for example.
Or... looking to your second log message during idling. When you have an extra Consumer, but there is no message for it.
The code on the matter looks like:
boolean receivedOk = receiveAndExecute(this.consumer); // At least one message received
if (SimpleMessageListenerContainer.this.maxConcurrentConsumers != null) {
    if (receivedOk) {
.....
    }
    else {
        consecutiveMessages = 0;
        if (consecutiveIdles++ > SimpleMessageListenerContainer.this.consecutiveIdleTrigger) {
            considerStoppingAConsumer(this.consumer);
            consecutiveIdles = 0;
        }
   }
}

So, maybe you worry for nothing. And you see the logs only for those extra consumers. For this case you have maxConcurrentConsumers > concurrentConsumers.


text:
Q: Revealing module pattern with prototype Te following code is fine:
var Pill = (function() {

    var hideCheckPricesPill = function() {
        $(HB.pillSearchBar.checkPrices).hide();
    };

    var hideAnyPill = function(pill) {
        $(pill).hide();
    };

    var displaySearchBar = function() {
        $("." + HB.pillSearchBar.hideSearchForm).removeClass(HB.pillSearchBar.hideSearchForm);
    };

    var isEditSearchPill = function(pill) {
        if(pill === HB.pillSearchBar.editSearchText) {
            hideCheckPricesPill();
        }
        else {
            hideAnyPill(pill);
        }
    };

    var isMobileSearch = function(pill) {
        if(!$(pill).hasClass(HB.pillSearchBar.jsOpenMobileSearch)){
            isEditSearchPill(pill);
            displaySearchBar();
        }
    };

    var addEventListenerOnPill = function(pill) {
        $(pill).on('click', 'a',  function() {
            isMobileSearch(pill);
        });
    };

    return {
        addEventListenerOnPill: addEventListenerOnPill
    }

})();

Is there a way to add a prototype functionality to one of the public functions so that it can be returned and initialized with the "new" key word?


text:
Q: Changing action based on input value using PHP I'm working on a form that I'd like to change the form action based off of the value of an input on form submit. This needs to be accomplished using PHP.
Here's what I've tried so far:
<?php
    $action = "";
    $input = (isset($_POST["hp"]));
    if($input == "") {
      $action = "action1";
    } else {
      $action = "action2";
    }
?>
<form name="contactForm" id="contactForm" method="post" action="<?php echo $action; ?>">

    <!-- form stuff here -->

    <input id="hp" name="hp" type="text" class="hp"/>
    <input type="submit" name="submit" id="submit" value="Submit Query" class="button" />
</form>

This doesn't work because the hp field for (isset($_POST["hp"])) doesn't have a value from the get-go, so it always goes to action1.
I've also tried:
<?php
  if(isset($_POST['submit'])){
    $input = ($_POST['hp']);
    $action = "";
    if($input == "") {
      $action = "action1";
    } else {
      $action = "action2";
    }
  }
?>
<form name="contactForm" id="contactForm" method="post" action="<?php echo $action; ?>">

That didn't work because Perch (the CMS this is being built on) throws you an error that $action isn't defined yet.
And when I tried:
<?php
  $action = "";
  if(isset($_POST['submit'])){
    $input = ($_POST['hp']);
    if($input == "") {
      $action = "action1";
    } else {
      $action = "action2";
    }
  }
?>

It didn't do anything at all on submit because it set the action as "".
Any suggestions?

A: To write in short way
$action = isset($_POST['hp'])?'action2':'action1';

That's all.

A: Differents possibilities:
Same action and redirect
The most easy way probably is send form to the same PHP file, and in this file, get the content of this input via POST and redirect to the correct file.
Prevent default submit and add submit event via JavaScript
The second option, may be add an event to form on submit via JavaScript, prevent default action to prevent the submit, then check value of input, set action and submit form:
<form name="contactForm" id="contactForm" method="post" action="">
    ...
</form>

<script>
    document.querySelector('#contactForm').addEventListener('submit', function(e) {
        //Prevent default submit
        e.preventDefault();

        //Check input value
        if (...) {
            this.action = "page1.php";
        } else if (...) {
            this.action = "page1.php";
        }

        //perform submit form.
        this.submit();
    });
</script>

Use data binding library
This is probably the best form to do it, but the most complicated to understad, this form is based of use a data binding library like Vue.js, KnockoutJS or RactiveJS to set in model object the action string depending of input value.
Then, in HTML form tag, set in action the value of model data using the binding syntax of the chosen library:
//Vue.js syntax
<form name="contactForm" id="contactForm" method="post" :action="action">

//Ractive.js syntax
<form name="contactForm" id="contactForm" method="post" action="{{action}}">

What do I recommend?
If you're novel with PHP and don't know JavaScript, the first option is probably the best for you, if you If you know JavaScript and you know how to work with events, but never used a binding library, probably the second option is more recommended for you.
If you worked with some data binding library (or framework that implements data binding like Angular), the third options is probably the best for you.

A: If the 2nd and 3rd versions don't work, you must be missing an input like:
<input type="submit" name="submit">

You can either add that button to the form, or you can change your code to use if isset($_POST['hp'])
<?php
  $action = "";
  if(isset($_POST['hp'])){
    $input = ($_POST['hp']);
    if($input == "") {
      $action = "action1";
    } else {
      $action = "action2";
    }
  }
?>

A: None of the answers above worked for me, so here is what I ended up going with.
Use Case:

*

*I have a "Search" form with two fields. When a user clicks "Search",
these values should be added to the URL, so that previous searches
may be bookmarked. The search should then be performed.

*When the page is first loaded or no search criteria are used, all
possible results should be shown.

Code description:

*

*At the top of the file, check if the user submitted the form.
If so:

*

*get the values from the fields you want and save them to local variables.

*navigate to the same PHP file, this time passing the variables you are interested in

*If the user did not submit the form:

*

*check for URL parameters

*If there are URL parameters present, save them to local variables,
and use these local variables to run the search

Code Snippet:

  if(isset($_POST['submit'])){
    if(!empty($_POST['projectNameSearch'])){
      $projectNameSearch = mysqli_real_escape_string($conn, $_POST['projectNameSearch']);
    }
    if(!empty($_POST['projectDescriptionSearch'])){
      $projectDescriptionSearch = mysqli_real_escape_string($conn, $_POST['projectDescriptionSearch']);
    }
    if($projectNameSearch != '' || $projectDescriptionSearch != ''){
      header("Location: projects.php?projectnamesearch=$projectNameSearch&projectdescriptionsearch=$projectDescriptionSearch");
    }
  } else {
    if(isset($_GET['projectnamesearch'])){
      $projectNameSearch = mysqli_real_escape_string($conn, $_GET['projectnamesearch']);
    }
    if(isset($_GET['projectdescriptionsearch'])){
      $projectDescriptionSearch = mysqli_real_escape_string($conn, $_GET['projectdescriptionsearch']);
    }
  }


text:
Q: Error when populating array in async task In my iOS Swift app I populate 2 arrays with an async task in this way:
    let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT

    dispatch_async(dispatch_get_global_queue(priority, 0)) {

        for n: Node in DataManager.sharedInstance.allNodes {

            locationNode = CLLocationCoordinate2D(latitude: n.Lat, longitude: n.Lon)

            if locationNode.latitude < ne.latitude && locationNode.longitude < ne.longitude && locationNode.latitude > sw.latitude && locationNode.longitude > sw.longitude {

                self.listVisibleNodes.append(n)

                // Declare the marker `hello` and set its coordinates, title, and subtitle
                let hello = CustomPointAnnotation()
                hello.coordinate = locationNode
                hello.title = n.Label
                hello.subtitle = n.Net+"_"+String(n.Id)
                hello.imageName = n.Label

                self.visibleMarkersOnMap.append(hello)
            }
        }

        dispatch_async(dispatch_get_main_queue()) {

            // update some UI
            mapView.addAnnotations(self.visibleMarkersOnMap)
        }
      }

As you can see, I append values to an array on 2 places. Sometimes I get an error while running this code, not always. Once I had this fatal error:

UnsafeMutablePointer.destroy with negative count

And sometimes I get an EXC_BAD_ACCESS.
I can't figure out what's wrong with this code. Can someone help me? Thanks.


text:
Q: How to get one line from a print output in linux? I'm trying to pull one line from a subprocess.check_output but so far I have no luck. I'm running a Python script and this is my code:
output = subprocess.check_output("sox /home/pi/OnoSW/data/opsoroassistant/rec.wav -n stat", shell=True)

and this is what I get back when I run the script:
Samples read:             80000
Length (seconds):      5.000000
Scaled by:         2147483647.0
Maximum amplitude:     0.001129
Minimum amplitude:    -0.006561
Midline amplitude:    -0.002716
Mean    norm:          0.000291
Mean    amplitude:    -0.000001
RMS     amplitude:     0.000477
Maximum delta:         0.002930
Minimum delta:         0.000000
Mean    delta:         0.000052
RMS     delta:         0.000102
Rough   frequency:          272
Volume adjustment:      152.409

Now I want to get the 9th line (RMS amplitude) out of this list. I already tried something with sed but it didnt gave anything back:
output = subprocess.check_output("sox /home/pi/OnoSW/data/opsoroassistant/rec.wav -n stat 2>&1 | sed -n 's#^RMS     amplitude:[^0-9]*\([0-9.]*\)$#\1#p0'",stderr= subprocess.STDOUT, shell=True)

Thank You

A: What about grep-ing the line ?
output = subprocess.check_output("sox /home/pi/OnoSW/data/opsoroassistant/rec.wav -n stat 2>&1 | grep 'RMS     amplitude:'",stderr= subprocess.STDOUT, shell=True)

A: I think the problem might that you're matching for spaces, but sox is actually outputting a tab characters to do the column spacing. Your terminal is likely expanding the tab to spaces, so when you copy/paste the output, you see spaces. Try matching for [[:space:]] (any whitespace character) instead of literal spaces:
output = subprocess.check_output("sox /home/pi/OnoSW/data/opsoroassistant/rec.wav -n stat | sed -n 's#^RMS[[:space:]]*amplitude:[[:space:]]*\([0-9.]*\)$#\1#p'", shell=True)

I also had to remove the 0 after the p at the end of your sed replace command.
You could also do the output processing in Python (using re) rather than spinning off another subprocess to execute the sed command. That would probably be easier to debug.

A: In order to fix your line, you need to remove the 0 at the end and escape the '\1':
output = subprocess.check_output("sox /home/pi/OnoSW/data/opsoroassistant/rec.wav -n stat 2>&1 | sed -n 's#^RMS     amplitude:[^0-9]*\([0-9.]*\)$#\\1#p'",stderr= subprocess.STDOUT, shell=True)

Also using a pipe isn't really advisable, security wise, I'd suggest changing this line to:
p      = subprocess.Popen(('sox', '/home/pi/OnoSW/data/opsoroassistant/rec.wav', '-n', 'stat', '2>&1'), stdout=subprocess.PIPE)
output = subprocess.check_output(('sed', '-n', 's#^RMS     amplitude:[^0-9]*\([0-9.]*\)$#\\1#p'), stdin=p.stdout)
p.wait()


text:
Q: How to obtain SpatialPolygonsDataframe that contains coordinates I have a SpatialPolygonsDataFrame of the Spanish census tracts and a set of coordinates.
What I would like to do is to obtain the subset of census tract that contains a pair of coordinates (as a new SpatialPolygonsDataFrame).
I came closest using 'over' following this example: https://www.nceas.ucsb.edu/scicomp/usecases/point-in-polygon But 'over' does not return a SpatialPolygonsDataFrame. seccion contains columns "Long" and "Lat" with the coordinates. map is the SpatialPolygonsDataFrame
# turn seccion into a SpatialPoints
coordinates(seccion) <- c("Long", "Lat")
# the coordinates are in the same lat/lon reference system (as is "map")
proj4string(seccion) <- proj4string(map)
# use 'over' with map as a SpatialPolygonsDataFrame
# object, to determine which section (if any) contains the coordinates
sec <- over(seccion, map)

I tried other things and also had a look at the raster library but until now, no luck...

A: You can use the intersect function from the raster package
Example data:
library(raster)
pols <- shapefile(system.file("external/lux.shp", package="raster"))
pnts <- SpatialPoints(matrix(c(6, 5.91, 6.13, 6.23, 6.18,
                       50.08, 49.95, 49.63, 49.64, 49.59),
                       ncol=2), proj4string=crs(pols))

x <- intersect(pols, pnts)

check out the result:
plot(pols, col='light gray')
plot(x, col='blue', add=TRUE)
points(pnts, pch=20, col='red')

It is possible to get there via over (note the order of the arguments)
v <- over(pols, pnts)
xx <- pols[which(!is.na(v)), ]


text:
Q: Эффект подчеркивания разорванной линией при наведении
Помогите добавить такое же подчёркивание как у Home, двойная линия, которая будет под размер контента. Добавить нужно к a:hover

A: Градиент Вам в помощь:

a:hover {
  background: linear-gradient(to right,
    #008ed6 calc(50% - 2px),
    #0000   calc(50% - 1px),
    #0000   calc(50% + 1px),
    #008ed6 calc(50% + 2px)
  );
  background-size: 100% 3px;
  background-repeat: no-repeat;
  background-position: 0 100%;
}

a {
  margin: 10px;
  padding-bottom: 5px;
  color: white;
  font-size: 20px;
  font-family: Arial;
  text-decoration:none;
}

body {
  background: black;
}
Home
Features
About
Pricing

A: Варианты с помощью псевдоэлементов :before и :after:

body {
  background-color: black;
  margin: 20px;
}

div {
  margin-bottom: 10px;
}

a {
  text-decoration: none;
  color: white;
  font-size: 3vw;
  display: inline-block;
  position: relative;
  overflow: hidden;
  margin-right: 20px;
  padding-bottom: 10px;
  cursor: pointer;
}

a:before,
a:after {
  content: "";
  display: block;
  position: absolute;
  bottom: 0;
  height: 2px;
  width: 0;
  background-color: red;
  transition: width 0.4s ease-in-out;
}

.primer1 a:hover:before {
  left: 0;
  width: 50%;
  margin-left: -3px;
}

.primer1 a:hover:after {
  right: 0;
  width: 50%;
  margin-right: -3px;
}

.primer2 a:hover:before {
  left: 0;
  width: 50%;
  margin-left: -6px;
}

.primer2 a:hover:after {
  left: 50%;
  width: 50%;
  margin-right: -6px;
}

.primer3 a:hover:before {
  left: 0;
  right: 0;
  width: 100%;
}

.primer3 a:hover:after {
  right: 50%;
  left: 50%;
  width: 6px;
  background-color: black;
}

.primer4 a:hover:before {
  right: 0;
  width: 100%;
}

.primer4 a:hover:after {
  right: 50%;
  left: 50%;
  width: 6px;
  background-color: black;
}

.primer5 a:before,
.primer5 a:after {
  height: 0px !important;
  background-color: white;
  transition: height 0.4s ease-in-out;
}

.primer5 a:before {
  width: 100% !important;
  background-color: red;
}

.primer5 a:after {
  width: 6px !important;
  right: 50%;
  left: 50%;
  background-color: black;
}

.primer5 a:hover:before {
  height: 2px !important;
}

.primer5 a:hover:after {
  height: 2px !important;
}

  Home
  Features
  About
  Home+Features+About

  Home
  Features
  About
  Home+Features+About

  Home
  Features
  About
  Home+Features+About

  Home
  Features
  About
  Home+Features+About

  Home
  Features
  About
  Home+Features+About


text:
Q: Google App Engine does not deploy two services (seem to be overriding each other) I have a Django backend and an Angular frontend and i'm trying to deploy both of them to a Google App Engine Standard app as two services within the same app.
The directory looks like this:
-backend
--cloudbuild.yaml
--app.yaml
-- ...
-frontend
--cloudbuild.yaml
--app.yaml
-- ...
-cloudbuild.yaml

The main cloudbuild.yaml goes through each folder and looks for a cloudbuild.yaml file and submits the build:
steps:
- name: 'gcr.io/cloud-builders/gcloud'
  entrypoint: 'bash'
  args:
  - '-c'
  - |
    for d in */; do
      config="${d}cloudbuild.yaml"
      if [[ ! -f "${config}" ]]; then
        continue
      fi

      echo "Building $d ... "
      (
        gcloud builds submit $d --config=${config}
      ) &
    done
    wait

When i push the code to my Github repo, they get deployed successfully. However, both logs show something like below:
Step #2: Beginning deployment of service [default]...
Step #2: #============================================================#
Step #2: #= Uploading 0 files to Google Cloud Storage =#
Step #2: #============================================================#
Step #2: File upload done.
Step #2: Updating service [default]...
Step #2: ................................done.
Step #2: Setting traffic split for service [default]...
Step #2: .....done.
Step #2: Deployed service [default] to [https://thisapp.appspot.com]

So it seems like one is overriding the other as the default service. When I go to the services page, there is only one service which is the default one.
I know that we first have to deploy the default service and then the rest. However i thought since the main cloudbuild.yaml submits the build one by one, then there would be a default service and the second build would create a second service.
The other two cloudbuild.yaml files are as below:
steps:

  # Install node packages
  - name: 'gcr.io/cloud-builders/npm'
    args: [ 'install' ]

  # Build productive files
  - name: 'gcr.io/cloud-builders/npm'
    args: [ 'run', 'build', '--prod']

  # Deploy to google cloud app egnine
  - name: 'gcr.io/cloud-builders/gcloud'
    args: ['app', 'deploy', '--version=prod']

steps:

  - name: 'python:3.7'
    entrypoint: python3
    args: ['-m', 'pip', 'install', '-t', '.', '-r', 'requirements.txt']

  - name: 'python:3.7'
    entrypoint: python3
    args: ['./manage.py', 'collectstatic', '--noinput']

  - name: 'gcr.io/cloud-builders/gcloud'
    args: ['app', 'deploy', '--version=prod']

I'd be grateful if you can help me on this.
Thanks

A: It is happening because in your app.yaml file, you have not provided the service tag. If service tag is not provided, the service will be deployed as default service. For e.g. when you deploy your frontend, it is getting deployed as default service. And then you deploy your backend, it is also getting deployed as default service overriding the existing default service. or the vice versa.
Add the service tag in your frontend's app.yaml:
service: frontend
runtime: nodejs10

You may keep the backend as default service i.e. no service tag in backend's app.yaml


text:
Q: Unable to locate package python3-pip in Dockerfile while having Universal Repos enabled I am trying to install python3 and pip.
So, I have a dockerfile
(I also tried with ubuntu:20.04)-
(Note- I have made the Dockerfile short, for full dockerfile you can see here)
FROM ubuntu:latest

WORKDIR /app
COPY . /app
RUN apt-get update
RUN apt-get install -y software-properties-common
RUN add-apt-repository universe

ENV PYTHONUNBUFFERED=1
RUN apt install -y python3
RUN apt-get -y install python3-pip
RUN pip install --no-cache --upgrade pip setuptools

But it always give me error-
 ---> Running in ba9f299b852b
Reading package lists...
Building dependency tree...
Reading state information...
E: Unable to locate package python3-pip
The command '/bin/sh -c apt-get -y install python3-pip' returned a non-zero code: 100

While finding more out in the error, I found out that while the universal repositories were added, python3-pip didnt got installed, while other things like python3-sip got installed.
How do I fix this error and why did it happened?

A: The software-properties-common meta-packages installs a bunch of softwares that are not required in a docker image and make its the size quite huge.
This simpler Dockerfile does the job for me.
FROM ubuntu:latest

WORKDIR /app
#COPY . /app
RUN apt-get update \
 && apt-get install --assume-yes --no-install-recommends --quiet \
        python3 \
        python3-pip \
 && apt-get clean all

RUN pip install --no-cache --upgrade pip setuptools

RUN pip --version  # just for test

Output:
STEP 1/5: FROM ubuntu:latest
STEP 2/5: WORKDIR /app
--> Using cache 9f1d34a70ba9e13074601d16456fda97b2de87a0be3b18ddc6963fb65aaee096
--> 9f1d34a70ba
STEP 3/5: RUN apt-get update  && apt-get install --assume-yes --no-install-recommends --quiet         python3         python3-pip  && apt-get clean all
[...]
STEP 4/5: RUN pip install --no-cache --upgrade pip setuptools
Collecting pip
  Downloading pip-21.3-py3-none-any.whl (1.7 MB)
Collecting setuptools
  Downloading setuptools-58.2.0-py3-none-any.whl (946 kB)
Installing collected packages: pip, setuptools
  Attempting uninstall: pip
    Found existing installation: pip 20.0.2
    Not uninstalling pip at /usr/lib/python3/dist-packages, outside environment /usr
    Can't uninstall 'pip'. No files were found to uninstall.
  Attempting uninstall: setuptools
    Found existing installation: setuptools 45.2.0
    Not uninstalling setuptools at /usr/lib/python3/dist-packages, outside environment /usr
    Can't uninstall 'setuptools'. No files were found to uninstall.
Successfully installed pip-21.3 setuptools-58.2.0
STEP 5/5: RUN pip --version
pip 21.3 from /usr/local/lib/python3.8/dist-packages/pip (python 3.8)
COMMIT staskoverflow-ubuntu
--> 2498ddc1767
Successfully tagged localhost/staskoverflow-ubuntu:latest
2498ddc17672584d2dd38bf23ae63521d9adb43465cf8c7b415c33dc2aa0aa01

The tool pip is updated to the version 21.3 and the OS-provided one is not uninstalled (this is a pip feature).
Anyway this dockefile, more similar to yours, works too:
RUN apt-get update \
 && apt-get install --assume-yes --no-install-recommends --quiet \
        software-properties-common \
 && add-apt-repository universe \
 && apt-get update \
 && apt-get install --assume-yes --no-install-recommends --quiet \
        python3 \
        python3-pip \
 && apt-get clean all

RUN pip install --no-cache --upgrade pip setuptools

After adding the universe repository, you should run again apt-get update to retrieve the new lists of packages with the new apt configuration. This is the root cause of the problem I think.


text:
Q: How to get an iterator over the return values of member function? class A
{
   public:
     const B& GetB() const;
};

vector<A> manyA;

template<typename ConstBIter>
void foo(ConstBIter beginB, ConstBIter endB);

Whats the most elegant way to get a iterator over the Bs stored in A. Could get the pointers, store them in an array and use a boost::indirect_iterator. But there is certainly a better way?

A: Write your own iterator class. In C++, you are not limited to using only the iterator classes that are defined in the standard C++ library.
If your class meets the requirements for an iterator, as defined in the C++ standard, it can be used with the C++ library anywhere where any other iterator, that meets the same requirements, can be used.
Many large software libraries, in fact, declare and define their own iterators, for their own particular purposes.

A: Got the solution...
typedef boost::transform_iterator<boost::function<B&(A&)>, vector<A>::iterator> BIter;

BIter beginBIter(manyA.begin(), boost::mem_fn(&Layer::GetB));
BIter endBIter(manyA.end(), boost::mem_fn(&Layer::GetB));