text:
Q: Paper.js shim config Require.js I'm trying to initialize an application but seem to be having trouble getting paper js to properly load into my script. I'm using require.js as my AMD loader and am trying to load paper js with the shim module.
Here's my code:
requirejs.config({
    urlArgs: "bust=" + (new Date()).getTime(),//used to keep the browser from caching the scripts as we move
    baseUrl : "scripts",//base scripts page!
    paths : {
        'jquery' : "../components/jquery/jquery.min", //specific libraries -- can be specified later
        'underscore' : "../components/underscore/underscore",
        'paper' : "../components/paper/paper"
    },
    shim: {
        'underscore': {
            exports: '_'
        },
        'paper' : {
            exports: 'Paper'
        },
    },
});

// initialize the document with a doc ready!

requirejs(["jquery", "underscore", "paper"], function ($, _, Paper) {
    alert(_);
    alert(Paper);
});

The first alert works fine, (the underscore) meaning that it loads okay, but I can't seem to figure out how to get paper.js working properly.
Any help would be greatly appreciated.

A: The PaperJS global namespace is "paper".
Simply replace "Paper" by "paper" and it should work.
'paper' : {
    exports: 'paper'
}


text:
Q: How to make a method with a return statement that is inside an abstract class which implements an interface get inherited by a subclass? I will post the part of the code that I have trouble with. I scoured the internet for hours and cannot find a solution to how to properly solve this problem with a method that has a return and isn't just a sentence. I would seriously appreciate any help that I can get! Essentially what I need is for my subclass to inherit the same method in its abstract father without any changes, so that I can apply that in my main code.
public class Main {
interface Dodela
{
public int PovecajKS();
public int SmanjiS();
}

public static abstract class Ekspanzija implements Dodela
{

final public int PovecajKS(int a, int b)
{
a = a + b;
return a;
}
final public int SmanjiS(int a, int b)
{
a = a - b;
return a;
}
}

public static class EkspanzijaP extends Ekspanzija implements Dodela
{

    public int PovecajKS()
    {
    }

    public int SmanjiS() {
        int a = 0, b = 0;
        a = a - b;
        return a;
    }

}

A: It already inherits all methods of its father, to use the method inside the subclass, it can be called like this

super.yourFunctionName()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Delayed post parameters when submitting via onChange in reactjs I'm trying to send a parameter to the api to give me an exact json response, but when i'm trying to submit my form via select onChange={onAddSubmit}, it is still passing the default value 146846 but I already changed my select to 146847 so i'm getting the invalid response.
Home.js
import React, { useEffect, useState } from "react";
import Api from "../Api";

import AppContainer from "../tmp/AppContainer";
import HomeContainer from "./HomeContainer";

const Home = () => {
    const [posts, setPosts] = useState();
    const [loading, setLoading] = useState(false);
    const [allValues, setAllValues] = useState({
        contractId: "146846",
        planId: "1028",
        dateStart: "2021-01-30",
        dateEnd: "2021-01-31",
        numberOfAdults: 1,
        numberOfChildren: 0,
        planOption: "Individual",
        unit: "day",
    });
    const changeHandler = (e) => {
        setAllValues({ ...allValues, [e.target.name]: e.target.value });
    };

    const onAddSubmit = async (e) => {
        e.preventDefault();
        setLoading(true);
        try {
            await Api.getCurlPost({
                ...allValues,
            }).then((response) => {
                const result = response.data;
                setPosts(result.data);
            });
        } catch {
            alert("Failed to add post!");
        } finally {
            setLoading(false);
        }
    };
    useEffect(() => {
        onAddSubmit;
    }, []);

    return (
        <AppContainer>
            <HomeContainer
                onAddSubmit={onAddSubmit}
                changeHandler={changeHandler}
                loading={loading}
                posts={posts}
            />
        </AppContainer>
    );
};

export default Home;

Here is my HomeContainer.js that contains my html and bootstrap design
import React, { Component } from "react";

import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faPlane } from "@fortawesome/free-solid-svg-icons";
import { faCircleNotch } from "@fortawesome/free-solid-svg-icons";

class HomeContainer extends Component {
    render() {
        const { onAddSubmit, changeHandler, loading, posts } = this.props;
        return (

                                <FontAwesomeIcon
                                    icon={faPlane}
                                    rotation={0}
                                    style={{ marginRight: 5 }}
                                />
                                Travel Details

                            <form onChange={onAddSubmit}>

                                    <select
                                        className="form-control"
                                        name="contractId"
                                        onChange={changeHandler}
                                    >
                                        <option value="146846">
                                            TravelLead Domestic Travel Insurance
                                        </option>
                                        <option value="146847">
                                            TravelLead International Travel
                                            Insurance
                                        </option>
                                    </select>

                                    <select
                                        className="form-control"
                                        name="planId"
                                        onChange={changeHandler}
                                    >
                                        <option value="1028">
                                            Economy (Single Trip)
                                        </option>
                                        <option value="1029">
                                            Elite (Single Trip)
                                        </option>
                                    </select>

                            </form>

        );
    }
}

export default HomeContainer;

A: I figured it already, I just added allValues as a parameter when calling onAddSubmit on my useEffect hook, and if there is something changes happen to allValues list it will automatically submit a request to the API and throw a response.
    useEffect(() => {
        onAddSubmit(allValues);
    }, [allValues]);

And onAddSubmit function, just change the ...allValues to ...data on api parameter that sends a request to axios.
const onAddSubmit = async (data) => {
        setLoading(true);
        try {
            await Api.getCurlPost({
                ...data,
            }).then((response) => {
                const result = response.data;
                setPosts(result.data);
            });
        } catch {
            alert("Failed to add post!");
        } finally {
            setLoading(false);
        }
    };


text:
Q: How to pass alert box value to fragment I have two java file one is fragment and another one DialogFragment. In my app i show alert box with radio button. If user choose anyone option, i want to pass that item to fragment(Address Fragment). I wrote some code its show alert box. but, i can't pass that item to Address Fragment..
Please anyone help to me!
My code here...
AddressFragment.java:

public class AddressFragment extends Fragment implements RadioListAlert.AddressListener {

    int position = 0;

    EditText line1;
    EditText line2;
    EditText landmark;
    AutoCompleteTextView cityText;
    EditText zipcode;
    Spinner country;
    Spinner state;
    RadioGroup tag;
    Button savaddr;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_layout_address, container, false);

        savaddr = (Button) view.findViewById(R.id.addrsave);
        tag = (RadioGroup) view.findViewById(R.id.radioGroup);
        line1 = (EditText) view.findViewById(R.id.line1);
        line2 = (EditText) view.findViewById(R.id.line2);
        cityText = (AutoCompleteTextView) view.findViewById(R.id.city_autoCompleteTextView);
        zipcode = (EditText) view.findViewById(R.id.zipcode);
        country = (Spinner) view.findViewById(R.id.countrySpinner);
        state = (Spinner) view.findViewById(R.id.stateSpinner);
        landmark = (EditText) view.findViewById(R.id.landmark);

        // Get a reference to the AutoCompleteTextView in the layout
        AutoCompleteTextView textView = (AutoCompleteTextView) view.findViewById(R.id.city_autoCompleteTextView);
        // Get the string array
        String[] city = getResources().getStringArray(R.array.city);
        // Create the adapter and set it to the AutoCompleteTextView
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, city);

        textView.setAdapter(adapter);

        savaddr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String addr1 = line1.getText().toString();
                String addr2 = line2.getText().toString();
                String addr_city = cityText.getText().toString();
                String addr_zipcode = zipcode.getText().toString();
                String addr_country = country.getSelectedItem().toString();
                String addr_state = state.getSelectedItem().toString();

                //Field Validation

                if (Utility.isNotNull(addr1) && Utility.isNotNull(addr2) && Utility.isNotNull(addr_city) && Utility.isNotNull(addr_zipcode) && Utility.isNotNull(addr_country) && Utility.isNotNull(addr_state)) {
                    if (Utility.line2_validate(addr2)) {
                        if (Utility.line2_validate(addr_city)) {

                            Toast.makeText(getActivity().getApplicationContext(), "Success.", Toast.LENGTH_SHORT).show();
                            new RadioListAlert().setListener(this).show(getActivity().getFragmentManager(), "Radio Alert");// I got error in this line setListener(this)

                        } else {
                            cityText.setError("Enter valid City");
                        }
                    } else {
                        line2.setError("Enter valid Address");
                    }
                } else {
                    Toast.makeText(getActivity().getApplicationContext(), "Please fill the form, don't leave any field blank", Toast.LENGTH_SHORT).show();
                }
            }
        });

        return view;

    }

    @Override
    public void itemClicked(String text) {
        TextView tv = (TextView) getActivity().findViewById(R.id.tv_android);

        /** Setting the selected android version in the textview */
        tv.setText("Your Choice : " + text);

    }
}

RadioListAlert.java:

public class RadioListAlert extends DialogFragment {

    CharSequence[] tag = { "BMW", "AUDI", "MERCEDES", "FERRARI", "SKODA" };
    private AddressListener addressListener;
    private String itemClicked;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setCancelable(true);
        builder.setTitle("Tag Your Car").setSingleChoiceItems(tag, -1,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        Toast.makeText(getActivity(), tag[which],Toast.LENGTH_SHORT).show();
                        itemClicked = (String) tag[which];
                    }
                }).setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if (addressListener != null)
                    addressListener.itemClicked(itemClicked);
                //to dismiss the dialog after user choose an item and click ok, you can also add some validation before dismissing the dialog
                dismiss();
            }
        }).setNegativeButton("Cancel",new DialogInterface.OnClickListener(){

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dismiss();
            }
        });
        return builder.create();
    }

    public void setListener(AddressListener addressListener)
    {
        this.addressListener = addressListener;
    }

   public interface AddressListener
    {
        void itemClicked(String text);
    }
}

