text:
Q: Android-studio java : Activity cannot be cast to AdapterInterface in fragment I have an ActivityController that contains a bottom navigation and I want to create interface between RecyclerviewAdapter and Fragment that are inside the bottom navigation to send the adapter position.
I get this error
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.my.money, PID: 10644
    java.lang.ClassCastException: com.my.money.Content.ControllerActivity cannot be cast to com.my.money.Content.ui.debt.AdapterInterface
        at com.my.money.Content.ui.debt.DebtFragment.onCreateView(DebtFragment.java:52)

DebtFragment :
public class DebtFragment extends Fragment implements View.OnClickListener, AdapterInterface {

    private FragmentDebtBinding binding;
    private ClassAdapterDebt adapter;
    private ArrayList<CustomListDebt> arrayList = new ArrayList<>();
    private Context context;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentDebtBinding.inflate(inflater, container, false);
        View view = binding.getRoot();

        binding.recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        adapter = new ClassAdapterDebt(arrayList, getActivity(), (AdapterInterface) getActivity());
        binding.recyclerView.setAdapter(adapter);
        showAllData();

        return view;
    }

    ...

    @Override
    public void onClickItem(int position) {
        Toast.makeText(getContext(), String.valueOf(position), Toast.LENGTH_SHORT).show();
    }

Interface
public interface AdapterInterface {
    void onClickItem(int position);
}

Adapter
private ArrayList<CustomListDebt> arrayList = new ArrayList<>();
private Context context;
private AdapterInterface adapterInterface;

// Constructor
public ClassAdapterDebt(ArrayList<CustomListDebt> arrayList, Context context, AdapterInterface anInterface) {
    this.arrayList = arrayList;
    this.context = context;
    this.adapterInterface = anInterface;
}

This in onBindViewHolder
holder.itemView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if (adapterInterface != null) {
            adapterInterface.onClickItem(position);
        } else {
            adapterInterface.onClickItem(0);
        }
    }
});

My try
I try to change this
adapter = new ClassAdapterDebt(arrayList, getActivity(), (AdapterInterface) getActivity());

To this :
adapter = new ClassAdapterDebt(arrayList, getActivity(), (AdapterInterface) context);

Error cannot cast will disappear and replaced with error :
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.my.money, PID: 22316
    java.lang.NullPointerException: Attempt to invoke interface method 'void com.my.money.Content.ui.debt.AdapterInterface.onClickItem(int)' on a null object reference
        at com.my.money.Content.ui.debt.ClassAdapterDebt$1.onClick(ClassAdapterDebt.java:68)

There are some notes during the build proccess, does this have any effect?
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: C:\Users\asus\AndroidStudioProjects\PencatatKeuangan\app\src\main\java\com\my\money\Content\ui\Adapter\RecyclerHomeAdapter.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

Any help will be very important

A: I found a way. To make the interface between the adapter and the fragment in the navHost a little different
The logic I use

*

*First I create an InterfaceAdapter between the adapter and the
activity_main.java used as the navHost controller.

*I sending data from activity_main.java to fragment using
InterfaceActivity. The data comes from the InterfaceAdapter.

InterfaceAdapter
public interface AdapterInterface {
    void sendPosition(int position);
}

InterfaceActivity
public interface AdapterInterface {
    void sendPosition2(int position);
}

ClassAdapter
private ArrayList<CustomList> arrayList = new ArrayList<>();
private Context context;
private AdapterInterface adapterInterface;

// Edit the contructor
public ClassAdapter(Context context, ArrayList<CustomList> arrayList, AdapterInterface adapterInterface) {
    this.context = context;
    this.arrayList = arrayList;
    this.adapterInterface = adapterInterface;
}

// example send position when onClick, do this in onBindViewHolder
holder.itemView.setOnClickListener((view) -> {
    adapterInterface.sendPosition(position);
});

MainActivity
public class MainActivity extends AppCompatActivity implements AdapterInterface {

    private Bundle bundle;
    private InterfaceActivity interfaceActivity;

    // alt+enter and implement method

    @Override
    public void sendPosition(int position) {
        interfaceActivity.sendPosition2(position);
    }

    public void dataHome(InterfaceActivity interfaceActivity) {
        this.interfaceActivity = interfaceActivity;
    }

}

Fragment in navHost
Do this in onCreateView
arrayList1.addAll(arrayList);
binding.recyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter = new ClassAdapter(getActivity(), arrayList1, (AdapterInterface) getActivity());
binding.recyclerview.setAdapter(adapter);

((MainActivity)getActivity()).dataHome(new InterfaceActivity() {
    @Override
    public void sendPosition(int position) {
        // do something
    }
});

Hope this will help someone


text:
Q: How to use jQuery code in meteor? so I can't make run JQuery code in meteor! I have added package meteor add jquery.
Solutions:
make jquery run in meteor OR convert JQuery code to JS code
Somebody knows how to solve it?
thanks a lot for your help!
Example
$(document).ready(function() {
    $('.collapsible').collapsible({
        accordion: false
    });
});

A: You don't need to explicitly add the jquery package inside a Meteor project because it usually already includes packages depending on jquery (namely the templating packages).
However, you can't just copy jQuery code examples inside a Meteor app and expect them to work without a little bit of extra work : in particular you need to initialize jQuery plugins only when the corresponding DOM elements have been inserted in the DOM by Blaze, the Meteor template rendering engine.
Assuming that you have the following (MaterializeCSS) template markup :
<template name="collapsible">

First

Lorem ipsum dolor sit amet.

Second

Lorem ipsum dolor sit amet.

Third

Lorem ipsum dolor sit amet.

</template>

