text:
Q: Acunetix scan of Laravel login page I have an application written using Laravel 5.1 framework. Recently, one of my clients ran an Acunetix security scan on the application and found HTML form with no apparent CSRF protection on my login page.
However, the login form DOES have CSRF protection. The name of the element with the CSRF token is "_token". The scan result says "Discovered by: Crawler".
So my questions are:

*

*Why is acunetix showing this result?

*Is "_token" not a recognized name for a CSRF token element? Should I add another hidden element into the form with the same value using a more recognizable name?

*What does it mean "Discovered by: Crawler"? Does this mean the scan only checks the form HTML and nothing else?

Below is the snippet of the HTML form blade template:

@section('content')
        <form id="loginForm" class="form-signin" role="form" method="POST" action="{{ url('/auth/login') }}">

            <input type="hidden" name="_token" value="">
            {{ trans('auth.login.username') }}
            <input type="username" class="form-control" name="username" value="{{ old('username') }}">
            {{ trans('auth.login.password') }}
            <input type="password" class="form-control" name="password" autocomplete="off">

<input type="checkbox" name="remember"> {{ trans('auth.login.remember_me') }}

{{ trans('auth.login.forgot_password') }}

            <button type="submit" class="btn btn-lg btn-primary btn-block">{{ trans('auth.login.login') }}</button>
@if (count($errors) > 0)

@foreach($errors->all() as $error)
                {{ $error }}

@endforeach

@endif
        </form>
@endsection

You may notice that in the above snippet, the "_token" element value is blank. This is intentional since I am basically trying to "circumvent" acunetix's detection by only setting its value using javascript since everything I have tried so far does not seem to work.

A: The alert provided most probably indicates that this may be a false positive. CSRF alerts more often than not require human intervention to verify whether:

*

*There actually is an anti-CSRF token

*If the form (or rather, input) requires any anti-CSRF

If you are already making use of the anti-CSRF token, then you can go ahead and mark that alert as a false positive. That will omit it from any future scans on the affected item (e.g. userinfo.php, being considered an item).
Certain alerts such as the one you specified, are discovered by the crawler module. Since Acunetix Vulnerability Scanner adopts a black-box methodology, it has no prior knowledge of the application it is scanning.
Thus, it first starts by dynamicaly mapping out the application's site structure using the crawler module and at the same time discovering particular alerts (Medium or Low alerts generally). Once the crawl is complete, the actual scanner module starts which proceeds to run every security test (script) on all the items discovered by the crawler.

Regarding one of you comments - "I am assuming that the acunetix crawler does not run javascript and would not populate the _token element."
The crawler perse does not execute and analyze Javascript, however the DeepScan (read more here) technology does, which occurs during the crawling stage. Thus the scanner is still able to understand client-side heavy application such as SPAs making use of frameworks like AngularJS, ReactJS etc.


text:
Q: VirtualBox: Kali Linux does not work in full screen mode after installing VBoxLinuxAdditions In my VirtualBox, when I execute VBoxLinuxAdditions.run, Kali Linux is not working in full screen mode.
I get the following error log file, otherwise everything else goes perfectly.
Uninstalling modules from DKMS
Attempting to install using DKMS

Creating symlink /var/lib/dkms/vboxguest/5.0.20/source ->
             /usr/src/vboxguest-5.0.20

DKMS: add completed.
Error! echo
Your kernel headers for kernel 4.3.0-kali1-amd64 cannot be found at
/lib/modules/4.3.0-kali1-amd64/build or /lib/modules/4.3.0-kali1-amd64/source.
Failed to install using DKMS, attempting to install without
/tmp/vbox.0/Makefile.include.header:97: *** Error: unable to find the sources of     your current Linux kernel. Specify KERN_DIR=<directory> and run Make again.  Stop.
Creating user for the Guest Additions.
Creating udev rule for the Guest Additions kernel module.

How can I fix this?

A: Use Kali 2016.1 Rolling Edition, it's far more better.
You may go to settings>>display>>monitor>>choose your desktop size>>done
Nothing more to do.

A: In this case, current virtualbox guest additions has a known bug. You need to install from the repositories. I'm not sure how to go about removing the incorrect application.

*

*apt-get update

*apt-get install -y virtualbox-guest-x11

*reboot

redpajama_set_name: RedPajamaStackExchange


text:
Q: #value not being changed in custom drupal form I have created a custom drupal 7 form with a submit button. when submit is pressed the values in $form_state['values'] are not changed. see the code below:
  $form[$tag] = array(
  '#title' => t($tag),
  '#type' => 'textfield',
  '#default_value' => !empty($form_state['values'][$tag]) ? $form_state['values'][$tag] : $value,
 );

 $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Submit'),
  '#weight' => 5,
  '#submit' => array('xml_form_builder_edit_datastream_form_submit'),
  );

Then the submit function is:
 function xml_form_builder_edit_datastream_form_submit($form, &$form_state){

    dsm('SUBMITTED');
    dpm($form);
    dpm($form_state);
    dsm('SUBEND');
}

the $form_id is 'xml_form_builder_edit_datastream_form'.
Ive been trying to figure this out for a good few hours.
Anyone got any ideas?

A: Try $form_state['input'][$tag] , that should have the user input value.


text:
Q: How to compare value in two columns in FuelPHP I have problem when query table using FuelPHP 1.3's Model.
Entries table have three columns ('id', 'status', 'current', 'max' ).
$result = Model_Entry::query()
    ->where('status', 1)
    ->where('count_current', '>=', 'count_max');

I want to use 'where' method's third argument as column name, but it handled as value in generated query.
Example
SELECT * FROM `entries` AS `t0` WHERE `t0`.`status` = 1 AND `t0`.`count_current` >= 'count_max'

My Goal
SELECT * FROM `entries` AS `t0` WHERE `t0`.`status` = 1 AND `t0`.`count_current` >= `t0`.`count_max`

Any help would be appreciated.

A: To achieve what you want, you have to use DB::expr()
So, your code will be:
$result = Model_Entry::query()
    ->where('status', 1)
    ->where('count_current', '>=', DB::expr('count_max'));


text:
Q: How to specify memory per process in an array job in slurm? I want to run thousands of identical single-thread simulations with different random seeds (which I pass to my program). Some of them have gone out of memory, yet I don't know why. I call run_batch_job as sbatch --array=0-999%100 --mem=200M run_batch_job, where run_batch_job contains:
#!/bin/env bash
#SBATCH --ntasks=1  # Number of cores
#SBATCH --nodes=1  # All cores on one machine

srun my_program.out $SLURM_ARRAY_TASK_ID

For a single thread, 200M should be more than enough memory, yet for some simulations, I get the error:
slurmstepd: error: Exceeded step memory limit at some point.
slurmstepd: error: Exceeded job memory limit at some point.
srun: error: cluster-cn002: task 0: Out Of Memory
slurmstepd: error: Exceeded job memory limit at some point.

Am I allocating 200M to each of the thousand threads, or am I doing something wrong?
EDIT: I've tried specifying --cpus-per-task=1 and --mem-per-cpu=200M instead of --ntasks=1, --nodes=1 and --mem=200M, with the same results.

A: Your submission is correct, but 200M might be low depending on the libraries you use or the files you read. Request at least 2G as virtually all clusters have at least 2GB of memory per core.


text:
Q: fetch promises - return 500 internals server error I am trying to handle 500 internal server errors inside fetch.  If an internal error occurs, the server responds with a message.  I want to extract that message.
const req = new Request(url, {
      method: node.method,
      mode: 'cors',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(body),
    });
    fetch(req)
      .then((response) => {
        if (response.status === 500) {
          // res.json extracts the body from the response as a promise, chain
          // .then on it and throw an error to be caught in the lower catch.
          response.json()
          .then((json) => {
            const { message, stackTrace } = json;
            throw new ServerException(message, stackTrace); // note 1
          })
          .catch((error) => {
            return Promise.reject(RawException(error)); // note 2
          });
        } else {
          return response.json();
        }
      })
      .then((json) => { // note 3
        dispatch(stopLoading());
        dispatch(recieveResponse(typeOfRequest, json));
      })
      .catch((e) => {
        dispatch(stopLoading());
        dispatch(responseError());
        dispatch(showError(e.message));
      });
  };

My issue is that extracting the body of the response creates a new promise, and I am unable to reject the outer promise from the inner one.
Note 1 triggers the catch method of the inner promise.  Inside catch, I have tried throwing another error but it doesn't seem to work.  If I throw new RawException(error) on the second noted line, nothing happens and the then method on the third noted line triggers.  If I return a rejected promise as I have in the code provided, then still triggers but json is undefined.
How do I do this?

A: The solution is not to nest promises, but to resolve/return the .then of the outer promise with the conclusion of the inner promise.
if (response.status === 500) {
  response.json()   // response.json returns a promise, we chose to do nothing with its
  .then((json) => { // conclusion
    const { message, stackTrace } = json;
    throw new ServerException(message, stackTrace); // note 1
  })
  .catch((error) => {
    return Promise.reject(RawException(error)); // note 2
  });
} else {
  return response.json();
}

Should become
if (response.status === 500) {
  return response.json() // return the result of the inner promise, which is an error
  .then((json) => {
    const { message, stackTrace } = json;
    throw new ServerException(message, stackTrace);
  });
} else {
  return response.json();
}

The else clause can be removed as well if that syntax is preferred.  ESLint complains about the else being wasteful, but I perfer the way it makes the code's branching explicit.


text:
Q: Homeomorphism Between Closed Riemann Surfaces Homotopic to Quasiconformal Mapping I'm re-reading a paper of Bers and for the second time, and I am yet again confused about the claim in the title, which Bers declares to be easy to prove.
For context, I'll lay out some terminology. We call a pair $(S, \alpha)$ a marked Riemann surface when $S$ is a Riemann surface and $\alpha$ is an equivalence class of generators of $\pi_1S$, each of which $\{a_i\}_{i=1}^{2g}$ satisfies the standard one relation $1= \prod_{j=1}^{2g} a_{2j-1} a_{2j} a_{2j-1}^{-1}a_{2j}^{-1}$. A map between marked Riemann surfaces $f:(S, \alpha) \rightarrow (S',\alpha')$
is a homeomorphism that respects the markings. Finally, call a pair of marked Riemann surfaces $(S, \alpha), (S', \alpha')$ to be similarly oriented if there is an orientation-preserving homeomorphism $f: S \rightarrow S'$.
Now, Bers goes on to make the following claim:

If $(S, \alpha)$ and $(S', \alpha')$ are similarly oriented marked Riemann surfaces, then there is a quasiconformal mapping $f: (S, \alpha) \rightarrow (S', \alpha')$.

Ok, this sounds plausible enough to me. On the other hand, it is by no means obvious. Here, I should mention Bers has earlier stated the equivalence of a few (standard) definitions of quasiconformality for a mapping $f: S \rightarrow S'$, including the following:
(i) $\hat{f}_\bar{z} = \mu \hat{f}_{z}$, in terms of weak derivatives, for any coordinate representation $\hat{f}$, where $\mu \in L^{\infty}$
(ii) any coordinate representation $\hat{f}$ has bounded dilatation across all quadrilaterals.
Specifically, Bers goes on to say