I got an error in this line in Address Fragment:
new RadioListAlert().setListener(this).show(getActivity().getFragmentManager(), "Radio Alert");
especially,  .setListener(this)
Its throw an Error:

setListener(RadioListAlert.AddressListener) in RadioListAlert cannot be applied to (anonymous android.view.View.OnClickListener)

Please anyone help me!
Thanks in advance!!

A:
setListener(RadioListAlert.AddressListener) in RadioListAlert cannot
  be applied to (anonymous android.view.View.OnClickListener)

Due to passing onClick method context to setListener method but required is context of class which is currently implementing AddressListener interface:
new RadioListAlert().setListener(AddressFragment.this).show(
                        getActivity().getFragmentManager(), "Radio Alert");


text:
Q: Updating two tables for generating invoice and activate user I need to generate invoice at the time of activate user where mobile_no is in both table as foreign key.
I have two tables required update as follows
Table1 CI_USER
is_active = 0/1
mobile_no
Table2 VOUCHER
mobile_no voucher_no | Auto Increment voucher_date
voucher_amount reward1_amt reward2_amt
is_reward1
is_reward2 reward1_date reward2_date
but i am facing some problem in function or controller so please provide me any solution for that
Model
public function edit_user($data, $id){
         $this->db->set($data);
         $this->db->where('ci_users.id', $id);
         $this->db->where( 'voucher.id', $id );
         $this->db->update(array('ci_users as a', 'voucher as b'));
        return true;
    }

Controler
public function activate($id = 0)($mobile_no = mobile_no){
        if($this->input->post('submit')){
            $this->form_validation->set_rules('voucher_amount', 'Voucher Amount', 'trim|required');
            $this->form_validation->set_rules('status', 'Status', 'trim|required');

            if ($this->form_validation->run() == FALSE) {
                $data['user'] = $this->Activate_member_model->get_user_by_id($id);
                $data['user_groups'] = $this->Activate_member_model->get_user_groups();
                $data['view'] = 'admin/Activate_member/member_edit';
                $this->load->view('layout', $data);
            }
            else{
                $data = array(
                    'mobile_no' => $this->session->userdata('mobile_no'),
                    'voucher_amount' => $this->input->post('voucher_amount'),
                    'is_active' => $this->input->post('status'),
                    'updated_at' => date('Y-m-d : h:m:s'),
                    'voucher_date' => date('Y-m-d : h:m:s'),
                    'voucher_no' => $this->input->post('voucher_no'),
                );
                $data = $this->security->xss_clean($data);
                $result = $this->Activate_member_model->edit_user($data, $id);
                if($result){
                    $this->session->set_flashdata('msg', 'User has been updated successfully!');
                    redirect(base_url('admin/Activate_member'));
                }
            }
        }
        else{
            $data['user'] = $this->Activate_member_model->get_user_by_id($id);
            $data['user_groups'] = $this->Activate_member_model->get_user_groups();
            $data['view'] = 'admin/Activate_member/member_edit';
            $this->load->view('layout', $data);
        }
    }

Problem 1 of phrase on line no 1 of activate function
Message: syntax error, unexpected '(', expecting ';' or '{'
if calling 1 table like this working fine
public function activate($id = 0){

}
Problem 2 If going with only ($id = 0)
Messege :'UPDATE Array SET mobile_no = '', voucher_amount = '11000', is_active = '1', updated_at = '2018-06-06 : 07:06:19', voucher_date = '2018-06-06 : 07:06:19', voucher_no = '' WHERE ci_users.id = '8' AND voucher.id = '8'`


text:
Q: How to set multiple conditions for multiple values in a row in R? I have a genetic data set where each row describes a gene and has a beta column with multiple beta values I've compressed into one row/cell (from the variant level where multiple variants in one gene gave multiple betas). The beta is the effect size that the gene can have on a condition so large negative values are important as well as large positive values. I am trying to write code that selects either the largest negative or largest positive beta value for a gene, cutting off at -0.5 and 0.5.
The rules I am trying to code are these:
If a gene/row has a value less than -0.5 and no values higher than 0.5 then keep only the largest negative value.
If it has a value higher than 0.5 and no values less than -0.5 keep only the largest positive value.
If it has no values less than -0.5 or more than 0.5 keep the largest value.
If it has both values less than -0.5 and more than 0.5 keep the largest value.
For example my data looks like this:
Gene    Beta(s)
ACE     0.01, -0.6, 0.4
BRCA    0.7, -0.2, 0.2
ZAP70   0.001, 0.02, -0.003
P53     0.8, -0.6, 0.001

Expected output (selecting largest negative or positive values depending on set conditions):
Gene    Beta(s)
ACE     -0.6
BRCA     0.7
ZAP70    0.02
P53      0.8

I am from a biology background and new to R, so not sure how to code this. At the moment I am working with functions to select either the maximum or minimum beta values for a gene, but I don't know how to amend this with further conditions:
max2 = function(x) if(all(is.na(x))) NA else max(x,na.rm = T)
getmax = function(col) str_extract_all(col,"[0-9\\.-]+") %>%
  lapply(.,function(x)max2(as.numeric(x)) ) %>%
  unlist()

min2 = function(x) if(all(is.na(x))) NA else min(x,na.rm = T)
getmin = function(col) str_extract_all(col,"[0-9\\.-]+") %>%
  lapply(.,function(x)min2(as.numeric(x)) ) %>%
  unlist()

test <- df %>%
  mutate_at(names(df)[2],getmax)

Any help in the right direction of how to set multiple conditional statements would be appreciated.
Example data:
 dput(df)
structure(list(Gene = c("ACE", "BRCA", "ZAP70", "P53"), `Beta(s)` = c("0.01, -0.6, 0.4",
"0.7, -0.2, 0.2", "0.001, 0.02, -0.003", "0.8, -0.6, 0.001")), row.names = c(NA,
-4L), class = c("data.table", "data.frame"))

A: Here is a data.table solution that should work fast and indepentant of the number of beta's provided.
library( data.table )
library( matrixStats )
#set df as data.table
setDT( df )
#split Beta(s) to columns (dynamically)
df[, paste0( "Beta",
             1:length( tstrsplit( df$`Beta(s)`, "," ) ) ) :=
     lapply( tstrsplit( `Beta(s)`, "," ), as.numeric ) ][]
#     Gene             Beta(s) Beta1 Beta2  Beta3
# 1:   ACE     0.01, -0.6, 0.4 0.010 -0.60  0.400
# 2:  BRCA      0.7, -0.2, 0.2 0.700 -0.20  0.200
# 3: ZAP70 0.001, 0.02, -0.003 0.001  0.02 -0.003
# 4:   P53    0.8, -0.6, 0.001 0.800 -0.60  0.001

#now, using rowMINs ans RowMAxs from the matrixStats-package (=FAST!!)
# get the filtering (and updating) done by reference.

#If a gene/row has a value less than -0.5 and no values higher than 0.5 then keep only the largest negative value.
df[ df[, rowMins( as.matrix(.SD), na.rm = TRUE ), .SDcols = patterns("^Beta[0-9]") ] < -0.5 &
      df[, rowMaxs( as.matrix(.SD), na.rm = TRUE ), .SDcols = patterns("^Beta[0-9]") ] <= 0.5,
    Beta.final := rowMins( as.matrix(.SD), na.rm = TRUE ), .SDcols = patterns("^Beta[0-9]") ]
#If it has a value higher than 0.5 and no values less than -0.5 keep only the largest positive value.
df[ df[, rowMaxs( as.matrix(.SD), na.rm = TRUE ), .SDcols = patterns("^Beta[0-9]") ] > 0.5 &
      df[, rowMins( as.matrix(.SD), na.rm = TRUE ), .SDcols = patterns("^Beta[0-9]") ] >= -0.5,
    Beta.final := rowMaxs( as.matrix(.SD), na.rm = TRUE ), .SDcols = patterns("^Beta[0-9]") ]
#If it has no values less than -0.5 or more than 0.5 keep the largest value.
df[ df[, rowMins( as.matrix(.SD), na.rm = TRUE ), .SDcols = patterns("^Beta[0-9]") ] >= -0.5 &
      df[, rowMaxs( as.matrix(.SD), na.rm = TRUE ), .SDcols = patterns("^Beta[0-9]") ] <= 0.5,
    Beta.final := rowMaxs( as.matrix(.SD), na.rm = TRUE ), .SDcols = patterns("^Beta[0-9]") ]
#If it has both values less than -0.5 and more than 0.5 keep the largest value.
df[ df[, rowMins( as.matrix(.SD), na.rm = TRUE ), .SDcols = patterns("^Beta[0-9]") ] < -0.5 &
      df[, rowMaxs( as.matrix(.SD), na.rm = TRUE ), .SDcols = patterns("^Beta[0-9]") ] > 0.5,
    Beta.final := rowMaxs( as.matrix(.SD), na.rm = TRUE ), .SDcols = patterns("^Beta[0-9]") ]

*output
#final output
df[, .(Gene, `Beta(s)` = Beta.final )][]
#     Gene Beta(s)
# 1:   ACE   -0.60
# 2:  BRCA    0.70
# 3: ZAP70    0.02
# 4:   P53    0.80

A: Though the logic is not fully clear to me, most likely something like that:
library(tidyverse)
library(stringr)

df %>%
  separate("Beta(s)", sep = ",", into = str_c("v", 1:3)) %>%
  mutate_at(vars(starts_with("v")), as.numeric) %>%
  mutate(vmax = pmax(v1, v2, v3), vmin = pmin(v1, v2, v3)) %>%
  mutate(want = case_when(vmax > 0.5 & vmin > -0.5 ~ vmax, # if vmax is > 0.5, it is always positive ..
                          abs(vmax) > abs(vmin) ~ vmax, # get largest absolute value ??
                          TRUE ~ vmin)) %>%
  select(Gene, want)