You'll need to initialize the collapsible plugin inside an onRendered lifecycle event :
Template.collapsible.onRendered(function(){
  // we're using the template instance scoped jQuery
  this.$('.collapsible').collapsible({
    accordion: false
  });
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Syncronous waiting for a Future or a Stream to complete in Dart I'm playing with a tiny web server and I'm implementing one version using the async package, and one synchronous version executing each request in a separate isolate. I would like to simply pipe a file stream to the HttpResponse, but I can't do that synchronously. And I can't find a way to wait for neither the Stream nor a Future synchronously. I'm now using a RandomAccessFile instead which works, but it becomes messier.
One solution would be to execute a periodical timer to check if the future is completed (by setting a boolean or similar), but that is most definitely not something I want to use.
Is there a way to wait synchronously for a Future and a Stream? If not, why?

A: For future visitors coming here simply wanting to perform some task after a Future or Stream completes, use await and await for inside an async method.
Future
final myInt = await getFutureInt();

Stream
int mySum = 0;
await for (int someInt in myIntStream) {
  mySum += someInt;
}

Note
This may be technically different than performing a synchronous task, but it achieves the goal of completing one task before doing another one.

A: AFAIK there isn't a way to wait synchronously for a Future or a Stream. Why? Because these are asynchronous pretty much definitionally, and as you are discovering, the APIs are designed with asynchronous behavior in mind.
There are a couple of Future constructors, Future.value() and Future.sync(), that execute immediately, but I don't think these are probably what you have in mind.


text: Q: Laravel scheduler is scheduled dailyAt('07:00') but running at (00:00) means at midnight I have added a scheduler at dailyAt('07:00) but it is running at midnight(00:00) in laravel. I have also added the timezone parameter. Please help


text:
Q: how to install laravel already build website I've purchased laravel script http://ondemandbay.com/. I'm trying to install already build laravel website on local server(wamp) as well as live shared server (linux). please help to install script.
Thanks

A: You can use this command:
composer create-project laravel/laravel {directory} 4.2 --prefer-dist

Via Composer Create-Project
You may also install Laravel by issuing the Composer create-project command in your terminal

You need to install composer (https://getcomposer.org/). This is for the composer command.
{directory} can be replaced with the folder you want for your Laravel installation (for example /my-laravel-site).
More information can be found at the laravel documentation page: https://laravel.com/docs/4.2


text:
Q: Auto Layout defining constraints I have two buttons on my UIView. I want the horizontal distance between these two buttons should, be the 20% width of the superview?
Any help about this?

A: You can accomplish this using an empty dummy view in between the two buttons, whose width is 20 % of the width of the superview.
In code, it would look something like this:
// The important thing here is that the buttons are flush against the spacer
[superview addConstraints:
 [NSLayoutConstraint
  constraintsWithVisualFormat:@"[button1]-0-[spacer]-0-[button2]"
  options:0
  metrics:nil
  views:@{@"button1" : button1, @"button2" : button2, @"spacer" : spacer}]];
// Here, we set the width of the spacer to 20% of the super view
[superview addConstraint:
 [NSLayoutConstraint
  constraintWithItem:spacer
  attribute:NSLayoutAttributeWidth
  relatedBy:NSLayoutRelationEqual
  toItem:superview
  attribute:NSLayoutAttributeWidth
  multiplier:0.2
  constant:0]];


text:
Q: connection refused while connecting to Cassandra I am trying to run cassandra but everytime it is giving same error while connecting  ... is there anything i need to edit in config file or property file
('Unable to connect to any servers', {'127.0.0.1:9042': error(61, "Tried connecting to [('127.0.0.1', 9042)]. Last error: Connection refused")})
There is error while starting cassandra
# A fatal error has been detected by the Java Runtime Environment:
#
#  SIGSEGV (0xb) at pc=0x0000000106116a8c, pid=27359, tid=0x0000000000006e03
#
# JRE version: OpenJDK Runtime Environment (8.0_275) (build 1.8.0_275-bre_2020_11_16_16_16-b00)
# Java VM: OpenJDK 64-Bit Server VM (25.275-b00 mixed mode bsd-amd64 compressed oops)
# Problematic frame:
# V  [libjvm.dylib+0x564a8c]
#
# Failed to write core dump. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again
#
# An error report file with more information is saved as:
# /Users/sandhyasingh/hs_err_pid27359.log
#
# If you would like to submit a bug report, please visit:
#   http://bugreport.java.com/bugreport/crash.jsp
#
Abort trap: 6

A: It means that you're trying to connect to localhost but either:

*

*Cassandra isn't running, or

*you've set rpc_address to something other than localhost
Run this command to see which IP address CQL port 9042 is bound to:
$ sudo lsof -nPi -sTCP:LISTEN

You need to connect to the IP that the server is listening for clients. Cheers!

A: Came here with a completely different application but an exact match on build 1.8.0_275-bre_2020_11_16_16_16-b00. After changing Java versions (went to 1.8.0_292) the "fatal error" went away.


text:
Q: Fsolve equivalent in C++ I am trying to replicate Matlab's Fsolve as my project is in C++ solving an implicit RK4 scheme. I am using the NLopt library using the NLOPT_LD_MMA algorithm. I have run the required section in matlab and it is considerably faster. I was wondering whether anyone had any ideas of a better Fsolve equivalent in C++? Another reason is that I would like f1 and f2 to both tend to zero and it seems suboptimal to calculate the L2 norm to include both of them as NLopt seems to only allow a scalar return value from the objective function. Does anyone have any ideas of an alternative library or perhaps using a different algorithm/constraints to more closely replicate the default fsolve.
Would it be better (faster) perhaps to call the python scipy.minimise.fsolve from C++?
double implicitRK4(double time, double V, double dt, double I, double O, double C, double R){

    const int number_of_parameters = 2;
    double lb[number_of_parameters];
    double ub[number_of_parameters];
    lb[0] = -999; // k1 lb
    lb[1] = -999;//  k2 lb

    ub[0] = 999; // k1 ub
    ub[1] = 999; // k2 ub

    double k [number_of_parameters];
    k[0] = 0.01;
    k[1] = 0.01;
    kOptData addData(time,V,dt,I,O,C,R);

    nlopt_opt opt; //NLOPT_LN_MMA NLOPT_LN_COBYLA
    opt = nlopt_create(NLOPT_LD_MMA, number_of_parameters);

    nlopt_set_lower_bounds(opt, lb);
    nlopt_set_upper_bounds(opt, ub);
    nlopt_result nlopt_remove_inequality_constraints(nlopt_opt opt);

//    nlopt_result nlopt_remove_equality_constraints(nlopt_opt opt);

    nlopt_set_min_objective(opt,solveKs,&addData);
    double minf;
    if (nlopt_optimize(opt, k, &minf) < 0) {
        printf("nlopt failed!\n");
    }
    else {
        printf("found minimum at f(%g,%g,%g) = %0.10g\n", k[0],k[1],minf);
    }

    nlopt_destroy(opt);

    return  V + (1/2)*dt*k[0] + (1/2)*dt*k[1];```

double solveKs(unsigned n, const double *x, double *grad, void *my_func_data){

    kOptData *unpackdata = (kOptData*) my_func_data;
    double t1,y1,t2,y2;
    double f1,f2;
    t1 = unpackdata->time + ((1/2)-(1/6)*sqrt(3));
    y1 = unpackdata->V + (1/4)*unpackdata->dt*x[0] + ((1/4)-(1/6)*sqrt(3))*unpackdata->dt*x[1];

    t2 = unpackdata->time + ((1/2)+(1/6)*sqrt(3));
    y2 = unpackdata->V + ((1/4)+(1/6)*sqrt(3))*unpackdata->dt*x[0] + (1/4)*unpackdata->dt*x[1];

    f1 = x[0] - stateDeriv_implicit(t1,y1,unpackdata->dt,unpackdata->I,unpackdata->O,unpackdata->C,unpackdata->R);
    f2 =  x[1] - stateDeriv_implicit(t2,y2,unpackdata->dt,unpackdata->I,unpackdata->O,unpackdata->C,unpackdata->R);

    return sqrt(pow(f1,2) + pow(f2,2));

My matlab version below seems to be a lot simpler but I would prefer the whole code in c++!
k1 = 0.01;
k2 = 0.01;
x0 = [k1,k2];
fun = @(x)solveKs(x,t,z,h,I,OCV1,Cap,Rct,static);
options = optimoptions('fsolve','Display','none');
k = fsolve(fun,x0,options);
% Calculate the next state vector from the previous one using RungeKutta
% update equation
znext = z + (1/2)*h*k(1) + (1/2)*h*k(2);``

function [F] = solveKs(x,t,z,h,I,O,C,R,static)

t1 = t + ((1/2)-(1/6)*sqrt(3));
y1 = z + (1/4)*h*x(1) + ((1/4)-(1/6)*sqrt(3))*h *x(2);

t2 = t + ((1/2)+(1/6)*sqrt(3));
y2 = z + ((1/4)+(1/6)*sqrt(3))*h*x(1) + (1/4)*h*x(2);

F(1) = x(1) - stateDeriv_implicit(t1,y1,h,I,O,C,R,static);
F(2) =  x(2) - stateDeriv_implicit(t2,y2,h,I,O,C,R,static);
end


text:
Q: Cannot pull correct memory being used Currently creating a script that will record CPU and memory currently being used every second until you hit a key, which will then graph the results via gnuplot. I cannot seem to figure out how to pull the correct percentage of memory being used. The command I currently have down is...
echo "(free | grep Mem | awk '${print $3/$2 * 100"%"}')"

This displays the current amount of memory that is free and gives me the following results...
ex.
97.0305%
98.06%
94.07%
87.950%

I do not need to have the amount that is free being displayed, but the current amount being used. It should be pretty simple to take that number and subtract it from 100 (setting it as a variable or something), but what I would like would be to keep it in a one line echo command like I have above. Any suggestions? Thank you

A: Sure, it's easy
echo "(free | grep Mem | awk '${print (100 - ( ($3/$2) * 100) ) "%"}')"

and I don't think you need the echo "..." wrapper, try
free | grep Mem | awk '{print (100 - ( ($3/$2) * 100) ) "%"}'

and you don't need the grep ;-) ,  try
free | awk '/Mem/{print (100 - ( ($3/$2) * 100) ) "%"}'

and to have the absolute minimum of code, as  Karoly Horvath reminds us, (in this case) "All the parentheses are unnecessary", you  can use
free | awk '/Mem/{print 100 - $3/$2 * 100 "%"}'

Sorry, but I don't have a system I can test this on right now.
IHTH

A: $ free
             total       used       free     shared    buffers     cached
Mem:      15360000    5837240    9522760          0    1202040    2490640
-/+ buffers/cache:    2144560   13215440
Swap:      1048568          0    1048568

Why not use the 4th column (free) instead? Also, you don't need that grep. Example:
$ while true; do awk '/Mem/{printf "\r"$4/$2*100"%"}' <(free); done
62.0591%

** note use the \r only if you want to overwrite the previous output and don't use "while true" - it's just an example.
Happy hacking!
EDIT: I completely misread your question, disregard me :(
This will provide you with the current actual usage, according to free, with the buffers/cache removed:
awk '/Mem/{t=$2;getline;print $3/t*100"%"}' <(free)
13.9609%


text:
Q: Build statically linked binary with waf I'm trying to build a smbclient binary from the latest source using static linking so it can be portable.   I'm doing this on a RHEL 7 machine with all the configure dependencies installed already.
I tried the following but ldd still says the binary has dynamic dependencies.
# wget https://www.samba.org/samba/ftp/samba-latest.tar.gz
# tar -zxvf samba-latest.tar.gz
# cd samba-4.5.1/
# ./configure
# make SHARED=0 CC='gcc -static'
# ldd /root/samba-4.5.1/bin/default/source4/client/smbclient4
    linux-vdso.so.1 =>  (0x00007fff3ebb1000)
    libpthread.so.0 => /lib64/libpthread.so.0 (0x00007fb7bf35d000)
    libcmdline-credentials-samba4.so => /root/samba-4.5.1/bin/shared/private/libcmdline-credentials-samba4.so (0x00007fb7bf159000)
    libsmbclient-raw-samba4.so => /root/samba-4.5.1/bin/shared/private/libsmbclient-raw-samba4.so (0x00007fb7bef0e000)
    libtalloc.so.2 => /root/samba-4.5.1/bin/shared/private/libtalloc.so.2 (0x00007fb7bed04000)
    libsamba-credentials.so.0 => /root/samba-4.5.1/bin/shared/libsamba-credentials.so.0 (0x00007fb7beaef000)
    libsamba-errors.so.1 => /root/samba-4.5.1/bin/shared/libsamba-errors.so.1 (0x00007fb7be7a0000)
    libsamba-hostconfig.so.0 => /root/samba-4.5.1/bin/shared/libsamba-hostconfig.so.0 (0x00007fb7be56f000)
    libsamba-security-samba4.so => /root/samba-4.5.1/bin/shared/private/libsamba-security-samba4.so (0x00007fb7be34b000)
    ...

I'm not sure if this is because Samba now uses WAF for builds or not.  So I'm looking for help on this.


text:
Q: How to set environment variables from platform hooks in elastic beanstalk? I am trying to deploy a django application using elastic beanstalk. The app connects to the database using the environment variables.
DATABASES = {
  'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': os.environ['RDS_DB_NAME'],
    'USER': os.environ['RDS_USERNAME'],
    'PASSWORD': os.environ['RDS_PASSWORD'],
    'HOST': os.environ['RDS_HOSTNAME'],
    'PORT': os.environ['RDS_PORT'],
  }
}

I don't want to set these variables explicitly in EB console or option_settings, as they would appear in EB console in plain text.
The RDS credentials are stored in AWS Secrets Manager. As EB doesn't support AWS secrets manager yet, I wrote a platform hook to fetch the secrets and export the credentials as environment variables.
django_app/.platform/hooks/prebuild/set_db_credentials.sh
#!/bin/sh

# fetch secrets from secrets manager and store in db_credentials.json
aws secretsmanager get-secret-value --secret-id="$RDS_SECRETS_ID" --region="$RDS_SECRETS_REGION" --query=SecretString --output text > db_credentials.json

# export as environment variables
export RDS_HOSTNAME="$(jq -r '.host' db_credentials.json)"
export RDS_PORT="$(jq -r '.port' db_credentials.json)"
export RDS_USERNAME="$(jq -r '.username' db_credentials.json)"
export RDS_PASSWORD="$(jq -r '.password' db_credentials.json)"
export RDS_DB_NAME="$(jq -r '.dbname' db_credentials.json)"

rm db_credentials.json

The hook is running fine but the environment variables are not available for the app. Does anyone know how to do this ?

A: You could probably use a EB hook to create dynamically aws:elasticbeanstalk:application:environment .ebextensions config file.
So the idea is to create proper .ebextensions file for env variables using one of the EB hooks, before EB is going to read and execute your .ebextensions files.

A: A work-around solution is to save your secret in config file inside your hook. Setting the variable in the bash scripts won't work since Elastic Beanstalk likely run hooks in different shells (and provides no support for secret management so far).
For instance if you are using docker (or any platform that automatically reads env variable from the a ".env" file) the solution described here will work. Saving it into an .ebextensions might also be a solution but it doesn't seem to work with docker platform.


text:
Q: What means syntax like the following: @var=("","") I'm using eclipse and I put a script into my project. In a config-file there are php-statements like the following:
@ftp_mode=(0,0,0);
@ftp_user=("","","");

Eclipse marks them as syntax errors but everything works. So I want to know if this is an error and if not what means it? It looks like an assignment, but there's no $-sign ...
Thanks in advance.
Regards Binabik

A: If it's a config file for an app it's likely that the app parses the file internally so the syntax won't matter. It would generate a parse error in standard PHP syntax.

A: @ is used just before an expression to make the interpreter suppress errors that would be generated from that expression.
Source: wiki
Well... this might not be the case here, @ is used usually before function calls to suppress error messages from that function. As Clive pointed out, it might be some custom config file format. Also, you say "In a config-file there are php-statements"... is that file a .php file? If not why are you saying these are php statements?


text:
Q: Add dependency to existing pom.xml via shell Is there a way to add dependencies to an existing pom.xml via shell script?
Something like:
mvn dependency:add -DgroupID=com.acme -DartifactId=project

[Update]
Clarified that I want to add to an existing pom

A: I assume you would like to add that dependency to an existing POM, so the answer is no.

A: I'm not aware of any plugin doing this (apart from the m2eclipse wizard but that's not what you're asking for). This would be  a nice addition to the dependency plugin (in the spirit of dependency:get) though. You should suggest to add the feature: http://jira.codehaus.org/browse/MDEP (I did a quick search but couldn't find something close).


text:
Q: Back to Back Bar Chart with one common Y axis and two independent X values I am trying to create a back to back bar chart with State in the middle axis and two independent variables on either side.  Here is example data:
State   MedA    MedI
AK  0.056   46
AL  0.06    43
AR  0.052   39
AZ  0.055   20.5
CA  0.058   42
CO  0.0605  40
CT  0.06    29
DC  0.0625  47.5
DE  0.055   52
FL  0.057   55`

I used the below code to create two side by side charts, but I would like to combine so that state is the legend in the middle and MedA is on the left and MedI is on the right.
The other posts I checked seemed to require this to be done with a single variable on the x axis (such as gender) that had subgroups.
ga <- ggplot(state, aes(x=reorder(State, -MedA), y=MedA, fill=MedA)) +
  geom_bar(stat="identity") +
  labs(x="State",y="Med A") +
  ggtitle("Median A by State") +
  theme(plot.title = element_text(hjust = 0.5))+
  theme(axis.text.y = element_text(hjust=1, vjust=0.5, size=5))+
  coord_flip()

gi<-ggplot(state, aes(x=reorder(State, -MedI), y=MedI, fill=MedI)) +
  geom_bar(stat="identity") +
  labs(x="State",y="MedI") +
  ggtitle("Median I by State") +
  theme(plot.title = element_text(hjust = 0.5))+
  theme(axis.text.y = element_text(hjust=1, vjust=0.5, size=5))+
  coord_flip()

plot_grid(ga, gi,labels = "AUTO")

A: You may have to play around with the figures and axis labels but this should work:
library(ggplot2)
library(cowplot)

state<-data.frame(State=c("AK","AL","AR","AZ","CA","CO","CT","DC","DE","FL"),
                  MedA=c(0.056, 0.06, 0.052, 0.055, 0.058, 0.0605, 0.06, 0.0625, 0.055, 0.057),
                  MedI=c(46,43,39,20.5,42,40,29,47.5,52,55))

ga<-ggplot(state, aes(x=reorder(State, -MedA), y=MedA, fill=MedA)) +
  geom_bar(stat="identity") +
  labs(x="State",y="Med A") +
  ggtitle("Median A by State") +
  theme(plot.title = element_text(hjust = 0.5),
        legend.position="left",
        axis.text.y = element_text(hjust=1, vjust=0.5, size=5)
        )+
  coord_flip()+
  scale_y_reverse()+
  scale_x_discrete(position = "left")

gi<-ggplot(state, aes(x=reorder(State, -MedI), y=MedI, fill=MedI)) +
  geom_bar(stat="identity") +
  labs(x="State",y="MedI") +
  ggtitle("Median I by State") +
  theme(plot.title = element_text(hjust = 0.5),
        legend.position="left",
        axis.text.y = element_text(hjust=1, vjust=0.5, size=5)
        )+
  coord_flip()

plot_grid(ga, gi,labels = "AUTO")

Please note using the same colors for two different scales might be confusing.


text:
Q: Visual Studio 2008 linker error: ALINK operation failed (80070005) : Access is denied I have Visual Studio 2008 (9.0.30729.1 SP) installed on my computer and a build machine.  On my computer, a project builds fine.  On the build machine, I have started getting this error.
ALINK operation failed (80070005) : Access is denied
This is incredibly irritating because it doesn't say Access TO WHAT??? is denied.
I've tried rebooting the machine, and changing the output directory of the project.
It's a C++/CLI DLL.  The project links with a large number of libraries so it's not really practical to extensively check everything it links with, but a quick scan of the project and nothing seems to be missing or locked.
Anyway I can figure out what the heck linker is complaining about?  Sounds like a bug in the linker(1), but as I said I have the same Visual Studio installed in my PC and the project builds fine.
(1) You could argue that an error message that unhelpful IS a bug.

A: It's always good to have FileMon as a tool in your toolkit:  it can log every file operation, and will help showing what exactly the linker wants to do with what file.
(Find it at sysinternals.com)

A: In the output window, can you see where it is failing while doing what operation?
Often you might get an error because a file it is trying to modify is under source control / not writeable because of SOME reason.
Also, you might just be missing some file which it is looking for.


text:
Q: Lavatory — US terms used in the 1950s I am trying to find out what would be natural terms to refer to the lavatory in the US in the 1950s. I am specifically interested in how a woman who was a teenager at that time in a poor working class area of a city might refer to this in a novel written today.
The reason behind this request is that I am reading Elena Ferrante's "My Brilliant Friend" in the original Italian (L'Amica Geniale) in a language class in Britain. The native Italian teacher does not like the English translation, and in particular objects to the use of 'bathroom' to translate the Italian 'cesso' (on p.89 of the Italian edition). This is in a poor area of Naples, where the apartment blocks, I imagine, had no bathrooms (in the literal British sense of a room with a bath) but just lavatories, perhaps shared and on the landing.
I did live in the Chicago in the early '70s, and am familiar with 'john' and 'can' and several other terms one can find on the web (e.g. here) but wonder what an educated American woman in her 70s might use as a better translation. Obviously New York brownstones are not Naples slums, so I appreciate that there is no exact equivalent. But still, anything other than bathroom!
Addendum 1
There has been comments asking for clarification of the meaning of the Italian, cesso. Collins English–Italian indicates that it is currently a familiar equivalent to the more usual word for lavatory, gabinetto, and rather unsatisfactorily translates it as bog (Brit) — haven't heard that in years — and john (Am). Diziario Italiano da un affiliato di Oxford University (built into iOS) defines it as the Italian, Latrina (latrine), and dates it to 1300. Although, as has been pointed out, its contemporary use is to indicate a primitive or dirty lavatory, its use in the book is neutral and secondary — to indicate the facility in use in the apartment block where the author grew up. The reason I dislike bathroom is that it brings up the image of a room with a bath, which is quite out of keeping with the poor area of Naples in which the book is set. The lavatory may well have been of the 'Elephant's foot' type, still encountered in Italy today, and its cleanliness will have depended on social standards of hygiene etc. It would certainly have been different from a US lavatory of the time (except perhaps in poor rural areas) and it would not have had a bath in it. However, the question is what would the US equivalent have been called.
Addendum 2
The British (non-dialect) answer would almost certainly be lavatory, and I am starting to wonder whether this is really so 'un-American'. After all, this is the term used in US airplanes/aeroplanes.

A: My grandmother calls bathrooms in homes a wash closet and for bathrooms in public areas such as: offices, restaurants, theaters, etc.; she calls them washrooms. She was in her early twenties in the 1950's and grew up in a poor area in the outskirts of Chicago.


text:
Q: Sample size is $10^7$, what happens if we bootstrap with replacement using subsample of size $5000$? Let $\{X_1,X_2,\dots,X_n\}$ be a sample of $n$ iid observations of a random variable $X$, and let $\overline X_n = \frac{1}{n} \sum_{i=1}^n X_i$ be the sample mean.
Now suppose we want to use bootstrapping to estimate, for example, the variance of the sample mean. Let $\{X_1^{*(i)},X_2^{*(i)},\dots,X_n^{*(i)}\}$ be a sample with replacement from the original sample and let $\overline X_n^{*(i)} = \frac{1}{n} \sum_{j=1}^n X_j^{*(i)}$ be the sample mean for the $i$-th bootstrap sample.
Let $B$ be the number of bootstrap rounds. Then we have a bootstrap estimate of the variance.
$$
\text{Var}_{B,n} = \frac{1}{B-1} \sum_{i=1}^B (\overline X_n^{*(i)} - \overline X_B^*)^2, \quad \quad \text{where} \ \overline X_B^* = \frac{1}{B} \sum_{i=1}^B \overline X_n^{*(i)}.
$$
Suppose $n$ is very large and computing the bootstrap variance estimate will be computationally intensive. For example suppose we were using a slow computer and take $n=10^7$
To speed things up, we decide that instead of repeatedly drawing samples of size $n$ we will instead draw samples of size $m \ll n$ with replacement. For example, for $n=10^7$, we could take $m=5000$.
Let $\{Y_1^{*(i)},Y_2^{*(i)},\dots,Y_m^{*(i)}\}$ be a sample with replacement from the original sample $\{X_1,X_2,\dots,X_n\}$ and let $\overline Y_m^{*(i)} = \frac{1}{m} \sum_{j=1}^m Y_j^{*(i)}$ be the sample mean for the $i$-th bootstrap sample.
Now, this time we have the variance estimate:
$$
\text{Var}_{B,m} = \frac{1}{B-1} \sum_{i=1}^B (\overline Y_m^{*(i)} - \overline Y_B^*)^2, \quad \quad \text{where} \ \overline Y_B^* = \frac{1}{B} \sum_{i=1}^B \overline Y_m^{*(i)}.
$$
Is $\text{Var}_{B,m}$ a valid estimate of the variance of the sample mean? One issue that I have noticed is that since $m$ is such so much smaller than $n$ that we have effectively sampled without replacement when we computed $\text{Var}_{B,m}$. Is this a problem?

A: I'm no expert in the bootstrap, but I anticipate that using fewer samples in your bootstrap means that the uncertainty in mean will be inflated.
The standard error of the sampling distribution is inversely proportional to the square root of the sample size.  A smaller sample size thus means larger uncertainty in your estimates.  Its easy to see evidence of this.  Shown below are bootstrap samples of a dataset I've simulated.  Blue histogram is resamples using the full size of the dataset.  Red histogram is using 1% of the dataset.
Bootstrapping is embarrassingly parallelized.  I'm willing to bet there is a good solution to this problem which does not require sub sampling of the data.


text:
Q: Make images only accessible by Googlebot-Image and block other bots via robot.txt Is it possible to block bots, exept Googlebot-Image, to access my website's images via robots.txt?
I thought about this code:

User-agent: Googlebot-Image
  Allow: /images-folder/
User-agent: *
  Disallow: /images-folder/

But I'd like to know if this is the right way to do this before changing my robots.txt definitively. What do you think about it?

A: I think that you need a newline between User-agent and Allow/Disallow like the following
User-agent: Googlebot-Image
Allow: /images-folder/

User-agent: *
Disallow: /images-folder/


text:
Q: How is User Identity | Principal set during the application lifecycle In ASP.NET (MVC and WebAPI), how is the User Identity object initialized with the data from the FormsAuthentication cookie?
What I want to do is to use 2 types of authentication, cookie based and a custom header based one. Since the AuthorizeAttribute class only checks the User.Identity.IsAuthorized() method and uses no code specific to FormsAuthentication, then that means all I have to do is to manually setup the User.Identity object, whether in the global.asax or in a DelegatingHandler.
So, how do I setup User.Identity? How does the framework automatically set it up using FormsAuthentication?

A: Here is a related answer.
Identity can be set in a handler, in a module, or in Global.asax.  You can modify it at any point in the request lifecycle, but usually the best place to do it is in PostAuthenticateRequest.  At this point, FormsAuthentication has done it's work and you can augment or replace the HttpContext.Current.User.

A: ASP.NET MVC Controller has a Controller.User but Web API does not have one. It is currenty being requested to be put in.


text:
Q: Woocommerce wc_create_new_customer override on checkout I am using the guest checkout and have enabled "Automatically generate username from customer email" and "Automatically generate customer password", also I created a hidden input
<input class="input-checkbox" id="createaccount" <?php checked( ( true === $checkout->get_value( 'createaccount' ) || ( true === apply_filters( 'woocommerce_create_account_default_checked', false ) ) ), true) ?> type="checkbox" name="createaccount" value="1" /> <label for="createaccount" class="checkbox"><?php _e( 'Create an account?', 'woocommerce' ); ?></label> , which helps automatically create a user on checkout so customers didn't know that a user has been generated by their email. But if the same user, with the same email tries to fill the same email on the checkout field, receives the message: "An account is already registered with your email address. Please login." , which comes from wc_create_new_customer function inside the /woocommerce/includes/class-wc-checkout.php.
I would like to override  wc_create_new_customer function and return the $customer_id for the existing user instead of firing and error for already registered account. Tried hooks and filters, but none of them works. Any help?
Thanks in advance!


text:
Q: Mosaicking many tif files in ArcMap for ENVI my question is how to go about mosaicking ~120GB, 1200+ tif files into one raster within ArcMap. I am currently splitting up the region in smaller sets and then plan to mosaic all these together to form the one final file at the end. I'm using the Mosaic to New Raster tool. The reason I need a single file is so I can use ENVI classification functions on it.
Does anyone know if ENVI can use an ESRI Mosaic Dataset? Is there a better way to go about this (e.g. file type, etc)? I'm using unsigned 8bit data, 4 band imagery. It's taking a long time and I don't know if ArcMap will even be able to mosaic the total, final file at the end of this. I feel like this is one of those "I don't know what I don't know" problems. What am I missing?

A: I wouldn't use Mosaic or Mosaic to New Raser, they are slow and cumbersome. Create a Mosaic Dataset then use Copy Raster to export to a single image, this is considerably faster and can be viewed in ArcMap before export to ensure the mosaic is done well before committing to a huge process. I would use either ERDAS Img or GeoTiff as the output format - they can have sizes over 2GB, support multiband and have support for the majority of pixel types.
The Mosaic Dataset is an Esri format, it is unlikely that ENVI (or GDAL, or File Geodatabase Api) will be able to access the mosaic dataset directly but they export fairly quickly.
ENVI should be able to access a virtual raster which does not duplicate the rasters or mosaic but rather sees them as a tile set (much like a mosaic dataset)... Esri will be able to read a VRT but is significantly slower than a mosaic dataset to refresh.
If you have GDAL you can use GDALbuildVRT to create a virtual raster and then GDALADDO to add pyramids (to make it quicker to view).


text:
Q: Is it OK to create an alarm each time the application is launched? My application creates an alarm that repeats every day. Since it is not possible to know if an alarm is already registered, I create the alarm every time the application is launched.
Here is the function that is called at the beginning of the main activity (inside onCreate()):
public static void setAlarm(Context context) {
    Intent intent = new Intent(context, AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

    AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);

    Calendar firingCal = Calendar.getInstance(TimeZone.getTimeZone("Europe/Paris"));
    Calendar currentCal = (Calendar)firingCal.clone();

    Random rnd = new Random();

    // Each day between 1:00 AM and 1:30 AM (some jitter added)
    firingCal.set(Calendar.HOUR_OF_DAY, 1);
    firingCal.set(Calendar.MINUTE, rnd.nextInt(30));
    firingCal.set(Calendar.SECOND, 0);

    long intendedTime = firingCal.getTimeInMillis();
    long currentTime = currentCal.getTimeInMillis();

    if (intendedTime >= currentTime) {
        //set from today
        alarmManager.setInexactRepeating(AlarmManager.RTC, intendedTime, AlarmManager.INTERVAL_DAY, pendingIntent);
    } else {
        //set from next day
        firingCal.add(Calendar.DAY_OF_MONTH, 1);
        intendedTime = firingCal.getTimeInMillis();

        alarmManager.setInexactRepeating(AlarmManager.RTC, intendedTime, AlarmManager.INTERVAL_DAY, pendingIntent);
    }
}

Is it OK to recreate the alarm each time the application is launched? Should I use some flags on the PendingIntent (like update or cancel existing PendingIntent)?
Thanks!
Update: is it a problem if I use flag 0 instead of PendingIntent.FLAG_UPDATE_CURRENT from a performance perspective?


text:
Q: When should I use old( key, value) on blade template ? Is it necessary in latest laravel version? I noticed that in the older laravel blade template it was recommended to use old (key, value) to retrieve old values when form validation fails. (controller method handling the validation will post back to the form with the as-is data in request object)
Is it still necessary to use it in the latest laravel version ?
When should one use the old (key, value) function on the form fields on laravel blade template?

A: In Laravel there is a convention that most "get me some value" like functions provide a way to cover case "there is no value to get", therefore signature of most getter like functions looks like:
get('key', $default = null)

So in your case you would want to use old('key', default) in:

*

*create form when you as programmer set valid default value (not placeholder), perhaps date of some action for "today/now" old('publish_at', Carbon::now()).

*edit form old('publish_at', $post->publish_at), which means that on first load of edit form input field is pre-populated with data from database


text:
Q: How to set the MSBuild verision for TeamCity NuGet Installer? I'm trying to restore NuGet packages for a .NET Core solution using NuGet Installer TeamCity build step. The 'MSBuild auto-detection' chooses MSBuild v4.0 instead of v15.0 which is required for .NET Core projects:
[15:41:53][restore] Starting NuGet.exe 4.1.0.2450 from C:\TeamCity\buildAgent\tools\NuGet.CommandLine.4.1.0\tools\NuGet.exe
[15:41:53][restore] MSBuild auto-detection: using msbuild version '4.0' from 'C:\Windows\Microsoft.NET\Framework64\v4.0.30319'.
[15:41:53][restore] Nothing to do. None of the projects in this solution specify any packages for NuGet to restore.
[15:41:53][restore] Process exited with code 0

This leads to the compilation error in the 'MSBuild' TeamCity step that runs after the package restoring:
Assets file 'C:\TeamCity\...\MyProj\obj\project.assets.json' not found.
Run a NuGet package restore to generate this file.

For the 'MSBuild' TeamCity step I choose the MSBuildTools version manually as described in this SO answer:

But I didn't manage to find the similar setting for the 'NuGet Installer' step. Am I missing something?

A: As @PeterLai said, nuget version is the right place to look.
So, because I had the same problem here, I updated Nuget inside Teamcity / Administration / Integrations / Tools.
I moved from 3.4.3 to 4.6.2, and just rebuild.

Now it finds my visual studio 2017 msbuild, version 15!
BEFORE:
NuGet command: D:\...\NuGet.CommandLine.3.4.3\tools\NuGet.exe restore D:\...\proj.sln
...
MSBuild auto-detection: using msbuild version '14.0' from 'C:\Program Files (x86)\MSBuild\14.0\bin'.
AFTER:
NuGet command: D:\...\NuGet.CommandLine.4.6.2\tools\NuGet.exe restore D:\...\proj.sln
...
MSBuild auto-detection: using msbuild version '15.5.180.51428' from 'C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\15.0\bin'.

A: I managed to overcome this specifying the -MSBuildPath command line parameter:

A: 2 things,
It might be because it's running it from the folder Starting NuGet.exe 4.1.0.2450 from C:\TeamCity\buildAgent\tools\NuGet.CommandLine.4.1.0\tools\NuGet.exe, and not in the source code directory as you'd expect.
Have you got a packages.config file in your project?

A: If you are only using .NET Core / .NET Standard projects ("SDK-based" csproj), you don't need to restore with nuget.exe but can create an msbuild invocation that calls the Restore target:
msbuild /t:Restore the.sln

This also applies to non-core/standard projects (classic csproj) if they use the PackageReference package management format:


text:
Q: How to get value of child tag of a button tag I am trying to get src value from html button when user clicks it.
<button type="button" value="95" id="load" onclick="functionName(this.src,this.value);">

    Welcome
</button>

Successfully getting value from this.value but this.src is not giving any value.

A: It is normal, when u pass the this to the function, the this is your button, or in your case the this.value is the attribute value of your button and the this.src the value of your button attribute src, and you dont have the button src attribute
What can you do?:

*

*Pass the only the param this to your function and over there, get the value of your attribute value.

*Inside your function, through the this, get the children image and get it attribute src

Is something like this:

function functionName(button) {
  var buttonValue = button.value;
  var imageSrc = button.getElementsByTagName('img')[0].getAttribute('src');
}
<button type="button" value="95" id="load" onclick="functionName(this);">

  Welcome
</button>

A: this is referring to the button which doesn't have the src attribute. Image inside the button has the src attribute.
You can pass this to your function and access src of the image using button.children[0].src or button.getElementsByTagName('img')[0].src

function functionName(button, value) {
  let src1 = button.children[0].src;
  let src2 = button.getElementsByTagName('img')[0].src;
  console.log(src1, src2, value);
}
<button type="button" value="95" id="load" onclick="functionName(this,this.value);">

  Welcome
</button>

A: How about using the querySelector to target the image source
Example:

function functionName(button) {
  var src = button.querySelector("img").src;
  console.log(src);
}
<button type="button" value="95" id="load" onclick="functionName(this);">

    Welcome
</button>

A: Pass the context this & use children method.The button does not have src property,it belongs to the img tag, so children will give array of children.

function functionName(elem) {
  //elem will be button itself
  var _childImg = elem.children[0].src
  console.log(_childImg, elem.value)
}
<button type="button" value="95" id="load" onclick="functionName(this);">

                        Welcome

    </button>


text:
Q: Electron/Positron pair production in free space? Is it true that both linear momentum and energy cannot be conserved if the production of an electron-positron pair via photon annihilation were to occur in free space?

A: There are two ways that I could interpret this question. If you're interested in the interaction
$$ \gamma \to e^+e^- $$
taking place in free space, that's forbidden.  The reason is that the electron-positron pair always has a rest frame where the momentum is zero, but the photon has no such rest frame.
If, on the other hand, you're asking about
$$ \gamma  \gamma \to e^+ e^- $$
that is allowed.  The matrix element is exactly the same as for the more familiar process $e^+e^-\to\gamma\gamma$, at least in the limit where time-reversal is a good symmetry of quantum electrodynamics.  However the phase space for the $\gamma\gamma$ process is very different and it has never been observed with free photons. Much more common is an interaction between a hard (MeV+ energy) photon and the virtual photons that make up the electric field around atomic nuclei.

A: I guess that depends on what you mean by free space. Yes that is true that a gamma ray in a perfect vacuum can not decay by pair production since it can not conserve both energy and momentum. It will undergo pair production however if near a nucleus. A nucleus will enable energy and momentum to be conserved.


text:
Q: Setting IOCP Threads min/max in .NET core - verifying the effect of the change Currently it is possible to set minimum and maximum worker threads via runtimeconfig.json (https://learn.microsoft.com/en-us/dotnet/core/runtime-config/threading).
The docs mention this is equivalent to calling ThreadPool.SetMinThreads() https://learn.microsoft.com/en-us/dotnet/api/system.threading.threadpool.setminthreads?view=net-7.0
There doesn't seem to be a way to set the IOCP threads via the runtime config.
This got me thinking - why is it so, and more importantly - what is the effect of setting the values for IOCP thread in .NET core?
Also, how can I simulate and verify the effect of this setting in a test app?
Based on answer to this question (https://stackoverflow.com/a/28690956/2892378), I have created a test app in which I can observe the effect of setting both min and max threads in .NET Framework, unfortunately, I am not able to create an equivalent sandbox in .NET Core.


text:
Q: Javascript Storage Event Handler Returns Undefined I am trying to troubleshoot this by capturing any storage events that remove values from local storage.  I have an always open dummy page that begins an event listener on load as such:
window.addEventListener("storage", function (evt) { if (evt.newValue == null || (evt.oldValue != "" && evt.newValue == "")) {alert(evt.url);} });

The listener fires just fine.  That is not the issue.  My issue is that the alert(evt.url) returns "undefined" in mobile browsers.  Works just fine on Chrome.
The device is the Samsung Galaxy Tab running Gingerbread OS.  The browsers are Dolphin HD and the stock webkit browser.
Edit:  Tried it on the iPhone and all works just fine on Safari.  Also, the problem only seems to pertain to the url attribute.  oldValue, newValue and key all return values.

A: As far as I understand Web Storage Events have very limited adoption rate among browsers, most of the implementation to date are partial with only Opera (and Chrome) coming close to the W3C standard. See Wikipedia and this Blog post.
I dont think it is very far fetched that while desktop versions of Chrome support 'events' in Web Storage (somewhat), the functionality has not been ported to most Android devices which rely on system updates (rather than through the app market) to keep their browsers updated.


text:
Q: Why is my multiplying not working? I have to create a class and a tester program called fraction. A fractions is created and it can be simplified, multiplied, divided, added, and subtracted. When ever I use the multiply method it keeps returning the square of the second multiply and I am not sure why.
  class Fraction{

     private static int numerator;
     private static int denominator;

  public Fraction(int num, int den){
  numerator = num;
  denominator = den;
  }

  public static int getNumerator(){
      return numerator;
  }

  public static int getDenominator(){
     return denominator;
   }

  public static String getFraction(){
     return (numerator + "/" + denominator);
  }

  public static void setNumerator(int x){
    numerator = x;
  }

  public static void setDenominator(int x){
     denominator = x;
  }

  public static Fraction multiply(Fraction fraction, Fraction fractionTwo){
     Fraction newFraction = new Fraction(fraction.getNumerator() * fractionTwo.getNumerator(), fraction.getDenominator() * fractionTwo.getDenominator());
     return reduce(newFraction.getNumerator(), newFraction.getDenominator());
  }

  public static Fraction divide(Fraction fraction, Fraction fractionTwo){
     Fraction newFraction = new Fraction(fraction.getNumerator() * fractionTwo.getDenominator(), fraction.getDenominator() *fractionTwo.getNumerator());
     return reduce(newFraction.getNumerator(), newFraction.getDenominator());

  }

   public static Fraction commonDenominator(Fraction fraction, Fraction fractionTwo){
      int x = 2;
      Fraction multiply = new Fraction(x, x);
      for(x = multiply.getNumerator(); fraction.getDenominator() != fractionTwo.getDenominator(); x++){
          multiply.setNumerator(x);
          multiply.setDenominator(x);

       }
      multiply(multiply, fraction);
      multiply(multiply, fractionTwo);
      Fraction commonDenominator = new Fraction(x, x);
      return commonDenominator;
    }

    public static Fraction addition(Fraction fraction, Fraction fractionTwo){
       Fraction commonDenominator = commonDenominator(fraction, fractionTwo);
       Fraction fractionAdd = multiply(fraction, commonDenominator);
       Fraction fractionAddTwo = multiply(fractionTwo, commonDenominator);
       Fraction newFraction = new Fraction((fractionAddTwo.getNumerator() + fractionAdd.getNumerator()), (fractionAddTwo.getDenominator() + fractionAdd.getDenominator()));
       return newFraction;
    }

    public static Fraction subtraction(Fraction fraction, Fraction fractionTwo){
       Fraction commonDenominator = commonDenominator(fraction, fractionTwo);
       Fraction fractionAdd = multiply(fraction, commonDenominator);
       Fraction fractionAddTwo = multiply(fractionTwo, commonDenominator);
       Fraction newFraction = new Fraction((fractionAdd.getNumerator() - fractionAddTwo.getNumerator()), (fractionAdd.getDenominator() + fractionAddTwo.getDenominator()));
       return newFraction;
    }

    public static boolean equals(Fraction fraction){
       if(numerator == fraction.getNumerator() && denominator == fraction.getDenominator()){
          return true;
       }
       else{
          return false;
       }
    }

    public static double decimalValue(Fraction fraction){
       double decimal = (double)fraction.getNumerator()/fraction.getDenominator();
       return decimal;
    }
    public static Fraction reduce(int numerator, int denominator){

       if(numerator==0&&denominator==0){
          numerator = 0;
          denominator = 0;
       }
       else{
          for(int x = Math.max(numerator, denominator); x>0; x--){
             if(denominator == numerator){
                numerator = 1;
                denominator = 1;
             }
             else if(numerator == 0){
                numerator = 0;
                denominator = 1;
             }
             else if(numerator%x==0 && denominator%x==0){
                numerator = numerator/x;
                denominator = denominator/x;
             }
          }
       }
       Fraction fraction = new Fraction(numerator, denominator);
       return fraction;
    }

    public String toString(){
       reduce(numerator, denominator);
       return (numerator) + "/" + (denominator);
    }

 }

A: This method should be static, and then you call it Fraction.multiply(f1, f2)
public static Fraction multiply(Fraction fraction, Fraction fractionTwo) {
    Fraction newFraction = new Fraction(fraction.getNumerator() * fractionTwo.getNumerator(), fraction.getDenominator() * fractionTwo.getDenominator());
    return newFraction.reduce();
}

or method should use the current status of the object. Then you call it new Fraction(3,4).multiply(f1). This method can look like this:
public Fraction multiply(Fraction fractionTwo) {
    Fraction newFraction = new Fraction(numerator * fractionTwo.getNumerator(), denominator * fractionTwo.getDenominator());
    return newFraction.reduce();
}

So, all the code can look like this.
class Fraction {

    private int numerator;
    private int denominator;

    public Fraction(int num, int den) {
        numerator = num;
        denominator = den;
    }

    public static void main (String[] args){
        Fraction r1 = new Fraction (2,3); // 2/3
        Fraction r2 = new Fraction(3,4); // 3/4
        Fraction r3 = r1.multiply(r2); // 2/3 * 3/4
        System.out.println(r3); // print 1/2
    }

    public int getNumerator() {
        return numerator;
    }

    public int getDenominator() {
        return denominator;
    }

    public Fraction multiply(Fraction fractionTwo) {
        Fraction newFraction = new Fraction(numerator * fractionTwo.getNumerator(), denominator * fractionTwo.getDenominator());
        return newFraction.reduce();
    }

    public Fraction reduce() {
        for (int x = Math.max(numerator, denominator); x > 0; x--) {
            if (numerator % x == 0 && denominator % x == 0) {
                numerator = numerator / x;
                denominator = denominator / x;
            }
            if (denominator == numerator) {
                numerator = 1;
                denominator = 1;
            }

        }
        return this;
    }

    @Override
    public String toString() {
        return numerator + " / " + denominator;
    }
}

A: I won't give the same answer as you already got. So I answer regarding the toString() method.
Please keep in mind that any object inherits from the class object. And if you use the method toString() you override it from the object class.
Here you can see the methods inside the object class:
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html
As you can see, the toString() method represents the object where it is used and it requires no parameter. So if you implement it as follows:
public String toString() {
    return **your Code**;
}

Then this one should give no weird numbers and letters (which are actually the current memory address of the object).
All the best

A: I figured out why it was squaring the last number instead of multiplying the two numbers. It was because my instance variables were static an they weren't supposed to be.


text:
Q: How to terminate collection Iterations in postman if test fails I am using postman for API's automation. Created collection runner and while execution, I provided Iterations as 5. I am trying to stop the whole test if any scenario fails.
I tried with the below options. But the current test is failing but it's going to the next iteration. How can I stop whole iterations?

*

*postman.setNextRequest(null);

*throw new Error('halt')

A: As you mentioned you can use postman.setNextRequest(null) and do something like this in your test:
// I used 500 status code for stopping condition
if(pm.response.code === 500) {
    postman.setNextRequest(null)
}


text:
Q: Finding the NaN boundary of a matrix in MATLAB I have a very large (2019x1678 double) DEM (digital elevation model) file put as a matrix in MATLAB. The edges of it contain NaN values. In order to account for edge effects in my code, I have to put a 1 cell buffer (same value as adjacent cell) around my DEM. Where NaNs are present, I need to find the edge of the NaN values in order to build that buffer. I have tried doing this two ways:
In the first I get the row and column coordinates all non-NaN DEM values, and find the first and last row numbers for each column to get the north and south boundaries, then find the first and last column numbers for each row to get the east and west boundaries. I use these in the sub2ind() to create my buffer.
[r, c] = find(~isnan(Zb_ext)); %Zb is my DEM matrix
idx = accumarray(c, r, [], @(x) {[min(x) max(x)]});
idx = vertcat(idx{:});

NorthBoundary_row = transpose(idx(:,1)); % the values to fill my buffer with
NorthBoundary_row_ext = transpose(idx(:,1) - 1); % My buffer cells
columnmax = length(NorthBoundary_row);
column1 = min(c);
Boundary_Colu = linspace(column1,column1+columnmax-1,columnmax);
SouthBoundary_row = (transpose(idx(:,2))); % Repeat for south Boundary
SouthBoundary_row_ext = transpose(idx(:,2) + 1);

SouthB_Ind = sub2ind(size(Zb_ext),SouthBoundary_row,Boundary_Colu);
SouthB_Ind_ext = sub2ind(size(Zb_ext),SouthBoundary_row_ext, Boundary_Colu);
NorthB_Ind = sub2ind(size(Zb_ext),NorthBoundary_row, Boundary_Colu);
NorthB_Ind_ext = sub2ind(size(Zb_ext),NorthBoundary_row_ext, Boundary_Colu);

Zb_ext(NorthB_Ind_ext) = Zb_ext(NorthB_Ind);
Zb_ext(SouthB_Ind_ext) = Zb_ext(SouthB_Ind);

% Repeat above for East and West Boundary by reversing the roles of row and
% column

[r, c] = find(~isnan(Zb_ext));
idx = accumarray(r, c, [], @(x) {[min(x) max(x)]});
idx = vertcat(idx{:});

EastBoundary_colu = transpose(idx(:,1)); % Repeat for east Boundary
EastBoundary_colu_ext = transpose(idx(:,1) - 1);
row1 = min(r);
rowmax = length(EastBoundary_colu);
Boundary_row = linspace(row1,row1+rowmax-1,rowmax);
WestBoundary_colu = transpose(idx(:,2)); % Repeat for west Boundary
WestBoundary_colu_ext = transpose(idx(:,2) + 1);

EastB_Ind = sub2ind(size(Zb_ext),Boundary_row, EastBoundary_colu);
EastB_Ind_ext = sub2ind(size(Zb_ext),Boundary_row, EastBoundary_colu_ext);
WestB_Ind = sub2ind(size(Zb_ext),Boundary_row, WestBoundary_colu);
WestB_Ind_ext = sub2ind(size(Zb_ext),Boundary_row, WestBoundary_colu_ext);

Zb_ext(NorthB_Ind_ext) = Zb_ext(NorthB_Ind);
Zb_ext(SouthB_Ind_ext) = Zb_ext(SouthB_Ind);
Zb_ext(EastB_Ind_ext) = Zb_ext(EastB_Ind);
Zb_ext(WestB_Ind_ext) = Zb_ext(WestB_Ind);

This works well on my small development matrix, but fails on my full sized DEM. I do not understand the behavior of my code, but looking at the data there are gaps in my boundary. I wonder if I need to better control the order of max/min row/column values, though in my test on a smaller dataset, all seemed in order....
The second method I got from a similar question to this and basically uses a dilation method. However, when I transition to my full dataset, it takes hours to calculate ZbDilated. Although my first method does not work, it at least calculates within seconds.
[m, n] = size(Zb); %
Zb_ext = nan(size(Zb)+2);
Zb_ext(2:end-1, 2:end-1) = Zb; % pad Zb with zeroes on each side
ZbNANs = ~isnan(Zb_ext);
ZbDilated = zeros(m + 2, n + 2); % this will hold the dilated shape.

for i = 1:(m+2)
    if i == 1 %handling boundary situations during dilation
        i_f = i;
        i_l = i+1;
    elseif i == m+2
        i_f = i-1;
        i_l = i;
    else
        i_f = i-1;
        i_l = i+1;
    end
    for j = 1:(n+2)
        mask = zeros(size(ZbNANs));
        if j == 1 %handling boundary situations again
            j_f = j;
            j_l = j+1;
        elseif j == n+2
            j_f = j-1;
            j_l = j;
        else
            j_f = j-1;
            j_l = j+1;
        end

        mask(i_f:i_l, j_f:j_l) = 1; % this places a 3x3 square of 1's around (i, j)
        ZbDilated(i, j) = max(ZbNANs(logical(mask)));
    end
end

Zb_ext(logical(ZbDilated)) = fillmissing(Zb_ext(logical(ZbDilated)),'nearest');

Does anyone have any ideas on making either of these usable?
Here is what I start out with:
   NaN   NaN     2     5    39    55    44     8   NaN   NaN
   NaN   NaN   NaN     7    33    48    31    66    17   NaN
   NaN   NaN   NaN    28   NaN    89   NaN   NaN   NaN   NaN

Here is the matrix buffered on the limits with NaNs:
   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN
   NaN   NaN   NaN     2     5    39    55    44     8   NaN   NaN   NaN
   NaN   NaN   NaN   NaN     7    33    48    31    66    17   NaN   NaN
   NaN   NaN   NaN   NaN    28   NaN    89   NaN   NaN   NaN   NaN   NaN
   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN

Here is what I want to get after using fillmissing (though I have noticed some irregularities with how buffer values are filled...):
   NaN   NaN     2     2     5    39    55    44     8    17   NaN   NaN
   NaN   NaN     2     2     5    39    55    44     8    17    17   NaN
   NaN   NaN     2     2     7    33    48    31    66    17    17   NaN
   NaN   NaN   NaN     2    28    33    89    31    66    17    17   NaN
   NaN   NaN   NaN     5    28    55    89     8   NaN   NaN   NaN   NaN

To try and clear up any confusion about what I am doing, here is the logical I get from dilation I use for fillmissing
       0   0   1     1    1    1    1    1   1   1   0   0
       0   0   1     1    1    1    1    1   1   1   1   0
       0   0   1     1    1    1    1    1   1   1   1   0
       0   0   0     1    1    1    1    1   1   1   1   0
       0   0   0     1    1    1    1    1   0   0   0   0

A: A faster way to apply a 3x3 dilation would be as follows. This does involve some large intermediate matrices, which make it less efficient than, say applying imdilate.
[m, n] = size(Zb); %
Zb_ext = nan(size(Zb)+2);
Zb_ext(2:end-1, 2:end-1) = Zb; % pad A with zeroes on each side
ZbNANs = ~isnan(Zb_ext);
ZbDilated = ZbNANs; % this will hold the dilated shape.

% up and down neighbors
ZbDilated(2:end, :) = max(ZbDilated(2:end, :), ZbNANs(1:end-1, :));
ZbDilated(1:end-1, :) = max(ZbDilated(1:end-1, :), ZbNANs(2:end, :));

% left and right neighbors
ZbDilated(:, 2:end) = max(ZbDilated(:, 2:end), ZbNANs(:, 1:end-1));
ZbDilated(:, 1:end-1) = max(ZbDilated(:, 1:end-1), ZbNANs(:, 2:end));

% and 4 diagonal neighbors
ZbDilated(2:end, 2:end) = max(ZbDilated(2:end, 2:end), ZbNANs(1:end-1, 1:end-1));
ZbDilated(1:end-1, 2:end) = max(ZbDilated(1:end-1, 2:end), ZbNANs(2:end, 1:end-1));
ZbDilated(2:end, 1:end-1) = max(ZbDilated(2:end, 1:end-1), ZbNANs(1:end-1, 2:end));
ZbDilated(1:end-1, 1:end-1) = max(ZbDilated(1:end-1, 1:end-1), ZbNANs(2:end, 2:end));

This is a tedious way to write it, I'm sure there's a loop that can be written that is shorter, but this I think makes the intention clearer.
[Edit: Because we're dealing with a logical array here, instead of max(A,B) we could also do A | B. I'm not sure if there would be any difference in time.]

What @beaker said in a comment was to not use
mask = zeros(size(ZbNANs));
mask(i_f:i_l, j_f:j_l) = 1; % this places a 3x3 square of 1's around (i, j)
ZbDilated(i, j) = max(ZbNANs(logical(mask)));

but rather do
ZbDilated(i, j) = max(ZbNANs(i_f:i_l, j_f:j_l), [], 'all');

[Edit: Because we're dealing with a logical array here, instead of max(A,[],'all') we could also do any(A,'all'), which should be faster. See @beaker's other comment.]


text:
Q: separating out a wcf service, server, and client I have a solution in VS 2010: a WCF Service Library project ("NotifyService") and two Windows Forms projects, one for a server ("NotifyServer")and one for a client ("NotifyClient"). My goal is to have a duplex WCF service that will notify any number of connected clients when the server pushes out a notification. The clients do not need to communicate to the server except to subscribe and unsubscribe from the server's updates. However I seem to be running into problems nailing down the InstanceContext.
Here's the code for the WCF service:
<ServiceContract(
    CallbackContract:=GetType(INotifyCallback),
    SessionMode:=SessionMode.Required)>
Public Interface INotifyService
    <OperationContract()>
    Sub Notify(ByVal what As String)

    <OperationContract()>
    Sub Subscribe()

    <OperationContract()>
    Sub Unsubscribe()

End Interface

Public Interface INotifyCallback
    <OperationContract(IsOneWay:=True)>
    Sub OnNotify(ByVal what As String)
End Interface

<ServiceBehavior(
    ConcurrencyMode:=ConcurrencyMode.Single,
    InstanceContextMode:=InstanceContextMode.PerCall)>
Public Class NotifyService
    Implements INotifyService

    Private _callbacks As New List(Of INotifyCallback)

    Public Sub Notify(ByVal what As String) Implements INotifyService.Notify
        For Each callback As INotifyCallback In _callbacks
            callback.OnNotify(what)
        Next
    End Sub

    Public Sub Subscribe() Implements INotifyService.Subscribe
        Dim client As INotifyCallback = OperationContext.Current.GetCallbackChannel(Of INotifyCallback)()
        If Not _callbacks.Contains(client) Then
            _callbacks.Add(client)
        End If
    End Sub

    Public Sub Unsubscribe() Implements INotifyService.Unsubscribe
        Dim client As INotifyCallback = OperationContext.Current.GetCallbackChannel(Of INotifyCallback)()
        If _callbacks.Contains(client) Then
            _callbacks.Remove(client)
        End If
    End Sub
End Class

The Server form has a reference to the DLL created by the service library and self-hosts an instance of the WCF server in code:
Public Class frmServer
    Private _host As ServiceHost
    Private _notifier As NotifyService.NotifyService

    Public Sub go() Handles Me.Load
        _host = New ServiceHost(GetType(NotifyService.NotifyService), New Uri("net.tcp://localhost:10000"))
        _host.AddServiceEndpoint(GetType(NotifyService.INotifyService), New NetTcpBinding, "NotifyService")
        _host.Description.Behaviors.Add(New ServiceMetadataBehavior)
        _host.AddServiceEndpoint(GetType(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding, "mex")
        _host.Open()
        _notifier = New NotifyService.NotifyService
    End Sub

    Private Sub send() Handles Button1.Click
        _notifier.Notify("Foo")
    End Sub
End Class

For the most part that all seems to work. I can use the WcfTestClient to connect and it at least sees the services, though since it's a net.tcp binding with duplex enabled I can't actually test it using that client.
When I created the client I added a service reference called NotifyGateway. Here's the client form code:
<CallbackBehavior(
    ConcurrencyMode:=ConcurrencyMode.Single,
    UseSynchronizationContext:=False)>
Public Class frmClient
    Implements NotifyGateway.INotifyServiceCallback

    Private _service As NotifyGateway.NotifyServiceClient = Nothing

    Public Sub OnNotify(ByVal what As String) Implements NotifyGateway.INotifyServiceCallback.OnNotify
        MsgBox(what)
    End Sub

    Public Sub go() Handles Button1.Click
        _service = New NotifyGateway.NotifyServiceClient(New InstanceContext(Me), New NetTcpBinding, New EndpointAddress("net.tcp://localhost:10000/NotifyService"))
        _service.Open()
        _service.Subscribe()
    End Sub
End Class

Since I'm setting everything up through code, there are no app.config files. The problem I'm having is that my Subscribe method is never called. When debugging, I get an error after stepping through that line (not an exception) that says "Unable to automatically step into the server. The debugger failed to stop in the server process." When I go back to my server form and click the button designed to raise an event on the callback clients, it steps into the NotifyService class but the _callbacks list is empty, meaning the Subscribe method either never ran, or it never ran on that instance.
I have fought with this for almost a week. This is nearly an identical copy, at least on the service-side, to what was described here, and I've compiled that and it works. So I'm a little lost as to where I'm going wrong...

A: I think the problem is with InstanceContextMode:=InstanceContextMode.PerCall on your service. This means that a new instance of your service is created every time a method is invoked. So when you call _notifier.Notify("Foo"), it creates a new instance of your service class, which means it doesn't have any subscribers. There are a few ways you can approach this:

*

*One way would be to set InstanceContextMode:=InstanceContextMode.Single, which means there will be a single instance of your service class which will handle all requests for the lifetime of your service. Together with your other setting of ConcurrencyMode:=ConcurrencyMode.Single, this can be a bottleneck if you expect your service to be used heavily, since only one request will ever be processed at a time. You can change it to ConcurrencyMode:=ConcurrencyMode.Multiple, but then you'll have to be responsible for handling thread-safety inside your class, since that allows the single instance of your class to handle multiple requests at the same time.

*Another approach would be to change your _callbacks collection to be a static (Shared in VB.NET) member. That way your list of subscribers would be the same across all instances of your service class. In this approach, you would again be responsible for handling thread-safety concerns, since there will be multiple instances of your service class potentially accessing the single collection at the same time from different threads.

*You could use some type of persistence mechanism, such as a database. This would be the most involved, since you would basically have to re-construct a new proxy to each subscriber for each notification, but has the advantage of not losing all your subscribers if your application is shut down. That sounds like it's probably not the best fit for your situation.


text:
Q: Python find elements in a list and return true or false I'm in stuck with a research elements in list of strings.
I take a text with numbers(string) and I try to find symbols like '+' or '-'
My code:
 Lista=np.array([s for s in text])
 y=np.where(Lista=='+')
 if y==[]: /*so, if it's void*/
        print("any elements")
  else:
        print("yes")

I try to do this, because I'd like to create a calculator, and for this moment I can do just + operation (in second part of my code, I use split("+") and cast string to int).
So I'd like to create with if, else, elif a struct similar to switch case. Something like: if ('+') -> do this operation, else if ('-')-> do this operation, ecc.
Obviously, I'd like to create 4 y=np.where(lista='+'/='-'/=''...) and for everyone create if else. So if in thirst case I don't find '+':pass. If in second case I don't find '-' :pass. If in third case I find '' : do the moltiplicato. This things I try to do with y==[] or y!=[]. When I print the results of y=np.where(lista='+'), so I see that it returns array[1] or array[], but if I try to make this as a condition, it doesn't work.
Example. In my calculator I wrote 4+5. 4+5 it's saved in a var called text. I convert the var text, in Lista=np.array([s for s in text]).
After I try to search in Lista the symbol '+' with y=np.where(Lista=='+'). In console I see that it's at first position, so in array[1]. So with if condition
    if y==[]:
       print("the list it's void")
       pass
    else: print("the elemnt it's at firt position")
    Lista=np.array([s for s in text.split('+')])
    v=[int(v) for v in Lista]
    c=sum(v)
    print(c)

But, when I wrote 4+5, with the condition y==[] it's print that the list it's void, but it doesnt true because at arrayIndex I see that in position y[1] ther're a '+'.
Example in Java code. I'd like to have the same in Python
public class Main {
    public static void main(String[] args) {
        boolean findSymbol=true;

        char [] p = {31, 28, 31, 30, 31, 30, 31, '-'};
        for (char c : p) {
            if (c == '+') {
                findSymbol= true;
                System.out.println("let's do something");
            } else
                findSymbol = false;
            System.out.println("Nope");

            if (c == '-') {
                findSymbol=true;
                System.out.println("let's do something");

            }else
                findSymbol = false;
            System.out.println("Nope");

            }
        }

}

A: Python 3.10 has a match statement which is the pythonic version of a switch.
Anyhow as you said you can get the same result with if ... elif ... else:
if s=='+':
    ##handle addition
elif s=='-':
    ##handle subtraction
elif s=='*':
    ##handle multiplication
##etc
else:
    ##did not match any previous check, raise exception or something


text:
Q: How to dynamically rebind JQuery Objects I am making a module for the Joomla! page of a client that uses Ajax to render different queries to the database. The result of these queries is that I regenerate the entire HTML code of the different DIVs. Within my jQuery Object I have a  function named as cache() that stores all objects that I need to attach them the different events. My problem is that every time I regenerate the HTML code from any of these divs, I have to rebuild all the objects, so I've created a new function recache() to make this work more easy.
I guess this is not the best procedure.
Is there any way to keep alive these handlers without having to call this function cache() each time, or is there any way to rebind dynamically this objects?
Thank you!
Here my code:
    var Object = {
        init: function() {
            this.cache();
            this.bindEvents();
            return this;
        },

        cache: function() {
                   OBJECTS....
                       this.nameObject = $('#anchor');
                       etc..
        },

        recache: function() {
            Objects to be recached as needed.
        },

        bindEvents: function() {
            EVENTS attached to the objects.
                        this.nameObject.on( 'click', 'context', this.nameFunction );

        },

                    nameFunction: function() {
                        #CODE....
                    }

                }; //END Playlist (Object)

window.Object = Object.init();

I usually use on() function instead of delegate(), live() or bind(), butI'm not sure this is exactly my problem.
Thanks in advance!

A: Bind the event handler on a parent element and use event delegation to handle the events. By binding the event handler on a parent element you don't need to bind it on all the child elements.
/HTML/
<div id="container">
    <button id="button1" class="click">button with click</button>
    <button id="button2" class="click">button with click</button>
</div>

/Javascript/
// use this
$("#container").on("click", ".click", function(){
    alert(this.id + ": I've been clicked.");
});

// don't use this
$(".click").on("click", function(){
    alert(this.id + ": I've been clicked.");
});

A: You hinted at the right plan: use .on(). Remember though that when you're delegating a listener, you need to delegate to a listener that will not be destroyed.
Or in other words:
// will not do anything useful for this scenario:
$('.something').on('click', function() { /* ... */ });

is different from
// use the document as a listener: will work but not efficient
$(document).on('click', '.something', function() { /* ... */ });

which is different from
// use a closer ancestor that is NOT destroyed. Best option if you can
$('#someAncestor').on('click', '.something', function() { /* ... */ });


text:
Q: Updating a SQL Server table with random names I am trying the following:
update [Employees] set Last_User =

(select top 1 name from
(select 'John' as name
union select 'Tim' as name
union select 'Jane' as name
union select 'Jack' as name
union select 'Steve' as name
union select 'Ann' as name
)

as names order by newid())

but keep getting the same name for all rows. how can I make it vary?
Note: names are entered in query and do not come from another table.
Thanks

A: You are trying to update the whole column instead of updating each row, hence the first value which is getting generated is updated to all the rows, you can do the intended task by using T-SQL
DECLARE @counter int = 1

WHILE @counter <= (SELECT COUNT(1) FROM [Employees]) --or any speific row set you want to modify
BEGIN

UPDATE a
 set Last_User =
(SELECT top 1 name from
(SELECT 'John' as name
UNION SELECT 'Tim' AS name
UNION SELECT 'Jane' AS name
UNION SELECT 'Jack' AS name
UNION SELECT 'Steve' AS name
UNION SELECT 'Ann' AS name
)

AS names ORDER BY NEWID())
 FROM (SELECT *,ROW_NUMBER() OVER (ORDER BY Last_User)rnum FROM [Employees])a
WHERE a.rnum = @counter

SET @counter = @counter + 1

END

A: You can try this approach:
declare  @Employees table (last_user nvarchar(100))
insert @Employees values('a')
insert @Employees values('b')
insert @Employees values('c')

declare @temp table(name nvarchar(100))
insert into @temp values('John')
insert into @temp values('Tim')
insert into @temp values('Jane')
insert into @temp values('Jack')
insert into @temp values('Steve')
insert into @temp values('Ann')

update @Employees set Last_User =

(select top 1 name from
    @temp as names order by newid())

select * from @Employees


text:
Q: An integral related to QFT How to show $$\displaystyle\int\int\int f(p,p')e^{ip\cdot x-ip'\cdot x}d^3pd^3p'd^3x=(2\pi)^3\int f(p,p)d^3p$$  ?
I have $p\cdot x=Et-\bf p\cdot x$

A: So, following the suggestion of Olaf and Vladimir,
assume that the momenta are on-shell, so that $E = E(p)$.
Then we first do the position integral to get a delta function
which lets us perform one of the momentum integrals:
$$\begin{align}
\int d^3p\,d^3p'\,d^3x\   f(p,p')e^{ip\cdot x-ip'\cdot x}
&=\int d^3p\,d^3p'\,d^3x\  f(p,p')e^{i(E(p)-E(p'))t - i(\vec p - \vec p')\cdot\vec x}\\
&=(2\pi)^3\int d^3p\,d^3p'\  f(p,p')e^{i(E(p)-E(p'))t}\delta^{(3)}(\vec p - \vec p')\\
&=(2\pi)^3\int d^3p \  f(p,p)
\end{align}$$

A: Are you sure that $x\cdot p$ is not just the ordinary 3D dot product? T
Because in this case you can use the property of the delta function,
$$\int  e^{i(p-p')\cdot x}  d^3x = (2\pi)^3 \delta^{(3)}(p-p')$$
which you can use to integrate out $p'$.


text:
Q: How can I connect to bluetooth headphones from command line? I have a pair of bluetooth headphones that, when started (or restarted) don't always trigger my computer to automatically connect to them. In those cases I have to go into the sound menu, find the headphones on the list of playback devices and right click -> connect.
Thats kind of tedious. Is there a way to do this from command line?

A: You can simply make the headset as the Default Playback Device. This should work and is a simple solution.


text:
Q: Can CDN caching prevent DoS attacks? Let's say I use Cloudflare to cache my images, CSS, and JS files. Requests for the HTML content itself still hit my server and an attacker could use that to his advantage.
However, if I tell Cloudflare to cache HTML as well, would a DoS attack be possible? If every single asset, including the HTML, is served by the CDN, my server wouldn't be bothered at all. No matter how much load the attacker throws, it would be handled by the CDN and wouldn't reach my server, thus making it immune to (D)DoS attacks. Is my theory correct?

A: Real visitors browsing your website will only request existing objects that can be cached and which will be served from the CDN caches as long as they don't expire.
For that kind of visitor your web server will only see the incidental request from the CDN revalidating or refreshing cached objects. And when the CDN caches haven't expired to those vistors your website will appear online even when your actual  web server is not.
An attacker attempting to (D)DoS your website by requesting those valid resources won't achieve much either.
But rather than requesting actual content a malicious user can also generate random and unique URI requests.
Those URI's won't already be present in the CDN caches because  they have never been requested before. Therefor the CDN will need to make a request to your webserver to load and start caching either the actual content on that URI or an error response.
Before the CDNs threshold levels are reached and DDoS protection kicks in and starts rate limiting or outright dropping such random URI requests, you can still expect to see quite a surge in requests being forwarded by the CDN and reaching  your web server.
But those probably won't be enough to knock your server out.

A: Yes, you are generally correct. However you need to make sure that you do not expose your public IP address to the attacker (make sure you proxy all the DNS entries through CDN). Also, if your website makes an HTTP request to your backend server then an attacker could potentially exploit that to create a DDoS attack.
On the other hand if you are hosting purely a static website and do not expose your public IP you should be safe.


text:
Q: Communicate with a device with an IP set to a broadcast address I have a wireless IP camera that I am setting up to use for Timelapse purposes.
When configuring a static IP selected 192.168.0.255 so as to be memorable, I latter found out (after I couldn't connect to the device) that this is a broadcast address and as a result I have not been able to communicate with the device.
What can I do to regain connection so I can set a new IP, there is no hardware reset button.
Other details

*

*Router IP 192.168.0.1

*Subnet mask 255.255.255.0

A: If you set your IP address to 192.168.0.2 subnet mask 255.255.0.0, when your PC tries to communicate with the router, it won't matter that the router address is 192.168.0.255 because from your PC's perspective, the broadcast address is 192.168.255.255.
So packets going to the router should be fine.  The router will respond to 192.168.0.2 which it thinks is part of its local network, and so will send them direct (it has no awareness of your subnet mask).
If you try and ping it, and it doesn't reply, it may be because it won't respond to an arp request on the broadcast address.  If so, then  you can confirm this by doing this on your PC:
arp -a

If this doesn't have an entry for 192.168.0.255, then you can add one:
arp -s 192.168.0.255 mac_address_of_router

The MAC address should be on a label on the router, and you enter it in the format 00-10-54-CA-E1-40.

A: There must be a way to factory reset the device (if there is no dedicated switch, it can usually be done by pressing a combination of buttons on power-up or shorting specific contacts on the circuit board), I suggest reading the manual (or finding it online) and seeing how to do a factory reset.
As far as I am aware, there is no way to connect to the device with an invalid IP address over network, it would be like trying to post a letter without knowing the address.
If you're unable to find the manual or the manual does not specify how to reset the device, I suggest a thorough googling, someone has probably had the same problem and found a way to factory reset the device.
For future reference, giving the make and model of the device in question will make answering much easier.


text:
Q: Unity launcher right click focus When right clicking an icon in the Unity launcher, the menu comes up but i cant select anything. Its like Unity does not have focus at all.
I have to click somewhere on the desktop and then the right click menu works correctly. This happens on all my installations of 11.10, but only after login. This is a serious bug since it totally breaks Unity if you dont know how to get around the bug.
Anyone experienced this ?

A: Yes. It is a known bug and people are working on it; https://bugs.launchpad.net/unity/+bug/819721. It seems to have been fixed, and you can expect to get an update after things have been properly tested. Unity 4.26 should not have this issue.


text:
Q: Elastic Beanstalk randomly goes offline My elastic beanstalk environment keeps switching the environment health from Warning to OK from OK to Warning almost every 15 minutes or so.
The Scale settings is Min: 2 max: 4 and there is 4  EC2 instances running.
Can somebody please help?
Screenshot

A: I can't tell from your screenshot if new instances were created, so it can be wither the scaling trigger being met, or the load balancing one.
Your load balancer trigger is configured here:
Configuration => Load Balancer => EC2 Instance Health Check

the default value is to perform an HTTP request to the root path (/), but you can configure it as you see fit. In most cases degradation happens because your app response time isn't fast enough. You can change the parameters, or fix the app.
As for the scaling trigger, it's configured here:
Configuration => Scaling => Scaling Trigger

By default this is set to NetworkOut, which is the number of bytes sent out from the node and has nothing to do with your server being overloaded. I'm not sure why beanstalk decided to use this metric by default, but you can change it to CPU utilization or any other metric documented here.


text:
Q: Can a beam of light be modulated close to it's frequency? I'm wondering if it would be possible to modulate a signal using photon pulses - where the frequency of the signal would be close to the frequency of the light. Also would it be possible to transmit multiple of these signals in parallel and have them not interfere with each other.
Thought experiment A:
I have a laser: green(500nm, 600kGhz) which can be controlled to emit individual photons. I feed a binary signal into this laser with the same frequency as the light frequency (600kGhz). For each 1 in the signal, the laser will emit a photon and for each 0 the laser will not emit a photon. Example: For an '1 1 0 1' bit stream - the laser is emitting photon A, waiting for the photon A to travel it's wavelength, it emits photon B, waits for photons A+B to travel their wavelength, does nothing, waits for photons A+B to travel another wavelength and then emits photon C. Using this scheme, I can transmit 600,000 GigaBits of information / sec to an observer 1 mile away by having a light sensor which would either sense a photon or not sense a photon at each wavelength interval.
Would this be possible ? How about if I emit/not emit a photon at 2*wavelength period ? What's the maximum signal frequency for which this would work ?
Thought experiment B:
Assuming the previous scenario works I have 2 signals + 2 lasers as described above :green(500nm, 600kGhz) & red(700nm, ~430kGhz).
Can I pass the two photon 'beams' through an optical fiber (ignoring material properties of the fiber such as loss & lower light speed), have the mixed beams emerge 1 mile away, separate them using a prism and measure the original signal on each beam using a photon sensor ?
Basically Would I be able to transmit a 600,000 GigaBit/s signal + a 430,000 GigaBit/s signal through an optical fiber using this method ? Or would the two signals somehow interfere with each other ?
Thanks!

A: There are (at least) a couple problems with your proposals:
In experiment A, you start with "a laser ... which can be controlled to emit individual photons." However, such a laser is, as far as I know, impossible to make, because the stimulated emission process that generates the output in the laser is a random process, emitting photons at random times. This "shot noise" problem (although it's normally looked at as a receiver problem rather than a source problem) gives a well-known result in optical communications that it requires about 9 photons per bit to transmit a signal reliably.
As for experiment B, when you modulate a signal, the signal bandwidth is spread by the bandwidth of the modulation. So if you modulate a 600 THz signal with a 600 THz signal, the bandwidth of the modulated signal is now 600 THz. The initially "green" beam is now spread across the whole spectrum (from 300 - 900 THz). This effect will prevent demultiplexing your 600 THz signal (modulated at more than 50 THz) from your 650 THz signal at the receiving end.


text:
Q: Can't add string to a string type variable in Python I wanted to make a very simple network scanner in python, and I wrote this:
import subprocess
ip_range = input("Enter ip range:")
start_ip = input("Enter start ip:")
end_ip = input("Enter end ip:")
result = "Result:"
for ping in range(int(start_ip), int(end_ip)):
    ip = ip_range + str(ping)
    connect = subprocess.call(["ping", "-c1",ip])
    if connect == 0:
        result += "---"
        result += "Ping to ",ip,"was OK"
        result += "---"
    else:
        result + "Couldn't ping to " + str(ip)
        result + "---"
        pass
print(result)

All of them work correct except one thing.
In this part
result + "Couldn't ping to " + str(ip)
result + "---"

The result doesn't add up to this code, I mean it just write result.

A: result + "Couldn't ping to " + str(ip) is an expression, not a statement. You don't assign that value to result. Try changing the + to +=. That will store the value result + "Couldn't ping to " + str(ip) in result.


text:
Q: Account Contact roles, pre-populating opportunity /contract contact roles i am hoping you can help,i am wondering is there a way i can populate the account contact roles, and it populates the contract,opportunity  contact roles automatically
For example In the scenario below image "ACCOUNT CR" is the contact roles on the client test1, they would like these contacts roles to be poplated on image "CONTRACT CR"
Looking forward to your response

A: Consider to implement an after insert /(Update) trigger, which queries contact roles from account-level and stores them as opportunity- / contract-contact-roles (opportunity team) records.
Here is a pseudo code implementation:
trigger OppContactRole on opportunity (after insert)
{
    Set<Id>accountIds = new Set<Id>();
    // To-Do: Collect account ids
    Map<Id, Account> accounts = new Map<Id, Account>([SELECT ID, (SELECT ContactId FROM AccountContactRoles) FROM Account WHERE ID IN :accountIds]);

    List<OpportunityContactRole> ocrs = new List<OpportunityContactRole>();
    for(Opportunity o in trigger.new)
    {
        for(AccountContactRole acr : accounts.get(o.AccountId).AccountContactRoles)
        {
            ocrs.add(new OpportunityContactRole(OpportunityId = o.Id, ContactId = acr.ContactId));
        }
    }

    insert ocrs;
}


text:
Q: prevent opening an URL in popup that is already open in another popup In my application I open tasks in popups.
An URL in a popup looks like this: 'https://my.app.com/Task.aspx?id=5'
I would like to prevent that a task with a certain id opens in a new popup when a popup is already open with the same id.
So for example, i have 3 open popups with the following URL's:

*

*https://my.app.com/Task.aspx?id=1

*https://my.app.com/Task.aspx?id=3

*https://my.app.com/Task.aspx?id=5
When I click an url with link to https://my.app.com/Task.aspx?id=6 a new popup should open.
When I click an url with link to https://my.app.com/Task.aspx?id=5 I should get a message that this popup is already open.
Background of request: I would like to prevent dataloss when 2 or more popups with same id are open.
Anybody any idea how to develop this in (probably) javascript? (my application is asp.net)
thx
Frederik


text:
Q: Why does JQuery only toggle the paragraphs and the first input field but not the second one? The paragraph is supposed to be a description for the input next to it. In reality only the paragraph is affected by the toggle.
I'm new to jQuery so I might be missing something obvious.

$(document).ready(function() {
  $("#ausfallcheck").change(function() {
    $("#ausfall").toggle();
    $("p").toggle();
  });
});

Ausfall Beginn:

    <input type="datetime-local" name="ausfall-anfang" id="ausfall" hidden required onchange="check_time_ausfall()" />

Ausfall Ende:

    <input type="datetime-local" name="ausfall-ende" id="ausfall" hidden required onchange="check_time_ausfall()"/>

EDIT:
Edited the question, since it was not possible to spot the error in it. All other answers reference the original, badly constructed, question!

A: You are having another child
 tag inside the parent paragraph. That one is not initially hidden and affect the input visibility when toggled.

A: The issue is because you have two p elements. One starts hidden, the other visible although hidden by its parent. As such, when you toggle() those elements the outer one become visible and the inner invisible.
To fix this provide the boolean checked property of the checkbox to both p elements so that their states align:

$(document).ready(function() {
  $("#ausfallcheck").change(function() {
    $("#ausfall").toggle(this.checked);
    $("p").toggle(this.checked);
  });
});

<input type="checkbox" id="ausfallcheck" />

Ausfall Beginn:

    <input type="datetime-local" name="ausfall-anfang" id="ausfall" hidden required onchange="check_time_ausfall()" />

Alternatively you could amend the p selector to only target the outer element.
Also note the use of the change event over click here, which is preferred on radio and checkbox inputs for accessibility reasons.

A: It is not possible to spot the problem in the question I provided.
I used the same ID multiple times resulting in the JQuery script to only toggle the first input and not the second one with the same ID.


text:
Q: Use of proper words: relative pronouns Q1: What is the correct one of the words "which" and "that" to use in the following sentence:

I know the man, which/that we met yesterday.

Q2: Is the word "give" and "that" correctly used in the following :

I gave him a watch, that he liked, on his birthday.

If there are mistakes in any other part of the question, please correct me.

A: Relative clauses can be restrictive (or defining) and non-restrictive (or non-defining).

*

*In defining relative clauses, we can use the relative pronouns which, where, who, whose and we can replace who, which with that. This type of clause immediately adds vital information about the noun and commas aren't used:

I know the man who/that we met yesterday.

*Non-defining relative clauses add extra information about the noun, which is unnecessary for the meaning. We put the extra information between commas and the relative pronouns who, which cannot be replaced by that:

I gave him a watch, which he liked, on his birthday.


text:
Q: Add Checkbox to Header Cell in Datagridview I have a form with a datagridview on it. In the first column of this datagridview is a CheckBoxColumn. I am trying to add a checkbox to the header of the first column to act as a select all for the checkboxes below it. I can't understand the C# examples I've found online and I haven't found any PowerShell examples. Can someone point me in the right direction of how to do this?
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
$form = New-Object System.Windows.Forms.Form
$form.Size = New-Object System.Drawing.Size(400, 400)
$form.KeyPreview = $true

$CheckBoxColumn1 = New-object System.Windows.Forms.DataGridViewCheckBoxColumn
$CheckBoxColumn1.Width = 30
$CheckBoxColumn1.ReadOnly = $false

$DataGrid1 = New-Object System.Windows.Forms.DataGridView
$DataGrid1.Dock = "Fill"
$DataGrid1.BorderStyle = 'FixedSingle'
$DataGrid1.AlternatingRowsDefaultCellStyle.BackColor = 'LightGray'
$DataGrid1.AllowUserToAddRows = $false
$DataGrid1.RowHeadersVisible = $false
$DataGrid1.BackgroundColor = "White"
$DataGrid1.Columns.Add($CheckBoxColumn1) | Out-Null
$DataGrid1.ColumnCount = 3
$DataGrid1.Columns[1].name = 'col1'
$DataGrid1.Columns[2].name = 'col2'
$DataGrid1.Rows.add($false,'one','two')
$DataGrid1.Rows.add($false,'three','four')

##Add checkbox to header row column 0

$form.Controls.Add($DataGrid1)
$form.ShowDialog()

A: I couldn't find a way to add a checkbox to the column header cell itself, so I developed a work around. I ended up adding a checkbox to the form and strategically placed it where the header cell would be. I then handled various events to make it work correctly with the datagridview.
Notice that for the checkbox, I used the Click event instead of the CheckStateChanged event. This is because I don't want all the cell checkboxes to uncheck everytime I click a checkbox, but only the specific box I changed and the header checkbox.
$checkbox1 = New-Object System.Windows.Forms.CheckBox
$checkbox1.Location = New-Object System.Drawing.Size(10,5)
$checkbox1.Size = New-Object System.Drawing.Size(13,13)
$checkbox1.Visible = $true
$checkbox1.add_Click({
    if($checkbox1.Checked){
        for($i = 0; $i -lt $datagrid1.RowCount;$i++){
            $datagrid1.Rows[$i].Cells[0].Value = $true
        }
    }
    else{
        for($i = 0; $i -lt $datagrid1.RowCount;$i++){
            $datagrid1.Rows[$i].Cells[0].Value = $false
        }
    }
})
$form.Controls.Add($checkbox1)

#Handle Events:
$DataGrid1.add_CellContentClick({
    $datagrid1.EndEdit() #otherwise the cell value won't have changed yet
    [System.Windows.Forms.DataGridViewCellEventArgs]$e = $args[1]
    if($e.columnIndex -eq 0){
        if($datagrid1.rows[$e.RowIndex].Cells[$e.ColumnIndex].value -eq $false){
            $checkbox1.CheckState = 'unchecked'
        }
    }
})

If you want your checkbox to only appear when the datagrid populates, look into the Visible property. It can be set to $true or $false like this: $datagrid1.Visible = $false