Had we demanded that the homeomorphism $f$ be continuously differentiable everywhere the proof would be somewhat laborious. Since we use a very general definition of quasiconformality, the proof presents no difficulties and may be omitted.

My question is thus, what is the idea that Bers' has in mind for the proof? By hypothesis, we've got our hands on a homeomorphism $f$ that respects the desired marking, but a priori $f$ might have unbounded dilatation. So, we need some clever way to homotope $f$ so that its dilatation becomes bounded across the whole surface, at which point we are done. However, I see no intuitive way to make this work. Technical details aside, I am very interested to see what ideas anyone has, or better yet, what idea they imagine Bers thought would easily yield a proof.
Bers, Lipman, Quasiconformal mappings and Teichmüller's theorem, Princeton Math. Ser. 24, 89-119 (1960). ZBL0100.28904.

A: These things are easier said than done. The relevant theorem is:
Theorem 1. Let $S$ be a closed connected oriented smooth surface. Then every orientation-preserving homeomorphism $f: S\to S$ is homotopic (equivalently, isotopic) to an (orientation-preserving) diffeomorphism $g: S\to S$. Alternatively, $g$ can be taken to be a piecewise-linear homeomorphism provided that $S$ is equipped with a PL structure.
If, in addition, $S$ is equipped with the structure of a Riemann surface, then $g$ is quasiconformal. (This is the easy part.)
The part about piecewise-linear homeomorphism is proven in Appendix to
D. B. A.  Epstein, Curves on 2-manifolds and isotopies. Acta Math. 115 (1966), 83–107.
From that result, one obtains (by one more isotopy) a diffeomorphism, according to
J. Munkres, Obstructions to the smoothing of piecewise-differentiable homeomorphisms. Ann. of Math. (2) 72 (1960), 521–554.
One can prove more:
Theorem 2. Let $S$ be as above. Then every automorphism $\phi: \pi_1(S)\to \pi_1(S)$ is induced by a diffeomorphism $S\to S$.
In fact, one can also detect (group-theoretically) if $\phi$ is "orientation-preserving," but I will not get into this.
There are several other arguments (neither one is easy) for proving this theorem, you can find these in
B. Farb, D. Margalit, A primer on mapping class groups. Princeton Mathematical Series, 49. Princeton University Press, Princeton, NJ, 2012. Chapter 8
and (an analytical proof)
J. Hubbard, Teichmüller theory and applications to geometry, topology, and dynamics. Vol. 1. Matrix Editions, Ithaca, NY, 2006. Section 5.1.
With more work, these proofs apply to compact Riemann surfaces with finitely many punctures as long as certain conditions on $\phi$ are satisfied (these conditions are automatically satisfied in Theorem 1). The proof given in Hubbard's book requires very little extra work.


text:
Q: How get the "data" at the server side I have the next config into my angularjs:
var config={ //config post
    method:"POST",
    url:"http://localhost/APIREST/controllersencillo",
    params: {tabla : "PintaMonas"}, //without id is insert, with id is update
    data: {PMcolor: "Azul tostado", PMpartes: "Un poquito de las orjeas y un bigote a lo Dali, quizas le alegre la cara", PMcosteTotal: "445" }
  }

When i call to the server work perfectly, this isn't the problem. The problem it's how get the data.
My function POST of my server is:
 $arrayDatos = $this->post('datosSend');
            echo 'Tipe of data: '.gettype($arrayDatos);
                    print_r($arrayDatos);

                    die();

Any solution? I didn't find anything similar in the web (include stack overflow).
Thanks in advance.

A: Try this $arrayDatos = $_POST;


text:
Q: MySQL making 6.5m row update filter through without errors I am running said query:
UPDATE `tbl_audit_trail`
   SET model = CONCAT('common\\models\\', model)
 WHERE model NOT LIKE 'common\\\\models%'

to update 6,567,780 records.
The current details are:

*

*Table size 1.6GB

*The engine is InnoDB

*Linux 2.6

*MySQL server 5.1.63-0+squeeze1-log

This results in said error:
The table 'tbl_audit_trail' is full

After reading the manual: https://dev.mysql.com/doc/refman/4.1/en/full-table.html I thought it might have been temp_table problems but it says that such problems should only effect people on older than 3.23.
What could be stopping my query from running?

A: Reasons this might happen :

*

*Check that the disk the InnoDB data file is stored on isn't full

*Check your innodb_data_file_path variable form you my.cnf

For a complete troubleshoot here is an post from Rolando - this will defensively do it !

A: I never did truly find out the reason however, I batched the update, omitting the single commit of all 6m rows (which loses atomicity of the update) and it worked.
It does seem as though there was something attached to updating that caused it to crash and batching the updates to about 100,000 at a time worked, even if the next update was done straight after the previous giving the server no rest.


text:
Q: jquerymobile listview anchor tag not working I have a listview (jquerymobile) with 5

 items as follows -

John Smith

2 Cadeau Terr London ON N6K 4G1

Issue with set-top box

Sylvester Stallone

64 Faywood Dr Brampton ON L6Y 4L95

New Connection

Antenna Replacement

14 Grand St Brantford ON N3R 4B1

New Connection

Keanu Reaves

5617 Fourth Line Hillsburgh ON N0B 1Z0

Distorted Display

Tom Cruise

RR5 Perth ON K7H 3C7

Issue with set-top box

The href in each
 is referring to a div tag within same HTML page, whose data role is "page" -

   <button class="ui-btn-left" id="backbutton" data-icon="arrow-l" data-iconpos="left">Back</button>

XXX

    <button class="ui-btn-right" id="exit" data-icon="back" data-iconpos="right">Exit</button>

 Content

myFooter

This html page has different div-s with their data-role as "page" as per JQM's standards. Now when I click on the list item which is referring to a div (data-role as page), it is not navigating to that div.
But yes, it's working if I give link to a different HTML page instead of a div inside same HTML page.
Anyone, kindly let me know where there is a problem with this approach? Would this approach work at all?

A: Working fine here DEMO http://jsfiddle.net/yeyene/ttjGv/2/
It goes to that div. Check the html markup below.

Page Title

John Smith

2 Cadeau Terr London ON N6K 4G1

Issue with set-top box

Sylvester Stallone

64 Faywood Dr Brampton ON L6Y 4L95

New Connection

Antenna Replacement

14 Grand St Brantford ON N3R 4B1

New Connection

Keanu Reaves

5617 Fourth Line Hillsburgh ON N0B 1Z0

Distorted Display

Tom Cruise

RR5 Perth ON K7H 3C7

Issue with set-top box

Page Footer


text:
Q: Interpreting the results of dynamic panel models using GMM estimation I am working on my master dissertation and I am struggling in interpreting my results properly. I am looking for a good source (book, paper, or website) that provides explanation on how to interpret the results (coefficients, standard errors, etc.) of dynamic panel models.
I am using Stata to fit a dynamic panel model using GMM estimation methods. My problem is twofold:
First, I don't understand why the following was done, and how the findings can be interpreted: Multiplying the coefficient with the standard deviation of the variable in the sample to see the impact of the variable. What would the result of the above operation tell us?
Second, one of the papers I read using this method (Acemoglu et al. 2008) stated, "Although the pooled OLS estimate of the independent variable is quantitatively small, the two standard error bands of the fixed effects estimators almost exclude it." What does it mean? How do I get this?
Reference:
Acemoglu, D., Simon Johnson, James A. Robinson, and Pierre Yared
American Economic Review, 98(3), June 2008: pp. 808-42.


text:
Q: How Can I use Multiple cookies from Different user type Logins (Login from CSV file in a single thread) in other thread groups randomly? I have 4 different action types and I want to run 2 action with USER 1 and another 2 Action with USER 2.
I have set up two differet threads for 2 Logins and then used these cookies in 4 different actions randomly using Beanshell post processor and Beanshell preprocessor methods.
But now I want to use single thread for Login request and allow users login with CSV data. In this case how can I get the different cookie for each Login s that I can pass them randomly in 4 actions ?
Please help.

A: Given you have cookies defined like:
cookie_1=Cookie #1
cookie_2=Cookie #2
cookie_3=Cookie #3
cookie_4=Cookie #4

You can use __P() and __Random() functions combination in order to get a random cookie value like:
 ${__P(cookie_${__Random(1,4,)},)}

Demo:

See Apache JMeter Functions - An Introduction to get familiarized with JMeter Functions concept.


text:
Q: Implementing meta-function zip in c++11 I am actually trying to see if I can get a minimal library that supports the very few operations I use from boost::fusion.
Here is what I have so far...
template < typename... Types >
struct typelist
{
};

template < template < typename... > class F, typename... Args >
struct apply
{
  typedef typename F < Args... >::type type;
};

template < typename, template < typename... > class >
struct foreach;

template < typename... Types, template < typename Arg > class F >
struct foreach < typelist < Types... >, F >
{
  typedef typelist < typename apply < F, Types >::type... > type;
};

Since the meta-function foreach implementation is trivial, I thought zip would be easy too.  Apparently, this is not the case.
template < typename... >
struct zip;

template < typename...  Types0, typename... Types1 >
struct zip < typelist < Types0... >, typelist < Types1... > >
{
  typedef typelist < typelist < Types0, Types1 >... > type;
};

How can I generalize this zip meta-function to arbitrary number of typelists?  What we need here seems to be a parameter pack of parameter packs.  I am not sure how to do that.
Edit 1:
Implementation of is_equal...
template < std::size_t... Nn >
struct is_equal;

template < std::size_t N0, std::size_t N1, std::size_t... Nn >
struct is_equal < N0, N1, Nn... >
: and_ <
    typename is_equal < N0, N1 >::type
  , typename is_equal < N1, Nn... >::type
  >::type
{
};

template < std::size_t M, std::size_t N >
struct is_equal < M, N > : std::false_type
{
  typedef std::false_type type;
};

template < std::size_t N >
struct is_equal < N, N > : std::true_type
{
  typedef std::true_type type;
};

A similar approach can be taken to zip as well I think...  haven't tried with zip yet, but will do so when I get back home.
Edit 2:
Here is what I finally thought looked more elegant.  This is basically a variation of Vaughn Cato's approach.
namespace impl
{

template < typename Initial, template < typename, typename > class F, typename... Types >
struct foldl;

template < typename Initial, template < typename, typename > class F, typename First, typename... Rest >
struct foldl < Initial, F, First, Rest... >
{
  typedef typename foldl < typename F < Initial, First >::type, F, Rest... >::type type;
};

template < typename Final, template < typename, typename > class F >
struct foldl < Final, F >
{
  typedef Final type;
};

template < typename Type, typename TypeList >
struct cons;

template < typename Type, typename... Types >
struct cons < Type, typelist < Types... > >
{
  typedef typelist < Types..., Type > type;
};

template < typename, typename >
struct zip_accumulator;

template < typename... Types0, typename... Types1 >
struct zip_accumulator < typelist < Types0... >, typelist < Types1... > >
{
  typedef typelist < typename cons < Types1, Types0 >::type... > type;
};

template < typename... Types0 >
struct zip_accumulator < typelist <>, typelist < Types0... > >
{
  typedef typelist < typelist < Types0 >... > type;
};

template < typename... TypeLists >
struct zip
{
  typedef typename foldl < typelist <>, zip_accumulator, TypeLists... >::type type;
};

}