# Gene  want
# 1   ACE -0.60
# 2  BRCA  0.70
# 3 ZAP70  0.02
# 4   P53  0.80

## edited (handling multiple columns and NA):

df %>%
  bind_cols(df %>%
              pull("Beta(s)") %>%
              str_split(",", simplify = TRUE) %>%
              `colnames<-`(str_c("v", 1:NCOL(.))) %>%
              as_tibble() %>%
              mutate_all(~str_remove_all(., "\\s") %>%
                           str_remove_all(., "NA") %>%
                           as.numeric) %>%
              mutate(vmax = pmap_dbl(., pmax, na.rm = T),
                     vmin = pmap_dbl(., pmin, na.rm = T))) %>%
  mutate(want = case_when(vmax > 0.5 & vmin > -0.5 ~ vmax,
                          abs(vmax) > abs(vmin) ~ vmax,
                          TRUE ~ vmin)) %>%
  select(Gene, want)


text:
Q: Django timezone is wrong I can't seem to make timezone works with Django 1.11.
My Settings.py:
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True

I'm starting the server at :

And it outputs the following:

Which is 4:09PM
And of course when doing:
form django.utils import timezone
today = timezone.localtime(timezone.now())
print(today)

The outuput is also wrong by +1 hour, while the time is indeed specified as +00:

2017-08-10 16:09:04.208536+00:00

Any idea of what i'm missing ?


text:
Q: how to change class of a element multiple times in VueJS Function in vanilla js, which I want to implement in Vue.js
example: https://codesandbox.io/s/xjk3xqnprw
This is what I want to implement in Vue js
Below is my vue component, it is loading perfectly but it is not having animation
My Vue component:
<template>

Dice Game
* live

</template>

I want the toggle style class(in a loop) so that the animation of dice roll can be achieved
Thanks for the help in advance

A: You are now toggling your rollDice function beforeMount, if you change this to created the changes will be toggled correctly, also note that you will need to change toggleClasses to this.toggleClasses since it is defined in the methods section of your component and is therefore bound to the component and not a global function anymore.
I hope this helps you!
P.S. See my codepen for a working sample, note that I used a settimeout here for demo purposes, but you can adjust this to a @click="rollDice" on a button within your component and leave out the mounted alltogether


text:
Q: How do I eliminate rows with certain values in R? I am trying to eliminate the rows in my dataset that have as values of the variable income either 0 or NA. By running the two lines of code below, I found out that there are 1039 observations with the characteristics that I am looking for. In particular, even though I am only asking for income equal to 0, r automatically takes into also the NA values.
length(allregions$income[allregions$emp == 1 & allregions$income == 0])
allregions$income[allregions$emp == 1 & allregions$income == 0]

However, when I try to eliminate those rows, r only deletes the rows with income equal to 0 and keeps those with NA. Even if I add NA in the condition, those values still remain in my dataset.
allregions <- allregions[!(allregions$income == 0 & allregions$emp == 1),]

How can I drop the rows with NAs in a particular column?
Also, how is it possible that even though I apply the same condition, in one case R takes into account NAs too and in another it doesn't?
Thank you in advance for your help!

A: You can use %in% like this:
result <- allregions[!(allregions$income %in% c(0, NA)), ]

Or use is.na() to test for NA
result <- allregions[allregions$income != 0 & !is.na(allregions$income), ]

To understand why R behaves like it does, I'd suggest these FAQs: Logical operators (AND, OR) with NA, TRUE and FALSE, Dealing with TRUE, FALSE, NA and NaN

A: Tidyverse is a great package for this sort of task:
library(tidyverse)

result <- allregions %>%
  filter(!is.na(income) & income !=0)

result <- allregions %>%
  filter(!income %in% c(0, NA))


text:
Q: Update xml column in a table I need to remove a Xml element which has the attribute of A with the value of xxxx from the Xml values in a column.
Method 1:
update t set x = x.query('//E[@A != "xxxx"]')

Method 2:
update t set x.modify('delete /E[@A = "xxxx"]')

Which one is better?

A: Both calls would not do the same:
DECLARE @xml XML=
N'<root>
  <test pos="1" a="xxx">test 1</test>
  <test pos="2" a="SomeOther">test 2</test>
  <test pos="3" a="xxx">test 3</test>
  <OtherElement>This is another element</OtherElement>
  </root>';

--Try this with either this approach
SET @xml=@xml.query(N'//test[@a!="xxx"]')

--Or try it with this
SET @xml.modify(N'delete //test[@a="xxx"]')

SELECT @xml;

The result of the first is
<test pos="2" a="SomeOther">test 2</test>

While the second returns
<root>
  <test pos="2" a="SomeOther">test 2</test>
  <OtherElement>This is another element</OtherElement>
</root>

XML is not stored as the text you see. It is stored as a tree structure representing a complex document. To modify this is fairly easy, just kick out some elements. The query()approach has to rebuild the XML and replace the first with an new one. So my clear advise is: Use the modify()approach! If you are really good with XQuery and FLWOR the query() approach is much mightier, but this is another story...


text:
Q: How to bring Activity to top of stack and reset it? I'm trying to keep my activity calling flow simple for the user.  Always one instance of the activity on the history stack.
So using flag FLAG_ACTIVITY_REORDER_TO_FRONT, is perfect! but there is a slight issue.
The activity is brought to the front and the onCreate() is not called if already started. Makes sense but I want the behavior to be that it calls onCreate().
Thanks for the help!
-Jona

A: Maybe what you are searching for is the method onNewIntent(). This method should be called if your Activity is already in the stack and is started again.
In here the new Intent should be passed to you, so that you can react and initialize you variables like you would do in onCreate() with the intent data fetched via getIntent().


text:
Q: Login problems: Authentication autowired controller issue Apache Netbeans Java I'm constructing a Login with java, I've been following a tutorial but now I've encountered an issue. The app is supposed to be working and I should be able to try it on postman, but it is failing to start.
The issue is:
Description:
Field passwordEncoder in com.portfolio.anamorujaportfolio.Security.Controller.AuthController required a bean of type 'org.springframework.security.crypto.password.PasswordEncoder' that could
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'org.springframework.security.crypto.password.PasswordEncoder' in your configuration.
/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package com.portfolio.anamorujaportfolio.Security.Controller;

import com.portfolio.anamorujaportfolio.Security.Dto.JwtDto;
import com.portfolio.anamorujaportfolio.Security.Dto.LoginUsuario;
import com.portfolio.anamorujaportfolio.Security.Dto.NuevoUsuario;
import com.portfolio.anamorujaportfolio.Security.Entity.Rol;
import com.portfolio.anamorujaportfolio.Security.Entity.Usuario;
import com.portfolio.anamorujaportfolio.Security.Enums.RolNombre;
import com.portfolio.anamorujaportfolio.Security.Service.RolService;
import com.portfolio.anamorujaportfolio.Security.Service.UsuarioService;
import com.portfolio.anamorujaportfolio.Security.jwt.JwtProvider;
import java.util.HashSet;
import java.util.Set;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/auth")
@CrossOrigin
public class AuthController {
    @Autowired
    PasswordEncoder passwordEncoder;
    @Autowired
    AuthenticationManager authenticationManager;
    @Autowired
    UsuarioService usuarioService;
    @Autowired
    RolService rolService;
    @Autowired
    JwtProvider jwtProvider;

    @PostMapping("/nuevo")
    public ResponseEntity<?> nuevo(@Valid @RequestBody NuevoUsuario nuevoUsuario, BindingResult bindingResult){
        if(bindingResult.hasErrors())
            return new ResponseEntity(new Mensaje("Campos mal puestos o email invalido"), HttpStatus.BAD_REQUEST);

        if(usuarioService.existsByNombreUsuario(nuevoUsuario.getNombreUsuario()))
            return new ResponseEntity(new Mensaje("Ese nombre de usuario ya existe"), HttpStatus.BAD_REQUEST);

         if(usuarioService.existsByEmail(nuevoUsuario.getEmail()))
            return new ResponseEntity(new Mensaje("Ese email ya existe"), HttpStatus.BAD_REQUEST);

         Usuario usuario = new Usuario(nuevoUsuario.getNombre(), nuevoUsuario.getNombreUsuario(), nuevoUsuario.getEmail(), passwordEncoder.encode(nuevoUsuario.getPassword()));
         Set<Rol>roles=new HashSet<>();
         roles.add(rolService.getByRolNombre(RolNombre.ROLE_USER).get());

         if(nuevoUsuario.getRoles().contains("admin"))
             roles.add(rolService.getByRolNombre(RolNombre.ROLE_ADMIN).get());
         usuario.setRoles(roles);
         usuarioService.save(usuario);

         return new ResponseEntity(new Mensaje("Usuario guardado"), HttpStatus.CREATED);
    }

    @PostMapping("/login")
    public ResponseEntity<JwtDto> login(@Valid @RequestBody LoginUsuario loginUsuario, BindingResult bindingResult){
        if(bindingResult.hasErrors())
            return new ResponseEntity(new Mensaje("Campos mal puestos"), HttpStatus.BAD_REQUEST);
        Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginUsuario.getNombreUsuario(),loginUsuario.getPassword()));
        SecurityContextHolder.getContext().setAuthentication(authentication);

        String jwt = jwtProvider.generateToken(authentication);

        UserDetails userDetails = (UserDetails) authentication.getPrincipal();

        JwtDto jwtDto = new JwtDto(jwt, userDetails.getUsername(), userDetails.getAuthorities());
        return new ResponseEntity(jwtDto, HttpStatus.OK);
    }

}

It's my first go at Java, thanks in advance for the help!!

I've no idea, but I want it to run

A: The error says it all. Basically the application thinks that a configuration is missing which is unable to bind the PasswordEncoder.
Upon closer look, PasswordEncoder is part of the Spring package and the way AutoInjections work is (by default), spring only scans the classes from the root package and since its not part of the root it cant autowire the bean.
You can initialise it like this from a custom config class and annotate it as a Bean and then Autowire it..
@Bean
public PasswordEncoder passwordEncoder() {
    return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}

Please refer an implementation here
https://www.baeldung.com/spring-security-registration-password-encoding-bcrypt
Please refer to the documentation here
https://docs.spring.io/spring-security/reference/features/authentication/password-storage.html#authentication-password-storage
Hope this helps!


text:
Q: Data binding gives undefined value unexpectedly My binding does not work anymore when I added the computed property to my viewModel. Without the computed property I have no problem. My code:
var orgData =  @Html.Raw(Json.Encode(Model));
    var viewModel = {
        myData: ko.observable(orgData) ,
        displayTag: ko.computed(function() {
            return "(" +  orgData.Tag + ")";
        }, this)
     };

ko.applyBindings(viewModel);

and in html, my binding like this:
data-bind="text: myData.SerialNumber"

The value is undefined even thought the JSON data looks good.
Any suggestions?

A: Since this is a computed observable, rewrite your computed function to:
displayTag: ko.computed(function(){
   var data = this.myData();
   return "(" + data.Tag + ")";
}, this)

This way your computed gets updated if myData is updated. Currently, that wouldn't be the case.
If you are still seeing undefined in the display, then verify the data.Tag has a value.


text:
Q: Ng-content not parsed for downgraded angular 2 component My goal is to create an universal tab component for Angular2 as shown below:
<tabs>
   <tab tabTitle="Tab 1">This is tab 1 content</tab>
   <tab tabTitle="Tab 2">This is tab 2 content</tab>
</tabs>

However when I implement this component based on this excellent example I got this error:
TypeError: Cannot set property 'active' of undefined

The reason for this is probably @ContentChildren(Tab) tabs: QueryList<Tab>; is unable to parse the <tab> tags defined between the <tabs> tag. This leaves tabs without any children and therefore doesn't have any tabs to set to active.
A live example is available on plunkr
index.html
<tabscontainer></tabscontainer>

TabsContainer.ts
import {Tabs} from './Tabs';
import {Tab} from './Tab';

@Component({
  selector: 'tabscontainer',
  template: `
    <tabs>
      <tab tabTitle="Tab 1">This is tab 1 content</tab>
      <tab tabTitle="Tab 2">This is tab 2 content</tab>
    </tabs>
  `,
  directives: [Tabs, Tab]
})
export class TabsContainer {
  constructor() { }
}

Tab.ts
import { Component, Input, Injectable } from 'angular2/core';

@Component({
  selector: 'tab',
  template: `
    <div [hidden]="!active">
      <ng-content></ng-content>
    </div>
  `
})

@Injectable()
export class Tab {
  @Input('tabTitle') title: string;
  @Input() active = false;
}

A: Changing
  selectTab(tab: Tab) {
    // deactivate all tabs
    this.tabs.toArray().forEach(tab => tab.active = false);

    // activate the tab the user has clicked on.
    tab.active = true;
  }

to
  selectTab(tab: Tab) {
    // deactivate all tabs
    this.tabs.toArray().forEach(tab => tab.active = false);

    // activate the tab the user has clicked on.
    if(tab) {
      tab.active = true;
    }
  }

fixes the error message.
I don't know yet why selectTab(...) is called with tabs and then again without any tabs - this is when tab.active trhows because tab is null.
You have
<tabs>
  <tab>Tab 1</tab>
  <tab>Tab 2</tab>
</tabs>

in your index.html. <ng-content> isn't supported on the root component. You should wrap your entire application in an application component and put the tab in there.


text:
Q: Need equivalent command for "oc secret new-basicauth" which is deprecated in openshift I am following this guide (https://github.com/3scale/apicast) to create an environment with apicast and openshift.
The guide says that I need to create a secret using  "oc secret new-basicauth"  but I get the following message after executing the command.
> oc secret new-basicauth apicast-configuration-url-secret --password=https://ACCESS-TOKEN@ACCOUNT-admin.3scale.net
> Command "new-basicauth" is deprecated, use oc create secret
I understand that the command is deprecated and I need to use "oc create secret" instead.  However, I do not know how to use the new command to achieve the same result, which is creating a new-basicauth.

A: I had the same problem and following the docs it seems that the following command might do the trick:
oc create secret generic gitlab-credentials \
  --from-literal=username=<user_name> \
  --from-literal=password=<password> \
  --type=gitlab.com/basic-auth

"gitlab-credentials" here is the secret name.
Then, if you want to create an app using the secret you just created:
oc new-app \
  <imagestream-chosen>~<git-repo-url> \
  --context-dir=<context-dir> \
  --allow-missing-imagestream-tags \
  --source-secret=gitlab-credentials

The --source-secret gets the previously created secret.
Hope this helps.

A: If you are looking for oc create secret reference, the following link is helpful.
https://docs.openshift.com/container-platform/3.9/dev_guide/builds/build_inputs.html#source-secrets-basic-authentication

A: I had to tweak matthieusb answer a little bit for it to work for me. Note I was doing basic auth against github.com not gitlab.com. So for the sake of people in a similiar situtation as me, I am putting this answer up.
I consulted the Kubernetes secret builtin types found here, keep in mind Openshift is built on top of Kubernetes: Secrets | Kubernetes
I merely changed the type to kubernetes.io/basic-auth, I guessed this is the one I wanted since I was doing basic auth against github.com:
oc create secret generic gitlab-credentials \
  --from-literal=username=<user_name> \
  --from-literal=password=<password> \
  --type=kubernetes.io/basic-auth

This ended up being enough for the oc new-app to work for me.
One thing to note is that even though that command is deprecated you can still use it. I used it to confirm that the yaml generated for the secret is the same for the yaml of the non deprecated command above.
In fact, according to the 4.7 Release Notes, deprecated features are still supported but not recommended as they will be eventually removed.
Openshift Container Platform ... release notes


text:
Q: Redirect directory pages WITHOUT extension to WITH extension in .htaccess How redirect pages from directory like
site.com/directory/{code} (code with numbers and letters)
to
site.com/directory/{code}.html
I try this code, but its redirect to .html many times like circle
RewriteEngine on
RewriteRule ^directory/(.*)$ directory/$1.html [R=301,L]

A: solution
RewriteEngine on
RewriteCond %{REQUEST_URI} !(\.html)$ [NC]
RewriteRule ^directory/(.*)$ directory/$1.html [NS,L,R=301]


text:
Q: Horizontally of circular images to show user profile picture I need to show the users profile picture who all are joining in a specified event and it should be in horizontal circular images one after other and after 5 images. it should show the remaining users total count. I need both java and xml file. These profile images will be from database. Please suggest me any library or a way to do it

A:

OverlapImageViewActivity.kt

class OverlapImageViewActivity : AppCompatActivity(), RecyclerViewClickListener {

    private val mAdapter by lazy { OverlapRecyclerViewAdapter(this, this,overlapLimit) }

    //------limit number of items to be overlapped
    private val overlapLimit = 5

    //------set value of item overlapping
    private val overlapWidth = -50

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //------create dummy list to set on recycler view
        setDummyArrayList()

        //------set up recycler view
        val layoutManager = LinearLayoutManager(this,
                LinearLayoutManager.HORIZONTAL, false)
        recyclerView.layoutManager = layoutManager

        //------set item decoration for item overlapping
        recyclerView.addItemDecoration(OverlapRecyclerViewDecoration(overlapLimit, overlapWidth))
        recyclerView.adapter = mAdapter
        mAdapter.setImageList(setDummyArrayList())

    }

    /**
     * add dummy data to ArrayList
     */
    private fun setDummyArrayList(): ArrayList<OverlapImageModel> {
        val mArrayList = ArrayList<OverlapImageModel>()

        //-----fill data in to array list
        for (i in 0..30) {
            val imageModel = OverlapImageModel()
            imageModel.imageUrl = imageURLs[i % imageURLs.size]
            mArrayList.add(imageModel)
        }

        return mArrayList
    }

    override fun onNormalItemClicked(adapterPosition: Int) {
        toast(this,"Normal item clicked >> $adapterPosition")
    }

    override fun onNumberedItemClick(adapterPosition: Int) {
        toast(this,"Numbered item clicked >> $adapterPosition")
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="10dp"
    android:orientation="vertical"
    tools:context=".activities.OverlapImageViewActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:paddingEnd="5dp"
        app:layoutManager="android.support.v7.widget.LinearLayoutManager"
        tools:listitem="@layout/row_image" />

</LinearLayout>

OverLapRecyclerViewAdapter.kt

class OverlapRecyclerViewAdapter(private var mContext: Context, private var recyclerViewClickListener: RecyclerViewClickListener
                                 , private val overlapLimit: Int) : RecyclerView.Adapter<OverlapRecyclerViewAdapter.CustomViewHolder>() {

    private val TAG = OverlapRecyclerViewAdapter::class.java.simpleName

    //----array list to be shown
    private var mImageList = ArrayList<OverlapImageModel>()

    //----array list to be shown after expansion
    private var mImageExpandedList = ArrayList<OverlapImageModel>()

    //----flag to indicate recyclerview is expanded or not
    private var isExpanded = false

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomViewHolder {
        val view = LayoutInflater.from(mContext).inflate(R.layout.row_image, parent, false)
        return CustomViewHolder(view)
    }

    override fun onBindViewHolder(holder: CustomViewHolder, position: Int) {
        val mCurrentImageModel = mImageList[position]

        //----bind data to view
        holder.bind(mCurrentImageModel)
    }

    /**
     * set array list over adapter
     */
    fun setImageList(mImageList: ArrayList<OverlapImageModel>) {
        if (mImageList.size > overlapLimit) {
            for (mImageModel in mImageList) {
                if (this.mImageList.size <= overlapLimit) {
                    this.mImageList.add(mImageModel)
                } else {
                    this.mImageExpandedList.add(mImageModel)
                }
            }
        } else {
            this.mImageList = mImageList
        }
        notifyDataSetChanged()
    }

    /**
     * add items to array list
     */
    fun addItems(mImageList: ArrayList<OverlapImageModel>) {
        this.mImageList.addAll(mImageList)
        notifyDataSetChanged()
    }

    override fun getItemCount(): Int {
        return mImageList.size
    }

    /**
     * get item by its position
     */
    fun getItem(pos: Int): OverlapImageModel {
        return mImageList[pos]
    }

    inner class CustomViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        private var requestOptions: RequestOptions? = null

        /**
         * init request option for glide
         */
        private fun getGlideRequestOptions(): RequestOptions {
            if (requestOptions == null) {
                requestOptions = RequestOptions()
                requestOptions?.error(R.mipmap.ic_launcher)
                requestOptions?.placeholder(R.mipmap.ic_launcher)
            }
            return requestOptions!!
        }

        /**
         * bind model data to item
         */
        fun bind(mImageModel: OverlapImageModel) {

            if (adapterPosition == overlapLimit && !isExpanded) {

                //----set text drawable to show count on last imageview
                val text = mImageExpandedList.size.toString()
                val drawable = TextDrawable.builder()
                        .beginConfig()
                        .textColor(Color.WHITE)
                        .width(90)
                        .height(90)
                        .endConfig()
                        .buildRound(text, Color.parseColor("#8FAE5D"))
                itemView.imageView.setImageDrawable(drawable)
            } else {

                //----load image
                Glide.with(mContext)
                        .load(mImageModel.imageUrl)
                        .apply(getGlideRequestOptions())
                        .into(itemView.imageView)
            }

            //----handle item click
            itemView.imageView.setOnClickListener {
                if (adapterPosition == overlapLimit && !isExpanded) {
                    recyclerViewClickListener.onNumberedItemClick(adapterPosition)
                } else {
                    recyclerViewClickListener.onNormalItemClicked(adapterPosition)
                }
            }
        }
    }
}

OverlapRecyclerViewDecoration.kt

class OverlapRecyclerViewDecoration(private val overlapLimit: Int, private val overlapWidth: Int) : RecyclerView.ItemDecoration() {
    override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State?) {

        //-----get current position of item
        val itemPosition = parent.getChildAdapterPosition(view)

        //-----avoid first item decoration else it will go of the screen
        if (itemPosition == 0) {
            return
        } else {

            //-----apply decoration
            when {
                itemPosition <= overlapLimit -> outRect.set(overlapWidth, 0, 0, 0)

                else -> outRect.set(0, 0, 0, 0)
            }
        }
    }
}