template < typename... TypeLists >
struct zip
{
  static_assert(and_ < typename is_type_list < TypeLists >... >::value, "All parameters must be type lists for zip");
  static_assert(is_equal < TypeLists::length... >::value, "Length of all parameter type lists must be same for zip");
  typedef typename impl::zip < TypeLists... >::type type;
};

template < typename... TypeLists >
struct zip < typelist < TypeLists... > > : zip < TypeLists... >
{
};

This treats zip as a fold operation.

A: This is the shortest implementation I've discovered:
template <typename...> struct typelist { };
template <typename A,typename B> struct prepend;
template <typename A,typename B> struct joincols;
template <typename...> struct zip;

template <typename A,typename... B>
struct prepend<A,typelist<B...> > {
  typedef typelist<A,B...> type;
};

template <>
struct joincols<typelist<>,typelist<> > {
  typedef typelist<> type;
};

template <typename A,typename... B>
struct joincols<typelist<A,B...>,typelist<> > {
  typedef typename
    prepend<
      typelist<A>,
      typename joincols<typelist<B...>,typelist<> >::type
    >::type type;
};

template <typename A,typename... B,typename C,typename... D>
struct joincols<typelist<A,B...>,typelist<C,D...> > {
  typedef typename
    prepend<
      typename prepend<A,C>::type,
      typename joincols<typelist<B...>,typelist<D...> >::type
    >::type type;
};

template <>
struct zip<> {
  typedef typelist<> type;
};

template <typename A,typename... B>
struct zip<A,B...> {
  typedef typename joincols<A,typename zip<B...>::type>::type type;
};

A: Seems to be doable with fully-fledged lists (that means head, tail and cons operations) and recursion. Tested with a snapshot of GCC 4.7, all the std stuff is from <type_traits>:
struct nil {};

template<typename T>
struct is_nil: std::is_same<T, nil> {};

template<typename... T>
struct and_: std::true_type {};

template<typename First, typename... Rest>
struct and_<First, Rest...>
: std::integral_constant<
    bool
    , First::value && and_<Rest...>::value
> {};

template<typename T>
struct not_
: std::integral_constant<bool, !T::value> {};

template<typename... T>
struct typelist;

template<typename First, typename Second, typename... Rest>
struct typelist<First, Second, Rest...> {
    typedef First head;
    typedef typelist<Second, Rest...> tail;
};

template<typename Last>
struct typelist<Last> {
    typedef Last head;
    typedef nil tail;
};

template<typename T, typename List>
struct cons;

template<typename T, typename... Ts>
struct cons<T, typelist<Ts...>> {
    typedef typelist<T, Ts...> type;
};

// workaround for:
// sorry, unimplemented: cannot expand '...' into a fixed-length argument list
template<template<typename...> class Template, typename... T>
struct gcc_workaround {
    typedef Template<T...> type;
};

namespace detail {

template<typename Sfinae, typename... Lists>
struct zip;

template<typename... Lists>
struct zip<
    typename std::enable_if<and_<is_nil<typename Lists::tail>...>::value>::type
    , Lists...
> {
    typedef typelist<typelist<typename Lists::head...>> type;
};

template<typename... Lists>
struct zip<
    typename std::enable_if<and_<not_<is_nil<typename Lists::tail>>...>::value>::type
    , Lists...
> {
    typedef typename cons<
        typelist<typename Lists::head...>
        , typename gcc_workaround<zip, void, typename Lists::tail...>::type::type
    >::type type;
};

} // detail

template<typename... Lists>
struct zip: detail::zip<void, Lists...> {};

You might want to add error checking to all this (I'm thinking of invalid instantiations that are currently simply left as incomplete types). Frankly given the amount of time it took me to figure this out, I'd suggest sticking with Boost.MPL. Things like lazy evaluation (with which I wouldn't have needed to do the SFINAE stuff) are a boon and I'd don't like reinventing them. Plus the day it's C++11 enabled you reap the best of both worlds.

I forgot to mention that Boost.MPL also has the advantages of genericity. It can work on any type that satisfies one of its sequence concept (it's also possible to non-intrusively adapt a preexisting type), whereas you force the use of typelist.


text:
Q: Sencha proxy in Mozilla Firefox I have a problem with Firefox
[ERROR][Ext.data.proxy.Server#buildRequest] You are using a ServerProxy but have not supplied it with a url.
but in another bowser all work!
 extend : 'Ext.data.Store',
requires :['Ext.data.reader.Xml'],
config : {
    model : 'Colors',
    storeId : 'colorConfig',
    autoLoad : true,
    proxy : {
        type : 'ajax',
        url : 'test.xml',
        reader : {
            type : 'xml',
            rootProperty : 'test',
            record : 'color'
        }
    }
}

when i write
    var store = Ext.getStore('colorConfig');
    var references = Ext.Array.pluck(store.data.items, "data");

mozilla return data.url = null and all another browsera return right url.

A: Sencha have bug in src\touch\src\data\reader\Xml.js need replace function getNodeValue(line 189)
getNodeValue: function(node) {
    if (node && node.firstChild) {
        return node.firstChild.nodeValue;
    }
    if (node && node.nodeValue) {
        return node.nodeValue;
    }
    return undefined;
},


text:
Q: How do you integrate this new Spark libary for python? I am using spark with python using the pyspark command.
I came across this new library
https://github.com/databricks/spark-csv
which I want to integrate into my spark program written in python.
I have downloaded the complete codebase shown in the above link but not sure how to proceed from there. Should I just copy its contents somewhere?
Any guidance would help as I am still learning scala and spark and want to use the above library code.

A: Just to repeat information from the README file. To use spark-csv in your script you should use --packages option for each execution of spark-submit or pyspark shell.


text:
Q: Attempt to use Restricted Class: org.apache.catalina.tribes.util.Arrays I am trying to deploy a java app on WSO2 cloud.
When running i get this Exception:
exception

javax.servlet.ServletException: org/apache/catalina/tribes/util/Arrays
org.apache.catalina.security.SecurityUtil.execute(SecurityUtil.java:329)
org.apache.catalina.security.SecurityUtil.doAsPrivilege(SecurityUtil.java:166)

root cause

java.lang.ClassNotFoundException: Security Violation, attempt to use Restricted Class: org.apache.catalina.tribes.util.Arrays

However, this app is working fine locally

A: I used java.util.Arrays instead of org.apache.catalina.tribes.util.Arrays and it worked now


text:
Q: Is it possible to show all local branches at the same time in Windows Explorer? Let's say i have 2 remote branches, Master and Developer, and that my local repository is on the folder D:/Git_Project.
On git bash i go to the repository directory and select Master branch, i make a folder and a file inside it, commit changes, push it to remote master branch.
Now i switch to the developer branch, and if i now go to D:/Git_Project with windows explorer, i can't see the folders / files from the master branch.
Now, i know that git saves those changes under the .git folder, and loads / saves them whenever we switch branches. But is it possible to have it always show both branches, each with their own folder?
Basically having a "Master" and "Developer" folder under D:/Git_Project .
I know i could "cheat" and make it all in the same branch and create those folders myself, but i would lose the git branch features if i did so.
The reason i would want this is because sometimes when working on some file in the developer, or any other branch, i might want to check a particular file from another branch, and it's quite annoying to always have to switch branch just to open a file locally.
Thank you.

A: Instead of placing your repo directly under D:/Git_Project, you can clone it under
D:/Git_Project/master

Then, with git worktree (with Git 2.5+), you can checkout the develop branch of that same repo in
git worktree add ../develop develop
D:/Git_Project/develop

That way, you don't need to clone twice (even shared clones are not needed here)

A: The simplest solution would be to clone the repository locally - make extra directories to keep the "viewing copies" of each branch in, and just never check out different branches for those copies. git clone --local --shared /path/to/original /intended/path/to/copy, then git checkout master in the new one. Rinse and repeat for however many extra copies you want. You don't have to stick with just one copy to make edits in, but it would probably help from an organizational standpoint.
Since it's shared, they'll share all the actual commit records - this doesn't give you a backup of your repo, just a second place to look at it from, so don't delete a branch on one thinking that you can just get it back from the other.
See also: the docs for git clone.


text:
Q: Ubuntu 12.04: No Wifi Option here's my problem: I have no wifi option showing up in the network manager... So I looked here (ask ubuntu) for the solution and there are hundreds of answers, but I just need one..
So I check for additional drivers from the system settings and it says no proprietary drivers (the card the box came in says it's linux capable)? So I find the hardware driver I need (from the ubuntu hardware driver page).. it's for a 7260AC wireless card.. I know it works cause I loaded it on here once before but for some reason, it disappeared.
So where can I find the answer on how to reload this driver to make it work again? I know it's on here somewhere.. I saved this in case the problem happened again but it's no longer there: askubuntu.com/questions/374165/ubuntu-12-04-no-wireless-after-install

A: While the instructions I linked should work perfectly for your device, there is a newer firmware file that corrects instability sometimes found with older firmware. With a working wired ethernet connection, please open a terminal and do:
cd /lib/firmware
sudo mv iwlwifi-7260-7.ucode  iwlwifi-7260-7.ucode.bak
sudo wget https://git.kernel.org/cgit/linux/kernel/git/egrumbach/linux-firmware.git/plain/iwlwifi-7260-7.ucode

Unload and reload the driver so it sees and uses the newer firmware:
sudo modprobe -r iwldvm
sudo modprobe -r iwlwifi
sudo modprobe iwlwifi

Detach the ethernet and your wireless should be working.
If it still isn't working, check for informative clues:
dmesg | grep iwl
ls -al /lib/firmware/iwlwifi-7260-7.ucode


text:
Q: What is the best coding style for performance? The problem of Mathematica is there are too many ways to perform one task. That leads to confusion for new users because the performances of these methods are so different.
I'm learning the best coding style to gain performance in Mathematica. However, there is something that I don't understand and need the explication of the experts.

Let takes this simple example. I have a list of data consist of 10^7 elements {{x1,y1},{x2,y2},...}. Now I want to make a list like {{x1,f[y1]},{x2,f[y2]},...}. For this task, there are about 13 methods.
list = Table[{i, 2 i}, {i, 1., 10^7}];

This is the packed array:
Developer`PackedArrayQ[list]
On["Packing"];

And here is the performance of these 13 methods. The performance difference between these methods is huge. (from 0.5s to 20s). The time is measured by AbsoluteTiming, the f function is Sin.

Here are my questions:

*

*Q1: Let's compare methods #11 vs #10. Why using only one built-in function MapAt is much slower than {Copy the whole list, apply function f to the Part, and recall the new list}? In general, using 1 Function is faster than combine several functions.

*Q2: Between the #9, and #10. Again, using MapAt, Pure function, and Map is faster than using MapAt with a built-in position option. Why? What is the purpose of implementing the position option in MapAt when this method is slower than combining other existing functions?

*Q3: Compare #3, and #4, using the same function Table, but with a different approach, the performance is 3 times slowers. Should Mathematica eliminate the method that is not optimized?

*Q4: Compare 6 and 4. Method 6 is the Functional Style with Apply, Pure Function. Method 4 is a Procedural way and breaking the list into each element. Why the functional style which treats the data as the whole list is much slower than the naive Procedural style?

*A1: Unpacking verify is very useful.

So in general, which is your preferred coding style for performance? I would like to learn.

In[138]:= $Version

Out[138]= "12.0.0 for Microsoft Windows (64-bit) (April 6, 2019)"

Here is the code to verify:
list = Table[{i, 2 i}, {i, 1., 10^7}];
Developer`PackedArrayQ[list]
On["Packing"];

timelist = {
   Transpose[{#[[1]], Sin[#[[2]]]}] &@Transpose@list; //
    AbsoluteTiming,
   Transpose[{list[[All, 1]], Sin[list[[All, 2]]]}]; // AbsoluteTiming,
   Table[{i[[1]], Sin[i[[2]]]}, {i, list}]; // AbsoluteTiming,
   Table[{list[[i, 1]], Sin[list[[i, 2]]]}, {i, 1, Length[list]}]; //
    AbsoluteTiming,
   {#[[1]], Sin[#[[2]]]} & /@ list; // AbsoluteTiming,
   {#1, Sin[#2]} & @@@ list; // AbsoluteTiming,
   MapThread[{#1, Sin[#2]} &, Transpose[list]]; // AbsoluteTiming,
   Inner[#1[#2] &, {# &, Sin[#] &}, Transpose[list], List]; //
    AbsoluteTiming,
   MapAt[Sin, #, 2] & /@ list; // AbsoluteTiming,
   MapAt[Sin, list, {All, 2}]; // AbsoluteTiming,
   AbsoluteTiming[list2 = list;
    list2[[All, 2]] = Sin[list2[[All, 2]]]; list2;],
   Map[Composition[
       Through, {Composition[Identity, First],
        Composition[Sin, Last]}], list]; // AbsoluteTiming,
   list /. {x_, y_} -> {x, Sin[y]}; // AbsoluteTiming
   };

funclist = ToString /@ {
    HoldForm[Transpose[{#[[1]], Sin[#[[2]]]}] &@Transpose@list],
    HoldForm[Transpose[{list[[All, 1]], Sin[list[[All, 2]]]}]],
    HoldForm[Table[{i[[1]], Sin[i[[2]]]}, {i, list}]],
    HoldForm[
     Table[{list[[i, 1]], Sin[list[[i, 2]]]}, {i, 1, Length[list]}]],
    HoldForm[{#[[1]], Sin[#[[2]]]} & /@ list],
    HoldForm[{#1, Sin[#2]} & @@@ list],
    HoldForm[MapThread[{#1, Sin[#2]} &, Transpose[list]]],
    HoldForm[Inner[#1[#2] &, {# &, Sin[#] &}, Transpose[list], List];],
    HoldForm[MapAt[Sin, #, 2] & /@ list],
    HoldForm[MapAt[Sin, list, {All, 2}]],
    HoldForm[list2 = list; list2[[All, 2]] = Sin[list2[[All, 2]]];
     list2],
    HoldForm@
     Map[Composition[
       Through, {Composition[Identity, First],
        Composition[Sin, Last]}], list],
    HoldForm[list /. {x_, y_} -> {x, Sin[y]}]
    };

unpack = {"No", "No", "No", "No", "No", "Yes", "Yes", "Yes", "No",
    "Yes", "No", "Yes", "Yes"};;
sol = SortBy[
   Transpose[{Range@Length@funclist, funclist, unpack,
     timelist[[All, 1]]}], Last];
Grid[PrependTo[sol, {"#", "Method", "Unpacking", "AbsoluteTiming"}],
 Frame -> All]


text:
Q: Add git submodule using a specific commit number I'm using git submodule commands to add this FSM repo in my project. I want to checkout a specific release commit. By default the master branch is checked out.
After adding the git repo, when I run
$ git submodule
It gives
d1b66d66cfa95f238a7498465908a262f4b2326a directory_path/fsmlite
The commit number here belongs to a master branch commit. How can I checkout another commit instead, using its commit number?

A: There might be some other way to do this, but I got the desired commit by
$ cd directory_path/fsmlite
$ git checkout v0.7.1      (this is the branch I wanted to point to)
$ git submodule update
$ cd parent_dir
$ git submodule

  +de19ea0a71cb6082fe9311694a27e8f0cc2f972a directory_path/fsmlite (v0.7.1)

which is the specific commit number I wanted


text:
Q: Save array in ng-storage AngularJS how save and display array in angular?
example:
$scope.save = function () {
    var myOby= [
    { name: 'A', address: '1' },
    { name: 'B', address: '2' },
    { name: 'C', address: '3' },
    { name: 'D', address: '4' }
    ];
    //save
}
$scope.load = function() {
    //show
}

Any solution?

A: localStorage supports arrays, and any other valid JSON (objects, strings, numbers), and not for example functions.
Here is a plunkr demonstrating this
The angular code:
var app = angular.module('myApp', ['ngStorage']);

app.controller('myCtrl', function($scope, $localStorage) {
  $scope.text = "Hello!";
  $scope.save = function () {
    var myOby= [
    { name: 'A', address: '1' },
    { name: 'B', address: '2' },
    { name: 'C', address: '3' },
    { name: 'D', address: '4' }
    ];
    //save
    $localStorage.myKey =  myOby;
}
$scope.load = function() {
    //show
    $scope.restored_data = $localStorage.myKey;
}
});

As mentioned in the comments above, this information is readily available in the documentation: Documentation


text:
Q: Excel COUNTIF with strings, separated by comma I am trying to write a simple formula to count how many times a particular name appears in a column. I am using COUNTIF as it is a pretty straight forward process but I cannot work out how to make it happen for a name in particular. This is the case:

The column named Age will display cells with one or more names, separated by commas in case there are more than one value. Putting "Young" as an example is easy to tell the COUNTIF formula to give me the number representing how many times this word appears, either being the only value in cell or as a part of a cell with a longer string value by giving the formula the "Young" statement.
The problem comes when I want the formula to count how many times "Mature" appears in my column. I cannot work out the way to make it count only when it says "Mature" without also taking all the "Early_Mature" or "Semi_Mature"
I know this is easy for whoever knows the basics of Excel so I don't think there is need to give more details.
Thanks

A: Most of the times I succeed solving such problems by adding the same delimiter (of our string) at the beginning and end of the main string.
So since your data is at COL:Y, you may create a new helper COL:Z and enter this formula:
="," & Y1 & ","

I did not use any spaces before or after comma since your data seems not having any space. Depending on your case, you may have to use spaces.
Now your string is wrapped with commas, which you may alter COUNTIF formula to such:
=COUNTIF(Z:Z,"*,"&B1&",*")

* characters are jokers which stand for "anything" in this context.

A: With an UDF. Code goes in a standard module added by opening the VBE with Alt + F11 then right-click in project explorer and add module.

Code
Option Explicit

Public Function GetCount(ByRef selectRange As Range, ByVal searchTerm As String) As Long
    Application.Volatile
    With selectRange

        Dim arr(), joinedString As String, i As Long, outputCount As Long
        arr = .Value

        joinedString = Join(Application.WorksheetFunction.Transpose(Application.WorksheetFunction.Index(arr, 0, 1)), ",")

        Dim arr2() As String
        arr2 = Split(joinedString, ",")

        For i = LBound(arr2) To UBound(arr2)
            If Trim$(arr2(i)) = "Mature" Then
                outputCount = outputCount + 1
            End If
        Next i
    End With

    GetCount = outputCount

End Function

Usage in sheet

A: To get the number of occurrences of Mature excluding those that have prefix you can use this array formula:
=SUM(((LEN(A2:A7)-LEN(SUBSTITUTE(A2:A7,"Mature",""))) / LEN("Mature"))-((LEN(A2:A7)-LEN(SUBSTITUTE(A2:A7,"_Mature",""))) / LEN("_Mature")))

Please take note that this formula is applied with Ctrl + Shift + Enter.
Given that your range is in Y:Y column, just change the range to one you need.

A: An alternative would be to change "Mature" to "Fully_Mature". Then you could just use Countif().
You'd have to do this in steps:
1) Change "Early_Mature" to "E_M"
2) Change "Semi_Mature" to "S_M"
3) Change "Mature" to "Fully_Mature"
4) reverse of step 1).
5) reverse of step 2).


text:
Q: Flash Player breaks Safari! As of a few days ago, some Safari webpages (the first and most frequently-occurring of which was Facebook's News Feed) would start loading but then freeze up. I went into Activity Monitor, and while it did say that Safari Web Content wasn't responding, it also said that Flash Player (Safari web plugin) wasn't responding. Force Quitting the Safari Web Content didn't do anything; the page just reloaded and froze up again, but when I forced Flash Player to quit, the misbehaving webpage refreshed and worked perfectly. After several more instances of the problem I uninstalled and reinstalled Flash Player, and the problem happened again.
I've currently got Flash Player uninstalled for stability's sake, but I can't live a Flashless life forever. How can I fix the problem?
UPDATE: It just happened again after I attempted a reinstall. This time, I checked my Flash version.
OS X 10.10.2, Safari 8.0.3, Flash "NPAPI Plug-in version 16.0.0.305 is installed."

A: Google's Chrome browser includes a built-in flash plugin. I uninstalled Flash on my system too but I use Chrome for loading up sites which require flash.
Another tack you might try is to install Click to Plugin. I was going to recommend Click to Flash, but apparently that isn't under development anymore and the developer recommends Click to Plugin.


text:
Q: Every time when i open class teacher's project to my system it shows this error.Error running app: Default activity not found
I'm a beginner in Android.
Every time when I open class teacher's project to my system it shows this error.
Error running app: Default activity not found.

What should I do to match the same project as my teacher's?
I've tried many solutions.

My Manifest file is
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.assigncheckbox">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

A: maybe it happen because you didn't add this activity to your AndroidManifest.xml
  <activity
            android:name=".yourActivity"
             />


text: Q: How to take input from a file in chrome console? While debugging from console in Google Chrome, I'd like to take my testcases from a text file uploaded at a url, say mysite.com/testcases.txt. How can I do that?


text:
Q: Count of previously smaller elements encountered in an input stream of integers? Given an input stream of numbers ranging from 1 to 10^5 (non-repeating) we need to be able to tell at each point how many numbers smaller than this have been previously encountered.
I tried to use the set in C++ to maintain the elements already encountered and then taking upper_bound on the set for the current number. But upper_bound gives me the iterator of the element and then again I have to iterate through the set or use std::distance which is again linear in time.
Can I maintain some other data structure or follow some other algorithm in order to achieve this task more efficiently?
EDIT : Found an older question related to fenwick trees that is helpful here. Btw I have solved this problem now using segment trees taking hints from @doynax comment.
How to use Binary Indexed tree to count the number of elements that is smaller than the value at index?

A: Regardless of the container you are using, it is very good idea to enter them as sorted set so at any point we can just get the element index or iterator to know how many elements are before it.

A: Keep your table sorted at each step. Use binary search. At each point, when you are searching  for the number that was just given to you by the input stream, binary search is going to find either the next greatest number, or the next smallest one. Using the comparison, you can find the current input's index, and its index will be the numbers that are less than the current one. This algorithm takes O(n^2) time.

A: You need to implement your own binary search tree algorithm. Each node should store two counters with total number of its child nodes.
Insertion to binary tree takes O(log n). During the insertion counters of all parents of that new element should be incremented O(log n).
Number of elements that are smaller than the new element can be derived from stored counters O(log n).
So, total running time O(n log n).

A: What if you used insertion sort to store each number into a linked list? Then you can count the number of elements less than the new one when finding where to put it in the list.

A: It depends on whether you want to use std or not. In certain situations, some parts of std are inefficient. (For example, std::vector can be considered inefficient in some cases due to the amount of dynamic allocation that occurs.) It's a case-by-case type of thing.
One possible solution here might be to use a skip list (relative of linked lists), as it is easier and more efficient to insert an element into a skip list than into an array.
You have to use the skip list approach, so you can use a binary search to insert each new element. (One cannot use binary search on a normal linked list.) If you're tracking the length with an accumulator, returning the number of larger elements would be as simple as length-index.
One more possible bonus to using this approach is that std::set.insert() is log(n) efficient already without a hint, so efficiency is already in question.


text:
Q: Super + w shows windows from current workspace only
Possible Duplicate:
How to do super w show open apps of all workspaces?

After upgrading from 11.10 to 12.04 pressing Super + w shows the windows from the current workspace only and not from all workspaces.
How can I make unity to show again all windows from all workspaces when pressing Super + w?


text:
Q: Keep reference to object created with Internet Explorer I am trying to login to a website and then continue clicking on and filling in information within that same website. However, when I run my code I run into an error that says the object is forgotten.
Here is the code
Sub Vba2HtmlForm()
    Dim IE as Object
    Dim frm as variant
    dim element as variant

    Set IE = CreateObject("InternetExplorer.Application")
    IE.Visible = True
    IE.navigate "https://www.programworkshop.com/6.0.0.0/login/login.aspx?skin=default&lang=enu"
    While IE.readyState <> 4: DoEvents: Wend

    ''trying to get form by ID''

    IE.document.getElementById("Login").Value = "something@something.com"

    IE.document.getElementById("Pass").Value = "somepassword"
    IE.document.getElementById("btnlogin").Click
    While IE.readyState <> 4: DoEvents: Wend

     Application.Wait (Now + TimeValue("00:00:02"))

    ' And then here is where I run into the following error:
    ' Run-time error '424':
    ' Object Required

    IE.document.all("sd5").Click
    '''just a note here. I have also tried getelementbyId and getelementbyname with no luck''''

End Sub

Here is the HTML
Examinees

A: After you navigate is when it Loses its place.   You can use a small method to obtain the correct IE object by passing in the URL you navigated to, assuming it isn't redirected and only one instance of IE has the url.  You will need to add a reference to Microsoft Shell Controls and Automation.
Call it like
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
IE.navigate "https://www.programworkshop.com/6.0.0.0/login/login.aspx?skin=default&lang=enu"
While IE.readyState <> 4: DoEvents: Wend
set IE = GetWebPage("https://www.programworkshop.com/6.0.0.0/login/login.aspx?skin=default&lang=enu")

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Desc: The Function gets the Internet Explorer window that has the current
'   URL from the sURL Parameter.  The Function Timesout after 30 seconds
'Input parameters:
    'String sURL - The URL to look for
'Output parameters:
    'InternetExplorer ieWin - the Internet Explorer window holding the webpage
'Result: returns the Internet Explorer window holding the webpage
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function GetWebPage(sURL As String) As InternetExplorer
Dim winShell As Shell
Dim dt As Date
Dim ieWin As InternetExplorer

dt = DateAdd("s", 30, DateTime.Now)

Do While dt > DateTime.Now
    Set winShell = New Shell
    'loop through the windows and check the internet explorer windows
    For Each ieWin In winShell.Windows
        If ieWin.LocationURL = sURL Then
            ieWin.Visible = True
            Set GetWebPage = ieWin
            Do While ieWin.Busy
                DoEvents
            Loop
            Exit Do
        Set winShell = Nothing
        End If
    Next ieWin
    Set winShell = Nothing
    DoEvents
Loop
End Function


text:
Q: Can a collection in NHibernate be mapped as read-only? I have a mapping defined where a parent object has a collection of child objects.  In my design, I'd like to be able to delete the child objects without having to remove them from the collection on the parent object and re-saving the parent object.  However, when I try this, I get the "deleted object would be re-created on save" error.  Is there a way to prevent this such that I could simply delete the child object and not worry about removing it from the parent's collection too?  That feels like doing double the work.  Ideally I'd like to treat the parent's collection as read-only from NHibernate's perspective.

A: It'd help if you post your mapping files, but it sounds like you need to add Inverse=true to the collection mapping. This means that the child object is responsible for handling any save or updates, not the parent.
However, in the database it's all modelled the same. The child should have a column for the parent row's ID. NHibernate will create different SQL based on the Inverse property though. I'd like to give more detail, but I'm learning NHibernate myself as well.

A: I believe the only thing you need to do is just set the collection of child objects in the parent's mapping file to be cascade="none".
Of course that will also prevent saving child objects by assigning them to the parent's collection and updating the parent. If that is OK then you got your solution.


text:
Q: .Net MemoryCache Miss when using Objects as Keys When using IMemoryCache with an object, TryGetValue always miss. I am trying to have a tuple<string, object> as the key, and a tuple<string, string> works perfectly fine.
This code here always gets me a cache miss:
_cache.TryGetValue(("typeOfCache", query), out var something);
if(something == null) _cache.CreateEntry(("typeOfCache", query));

The object I'm using has lists of lists inside, not no dictionary/set (nothing that has a random ordering).
Is this a .net bug or am I doing something incorrectly?

A: MemoryCache internally uses a ConcurrentDictionary<object, CacheEntry>, which in turn uses the default comparer for the object type, which performs equality comparisons based on the actual type's overrides of Object.Equals and Object.GetHashCode. In your case, your keys are ValueTuple<string, Query>, whatever your Query class is. ValueTuple<T1,T2>.Equals evaluates to true if the components of the compared instance are of the same types as those of the current instance, and if the components are equal to those of the current instance, with equality being determined by the default equality comparer for each component.
Thus, how the equality comparison gets performed depends on the implementation of your Query type. If this type does not override Equals and GetHashCode, nor implements IEquatable<T>, then reference equality is performed, meaning that you only get equality when you pass in the same instance of the query. If you want to alter this behavior, you should extend your Query class to implement IEquatable<Query>.
I also found that CreateEntry does not immediately add the new entry to the cache. .NET Core documentation is disappointingly sparse, so I haven't found the intended behavior; however, you can ensure that the entry is added by calling Set instead.
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Caching.Memory;

class Program
{
    static void Main(string[] args)
    {
        var query1 = new Query { Parts = { new List<string> { "abc", "def", "ghi" } } };
        var query2 = new Query { Parts = { new List<string> { "abc", "def", "ghi" } } };

        var memoryCache = new MemoryCache(new MemoryCacheOptions());
        memoryCache.Set(("typeOfCache", query1), new object());
        var found = memoryCache.TryGetValue(("typeOfCache", query2), out var something);
        Console.WriteLine(found);
    }

    public class Query : IEquatable<Query>
    {
        public List<List<string>> Parts { get; } = new List<List<string>>();

        public bool Equals(Query other)
        {
            if (ReferenceEquals(this, other)) return true;
            if (ReferenceEquals(other, null)) return false;
            return this.Parts.Length == other.Parts.Length
                && this.Parts.Zip(other.Parts, (x, y) => x.SequenceEqual(y)).All(b => b);
        }

        public override bool Equals(object obj)
        {
            return Equals(obj as Query);
        }

        public override int GetHashCode()
        {
            return this.Parts.SelectMany(p => p).Take(10).Aggregate(17, (acc, p) => acc * 23 + p?.GetHashCode() ?? 0);
        }
    }
}


text:
Q: Wordpress Multisite "Error establishing a database connection" in localhost When attempting to convert WordPress to a Multisite setup, I get the error:

Error establishing a database connection

I'm using WordPress 3.7.1 on Windows 7 with a WAMP server.
wp-config.php
define('WP_ALLOW_MULTISITE', true );
define('SUBDOMAIN_INSTALL', false);
define('DOMAIN_CURRENT_SITE', 'localhost');
define('PATH_CURRENT_SITE', '/wordpress_test4/');
define('SITE_ID_CURRENT_SITE', 1);
define('BLOG_ID_CURRENT_SITE', 1);

.htaccess
RewriteEngine On
RewriteBase /wordpress_test4/
RewriteRule ^index\.php$ - [L]

# add a trailing slash to /wp-admin
RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L]
RewriteRule . index.php [L]

A: I had a strange encounter very recently. After setting up a dev server which runs under a different domain and moving a multisite setup to it I got the same error "Error establishing a database connection". I had checked that all the wp_options tables have the correct domains in the respective settings and that my database connection had the right credentials and would work under normal circumferences.
I found a way to get a better error reporting. I added an output of the database object in the function dead_db() in functions.php which then showed me that it couldn't find any blogs for my site in the table wp_blogs. I simply forgot to update the domains for the test server in this table.
function dead_db() {
  global $wpdb;

  echo "<pre>";
  print_r($wpdb);
  echo "</pre>";

  wp_load_translations_early();

A: You need to add to your wp-config.php:
define('MULTISITE', true);

I had the same problem. I skipped this line because I already had define('WP_ALLOW_MULTISITE', true); in my wp-config and it looked to me the same.

A: Had same problem, found 3 possible solutions:

*

*Make sure: DB_NAME, DB_USER, DB_PASSWORD, and DB_HOST in your wp-config.php are really the ones expectected.

*As Dima L. mentioned before, define('MULTISITE', true); is expected too.

*But what solved it for me* is etting up multi-site for WordPress, changed the wp_blogs table's column path to an undefined location for my website. I changed it to / and the DB connection was re-established.

A: My DOMAIN_CURRENT_SITE in wp-config.php was define('DOMAIN_CURRENT_SITE', 'www.example.com');
Removing http:// in wp_blogs -> domain fixed my issue.

A: I added $base = '/'; into the config, which solved the issue.
define('MULTISITE', true);
define('SUBDOMAIN_INSTALL', true);
define('DOMAIN_CURRENT_SITE', 'mydomain.com');
$base = '/';
define('PATH_CURRENT_SITE', '/');
define('SITE_ID_CURRENT_SITE', 1);
define('BLOG_ID_CURRENT_SITE', 1);

A: If you have taken an entire database dump of a multisite, you would have to change the domain name to match your localhost domain on the following tables:

*

*wp_blogs [update the domain fields]

*wp_options [siteurl and home]

*wp_site [domain field]

For a multisite, defining WP_HOME and WP_SITEURL on the config.php will not work.
Ideally before importing the DB dump, if you have the .sql file, you could do a search and replace of all the domains to your own localhost domain.
These above steps worked for me.

A: I struggled a long time because of this issue. And finally found a solution.
You should not add all those settings at once in the wp-config.php file. Follow the exact steps described here: http://codex.wordpress.org/Create_A_Network
Only add the following code as the first step:
/* Multisite */
define( 'WP_ALLOW_MULTISITE', true );

And then refresh your page.
After that, in your administration panel go to Tools -> Network Setup and choose your sub-site settings.
For the rest, just use the instructions from the link above.

A: Besides to all said above, if working with multisite environment please check also the following:
in the respective subdirectories (/home/subsitename) there exist separate wp-config.php and .htaccess files for each of (sub)sites, so the above mentioned parameters have to be adjusted in all of these files.
For example, my main site was working correctly since these files in my /home directory were OK, but when tried to access my sub-sites, I've been receiving database connection error message until I adjusted these files too.

A: Inspired by Sabin's answer, I checked wp_blogs and found that the domain value was still pointing to the wrong domain (I was moving a multi-site to a dev server).  Running UPDATE wp_blogs SET domain='example.com'; fixed my issue (note that I'm using subfolder multisite, not subdomain - don't blindly run that SQL!)

A: I had the problem after moving the multisite from a sub directory to the root directory.
What solved it for me was partly what has been mentioned by Sabin Chirila :

*

*Make sure: DB_NAME, DB_USER, DB_PASSWORD, and DB_HOST in your wp-config.php are really the ones expectected.

*As Dima L. mentioned before, define('MULTISITE', true); is expected too.

*Change the 'wp_blogs' table's column 'path' to "/" and the DB connection was re-established.

but I had to change some more things.

*In order to be able to view the frontend I also had to change the 'wp_site' table's column 'path' to "/"

*and then (in theme twentyseventeen-child) I had to reconfigure some configuration settings in the backend as they weren't taken into account. But that was simple as the data was still there.

A: If you're running WHM/cPanel and you've already checked that you've added the MULTISITE/WP_ALLOW_MULTISITE constant, you're probably running into virtual host issues.
If you're getting the database error, chances are, your name servers or A record is correct. Otherwise your domain wouldn't be pointing to your server with a database connection. But, you've probably forgotten, or missed, the domain name from the cPanel aliases.
Just head to cPanel, search for 'Aliases' and type in the domain name you're missing under 'Create a New Alias'.
You can also get to cPanel by logging into WHM, searching for 'List Accounts', searching for the account you want and clicking on the CP icon.

A: Here's How I fixed it
config settings
define( 'MULTISITE', true );
define( 'SUBDOMAIN_INSTALL', false );
define( 'DOMAIN_CURRENT_SITE', 'localhost' );
define( 'PATH_CURRENT_SITE', '/myblog/' );
define( 'SITE_ID_CURRENT_SITE', 1 );
define( 'BLOG_ID_CURRENT_SITE', 1 );

then in the database table (found using phpmyadmin) wp_blogs set the values for your root blog (which should be lie/number 1) to
domain localhost
root /myblog/

And finally - reset the sitrurl and homepage in options table (again found using phpmyadmin) to
 http://localhost/myblog/


text:
Q: No setter/field 'image' found on class 'model' I already find question-related to my problem but I still don't really get the idea. I want to get data images from the database URL in firebase storage using glide. but my logcat shows this line.
2023-02-14 10:02:36.417 25063-25063/com.isjieman.ocion W/ClassMapper: No setter/field for post_image found on class com.isjieman.ocion.model.Post
2023-02-14 10:02:36.436 25063-25063/com.isjieman.ocion W/ClassMapper: No setter/field for background_image found on class com.isjieman.ocion.model.User
2023-02-14 10:02:36.436 25063-25063/com.isjieman.ocion W/ClassMapper: No setter/field for profile_image found on class com.isjieman.ocion.model.User
2023-02-14 10:02:36.438 25063-25063/com.isjieman.ocion W/Glide: Load failed for  with size [960x240]
    class com.bumptech.glide.load.engine.GlideException: Failed to load resource

the problem is only for field image on the model. i already succeed on retrieve the other data from firebase except the image only. how do i solve this more technically? glad if someone wants to explain my problem
here's the database structure
{
  "Posts": {
    "-NNsor5WiX9wxTDf7qo5": {
      "category": "Art",
      "description": "tes 123",
      "duration": "-",
      "paymentMethods": "e-wallet",
      "postId": "-NNsor5WiX9wxTDf7qo5",
      "post_image": "https://firebasestorage.googleapis.com/v0/b/final-project-idn.appspot.com/o/Posts%20Pictures%2F1675990621049.jpg?alt=media&token=f7b747c0-1efe-4f43-9ff1-729c7d99c7c1",
      "priceRange": "Rp 0 - 10.000",
      "publisher": "6FzpJ2sQC9gewbUIGHB8hiNWK1z2",
      "title": "tes"
    }
  },
  "User": {
    "6FzpJ2sQC9gewbUIGHB8hiNWK1z2": {
      "background_image": "https://firebasestorage.googleapis.com/v0/b/final-project-idn.appspot.com/o/Default%20Images%2Fimg_background.png?alt=media&token=b51e7cf5-2015-4cc4-9583-159373d081e2",
      "bio": "Member of NCT",
      "email": "mark@gmail.com",
      "link": "",
      "profile_image": "https://firebasestorage.googleapis.com/v0/b/final-project-idn.appspot.com/o/Profile%20Pictures%2F6FzpJ2sQC9gewbUIGHB8hiNWK1z2.jpg?alt=media&token=d174fad9-2f8c-4964-83ec-549f18876587",
      "uid": "6FzpJ2sQC9gewbUIGHB8hiNWK1z2",
      "userName": "marklee"
    }
  }
}

here's my User model
class User {
    private var uid: String = "0"
    private var userName: String = ""
    private var email: String = ""
    private var bio: String? = null
    private var link: String? = null
    private var profile_image: String = ""
    private var background_image: String = ""

    constructor()

    constructor(uid : String, userName : String, email : String, bio : String, link : String, profile_image : String, background_image : String){
        this.uid = uid
        this.userName = userName
        this.email = email
        this.bio = bio
        this.link = link
        this.profile_image = profile_image
        this.background_image = background_image
    }

    //function UID
    fun getUID(): String{
        return uid
    }

    fun setUID(uid: String){
        this.uid = uid
    }

    //function User Name
    fun getUserName(): String{
        return userName
    }

    fun setUserName(userName: String){
        this.userName = userName
    }

    //function Email
    fun getEmail(): String{
        return email
    }

    fun setEmail(email: String){
        this.email = email
    }

    //function bio
    fun getBio(): String?{
        return bio
    }

    fun setBio(bio: String?){
        this.bio = bio
    }

    //function link
    fun getLink(): String?{
        return link
    }

    fun setLink(link: String?){
        this.link = link
    }

    //function Profile Image
    fun getProfileImage(): String{
        return profile_image
    }

    fun setProfileImage(profile_image: String){
        this.profile_image = profile_image
    }

    //function Background Image
    fun getBackgroundImage(): String{
        return background_image
    }

    fun setBackgroundImage(background_image: String){
        this.background_image = background_image
    }

}

here's Post model
class Post {
    private var postId: String = ""
    private var title: String = ""
    private var post_image: String = ""
    private var description: String = ""
    private var category: String = ""
    private var priceRange: String = ""
    private var duration: String = ""
    private var paymentMethods: String = ""
    private var publisher: String = ""

    constructor()
    constructor(
        postId: String,
        title: String,
        post_image: String,
        description: String,
        category: String,
        priceRange: String,
        duration: String,
        paymentMethods: String,
        publisher: String
    ) {
        this.postId = postId
        this.title = title
        this.post_image = post_image
        this.description = description
        this.category = category
        this.priceRange = priceRange
        this.duration = duration
        this.paymentMethods = paymentMethods
        this.publisher = publisher
    }

    //Get
    fun getPostId(): String{
        return postId
    }

    fun getTitle(): String{
        return title
    }

    fun getPostImage(): String{
        return post_image
    }

    fun getDescription(): String{
        return description
    }

    fun getCategory(): String{
        return category
    }

    fun getPriceRange(): String{
        return priceRange
    }

    fun getDuration(): String{
        return duration
    }

    fun getPaymentMethods(): String{
        return paymentMethods
    }

    fun getPublisher(): String{
        return publisher
    }

    //Set
    fun setPostId(postId: String){
        this.postId = postId
    }

    fun setTitle(title: String){
        this.title = title
    }

    fun setPostImage(post_image: String){
        this.post_image = post_image
    }

    fun setDescription(description: String){
        this.description = description
    }

    fun setCategory(category: String){
        this.category = category
    }

    fun setPriceRange(priceRange: String){
        this.priceRange = priceRange
    }

    fun setDuration(duration: String){
        this.duration = duration
    }

    fun setPaymentMethods(paymentMethods: String){
        this.paymentMethods = paymentMethods
    }

    fun setPublisher(publisher: String){
        this.publisher = publisher
    }

}

here's my PostAdapter.kt
class PostAdapter(private val mContext: Context,
                  private val mPost: List<Post>) : RecyclerView.Adapter<PostAdapter.ViewHolder>()
{
    private var firebaseUser: FirebaseUser? = null

    inner class ViewHolder(@NonNull itemView: View) : RecyclerView.ViewHolder(itemView){
        var profileImage: CircleImageView
        var tvUsername: TextView
        var likeButton: ImageButton
        var tvTitle: TextView
        var tvPrice: TextView
        var tvDescription: TextView
        var tvSeeMore: TextView
        var postImage: ImageView

        init {
            profileImage = itemView.findViewById(R.id.cvProfile)
            tvUsername = itemView.findViewById(R.id.tvCvUsername)
            likeButton = itemView.findViewById(R.id.cvFav)
            tvTitle = itemView.findViewById(R.id.tvCvTitle)
            tvPrice = itemView.findViewById(R.id.tvCvPrice)
            tvDescription = itemView.findViewById(R.id.tvCvDesc)
            tvSeeMore = itemView.findViewById(R.id.tvCvSeeMore)
            postImage = itemView.findViewById(R.id.ivPostImage)

        }
    }

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

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        firebaseUser = FirebaseAuth.getInstance().currentUser
        val post = mPost[position]

        Glide.with(mContext.applicationContext).load(post.getPostImage()).into(holder.postImage)
        holder.tvTitle.text = post.getTitle()
        holder.tvDescription.text = post.getDescription()
        holder.tvPrice.text = post.getPriceRange()

        publisherInfo(holder.profileImage, holder.tvUsername, post.getPublisher())
    }

    private fun publisherInfo(
        profileImage: CircleImageView,
        tvUsername: TextView,
        publisher: String
    ) {
        val usersRef = FirebaseDatabase.getInstance().reference.child("User").child(publisher)

        usersRef.addValueEventListener(object : ValueEventListener{
            override fun onDataChange(snapshot: DataSnapshot) {
                if (snapshot.exists())
                {
                    val user = snapshot.getValue(User::class.java)

                    Glide.with(mContext.applicationContext).load(user!!.getProfileImage()).into(profileImage)
                    tvUsername.text = user!!.getUserName()
                }
            }

            override fun onCancelled(error: DatabaseError) {
                Toast.makeText(mContext, error.message, Toast.LENGTH_LONG).show()
            }

        })
    }

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

any help i would really appreciate. thanks

A: You are getting the following warning:
No setter/field for post_image found on class com.isjieman.ocion.model.Post

Because in the Post class, you have an incorrect getter for the post_image field. The getter is defined as:
fun getPostImage(): String{
    return post_image
}

While it should be defined as:
fun getPost_image(): String{
    return post_image
}

You're getting the following warnings:
No setter/field for background_image found on class com.isjieman.ocion.model.User
No setter/field for profile_image found on class com.isjieman.ocion.model.User

Due to the exact same reason as above. You have these getters:
fun getBackgroundImage(): String{
    return background_image
}

fun getProfileImage(): String{
    return profile_image
}

Which should have been defined as:
fun getBackground_image(): String{
    return background_image
}

fun getProfile_image(): String{
    return profile_image
}

Bear in mind that Firebase Realtime Database serializes/deserializes any public fields and public properties that follow JavaBean naming conventions for getters and setters. That's the reason why you got those warnings.


text:
Q: Celery Python logging config to log DEBUG only from specified modules I'm trying to get django celery to log (to console) DEBUG (and higher) events coming from my modules (and not those of libraries). So starting celeryd with:
python hack/manage.py celeryd -E -l DEBUG -c 2

will mean that all DEBUG events are passed to console (which is a handler on my root logger). I'd like to modify this behaviour so that:

*

*DEBUG events from mymodule (and children) go to console

*DEBUG events from all other modules are ignored (eg: go to the Null Handler)

*all other events are processed as normal (eg: ERROR continues to go to the mail handler)

What is the best way to do this?

A: I have stubbled with this and there isn't a single "best" way to do this.  It's important to keep in mind a few things.

*

*Celery is run on production as a separate executable.  This seems obvious but that means that sharing log files with other stuff (like django) won't work nicely (See CELERYD_HIJACK_ROOT_LOGGER) so don't do it..

*Keeping things running in a similar manner on both production and your development environment is really critical so things don't go awry when you move to procution  (See CELERY_ALWAYS_EAGER and use it)

*Celery when run from manage.py will reference your settings.py file for configuration if you use settings

With that in mind here is how I would suggest you set up your logging to meet your needs.  First make sure that you have the logging level for your modules appropriately set.  See my other post on how to set up logging. Here is a condensed version to meet your needs
LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'standard': {
            'format': "[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s",
            'datefmt': "%d/%b/%Y %H:%M:%S"
        },
    },
    'handlers': {
        'console': {
            'level': 'DEBUG',
            '()': 'logutils.colorize.ColorizingStreamHandler',
            'formatter': 'standard',
            'stream': sys.stdout
        },
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler',
            'include_html': True,
        },

    },
    'loggers': {
        'django': {
            'handlers': ['mail_admins'],
            'propagate': True,
            'level': 'ERROR',
        },
        'mymodule': {
            'handlers': ['console', 'mail_admins'],
            'propagate': True,
            'level': 'DEBUG'

        },
    }
}

Then run it like this.
./manage.py celeryd --event --beat --settings=dev

What this does is sets two different handlers.  The first one is the console handler which reports out anything DEBUG and above.  The second is the mail handler which only looks at ERRORS and above.  Next is what gets reported from the loggers.  All django.* loggers will get reported to the any ERROR level handler (mail_admins).  And any of our modules get push DEBUG and above to both.
I think this is what you are after.


text:
Q: Java determine screen instance when monitor is added When a new monitor is added to a PC or a laptop that's already running a JRE instance, we find that the monitor just added is not considered an extension of a larger virtual screen, but rather JRE creates two separate virtual screens (each with (0,0) as the upper left coordinate as indicated by the GraphicsConfiguration associated the list of devices retrieved using getScreenDevices()). Restarting the JRE fixes the problem (i.e., the two screens are now treated as part of a larger virtual screen with separate starting coordinates).
My question is: How do you correctly determine the monitor (GraphicsDevice) instance where a Java Applet is currently displayed under the following circumstances:
    1. The user adds a monitor to his PC/laptop
    2. User drags the browser window running the Applet and repositions it in the new screen.
    3. Any JDialog or other frames need to open in the new screen, but this can only be done if we can automatically detect the screen instance where the Applet was repositioned.
As mentioned earlier, simply checking the position of the Java Applet against the bounds of the graphics configuration of the various screens does not work, as the bounds all start at (0,0).
I don't want my users or customers to have to kill and restart their Java.exe just because a new monitor was added so that screen instances can be correctly melded by JRE into a single Virtual Screen. Any ideas?


text:
Q: Renumbering ordered sequence in R and then use the mappings dt <- structure(list(X2 = c(-1, -1, 2, 2, 2, -5, 10, 16, 19, 10, -9,
-9, 23, 28, -21), X3 = c(-5, -9, 10, 12, 16, -21, 19, 20, 23,
24, -26, -27, 28, 29, -30)), class = "data.frame", row.names = c(1L,
2L, 3L, 4L, 5L, 8L, 6L, 7L, 9L, 10L, 11L, 12L, 13L, 14L, 15L))

Let's say we have a dt like this
    X2  X3
1   -1  -5
2   -1  -9
3    2  10
4    2  12
5    2  16
6   -5 -21
7   10  19
8   16  20
9   19  23
10  10  24
11  -9 -26
12  -9 -27
13  23  28
14  28  29
15 -21 -30

At the second column, I want to renumber -5 to -1, -9 to -2, 10 to 3, 12 to 4, 16 to 5, -21 to -6, etc..., and let's say they are the mappings.
The rule is to renumber the numbers in the second column while retaining their signs, to make dt become this:
    X2  X3
1   -1  -1
2   -1  -2
3    2   3
4    2   4
5    2   5
6   -5  -6
7   10   7
8   16   8
9   19   9
10  10  10
11  -9 -11
12  -9 -12
13  23  13
14  28  14
15 -21 -15

After this, I want to renumber the first column according to the mappings in the previous step, if the mappings exist:
    X2  X3
1   -1  -1
2   -1  -2
3    2   3
4    2   4
5    2   5
6   -1  -6
7    3   7
8    5   8
9    7   9
10   3  10
11  -2 -11
12  -2 -12
13   9  13
14  13  14
15  -6 -15

A: The first step of creating a "lookup" can be done by multiplying seq_along(dt$X3) by sign(dt$X3).
My understanding of the second step is that you want to find the indices of the original X3 where each entry in X2 is present. If there is no match, we keep X2 unchanged, otherwise we replace the value of the lookup at the matched index.
Assuming I have interpreted this correctly, we can do
lookup <- seq_along(dt$X3) * sign(dt$X3)
data.frame(X2 = ifelse(is.na(match(dt$X2, dt$X3)),
                       dt$X2, lookup[match(dt$X2, dt$X3)]),
           X3 = lookup)

#>    X2  X3
#> 1  -1  -1
#> 2  -1  -2
#> 3   2   3
#> 4   2   4
#> 5   2   5
#> 6  -1  -6
#> 7   3   7
#> 8   5   8
#> 9   7   9
#> 10  3  10
#> 11 -2 -11
#> 12 -2 -12
#> 13  9  13
#> 14 13  14
#> 15 -6 -15

Created on 2022-05-21 by the reprex package (v2.0.1)


text:
Q: How to subtract 2D data(lots) with 2D data(one) in MATLAB Hi I am new using MATLAB
What I am going to do is that
I have m-dimensional samples(data), which m is 2 here.
Data in MATLAB code is like this
X1 = [4,2;2,4;2,3;3,6;4,4];
X2 = [9,10;6,8;9,5;8,7;10,8];

I am going to subtract average of samples, which is
Mu1 = [3;3.8];

Then can I subtract each 2D data with average of samples in MATLAB code in one line

A: If I understand you correctly, you want to subtract the average Mu1 from your data (x1 and x2).
If so you could use the bsxfun function:
X1_subtracted = bsxfun(@minus, X1, Mu1')

which outputs:
X1_subtracted =
     1.0000   -1.8000
    -1.0000    0.2000
    -1.0000   -0.8000
          0    2.2000
     1.0000    0.2000

Note you are going to have to use ' with the Mu1 as X1 has the shape 5x2 while Mu1 has the shape 1x2.

A: To get X1 - mean(X1) you could try
X = [X1(:,1) - mean(X1(:,1)), X1(:,2) - mean(X1(:,2))]

this will output

    1.  - 1.8
  - 1.    0.2
  - 1.  - 0.8
    0.    2.2
    1.    0.2


text:
Q: determine whether point lies inside triangle The program needs to read the values of three coordinates

*

*P1(x1,y1)

*P2(x2,y2)

*P3(x3,y3)

as well as another coordinate P(x,y) and determine whether this point is inside a triangle formed from the 3 point above.

A: The proper way to do this is by calculating the barycentric coordinates of the fourth point given the three points of your triangle.  The formula to compute them is given at the end of the section "Converting to barycentric coordinates", but I hope to provide a less mathematics-intense explanation here.
Assume, for simplicity, that you have a struct, point, that has values x and y.  You defined your points as:
point p1(x1, y1);
point p2(x2, y2);
point p3(x3, y3);

point p(x,y); // <-- You are checking if this point lies in the triangle.

Now, the barycentric coordinates, generally called alpha, beta, and gamma, are calculated as follows:
float alpha = ((p2.y - p3.y)*(p.x - p3.x) + (p3.x - p2.x)*(p.y - p3.y)) /
        ((p2.y - p3.y)*(p1.x - p3.x) + (p3.x - p2.x)*(p1.y - p3.y));
float beta = ((p3.y - p1.y)*(p.x - p3.x) + (p1.x - p3.x)*(p.y - p3.y)) /
       ((p2.y - p3.y)*(p1.x - p3.x) + (p3.x - p2.x)*(p1.y - p3.y));
float gamma = 1.0f - alpha - beta;

If all of alpha, beta, and gamma are greater than 0, then the point p lies within the triangle made of points p1, p2, and p3.
The explanation behind this is that a point inside a triangle can be described using the points of the triangle, and three coefficients (one for each point, in the range [0,1]):
p = (alpha)*p1 + (beta)*p2 + (gamma)*p3

Rearranging this function gives you the formula to compute barycentric coordinates, but I feel like the steps to do so might be beyond the scope of the question.  They are provided on the Wikipedia page that I linked up top.
It follows that each coefficient must be greater than 0 in order for the point p to lie within the area described by the three points.

A: Take the average of the three given points. This new point P4 will always lie inside the triangle.
Now check if P and P4 lie on the same side of each of the three lines P1P2 P2P3 and P3P1. You can do this by checking the signs of the cross products (P -> P1) x (P -> P2) and (P4 -> P1) x (P4 -> P2) (where P->P1 is the vector from P to P1), and then the other two pairs.

A: Instead of P1, P2 and P3, lets assume the points as A,B and C.
          A(10,30)
            / \
           /   \
          /     \
         /   P   \      P'
        /         \
B (0,0) ----------- C(20,0)

Algorithm :
1) Calculate area of the given triangle, i.e., area of the triangle ABC in the above diagram.

    Area A = [ x1(y2 - y3) + x2(y3 - y1) + x3(y1-y2)]/2

2) Calculate area of the triangle PAB. We can use the same formula for this. Let this area be A1.
3) Calculate area of the triangle PBC. Let this area be A2.
4) Calculate area of the triangle PAC. Let this area be A3.
5) If P lies inside the triangle, then A1 + A2 + A3 must be equal to A.

Given below is a program in C:
#include <stdio.h>
#include <stdlib.h>

/* A utility function to calculate area of triangle formed by (x1, y1),
   (x2, y2) and (x3, y3) */
float area(int x1, int y1, int x2, int y2, int x3, int y3)
{
   return abs((x1*(y2-y3) + x2*(y3-y1)+ x3*(y1-y2))/2.0);
}

/* A function to check whether point P(x, y) lies inside the triangle formed
   by A(x1, y1), B(x2, y2) and C(x3, y3) */
bool isInside(int x1, int y1, int x2, int y2, int x3, int y3, int x, int y)
{
   /* Calculate area of triangle ABC */
   float A = area (x1, y1, x2, y2, x3, y3);

   /* Calculate area of triangle PBC */
   float A1 = area (x, y, x2, y2, x3, y3);

   /* Calculate area of triangle PAC */
   float A2 = area (x1, y1, x, y, x3, y3);

   /* Calculate area of triangle PAB */
   float A3 = area (x1, y1, x2, y2, x, y);

   /* Check if sum of A1, A2 and A3 is same as A */
   return (A == A1 + A2 + A3);
}

/* Driver program to test above function */
int main()
{
   /* Let us check whether the point P(10, 15) lies inside the triangle
      formed by A(0, 0), B(20, 0) and C(10, 30) */
   if (isInside(0, 0, 20, 0, 10, 30, 10, 15))
     printf ("Inside");
   else
     printf ("Not Inside");

   return 0;
}

Time : O(1)
Space: O(1)


text:
Q: Having trouble implementing onClickListener for a custom ListAdapter Listview I am having trouble implementing onItemClick for my ListView . I need to open a new activity on clicking the item in my ListView and pass the title/genre/rating/release year data to this new activity. I would also like to know how can I pass the thumbnail image of the clicked Item in ListView and display it in a new activity.
CustomListAdapter.java
public class CustomListAdapter extends BaseAdapter {
    private Activity activity;
    private LayoutInflater inflater;
    private List<Movie> movieItems;
    ImageLoader imageLoader = AppController.getInstance().getImageLoader();

    public CustomListAdapter(Activity activity, List<Movie> movieItems) {
        this.activity = activity;
        this.movieItems = movieItems;
    }

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

    @Override
    public Object getItem(int location) {
        return movieItems.get(location);
    }

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

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

        if (inflater == null)
            inflater = (LayoutInflater) activity
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (convertView == null)
            convertView = inflater.inflate(R.layout.list_row, null);

        if (imageLoader == null)
            imageLoader = AppController.getInstance().getImageLoader();
        NetworkImageView thumbNail = (NetworkImageView) convertView
                .findViewById(R.id.thumbnail);
        TextView title = (TextView) convertView.findViewById(R.id.title);
        TextView rating = (TextView) convertView.findViewById(R.id.rating);
        TextView genre = (TextView) convertView.findViewById(R.id.genre);
        TextView year = (TextView) convertView.findViewById(R.id.releaseYear);

        // getting movie data for the row
        Movie m = movieItems.get(position);

        // thumbnail image
        thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);

        // title
        title.setText(m.getTitle());

        // rating
        rating.setText("Rating: " + String.valueOf(m.getRating()));

        // genre
        String genreStr = "";
        for (String str : m.getGenre()) {
            genreStr += str + ", ";
        }
        genreStr = genreStr.length() > 0 ? genreStr.substring(0,
                genreStr.length() - 2) : genreStr;
        genre.setText(genreStr);

        // release year
        year.setText(String.valueOf(m.getYear()));

        return convertView;
    }

}

Main2Activity.java
public class Main2Activity extends AppCompatActivity  {
    // Log tag
    private static final String TAG = Main2Activity.class.getSimpleName();

    // Movies json url
    private static final String url = "http://api.androidhive.info/json/movies.json";
    private ProgressDialog pDialog;
    private List<Movie> movieList = new ArrayList<Movie>();
    private ListView listView;
    private CustomListAdapter adapter;

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

        listView = (ListView) findViewById(service_list);
        adapter = new CustomListAdapter(this, movieList);
        listView.setAdapter(adapter);

        pDialog = new ProgressDialog(this);
        // Showing progress dialog before making http request
        pDialog.setMessage("Loading...");
        pDialog.show();

        // changing action bar color
        //getActionBar().setBackgroundDrawable(
                //new ColorDrawable(Color.parseColor("#1b1b1b")));

        // Creating volley request obj
        JsonArrayRequest movieReq = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());
                        hidePDialog();

                        // Parsing json
                        for (int i = 0; i < response.length(); i++) {
                            try {

                                JSONObject obj = response.getJSONObject(i);
                                Movie movie = new Movie();
                                movie.setTitle(obj.getString("title"));
                                movie.setThumbnailUrl(obj.getString("image"));
                                movie.setRating(((Number) obj.get("rating"))
                                        .doubleValue());
                                movie.setYear(obj.getInt("releaseYear"));

                                // Genre is json array
                                JSONArray genreArry = obj.getJSONArray("genre");
                                ArrayList<String> genre = new ArrayList<String>();
                                for (int j = 0; j < genreArry.length(); j++) {
                                    genre.add((String) genreArry.get(j));
                                }
                                movie.setGenre(genre);

                                // adding movie to movies array
                                movieList.add(movie);

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }

                        // notifying list adapter about data changes
                        // so that it renders the list view with updated data
                        adapter.notifyDataSetChanged();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hidePDialog();

            }
        });

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(movieReq);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        hidePDialog();
    }

    private void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
    }
}

A: You can add the individual items of the model calls as Extras to an intent, or you can make the model class implement the Serializable interface and just add the whole object to the intent manually :
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Movie movie = (Movie) adapterView.getItemAtPosition(i);
            Intent intent = new Intent(view.getContext(), DetailActivity.class);
            intent.putExtra("mName", movie.getTitle());
            intent.putExtra("mRating", movie.getRating());
            intent.putExtra("mGenre", movie.getGenre());
            intent.putExtra("mYear". movie.getYear());

            //Get the Bitmap object from the NetworkImageView
            Bitmap bm = ((BitmapDrawable)((NetworkImageView)view.findViewById(R.id.image)).getDrawable()).getBitmap();
            //Can be added directly as an Extra, as Bitmap implements Parcelable
            intent.putExtra("mImage", bm);

            //OR make Moview implement Serializable and do this :
            //intent.putExtra("clickedObject", movie);

            startActivity(intent);
        }
    });

In the receiving activity, you can use getExtras() to get the values :
Bitmap bm = getIntent().getExtras().getParcelable("mImage");
imageView.setImageBitmap(bm);

A: You can send whole object movieItem and position of item click then In next activity you can extract them like this.
 listview.setOnItemClickListener(new OnItemClickListener(){

            @Override
            public void onItemClick(AdapterView<?> p1, View p2, int p3, long p4)
            {
                intent=new Intent(getBaseContext(),NextActivity.class);
            intent.putParcelableArrayListExtra("key", movielist);
intent.putExtra("IntKey",p3);
            }
        });

A: Everything works fine, after i changed the code with the help of people who answered to this question.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Movie movie = (Movie) adapterView.getItemAtPosition(i);
            Intent intent = new Intent(view.getContext(), Main3Activity.class);
            intent.putExtra("mName", movie.getTitle());
            intent.putExtra("mRating", movie.getRating());
            intent.putExtra("mGenre", movie.getGenre());
            intent.putExtra("mYear", movie.getYear());
            intent.putExtra("mServiceImage",movie.getThumbnailUrl());
            //OR make Moview implement Serializable and do this :
            //intent.putExtra("clickedObject", movie);
            startActivity(intent);
        }
    });

In the final activity i use Android-Universal-Image-Loader to load the image  from the url i passed from first activity.
  String mName = getIntent().getExtras().getString("mServiceImage");
  imageLoader.displayImage(mName, imageView);


text:
Q: How can I see my full PCA data on the ordination map? and how can I change geom point colors of my data in R? I am using a package called Vegan to calculate the PCA of my environmental samples and then plot my PCA values on the ordination space in R, I am using the data from an excel sheet where certain columns are chosen for the PCA calculation as below:
library(vegan)
library("readxl")
library(devtools)

SRSummer21 <- read_excel(file.choose())

SRSummer21PCA <- rda(SRSummer21[,c(3:17)], scale = TRUE)

summary(SRSummer21PCA)

ordiplot (SRSummer21PCA, display = 'species', type = 't')

ef <- envfit (SRSummer21PCA, SRSummer21[,c(41:43)])

plot (ef)

I try to add 3 other variables on top of the PCA calculation, as I don't want them to be in the original calculation, they are "Alkalinity", "Conductivity", and "pH", which are in columns 41 to 43 in my datasheet. Now when I plot the data, it gives me a simple plot with a set of black geom points as my data, however, I can't completely see the arrows of the data I added on top, I need to fit in the image so that all data and arrows can be seen in the space, I also like to change the shape and color of my data points according to their "Treatment" which is either of 3 different values: Cold, Moderate, Warm, which are written in column "Treatment" of my excel datasheet. you can see that part of the alkalinity arrow is present but the rest I can't see
Does anyone know how I can do this?
Thanks


text:
Q: How to turn multiple variables in a python list into a single variable? I'm not quite sure how to go about mashing multiple variables of a list as one single variable, for example if I start started with something like:
numbers = [1,2,3,4] # so numbers = [1,2,3,4]

How could I manage to get this as my output newnumber[1234]

A: numbers=[1, 2, 3, 4]
newnumber=int(''.join(map(str,numbers))) #1234