TextDrawable.kt

class TextDrawable(builder: Builder) : ShapeDrawable(builder.shape) {

    private val textPaint: Paint
    private val borderPaint: Paint
    private val text: String?
    private val color: Int
    private val shape: RectShape?
    private val height: Int
    private val width: Int
    private val fontSize: Int
    private val radius: Float
    private val borderThickness: Int

    init {

        // shape properties
        shape = builder.shape
        height = builder.height
        width = builder.width
        radius = builder.radius

        // text and color
        text = if (builder.toUpperCase) builder.text!!.toUpperCase() else builder.text
        color = builder.color

        // text paint settings
        fontSize = builder.fontSize
        textPaint = Paint()
        textPaint.color = builder.textColor
        textPaint.isAntiAlias = true
        textPaint.isFakeBoldText = builder.isBold
        textPaint.style = Paint.Style.FILL
        textPaint.typeface = builder.font
        textPaint.textAlign = Paint.Align.CENTER
        textPaint.strokeWidth = builder.borderThickness.toFloat()

        // border paint settings
        borderThickness = builder.borderThickness
        borderPaint = Paint()
        borderPaint.color = getDarkerShade(builder.color)
        borderPaint.style = Paint.Style.STROKE
        borderPaint.strokeWidth = borderThickness.toFloat()

        // drawable paint color
        val paint = paint
        paint.color = color

    }

    private fun getDarkerShade(color: Int): Int {
        return Color.rgb((SHADE_FACTOR * Color.red(color)).toInt(),
                (SHADE_FACTOR * Color.green(color)).toInt(),
                (SHADE_FACTOR * Color.blue(color)).toInt())
    }

    override fun draw(canvas: Canvas) {
        super.draw(canvas)
        val r = bounds

        // draw border
        if (borderThickness > 0) {
            drawBorder(canvas)
        }

        val count = canvas.save()
        canvas.translate(r.left.toFloat(), r.top.toFloat())

        // draw text
        val width = if (this.width < 0) r.width() else this.width
        val height = if (this.height < 0) r.height() else this.height
        val fontSize = if (this.fontSize < 0) Math.min(width, height) / 2 else this.fontSize
        textPaint.textSize = fontSize.toFloat()
        canvas.drawText(text!!, (width / 2).toFloat(), height / 2 - (textPaint.descent() + textPaint.ascent()) / 2, textPaint)

        canvas.restoreToCount(count)

    }

    private fun drawBorder(canvas: Canvas) {
        val rect = RectF(bounds)
        rect.inset((borderThickness / 2).toFloat(), (borderThickness / 2).toFloat())

        when (shape) {
            is OvalShape -> canvas.drawOval(rect, borderPaint)
            is RoundRectShape -> canvas.drawRoundRect(rect, radius, radius, borderPaint)
            else -> canvas.drawRect(rect, borderPaint)
        }
    }

    override fun setAlpha(alpha: Int) {
        textPaint.alpha = alpha
    }

    override fun setColorFilter(cf: ColorFilter?) {
        textPaint.colorFilter = cf
    }

    override fun getOpacity(): Int {
        return PixelFormat.TRANSLUCENT
    }

    override fun getIntrinsicWidth(): Int {
        return width
    }

    override fun getIntrinsicHeight(): Int {
        return height
    }

    class Builder : IConfigBuilder, IShapeBuilder, IBuilder {

        var text: String? = null

        var color: Int = 0

        var borderThickness: Int = 0

        var borderColor: Int = 0

        var width: Int = 0

        var height: Int = 0

        var font: Typeface? = null

        var shape: RectShape? = null

        var textColor: Int = 0

        var fontSize: Int = 0

        var isBold: Boolean = false

        var toUpperCase: Boolean = false

        var radius: Float = 0.toFloat()

        init {
            text = ""
            color = Color.GRAY
            textColor = Color.WHITE
            borderThickness = 0
            borderColor = 0
            width = -1
            height = -1
            shape = RectShape()
            font = Typeface.create("sans-serif-light", Typeface.NORMAL)
            fontSize = -1
            isBold = false
            toUpperCase = false
        }

        override fun width(width: Int): IConfigBuilder {
            this.width = width
            return this
        }

        override fun height(height: Int): IConfigBuilder {
            this.height = height
            return this
        }

        override fun textColor(color: Int): IConfigBuilder {
            this.textColor = color
            return this
        }

        override fun withBorder(thickness: Int): IConfigBuilder {
            this.borderThickness = thickness
            return this
        }

        override fun borderColor(color: Int): IConfigBuilder {
            this.borderColor= borderColor
            return this
        }

        override fun useFont(font: Typeface): IConfigBuilder {
            this.font = font
            return this
        }

        override fun fontSize(size: Int): IConfigBuilder {
            this.fontSize = size
            return this
        }

        override fun bold(): IConfigBuilder {
            this.isBold = true
            return this
        }

        override fun toUpperCase(): IConfigBuilder {
            this.toUpperCase = true
            return this
        }

        override fun beginConfig(): IConfigBuilder {
            return this
        }

        override fun endConfig(): IShapeBuilder {
            return this
        }

        override fun rect(): IBuilder {
            this.shape = RectShape()
            return this
        }

        override fun round(): IBuilder {
            this.shape = OvalShape()
            return this
        }

        override fun roundRect(radius: Int): IBuilder {
            this.radius = radius.toFloat()
            val radii = floatArrayOf(radius.toFloat(), radius.toFloat(), radius.toFloat(), radius.toFloat(), radius.toFloat(), radius.toFloat(), radius.toFloat(), radius.toFloat())
            this.shape = RoundRectShape(radii, null, null)
            return this
        }

        override fun buildRect(text: String, color: Int): TextDrawable {
            rect()
            return build(text, color)
        }

        override fun buildRoundRect(text: String, color: Int, radius: Int): TextDrawable {
            roundRect(radius)
            return build(text, color)
        }

        override fun buildRound(text: String, color: Int): TextDrawable {
            round()
            return build(text, color)
        }

        override fun build(text: String, color: Int): TextDrawable {
            this.color = color
            this.text = text
            return TextDrawable(this)
        }
    }

    interface IConfigBuilder {
        fun width(width: Int): IConfigBuilder

        fun height(height: Int): IConfigBuilder

        fun textColor(color: Int): IConfigBuilder

        fun withBorder(thickness: Int): IConfigBuilder

        fun borderColor(color: Int): IConfigBuilder

        fun useFont(font: Typeface): IConfigBuilder

        fun fontSize(size: Int): IConfigBuilder

        fun bold(): IConfigBuilder

        fun toUpperCase(): IConfigBuilder

        fun endConfig(): IShapeBuilder
    }

    interface IBuilder {

        fun build(text: String, color: Int): TextDrawable
    }

    interface IShapeBuilder {

        fun beginConfig(): IConfigBuilder

        fun rect(): IBuilder

        fun round(): IBuilder

        fun roundRect(radius: Int): IBuilder

        fun buildRect(text: String, color: Int): TextDrawable

        fun buildRoundRect(text: String, color: Int, radius: Int): TextDrawable

        fun buildRound(text: String, color: Int): TextDrawable
    }

    companion object {
        private val SHADE_FACTOR = 0.9f

        fun builder(): IShapeBuilder {
            return Builder()
        }
    }
}

RecyclerViewClickListener.kt

interface RecyclerViewClickListener {
    fun onNormalItemClicked(adapterPosition: Int)

    fun onNumberedItemClick(adapterPosition: Int)
}

OverlapImageModel.kt

class OverlapImageModel {
    var imageUrl: String? = null
}

row_image.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="@dimen/image_size"
    android:layout_height="@dimen/image_size"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_gravity="center"
    android:animateLayoutChanges="true">

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/imageView"
        app:civ_border_color="#ffffff"
        app:civ_border_width="2dp"
        android:layout_width="@dimen/image_size"
        android:layout_height="@dimen/image_size"
        android:layout_centerInParent="true"
        tools:src="@mipmap/ic_launcher" />
</RelativeLayout>

A:
Try this here is the working code for java

RecyclerViewActivity

public class RecyclerViewActivity extends AppCompatActivity {

    private  final Integer[] IMAGES = {R.drawable.nilesh, R.drawable.nilesh, R.drawable.nilesh, R.drawable.nilesh,
            R.drawable.nilesh, R.drawable.nilesh, R.drawable.nilesh, R.drawable.nilesh};
    private ArrayList<Integer> arrayList = new ArrayList<Integer>();

    RecyclerView myRecyclerView;

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

        Collections.addAll(arrayList, IMAGES);

        myRecyclerView=findViewById(R.id.myRecyclerView);
        myRecyclerView.setLayoutManager(new LinearLayoutManager(this,
                LinearLayoutManager.HORIZONTAL,false));
        myRecyclerView.addItemDecoration(new OverlapDecoration());
        myRecyclerView.setHasFixedSize(true);
        myRecyclerView.setAdapter(new DataAdapter(this,arrayList));

    }

    public class OverlapDecoration extends RecyclerView.ItemDecoration {

        private final static int vertOverlap = -40;

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            final int itemPosition = parent.getChildAdapterPosition(view);

            outRect.set(0, 0, vertOverlap, 0);

        }
    }
}

activity_recycler_view

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="?attr/colorBackgroundFloating"
    android:orientation="vertical">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/myRecyclerView"
        android:layout_width="match_parent"
        android:layout_height="250dp"
         />

</LinearLayout>

DataAdapter

public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {

    private Context context;
    private ArrayList<Integer> arrayList = new ArrayList<Integer>();

    public DataAdapter(Context context, ArrayList<Integer> imagesArray) {
        this.context = context;
        arrayList = imagesArray;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View imageLayout = LayoutInflater.from(context).inflate(R.layout.aa, parent, false);
        return new ViewHolder(imageLayout);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

        holder.imageView.setImageResource(arrayList.get(position));

        if (position == 3) {
            holder.relativeLayout.setVisibility(View.VISIBLE);
            holder.tvCount.setText(String.valueOf(arrayList.size()-4));
        }else {
            holder.relativeLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public int getItemCount() {
        return 4;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        RelativeLayout relativeLayout;
        TextView tvCount;
        CircleImageView imageView;

        public ViewHolder(View itemView) {
            super(itemView);

            relativeLayout = itemView.findViewById(R.id.relative);
            tvCount = itemView.findViewById(R.id.tvCount);
            imageView = itemView
                    .findViewById(R.id.profile_image);

        }
    }
}

layout.aa

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <de.hdodenhof.circleimageview.CircleImageView xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/profile_image"
        android:layout_width="96dp"
        android:layout_height="96dp"
        android:src="@drawable/kid"
        app:civ_border_color="#FF000000"
        app:civ_border_width="2dp" />

    <RelativeLayout
        android:id="@+id/relative"
        android:visibility="gone"
        android:layout_marginLeft="-40dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <de.hdodenhof.circleimageview.CircleImageView
            android:id="@+id/imageCircleImageView"
            android:layout_width="96dp"
            android:layout_height="96dp"
            android:src="#919191"
            app:civ_border_color="#FF000000"
            app:civ_border_width="2dp"  />

        <TextView
            android:id="@+id/tvCount"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@id/imageCircleImageView"
            android:layout_alignEnd="@id/imageCircleImageView"
            android:layout_alignStart="@id/imageCircleImageView"
            android:layout_alignTop="@id/imageCircleImageView"
            android:layout_gravity="center"
            android:gravity="center"
            android:padding="10dp"
            android:text=""
            android:textColor="#FFFFFF" />

    </RelativeLayout>

</LinearLayout>

A: you can use this.
        fun createUsersPic(linearLayout: LinearLayout, images: List<Int>) {
        val MAX_PIC = 4

        val widthAndHeight = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 32f, linearLayout.context.resources.displayMetrics)
        val margin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, -16f, linearLayout.context.resources.displayMetrics)

        linearLayout.removeAllViews()

        val newList = images.subList(0, if (images.size < MAX_PIC + 1) images.size else MAX_PIC)
        newList.forEachIndexed { index, pic ->
            val img = ShapeableImageView(linearLayout.context).apply {
                shapeAppearanceModel = shapeAppearanceModel
                    .toBuilder()
                    .setAllCornerSizes(44F)
                    .build()
                cropToPadding = true
                scaleType = ImageView.ScaleType.CENTER_CROP
                val params = LinearLayoutCompat.LayoutParams(widthAndHeight.toInt(), widthAndHeight.toInt())
                params.setMargins(if (index == 0) 0 else margin.toInt(), 0, 0, 0)
                layoutParams = params
                setImageResource(pic)
            }
            linearLayout.addView(img)
        }
        if (images.size > MAX_PIC) {
            val tv = TextView(linearLayout.context).apply {
                background = ContextCompat.getDrawable(context, R.drawable.sh_with_radius_30)
                val params = LinearLayoutCompat.LayoutParams(widthAndHeight.toInt(), widthAndHeight.toInt())
                params.setMargins(margin.toInt(), 0, 0, 0)
                layoutParams = params
                gravity = Gravity.CENTER
                text = "+${images.size - MAX_PIC}"
            }
            linearLayout.addView(tv)
        }
    }

A: Here is a layout design of your requirment.
Take reference of these images.
like
       TextView =  itemView.findViewById(R.id.nmr_of_students);
        CircularImageViewstudent1 =  itemView.findViewById(R.id.student1);
        CircularImageViewstudent2 =  itemView.findViewById(R.id.student2);
        CircularImageViewstudent3 =  itemView.findViewById(R.id.student3);
        CircularImageViewstudent4 =  itemView.findViewById(R.id.student4);
        CircularImageViewstudent5 =  itemView.findViewById(R.id.student5);

now use below layout and assign value to them. and you are good to go.

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"

                >
                <FrameLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"

                    android:id="@+id/frames"
                    android:layout_centerHorizontal="true"
                    android:layout_centerInParent="true"
                    >
                    <com.mikhaellopez.circularimageview.CircularImageView
                        android:id="@+id/student1"
                        android:src="@drawable/user"
                        android:layout_width="36dip"
                        android:layout_height="36dip"
                        app:civ_border_width="1dp"
                        app:civ_border_color="#ffffff"

                        />
                    <com.mikhaellopez.circularimageview.CircularImageView
                        android:id="@+id/student2"
                        android:src="@drawable/user"
                        android:layout_width="36dip"
                        android:layout_height="36dip"
                        android:layout_marginLeft="20dip"
                        app:civ_border_width="1dp"
                        app:civ_border_color="#ffffff"

                        />
                    <com.mikhaellopez.circularimageview.CircularImageView
                        android:id="@+id/student3"
                        android:src="@drawable/user"
                        android:layout_width="36dip"
                        android:layout_height="36dip"
                        android:layout_marginLeft="40dip"
                        app:civ_border_width="1dp"
                        app:civ_border_color="#ffffff"

                        />
                    <com.mikhaellopez.circularimageview.CircularImageView
                        android:id="@+id/student4"
                        android:src="@drawable/user"
                        android:layout_width="36dip"
                        android:layout_height="36dip"
                        android:layout_marginLeft="60dip"
                        app:civ_border_width="1dp"
                        app:civ_border_color="#ffffff"

                        />
                    <com.mikhaellopez.circularimageview.CircularImageView
                        android:id="@+id/student5"
                        android:src="@drawable/user"
                        android:layout_width="36dip"
                        android:layout_height="36dip"
                        android:layout_marginLeft="80dip"
                        app:civ_border_width="1dp"
                        app:civ_border_color="#ffffff"

                        />

                </FrameLayout>
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_toRightOf="@+id/frames"
                    android:layout_centerVertical="true"
                    android:layout_marginLeft="2dip"
                    android:textSize="@dimen/home_nmruser_textsize"
                    android:text=""
                    android:textStyle="bold"
                    android:textColor="@color/text_color_gray"
                    android:id="@+id/nmr_of_students"
                    />
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text=""
                    android:textSize="@dimen/home_other_textview"
                    android:layout_marginLeft="@dimen/home_other_marginleft"
                    android:layout_toRightOf="@+id/nmr_of_students"
                    android:layout_centerVertical="true"
                    />
            </RelativeLayout>
        </FrameLayout>


text:
Q: why do I experience issues with SMTP server after upgrading from VB.net 3.5 to 4.8? I have a vb.net forms application that was written in vb.net 3.5. It sends email via smtp email server: office 365. Office 365 is ending support for TLS 1.0 & 1.1.
The program has started tossing the error: Authentication failed because the remote party has closed the transport stream. The weird thing is what when the error occurs, the email still gets sent.
Research shows that it's due to the security protocol being used to connect to the server and it's getting refused. The weird thing is that the email still gets sent.
I did some research and found that I need to upgrade the version of VB.net the site is written in to at least 4.6 in order to support TLS 1.2. I upgraded the website to VB.net 4.8 and got a new error message: SMTPException not handled.
I figured out how to handle the exception, but not how to fix the exception. I believe it has to do with the fact that I have used EnableSsl() and thus the program in trying to use SSl instead of TLS. I don't know.
Below is the code I use to sen email:
Dim smtp As New SmtpClient(Session("SMTPClient"))
    smtp.Port = 587
    mail.From = New MailAddress("email@company.com")
    mail.To.Add("email@company.com")
    mail.ReplyTo = New MailAddress("email@company.com")
    smtp.UseDefaultCredentials = False
    smtp.Credentials = New System.Net.NetworkCredential("user", "password", "domain")
    smtp.EnableSsl() = True

    If Session("sent") = 0 Then
        Try
            smtp.Send(mail)
        Catch ex As SmtpException
            Response.Write(ex)
        End Try
        Session("sent") = 1
    End If

The error I get when sending:
System.Net.Mail.SmtpException: Failure sending mail. ---> System.IO.IOException: Authentication failed because the remote party has closed the transport stream.at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)at System.Net.TlsStream.CallProcessAuthentication(Object state)at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)at System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result)at System.Net.TlsStream.Write(Byte[] buffer, Int32 offset, Int32 size)at System.Net.PooledStream.Write(Byte[] buffer, Int32 offset, Int32 size)at System.Net.Mail.SmtpConnection.Flush()at System.Net.Mail.ReadLinesCommand.Send(SmtpConnection conn)at System.Net.Mail.EHelloCommand.Send(SmtpConnection conn, String domain)at System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint)at System.Net.Mail.SmtpTransport.GetConnection(ServicePoint servicePoint)at System.Net.Mail.SmtpClient.GetConnection()at System.Net.Mail.SmtpClient.Send(MailMessage message)--- End of inner exception stack trace ---at System.Net.Mail.SmtpClient.Send(MailMessage message)at ASP.processform_aspx.__Render__control1(HtmlTextWriter __w, Control parameterContainer) in C:\Users\user\Documents\Visual Studio 2012\Projects\program - Copy\program\processForm.aspx:line 385

A: You can specify the protocol you want to use with
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12


text:
Q: Extension method resolution I wrote an extension method for String to get a char argument, string.Remove(char). But when I used this, it instead called the default string.Remove(int) method.
Shouldn't the presence of an actual method have higher priority than an implicit conversion?

A: This behavior is correct. The reason is that introducing an extension method should not change the way existing code executes. Code should behave exactly the same with or without this "superfluous" extension method. It may seem counter-intuitive in certain cases (like yours), but happens for a reason.

A: Instance methods have priority over extension methods. Your observation is proof of the same.
When resolving which method to call, it will always pick a matching instance method over an extension method... which is intuitive in a way.
Paraphrased from C# in depth,

When the compiler sees that you're
  trying to call a method which looks
  like an instance method but is unable
  to find one, it then looks for
  extension methods (that are visible
  based on your using directives). In
  case of multiple candidates as the
  target extension method, the one with
  "better conversion" similar to
  overloading (e.g. if IChild and IBase
  both have a similar extension method
  defined.. IChild.ExtensionMethod is
  chosen)

Also a hidden code-breaker could be lets say TypeA didn't have SecretMethod as an instance method in Libv1.0. So you write an extension method SecretMethod. If the author introduces an instance method of the same name and signature in v2.0 (sans the this param), and you recompile your source with the latest-n-greatest Libv2.0, all existing calls to the extension method would silently now be routed to the new instance method.


text:
Q: Reclaim free space in docker images I have a dockerfile which basically does :
FROM debian
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y build-essentials automake autoconf libtool
WORKDIR /opt/build
RUN git clone https://somestuff . && make install clean
RUN rm -rf /opt/build && apt-get remove -y build-essentials automake autoconf libtool

When done, I have a 900MB image, whit only (as shown by df in the container) 40GB used
How can I improve my build strategy in order to keep the image a reasonable size ?
Regards
Xavier

A: Split dockerfile to multi-stage builds image.
REF https://docs.docker.com/build/building/multi-stage/
Dockerfile:
#####
# base (init base image)
#####
FROM debian AS base
ENV DEBIAN_FRONTEND=noninteractive

#####
# build-somestuff (temp build image)
#####
FROM base AS build-somestuff
WORKDIR /opt/build
RUN apt-get update && apt-get install -y build-essentials automake autoconf libtool
RUN git clone https://somestuff . && make install clean
# RUN rm -rf /opt/build && apt-get remove -y build-essentials automake autoconf libtool

#####
# main (final image)
#####
FROM base AS main

COPY --from=build-somestuff /opt/build/somestuff   /bin/somestuff
WORKDIR /documents
VOLUME /documents
CMD ["/bin/bash"]

final image is main, not temp build image (build-somestuff)
main use COPY copy build make file from build-somestuff
Please reference https://hub.docker.com/r/asciidoctor/docker-asciidoctor/dockerfile for more details.


text:
Q: Turning off chunk coloring in Emac's nXhtml mode (load "~/.elisp/nxhtml/autostart.el")
(setq mumamo-chunk-coloring 'no-chunks-colored)

I currently have the above in my .emacs and the chunk coloring is still showing up.  I have also tried disabling it through customize-option and then setting the state to "no chunk coloring" in mumamo-chunk-coloring.  I'm using the latest emacs23 from cvs and have the most recent nxhtml release.
What is the correct way to disable the coloring of different major modes?

A: Bug. I forgot to add this possibility back when implementing chunks in chunks.
I have just corrected this in 1.88 (which is yet in beta).
Note that in the new version you will use a number for mumamo-chunk-coloring. Set this to 1 to avoid coloring main mode chunks etc.
BTW: Just happened to see this. If you want bugs to be corrected it is normally much better to report them in nXhtml bug database on Launchpad.


text:
Q: asp.net C# update textbox value without refresh I have a website where there are two pages, page1 contain textbox and button1,
if I cliked button1 it will open page2 which contain button2,
if I cliked button2 it will assign value from page2 to the textbox in page1
but the problem is the value will display in the textbox after I refresh page1,
and my question is how I can update textbox value directly without refresh in page1 after I click button2 in page2 like this:
here is my code:
page1 aspx.cs:
<script type="text/javascript">

function openPopup() {

    window.open("page2.aspx", "_blank", "WIDTH=1080,HEIGHT=790,scrollbars=no, menubar=no,resizable=yes,directories=no,location=no");

}

<asp:button text="clik" id="button1" runat="server" onclientclick="return openPopup()" xmlns:asp="#unknown" style="margin-right:30%" />

    protected void Page_Load(object sender, EventArgs e)
    {

       if (Session["userID"] != null)
                {
                    txtbox.Text = HttpContext.Current.Session["userID"].ToString();
                }
    }

page2:
   protected void button2(object sender, EventArgs e)
    {
      Session["userID"] = row.Cells[0].Text;
    }

A: we can do this in following way:

*

*create a javascript function on page 2, that refresh textbox1 on
page 1.

*on button2 click from page 2, using scriptmanager, call
the function created in step 1 with require param.

So, basically you code be like:
 // place this in page2.aspx
 // javascript function to update text box in page 1;
  function UpdateParentText(value){
     if(typeof(value) != undefined){
        window.opener.document.getElementById("TextBox1").value=value;
      }
   }

  //2. code behind call to the javascript function from page2.cs
  protected void button2(object sender, EventArgs e)
    {
    // code behind call to the javascript function.
    ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "MyScript", "UpdateParentText('" + row.Cells[0].Text + "'", true);
   }

If you are not using AJAX, then use this:
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "MyScript", "UpdateParentText('" + row.Cells[0].Text + "'", true);

A: You may use:

*

*window.postMessage() — to send the message

*window.addEventListener("message",callback) — to receive and process the message

See sample here.

A: thanks everyone I solve it by using session with javascript


text:
Q: HtmlDocument get a incomplete page I am doing a small web scraping project, and I am having a problem with the function that takes the html code. The web that I inspect in the browser is different from the web that downloads the method (for the same URL).
I have tried to improve the coding process, but to no avail. The same thing happens for "i=2".
static void Main(string[] args)
        {
            string prefixurl = "https://www.aaabbbcccdddeee.de/en/do-business-with-finland/finnish-suppliers/finnish-suppliers-results?query=africa";

            for (int i = 1; i < 18; i++)
            {
                string url = prefixurl;
                if (i > 1)
                {
                    url = prefixurl + "&page=" + i;
                }

                var doc = GetDocument(url);
                var links = GetBusinessLinks(url);
                List<Empresa> empresas = GetBusiness(links);
                Export(empresas);

            }

        }

static List<string> GetBusinessLinks(string url)
        {
            var doc = GetDocument(url);
            var linkNodes = doc.DocumentNode.SelectNodes("/html/body/section/div/div/div/div[2]/div[2]//a");

            // //a[@class=\"btn bf-ghost-button\"]
            var baseUri= new Uri(url);
            var links = new List<string>();

//The problem its there, in the incomplete page the program haven't found nodes
            foreach (var node in linkNodes)
            {
                var link = node.Attributes["href"].Value;
                bool business = link.Contains("companies");
                if (business)
                {
                    link = new Uri(baseUri, link).AbsoluteUri;
                    links.Add(link);
                }
            }
            return links;
        }
static HtmlDocument GetDocument(string url)
        {
            var web = new HtmlWeb();

            HtmlDocument doc = new HtmlDocument()
            {
                OptionDefaultStreamEncoding = Encoding.UTF8
            };
            doc = web.Load(url);
            return doc;
        }

´´´

A: Your suggestion has made me suspect where I should continue looking, thanks.
I have used PupperSharp in non-headless mode.
https://betterprogramming.pub/web-scraping-using-c-and-net-d99a085dace2


text:
Q: How to increment a value to a new table when a given column string matches exactly? mySQL can be easy, but can also be complicated especially when it's the first time trying to attempt to logically understand how to carry out a task and make the table visible as exact.
A question from my homework states:
How many times did each company interview?  Print out the companies with the most interviews first, then sort by company name in A-Z order.
+------------------------------+------------+
| companyname                  | Interviews |
+------------------------------+------------+
| Ajax Software, Inc.          |          2 |
| Cameron Industries           |          2 |
| Flordia Software Designs     |          2 |
| Manhattan-Made Software      |          2 |
| Mountainside Magic Software  |          2 |
| Acme Information Source      |          1 |
| ApplDesign                   |          1 |
<<<<<<< cut out some output >>>>>>>>>>>>>>>>>>>
| Vegas Programming and Design |          1 |
| Virginia Software Industries |          1 |
+------------------------------+------------+
23 rows in set (0.00 sec)

I got the first column perfectly by coding this:
SELECT DISTINCT companyname,
FROM interview
ORDER BY companyname ASC;

But the interviews, I'm trying to get the code for, if in companyname how ever many companies has the same exact strings to increment to the interview side. How does this work?
FULL OUTPUT:
+------------------------------+
| companyname                  |
+------------------------------+
| Acme Information Source      |
| Ajax Software, Inc.          |
| Ajax Software, Inc.          |
| ApplDesign                   |
| Bay Software Inc.            |
| Braddock Information Assoc.  |
| Buffalo Software Assoc.      |
| Cameron Industries           |
| Cameron Industries           |
| CCC Software                 |
| Davis-Klein Software         |
| DC Security Applications     |
| Flordia Software Designs     |
| Flordia Software Designs     |
| Focused Applications, Inc.   |
| Georgia Software Design      |
| Jersey Computer Services     |
| Long Island Apps, Inc.       |
| Manhattan-Made Software      |
| Manhattan-Made Software      |
| Mountainside Magic Software  |
| Mountainside Magic Software  |
| Nantucket Applications, Inc. |
| PennState Programming, Inc.  |
| Rochester Software Design    |
| Sandy Hook Software          |
| Vegas Programming and Design |
| Virginia Software Industries |
+------------------------------+
28 rows in set (0.00 sec)

A: Try this and check if it works
SELECT companyname ,count(companyname) as interviews
from interview GROUP BY companyname order by interviews desc, companyname asc

Check To see YOu demo


text:
Q: How to set password for file in Google App Script? I sent a link file via mail to someone in the google app script. I want to ask is there any way to set password for file in google app script? When users enter the link will ask to enter the password.
(sorry, my english is not good)

A: Based from this thread, there is no password in Google class yet implemented. You can file this as feature request in this link.


text:
Q: Prove that $\lim_{n\to ∞}\frac{\alpha(n)}{n}=0$ Prove that $$\lim_{n\to ∞}\frac{\alpha(n)}{n}=0$$ Where $\alpha(n)$ is the number of primes that divide n.
Tip: the fact that every prime number is ≥ 2 provides a simple estimation of how small it should be $\alpha(n)$.
any suggestions for how to tackle the problem?

A: Hint: If $\alpha(n) = k$, where the corresponding primes are $p_1, \ldots, p_k$, then $n \ge p_1 \cdot \ldots \cdot p_k \ge 2^k$.


text:
Q: How can I use the normal radio buttons in react? I am developing a webapp which uses materializecss, react along with ruby on rails. I'd like to know how I can use the radio buttons such that it can be rendered.
    class Radio extends React.Component {

      constructor(props) {
  super(props);

  this.state = {

  }

  this.setNewNumber = this.setNewNumber.bind(this)
};

 setNewNumber(event)
{
    this.setState({val : event.target.value})

}

render() {
  return (

        <input type="radio" name="gender" value="male" onChange={this.setNewNumber}/> Male

        <input type="radio" name="gender" value="female"onChange={this.setNewNumber}/> Female

        <input type="radio" name="gender" value="other"onChange={this.setNewNumber}/> Other

Enter {this.state.val}

     );
  }
}


text:
Q: Prototype objects, and object arrays If that title made no sense, let me elaborate.
I have a two objects one called area and one called enemy.
Each area has it's own enemies so I made enemy prototypes for each area.
Next I did an array.push(); function on each area prototype so if the user clicks a button they'll be shown a list of "area's" they can essentially explore.
the main part that gives me an error is if I try any function like alert(areas[0].enemies[0].name);
How can I use a button to display a specific enemy name?
No jQuery please
function area(name, enemies) {
  this.name = name;
  this.enemies = enemies;
}

function enemy(name, type) {
  this.name = name;
  this.type = type;
}

var cave = new area("Cave", {
  bat: new enemy("Bat", "Flying"),
  snake: new enemy("Snake", "Ground"),
});

var forest = new area("Forest", {
  bear: new enemy("Bear", "Animal"),
  coyote: new enemy("Coyote", "Wolf"),
});

areas = [];
areas.push(cave, forest);

var thatBtn = document.getElementById('thatBtn'),
    display = document.getElementById('display');

thatBtn.addEventListener('click', function() {
  for (i = 0; i < areas.length; i++) {
    var li = document.createElement('li'),
      liBtn = document.createElement('button');
    liBtn.textContent = areas[i].name;
    li.appendChild(liBtn);
    display.appendChild(li);
    liBtn.addEventListener('click', function() {
      for (j = 0; j < areas.length; j++) {
        if (areas[j].name == event.target.textContent) {
          alert(areas[j].name);
          for (k = 0; k < Object.keys(areas[j].enemies).length; k++) {
            alert(areas[j].enemies[k].name);
          }
        }
      }
    });
  }
});

<button id="thatBtn">click here</button>

A: It gives you an error because areas[0].enemies is not an array -- it's an object.
{
    bat: new enemy("Bat", "Flying"),
    snake: new enemy("Snake", "Ground"),
}

Change it to
for(var key in areas[j].enemies) {
    alert(areas[j].enemies[key].name);
}

A: enemies is an object and not an array, so you need to iterate through keys
and fetch from there and not from index, just updated your snippet with that, however the code can be better.

function area(name, enemies){
    this.name = name;
    this.enemies = enemies;
}

function enemy(name, type){
    this.name = name;
    this.type = type;
}

var cave = new area ("Cave", {
    bat: new enemy("Bat", "Flying"),
    snake: new enemy("Snake", "Ground"),
});

var forest = new area ("Forest", {
    bear: new enemy("Bear", "Animal"),
    coyote: new enemy("Coyote", "Wolf"),
});
areas = [];
areas.push(cave, forest);

var thatBtn = document.getElementById('thatBtn'),
    display = document.getElementById('display');

thatBtn.addEventListener('click', function(){
  for(i=0; i < areas.length; i++){
    var li = document.createElement('li'),
        liBtn = document.createElement('button');
    liBtn.textContent = areas[i].name;
    li.appendChild(liBtn);
    display.appendChild(li);

    liBtn.addEventListener('click', function(){
      for(j=0; j < areas.length; j++){
        if (areas[j].name == event.target.textContent){
          alert(areas[j].name);
          var keys = Object.keys(areas[j].enemies);
          for(k=0; k < Object.keys(areas[j].enemies).length; k++){
            alert(areas[j].enemies[keys[k]].name);
          }
        }
      }
    });

  }
});
<button id="thatBtn">click here</button>

A: add enemies as an array, no need to have them with "named keys" in an object

function area(name, enemies){
    this.name = name;
    this.enemies = enemies;
}

function enemy(name, type){
    this.name = name;
    this.type = type;
}

var cave = new area ("Cave", [
    new enemy("Bat", "Flying"),
    new enemy("Snake", "Ground"),
]);

var forest = new area ("Forest",[
    new enemy("Bear", "Animal"),
    new enemy("Coyote", "Wolf"),
]);
areas = [];
areas.push(cave, forest);

var thatBtn = document.getElementById('thatBtn'),
    display = document.getElementById('display');

thatBtn.addEventListener('click', function(){
  for(i=0; i < areas.length; i++){
    var li = document.createElement('li'),
        liBtn = document.createElement('button');
    liBtn.textContent = areas[i].name;
    li.appendChild(liBtn);
    display.appendChild(li);

    liBtn.addEventListener('click', function(){
      for(j=0; j < areas.length; j++){
        if (areas[j].name == event.target.textContent){
          alert(areas[j].name);

          for(k=0; k < Object.keys(areas[j].enemies).length; k++){
            alert(areas[j].enemies[k].name);
          }
        }
      }
    });

  }
});
<button id="thatBtn">click here</button>

A: Your primary issue is here:
for(k=0; k < Object.keys(areas[j].enemies).length; k++){
  alert(areas[j].enemies[k].name);
}

The expression Object.keys(areas[j].enemies) returns an array of object properties, but then you try to iterate over the object using k, not the property name.
Since Object.keys returns a array, you can use array methods so change the loop to:
Object.keys(areas[j].enemies).forEach(function(name) {
  alert(areas[j].enemies[name]);
});

You have a secondary issue that you aren't declaring the counters (i, j and k) used in loops so they become globals when the code runs. Declare them like:
for (var i=0; i < areas.length; i++) {