text:
Q: Unable To Install A NVIDIA Driver I'm new to Linux Ubuntu and wanted to change my driver from the stock Nouveau driver to the recommended: NVIDIA driver (open kernel) metapackage from nvidia-driver-525-open (proprietary, tested)
I have a GeForce RTX 3070 Ti running on Linux Ubuntu 22.04 'Jammy Jellyfish'.
It comes up with an non-interactive black screen:
/dev/nvme0n1p2: clean, 229203/61022208 files, 7625678/244059136 blocks.

I've also tried to disable secure boot via MOK and BIOS as it requested but still nothing.
I already tried to delete the drivers through the root in GRUB and reinstall them again, but that doesn't affect anything.
Is there anyway for me to download the driver?

A: If you use the Hardware Installer from Gnome/Ubuntu, it should work. But wayland will not work with these drivers. So log out,select "Ubuntu on Xorg" as described here and log in again.


text:
Q: C++ How to represent a string in binary format? For some reason, I need to frequently generate strings use characters in {'0', '1', '2', '3'}. My current code use push_back() function and looks like:
string test = ""
test.push_back('0')
test.push_back('2')
test.push_back('3') // test would be "023"

I want to store the string in a char type or int type, and use binary form of each character to recursively generate the string. "023" would be stored in a char = '0010 1100'.
Do you think the binary operation is more time-efficient than push_back? If so, how to write the code.
Thanks!

A: You might use bitfield, something like
struct data
{
    unsigned char v1 : 2; // Can only store 0, 1, 2, 3
    unsigned char v2 : 2;
    unsigned char v3 : 2;
    unsigned char v4 : 2;
};

and then use
std::vector<data> v;
int nd_elem_in_last_item = 0; // to differenciate 00 from 0 and not there for final item.

So your data would indeed be more compact.

A: make a string like string s="0123".
And , use next_permutation(s.begin(),s.end()) to generate all permutation of number consisting of 0,1,2,3.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get R function to return multiple values of parameters I would like that my function would produce values for different values of one of my parameters (in this case CC), so that I can easily turn this into a dataframe.
Here is the code I am using:
ub_duration <- function(age, cc = c(12, 18, 24), cc_lag, dur,
                        extended) {
    dur = if (age < 30){
        if (cc < 15) return(150)
        if (cc >= 15 & cc < 24) return(210)
        if (cc >= 24) return(330)
    }
    dur = if (age >= 30 & age < 40){
        if (cc < 15) return(180)
        if (cc >= 15 & cc < 24) return(330)
        if (cc >= 24) return(420)
    }
    dur = if (age >= 50){
        if (cc < 15) return(270)
        if (cc >= 15 & cc < 24) return(480)
        if (cc >= 24) return(540)
    }
    return(dur)
}

When I call the function, this is what  get
> ub_duration(25,c(12, 18, 24),0)
[1] 150
Warning message:
In if (cc < 15) return(150) :
the condition has length > 1 and only the first element will be used

A: I'm not 100% I understand, but I'm guessing you want to loop over each cc value. I use the apply function to do the looping.
ub_duration0 <- function(age, cc) {
dur = if (age < 30){
if (cc < 15) return(150)
if (cc >= 15 & cc < 24) return(210)
if (cc >= 24) return(330)
}
dur = if (age >= 30 & age < 40){
if (cc < 15) return(180)
if (cc >= 15 & cc < 24) return(330)
if (cc >= 24) return(420)
}
dur = if (age >= 50){
if (cc < 15) return(270)
if (cc >= 15 & cc < 24) return(480)
if (cc >= 24) return(540)
}
return(dur)
}
ub_duration <- function(age, cc = c(12, 18, 24)) {
  sapply(cc, function(x) ub_duration0(age,x))}

> ub_duration(25,c(12, 18, 24))
[1] 150 210 330

A: The function was written to accept scalar arguments but you can vectorize it like this:
Vectorize(ub_duration)(25, c(12, 18, 24), dur = 0)
## [1] 150 210 330

or use sapply:
sapply(c(12, 18, 24), ub_duration, age = 25, dur = 0)
## [1] 150 210 330

Note that dur, cc_lag and extended are arguments that are not used in the body of the function shown in the question.  Even if dur is passed it is immediately overwritten with NULL in the first if statement if that statement returns. Also, cc_lag and extended are not referenced at all.  Perhaps you intended that the dur argument is the default if the ages are between 40 and 50 since those ages are not otherwise handled but in fact it returns NULL in that case. The function itself needs to be fixed depending on what you want and that was not described in the question.
Rewriting Function
1) Here is an attempt at rewriting it.  First create an m matrix with the cutoff values.  The rows correspond to cc and the columns to age.  Ensure that cc and age are the same length by putting them into a data frame and extracting them back out.  Then compute the indexes into m for cc and age. Note that it is possible that an age does not correspond to any index so in that case set its index to NA. If that is the case return dur and otherwise return the value looked up in m.
ub_duration2 <- function(age, cc, dur = 0) {
  m <- matrix(c(150, 210, 310,
    180, 330, 420,
    270, 400, 540), 3, dimnames = list(cc = 1:3, age = 1:3))
  d <- data.frame(age, cc)
  age <- d$age
  cc <- d$cc
  cc.ix <- 1 + (cc >= 15) + (cc >= 24)
  age.ix <- 1 * (age < 30) + 2 * (age >= 30 & age < 40) + 3 * (age > 50)
  age.ix[age.ix == 0] <- NA
  ifelse(is.na(age.ix), dur, m[cbind(cc.ix, age.ix)])
}
ub_duration2(25,c(12, 18, 24))
## [1] 150 210 310

2) This attempt is closer in spirit to what you have in the question.  It works on scalars and then we use Vectorize to vectorize it.  Although tedious it may be preferred in terms of simplicity.
ub_duration_scalar <- function(age, cc, dur = 0) {
    if (age < 30) {
        if (cc < 15) 150
        else if (cc < 24) 210
        else 330
    } else if (age < 40) {
        if (cc < 15) 180
        else if (cc < 24) 330
        else 420
    } else if (age >= 50) {
        if (cc < 15) 270
        else if (cc < 24) 480
        else 540
    } else dur
}
ub_duration3 <- Vectorize(ub_duration_scalar)

ub_duration3(25,c(12, 18, 24))
## [1] 150 210 310

A: I think the warning is caused here if (cc < 15) because cc is not a single element but a vector. So you're having something like if (c(TRUE, FALSE, FALSE)). Since if needs one single condition it pics only the first one, which is true.
If you want to evaluate all elements of cc togehter you could check out functions like all or any.
for a little illustration of what i want to say:
if(c(TRUE, TRUE, FALSE))
{
  print("Entered if")
  # do something
} else {print("Entered else")}
# output:
# [1] "Entered if"
# Warning message:
# In if (c(TRUE, TRUE, FALSE)) { :
# the condition has length > 1 and only the first element will be used

if(c(FALSE, TRUE, FALSE))
{
 print("Entered if")
 # do something
} else {print("Entered else")}
# output:
# [1] "Entered else"
# Warning message:
# In if (c(FALSE, TRUE, FALSE)) { :
# the condition has length > 1 and only the first element will be used

a possible workaround might be something like this
ub_duration <- function(age, cc = c(12, 18, 24), cc_lag, dur,
                        extended) {
# create matrix countaining the desired values
outcome_matrix = data.frame("age_under_30" = c(150, 210, 330), "age_30_to_40" = c(180, 330, 420), "age_over_40" = c(270, 480, 540))
# reduced the highest age limit from 50 to 40. Not sure if this is intendet, but otherwise there would be an undefined gap for age 40 to 50
# check which column is needed for the given age value
coldedect = sum(c(30, 40)<=age)+1
# check wich rows are needed for the given cc values
rowdedect = sapply(cc, function(f) sum(c(14, 24)<=f)+1)
# select values and return them
return(outcome_matrix[rowdedect, coldedect])
}

ub_duration(25,c(12, 18, 24),0)

A: ub_duration1 = function(age,cc){
    cc_cat = findInterval(cc,c(15,24))+1
    age_cat =findInterval(age,c(30,40,50))+1
    cc = cbind(c(150,210,330),c(180,330,420),NA,c(270,480,540))
    cc[cc_cat,age_cat]
}

ub_duration(25,c(12, 18, 24))
[1] 150 210 330


text:
Q: 24-pad, 0.5mm pitch: better to use QFN or BGA? For a certain TI component, I'm choosing between these two packages, both of which are 24-pad and 0.5mm pitch:

*

*QFN: http://www.ti.com/lit/ml/mpqf167b/mpqf167b.pdf (4 x 4 mm)

*BGA: http://www.ti.com/lit/ml/mpbg520/mpbg520.pdf (3 x 3 mm)

Some considerations:

*

*BGA is cheaper for a PCBA house to assemble, correct?

*If I use 3 mil microvias (on a 6-8 layer board) to route out BGA components, how many rows/cols does a 0.5mm BGA have to be before the routing gets annoying?

Any advice appreciated!

A: AFAIK, there's no significant cost benefit to using BGAs over QFN's. I think the tradeoff is that the BGA is roughly 1/2 the area; whereas the QFN can definitely be routed without microvias. If you don't already need microvias for some other part in your design, adding them to support this part might increase your blank board cost by 50%.
On the other hand, are you sure you need microvias to route the BGA? The first two rows should be routeable without vias under 4/4 design rules. And the center ball has an escape at location b2, so you should be able to route that with a through via.

A: Why do you think the BGA is cheaper in assembly? The operation is the same for both: pick and place. But the BGA needs X-ray for inspection, and the assembly shop may charge extra for that. The QFN can be visually inspected.
The QFN also lets you reach the pins with a probe. For a scope probe no problem, but for a DMM you'll need needle probes.
If you can afford the extra couple of square mm the QFN needs I would go for that. After all you can still use via-in-pad to save space.


text:
Q: Synapse Pipeline : DF-Executor-OutOfMemoryError I am having nested json as source in gzip format. In Synapse pipeline I am using the dataflow activity where I have mentioned the compression type as gzip in the source dataset. The pipeline was executing fine for small size files under 10MB. When I tried to execute pipeline for a large gzip file about 89MB.
The dataflow activity failed with below error:
Error1 {"message":"Job failed due to reason: Cluster ran into out of memory issue during execution,
 please retry using an integration runtime with bigger core count and/or memory optimized compute type.
 Details:null","failureType":"UserError","target":"df_flatten_inf_provider_references_gz","errorCode":"DF-Executor-OutOfMemoryError"}

Error1
Requesting for your help and guidance.
To resolve Error1, I tried Azure integration runtime with bigger core count (128+16 cores) and memory optimized compute type but still the same error.
I thought it could be too intensive to read json directly from gzip so I tried a basic copy data activity to decompress the gzip file first but still its failing with the same error.

A: As per your scenario I would recommend Instead of pulling all the data from Json file, pulled from small Json files. You first partitioned your big Json file in few parts with the dataflow using Round robin partition technique. and store this files into a folder in blob storage

Data is evenly distributed among divisions while using round robin. When you don't have excellent key candidates, use round-robin to put a decent, clever partitioning scheme into place. The number of physical divisions is programmable.

You need to evaluate the data size or the partition number of input data, then set reasonable partition number under "Optimize". For example, the cluster that you use in the data flow pipeline execution is 8 cores and the memory of each core is 20GB, but the input data is 1000GB with 10 partitions. If you directly run the data flow, it will meet the OOM issue because 1000GB/10 > 20GB, so it is better to set repartition number to 100 (1000GB/100 < 20GB).

And after above process use these partitioned files to perform dataflow operations with for each activity and in last merge them in a single file.
Reference: Partition in dataflow.


text:
Q: Literal contains unmatched quote. (SAS) I am trying to get the values passed in a macro variable and put quotes around it. i.e. space separated list to space separated quoted list. e.g. given below. I have used the following approach given by Jeff in one of my earlier post.
data test;
   id =1; _var="ABC"; output;
   id =1; _var="DEF"; output;
   id =1; _var="UVW"; output;
   id =2; _var="UVW"; output;
   id =3; _var="ABC"; output;
   id =3; _var="UVW"; output;
   id =3; _var="XYZ"; output;
   id =4; _var="ABC"; output;
   id =4; _var="XYZ"; output;
run;

%macro __test1(_byvar=, _qnam=, _id=);
    proc sort data= test out=_test;
        by &_byvar.;

  %if %superq(_qnam) ne %then
  %do;
            %let __tmpmv_qnam = %qsysfunc(prxchange(%bquote(s/\b/"/),-1,%bquote(&_qnam)));
            *";
            %put ^^^^^&__tmpmv_qnam.;
      where upcase(&_id) in (&__tmpmv_qnam);
  %end;

    run;

%mend;

%__test1 (_byvar=id ,_qnam = ABC UVW, _id=_var);

The log diaplayed following error:
SYMBOLGEN:  Macro variable _QNAM resolves to ABC UVW
ERROR: Literal contains unmatched quote.

Please help on this one.

A: Here's an alternative approach to adding the quotes. It's pretty basic - it doesn't check whether the input is already quoted, and there must be exactly 1 space between list items, and there must be no leading or trailing spaces in the input list, but you can adapt it to suit your needs:
%let list = a b c;
%macro qlist(LIST);
%sysfunc(compbl(
%do i = 1 %to %eval(%sysfunc(count(&LIST, %str( ))) + 1);
    "%scan(&LIST,&i)" %str( )
%end;
))
%mend qlist;

%put %qlist(&list);

A: You can have an unmatched quote within a macro by using the %str() function like so:
%str(%')         <-- gives an unmatched single quote
%str(%")         <-- gives an unmatched double quote

I've applied this to your macro and reorganized/simplified it a little.  Firstly you'll see that I've removed redundant %bquote() functions and changed %qsysfunc() to just %sysfunc().
I'm also building the string for the where clause and saving it to a macro variable so that the sort statement stands out more and the result of the where clause is easier to debug.
%macro __test1(_byvar=, _qnam=, _id=);

  %local list where_clause;

  %if %length(_qnam) gt 0 %then%do;
      %let list = %sysfunc(prxchange(s/\b/%str(%")/,-1,&_qnam));
      %let where_clause = where upcase(&_id) in (&list);
  %end;

  proc sort data= test out=_test;
      by &_byvar.;
      &where_clause;
  run;

%mend;

A: You seem to be making the problem harder than it is. Why not just use the INDEXW() function?
where indexw(symget('_qnam'),upcase(&_id),' ');

Or if you want to convert ABC UVW to "ABC","UVW" then a simple TRANWRD() function call will do.
where upcase(&_id) in ("%sysfunc(tranwrd(&_qnam,%str( ),","))");

However if your list could have extra spaces, if it was typed by hand for example, you will want to first remove the extra spaces.
%let _qnam=%sysfunc(compbl(&_qnam));


text:
Q: how to find comma or other symbols in a string using javascript? Let's assume I have an string... I want to convert them to numbers.. and It will only work for alphabets...
if my string contains comma or dot... I would like to avoid it...
I'm working with words by word. so if the string is--
"Hi, let's play!"

it should be converted to--
 "4510, 584578'52 69775246!"

how can I do it?
 function hasNumber(gottenWord) {
        return (/\d/.test(gottenWord));
    }
    const numberTrue =  hasNumber(gottenWord);

I was able to search for numbers but not sure how to search for symbols.. and I even have some custom symbols to search.

A: If all you want is to avoid anything that's not in abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ then the easiest way is to change \d to [^a-zA-Z]. [] indicates a character set, and starting a set with ^ means "not these".


text:
Q: Problems with updating the version of an App via Xcode on iPhone Hi I have the following problem.
I am almost finished with creating a new update for my app.
Now I wanted to try if when I install an old version of my app and then run the new version of this app via Xcode on my iPhone.
If the app gets updated correctly to the new version.
Unfortunately this is not the case. I ran into a few problems:

*

*the icon does not get updated (only looses the shine cause the new
one does not have on)

*at the start screen of the app there are still parts of the old
version visible like buttons and labels

most of the app gets updated to the new version correctly.
is this a bug or problem from Xcode or will this be the same when my customers update via Appstore?

A: This problem won't be there when your customer updates via Apple. I have seen problems like this only during debug.


text:
Q: Format arguments as string I'm trying to pull in google service account details as an airflow variable and write this to file when running a KubernetesPodOperator. I'm currently trying to test this in pylance with a launch.json file as:
{
    "version": "0.2.0",
    "configurations": [

        {
            "name": "Python: Pipeline",
            "type": "python",
            "request": "launch",
            "program": "src",
            "console": "integratedTerminal",
            "args": [
                "--assets_path", "s3://test/models/",
                "--folder_source", "s3://test/data/ner/qle_v1_with_postags/20210118_2100/",
                "--folder_destination", "/tmp/test/new",
                "--gcs_folder_destination", "gs://test/tmp/test/gcs",
                "--aws_region", "us-west-2",
                "--s3_endpoint", "s3.us-west-2.amazonaws.com",
                "--gcs_credentials", """"type": "service_account",
  "project_id": "test",
  "private_key_id": "b618cd07af66a9d57786af2575a23a3821728297",
  "private_key": "-----BEGIN PRIVATE KEY-----\nvsdjkfsdkjfbsajfklsdabfjubskfllbsdlafgbsafgjlsdabfjsadbfsjhda\njhdsgfhjegfsdfvgbdshjfgdshfgsdajhfsadkfh\nfgjkfdhgjkdfshgjkdfgl/dfkjsdhftkrshfbsjdkdffdnkljgfhdjfkghhdfkjlfghdskjsnhdfklhskjlfh/dfbhjsdfdgbhjsafghsdajkfgvshadjgfdggfhdfk\ndES0n7MPdwOW2sgXUKqAOGxZUiZvqGaY+rRBqmhIMYA1No4uou+nB1pyvR/tbGUn\nuPi6mnAeisUy6PKpbK/0m1rOdjta+xs2D3KSodw8FvZTZO8qhzP0k3tkYB/LMNdh\n079pZOV7AgMBAAECggEAFD7sMomWfpnmp2R1RKXe4fy4ISkFRLnyspMQhvQp/vQt\nb5TXmBIdXaA3m8kSZ/9ILHfMRPPfm06uvl5HDRAN6idQ+Jwez43ULJoa06wQizUS\nV\niYWzyLqVjBm/ztnhsPbazT9jz+CONsVgO2ViMm4BvBLv600JwivwFKxftJocQ5bi\ncLw3QBCdFgU64yfEdpYOCsNb\n-----END PRIVATE KEY-----\n",
  "client_email": "ml-storage@test.iam.gserviceaccount.com",
  "client_id": "103551600936651887697",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/ml-storage%40test.iam.gserviceaccount.com"
}"""

            ]
        }
    ]
}

Unfortunately i can't seem to convert the gcs_credentials into a string for testing.


text:
Q: Unable to toggle class on onClick in React I am trying to learn how to use forms in React.
It is a form with options to select.
On an onclick event, the clicked span tag should change the background color (just to show it was clicked), I am able to achieve this for a single tag but for multiple tags if I click on a single span bg color of both the tags gets changed.
Code:
import React from "react";

class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = {
  userClick: true
};
this.handleChange = this.handleChange.bind(this);
this.handleChange1 = this.handleChange1.bind(this);
}

 handleChange(e) {
  alert(`You selected... ${e.target.textContent}`);
  this.setState({
  userClick: !this.state.userClick
  });
}

handleChange1(e) {
  alert(`You selected... ${e.target.textContent}`);
 this.setState({
  userClick: !this.state.userClick
  });
}

render() {
return (

Services:

        {" "}
        inPerson{" "}

       Virtual

  );
}
}

 export default MyForm;

A: Both on click functions are changing the same state variable, userClick. If you want the 2 spans to act independently, you'll need two state variables, e.g:
handleChange(e) {
  alert(`You selected... ${e.target.textContent}`);
  this.setState({
     firstSpanClick: !this.state.firstSpanClick
  });
}

handleChange1(e) {
  alert(`You selected... ${e.target.textContent}`);
  this.setState({
     secondSpanClick: !this.state.secondSpanClick
  });
}

 Virtual

 Virtual

A cleaner way of achieving the same outcome would be to name the spans and have one handleChange.
//Each toggle variable doesn't need to be initialised, this is just for demonstration.

this.state = {
   spanOne: false,
   spanTwo: false
}

handleChange = (e) => {
        let name = e.target.getAttribute('name');
        this.setState({
            [name]: !this.state[name]
        });
    };

 Virtual

 Virtual


text:
Q: A vector in a struct - best approach? C++ I am trying to include a vector in my struct.
Here is my struct:
struct Region
{
    bool hasPoly;
    long size1;
    long size2;
    long size3;
    long size4;
    long size5;
    long size6;
    //Mesh* meshRef; // the mesh with the polygons for this region
    long meshRef;
    std::vector<int> PVS;
} typedef Region;

Is the vector in this declaration valid or would it make more sense to do a pointer to a vector. In the case of a pointer to a vector, do I need to allocate a new vector. How would I accomplish this?
Thanks!
Edit: The problem is that it ends up causing an error that points to xmemory.h, a file included with the MSVC++ platform.
    void construct(pointer _Ptr, _Ty&& _Val)
        {   // construct object at _Ptr with value _Val
        ::new ((void _FARQ *)_Ptr) _Ty(_STD forward<_Ty>(_Val)); // this is the line
         }

Interestingly, it does not happen if I allocate it outside of the struct and simply in the function I use. Any ideas?

A: You can write it like this without the typedef:
struct Region
{
    bool hasPoly;
    long size1;
    long size2;
    long size3;
    long size4;
    long size5;
    long size6;
    long meshRef;
    std::vector<int> PVS;
}; // no typedef required

To answer your questions:

Is the vector in this declaration valid

Yes, it is.

or would it make more sense to do a pointer to a vector.

No, probably not. If you did then you would have to implement copy constructor, assignment operator and destructor for the copy behavior. You would end up with the same but it would be extra work and potentially introduce bugs.

In the case of a pointer to a vector, do I need to allocate a new vector. How would I accomplish this?

You would need to implement the copy constructor, the copy assignment operator and the destructor:
// Copy constructor
Region(const Region & rhs) :
    hasPoly(rhs.hasPoly),
    // ... copy other members just like hasPoly above, except for PVS below:
    PVS(new std::vector<int>(*rhs.PVS))
{
}

// Copy assignment operator
Region & operator=(const Region & rhs)
{
    if (this != &rhs)
    {
         hasPoly = rhs.hasPoly;
         // ... copy all fields like hasPoly above, except for PVS below:

         delete PVS;
        PVS = new std::vector<int>(*rhs.PVS);
    }
    return *this;
}

// Destructor
Region::~Region()
{
    delete PVS;
}

Bottom line: your code is fine. You don't need to change it.
EDIT: Fix assignment operator: check for comparison against this and return *this.

A: It makes complete sense to do that and you don't need new in any respect, unless you actually want to alias a separate vector. In addition, you don't need any typedef stuff going on here.

A: It depends on how you use it.
If you want to copy the vector and data when copying the Region struct, then leave it as a non-pointer.
If you don't want it copied over, then you will want some sort of pointer to a vector.
If you use a pointer to a vector, you should be very careful about allocation/deallocation exception safety.  If you can't scope your allocation in an exception safe way, then you'll leave a potential for memory leaks.
A couple options are:

*

*Make sure that the code that allocates the vector (and uses the Region) also deallocates the vector, and is itself exception safe.  This would require the Region to only exist inside that code's scope.
You could do this by simply allocating the vector on the stack, and pass that to the pointer in the Region.  Then make sure you never return a Region object above that stack frame.

*You could also use some sort of smart pointer -> vector in your Region.

A: The vector is fine. Be aware that if you copy this struct, then the vector will be copied with it. So in code with particular performance constraints, treat this struct the same way that you'd treat any other expensive-to-copy type.
In production code, some people would prefer you to use the class keyword rather than the struct keyword to define this class, since the vector member makes it non-POD. If you're the author of your own style guide there's nothing to worry about.
The typedef is wrong, though, just write struct Region { stuff };


text:
Q: Securing a RPC service I'm writing a small services which will store files on disk and later, on request, return them to the client.
I'm looking over my options when it comes to securing this service so no unauthorized program can read/write the data.
The simplest solution would use impersonation so that the service thread handling the call impersonate the client and have the file system sort out what can be done or not.
The problem here is that the service itself has to be able to read the files without the impersonation (periodical functions running in the background).
I do have read the following chapter on MSDN, I'm looking for practical tips that you or other have used in the past to secure such service.
http://msdn.microsoft.com/en-us/library/aa373582(v=vs.85).aspx

A: You typically only impersonate while handling a client request. The rest of the time, the service is configured to use a system account (usually THE system account) that has (or is configured to have) full privileges to do its necessary tasks.
The security issue to watch out for is of course, ensuring that a user can't elevate themselves to that account.

When you install a service, one of the things you need to put some thought into is choosing the service account. Either using one of the built in accounts, or creating a special purpose account for your service. There are built in accounts for "LocalService", "NetworkService", "LocalSystem" iirc, otherwise you can pick an existing or new user or administrative account (not recommended).
When you create the files (assuming you don't pass any explicit ACL information) they inherit the inheritable access rights of the owning folder.
These you setup such that "users (a group including your impersonated users)" have create rights. "owners" have read/write. and "your default service account" has full control.
This means that your service, when not impersonating anyone, has full access to the files. When impersonating someone, can only read/write that particular users file.
Any regular users logged onto the Server will also not be able to access the files (unless they happen to be the impersonated users). Administrators can take ownership however, and then assign themselves read/write access. There is no defense (nor should there be) from local administrators.


text:
Q: About two definitions of tensor product. (in James R. Munkres's book and Ichiro Satake's book) I am reading "Analysis on Manifolds" by James R. Munkres.

Definition:
  Let $f$ be a $k$-tensor on $V$ and let $g$ be an $l$-tensor on $V$. We define a $k+l$ tensor $f \otimes g$ on $V$ by the equation $$(f \otimes g)(v_1, \cdots, v_{k+l}) = f((v_1, \cdots, v_{k}) \cdot g(v_{k+1}, \cdots, v_{k+l}).$$
It is easy to check that the function $f \otimes g$ is multilinear; it is called the tensor product of $f$ and $g$.

In the above definition, the operands for $\otimes$ are tensors on $V$.
When I checked "Linear Algebra" by Ichiro Satake, I found the operands for $\otimes$ are vector spaces.
What is the relation between these two $\otimes$s?

A: If $V$ and $W$ are vector spaces, their tensor product is a vector space $V \otimes W$ with the following (informally stated) property:

$(\star)$ Linear maps $V \otimes W \to U$ are in bijective correspondence with bilinear functions $V \times W \to U$.

The motivation for this is to encode multilinear maps as linear maps, which we understand thoroughly.
Moreover, we have
$$
(V \otimes W)^\ast \simeq \hom(V \otimes W, \Bbbk) \simeq \operatorname{Bil}(V \times W,\Bbbk).
$$
If $f_1, \dots, f_n$ and $g_1, \dots, g_m$ are dual basis of basis $\{v_i\}$ and $\{w_i\}$ in $V$ and $W$, in particular they define linear functions $V \times W \to \Bbbk$ which I will denote with the same letters. For example $f_1$ induces the map $(v,w) \mapsto f_1(v)$.
Given $f_i$ and $g_j$, we can also define the bilinear function
$$
f_i \otimes g_j(v,w) = f_i(v)g_j(w).
$$
We will call this the tensor product of $f_i$ and $g_j$ because of their relation with respect to the roles of $V$ and $W$ in their tensor product,

Proposition: the set $\{f_i \otimes g_j\}_{i,j}$ is a basis for $(V \otimes W)^\ast$.

Proof. Linear independence comes from the fact that
$$
f_i \otimes g_j(v_k,w_l) = \delta_{ik}\delta_{jl}.
$$
If $d : V \times W \to \Bbbk$ is bilinear and $x = \sum a_iv_i, y = \sum b_iw_i$, then
$$
d(x,y) = \sum_{i,j}a_ib_jd(v_i,w_j)
$$
and thus $d$ only depends on its values in each pair $(v_i,w_j)$. Noting $d_{ij} = d(v_i,w_j)$ and writing $\varphi = \sum_{i,j}d_{ij}f_i \otimes g_j$, we thus obtain that $d = \varphi$ since $d(v_i,w_j) = \varphi(v_i,w_j)$ for each $i,j \ \square$.
In the same fashion, fixing a vector space $V$ we can consider the $n$ (tensor) powers of $V$,
$$
V^{\otimes n} := V \otimes \cdots \otimes V,
$$
whose dual space turns out to be the space of  $n$-multilinear maps $V^n \to \Bbbk$. Now, in general, if $v \in V^{\otimes k \ast}$ is a $k$-multiniear function and $w \in V^{\otimes l \ast}$ is an $l$-multilinear one, we can form their tensor product
$$
v \otimes w(v_1, \dots, v_k,{v'}_1,\dots,{v'}_l) = v(v_1,\dots,v_k)w({v'}_1,\dots,{v'}_l)$
$$
which is an element of ${V^{\otimes (k+l)}}^\ast$.


text:
Q: What are the fertile areas of research in Analytic Number Theory? My professor once told me that Analytic Number Theory was "dead," which at the time was something of a disappointment, and which I struggled to agree with. Surely any subject may appear inferrtile in periods when researchers do not study the subject? I was just wondering, is this a generally accepted view? What reasons would be behind such opinion, and what are the fertile directions of research in this field?

A: These and these are some sample and well known open problems in Analytic Number Theory. Also look at this to have a flavor of the most recent 'gossip' in Analytic Number Theory world.


text:
Q: How to send external event via send-event.pl script? I want to send the external event through send-event.pl script. I can send the event but getting an event such as "An event with no matching configuration...". Can you give me an IDEA to resolve this?*
Please find the info below what I have tried:
send-event.pl uei.opennms.org/vendor/traps/Down -x 5 -p 'Type 1' -p 'Down 0'

Do I need to mention OID too?
Here is the event info for your reference:
<event>
        <mask>
                <maskelement>
                        <mename>id</mename>
                        <mevalue>.1..9.8.9.9.0.1.1</mevalue>
                </maskelement>
                <maskelement>
                        <mename>generic</mename>
                        <mevalue>6</mevalue>
                </maskelement>
                <maskelement>
                        <mename>specific</mename>
                        <mevalue>2</mevalue>
                </maskelement>
        </mask>
        <uei>uei.opennms.org/vendor/traps/Down</uei>
        <event-label>...</event-label>
        <descr>...</descr>
                <logmsg dest='logndisplay'><p>
                        Down trap received
                        Type=%parm[#1]%
                        Down=%parm[#2]%</p>
                </logmsg>
        <severity>Minor</severity>
</event>

A: use
$OPENNMS_HOME/bin/send-trap.pl uei.opennms.org/vendor/traps/Down

A: I have finally got the IDEA. I have missed to add object id with the object name.

Please find the solution below,

send-event.pl
uei.opennms.org/vendor/traps/Down
-p 'Type.1.9.8.9.9.0.1.1.0 1'
-p 'Down.10.1.9.8.9.9.0.1.1.1 0'


text:
Q: controller is not working with route functionality I am new in angularjs tech. I have implemented one registration function in my project.
I have created one js file for routing and controller functionality in my project and its working fine, If i will do separate router and controller file then I am application is failing.
I need to do separate file for the router and controller.
Below is my code in one file.
app.js file
var app = angular.module('crasApp', [ 'ngRoute' ]);
app.config(function($routeProvider) {
    $routeProvider.when("/", {
        templateUrl : "./views/xyz.html",
        controller : "searchCtrl"
    }).when("/registration", {
        templateUrl : "./views/abc.html",
        controller : "MainCtrl"
    }).when("/view", {
        templateUrl : "./views/viewsdata.html",
        controller : "overViewCtrl"
    });
});
app
        .controller(
                "MainCtrl",
                function($scope, $http) {
         console.log("Hi");
});

index.html
<!DOCTYPE html>
<html ng-app="crasApp">
<script
    src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<head>
<!-- Use Bootstrap -->
<link rel="stylesheet" href="./css/bootstrap.min.css">
<link rel="stylesheet" href="./css/abn-stylesheet.css">
<link rel="stylesheet" href="./css/style.css">
<script src="./javascripts/jquery/jquery-1.12.4.js"></script>
<script src="./javascripts/jquery/jquery.min-1.12.4.js"></script>
<script src="./javascripts/angular/bootstrap.min.js"></script>
<!-- <script src="./javascripts/angular/angular.min.js"></script> -->
    <script src="./javascripts/controllers/app.js"></script>
<!-- <script src="./javascripts/angular/angular-route.js"></script> -->
<script src="./javascripts/router/router.js"></script>

<script
    src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>

</head>
<div ng-view></div>

</html>

xyz.html
<!DOCTYPE html>
<html ng-app="crasApp">
<head>
<!-- Use Bootstrap -->
<link rel="stylesheet" href="./css/bootstrap.min.css">
<link rel="stylesheet" href="./css/abn-stylesheet.css">
<link rel="stylesheet" href="./css/style.css">
<link rel="stylesheet" href="./css/ngDatepicker.css">
<script src="./javascripts/jquery/jquery-1.12.4.js"></script>
<script src="./javascripts/jquery/jquery.min-1.12.4.js"></script>
<script src="./javascripts/angular/bootstrap.min.js"></script>
<!-- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script> -->
<script src="./javascripts/controllers/app.js"></script>
</head>
<body ng-controller="MainCtrl">
 Hi
</body>
<html>

So, Its working file if I am using one app.js file
I want to do seprate router and controller file.
router functionality i moved into different file and its working router functionality but not working controller functionality..
Separate router file as below.
router.js
var app = angular.module('crasApp', [ 'ngRoute']);
app.config(function($routeProvider) {
    $routeProvider.when("/", {
        templateUrl : "./views/retrieveTerminationReason.html",
        /*controller : "searchCtrl"*/
    }).when("/registration", {
        templateUrl : "./views/registration.html",
        /*controller : "MainCtrl"*/
    }).when("/view", {
        templateUrl : "./views/forbearanceRegistartionOverview.html",
        /*controller : "overViewCtrl"*/
    });
});

app.js as a controller
var app = angular.module('crasApp', []);

app
        .controller(
                'MainCtrl',
                function($scope, $http) {
                    console.log("Hi");
});

Please any one can help on this part.

A: In router.js, change var app = angular.module('crasApp', [ 'ngRoute']) to var app = angular.module('crasApp').
Also, in app.js, your declaration should be: var app = angular.module('crasApp', ['ngRoute']);. Since you have a single module, 'crasApp', you must declare it's dependencies when you declare the module itself.
What you have currently is re-creating the module vs. appending functionality.
Also, be sure to include your router.js as well in your HTML .

A: the issue
when you're using var app = angular.module('crasApp', [ 'ngRoute']); in your route.js file you are initializing new module NOT adding config to existing module!
the best approach for structuring an Angular App is NOT using variable you can call your module in a different way like:
app.js
var MODULE_NAME = 'crasApp'
angular.module(MODULE_NAME, ['ngRoute']);

to create controller controllers.js
angular.module(MODULE_NAME).controller('MainCtrl',function($scope, $http) {  //Note removing the dependencies array
       console.log("Hi");
 });

to create config  routes.js
angular.module(MODULE_NAME).config(function($routeProvider) { //Note removing the dependencies array
$routeProvider.when("/", {
    templateUrl : "./views/retrieveTerminationReason.html",
    /*controller : "searchCtrl"*/
})

in your index.html
 <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.min.js"></script>
    <script src="js/app.js"></script>
    <script src="js/routes.js"></script>
    <script src="js/controllers.js"></script>
 </head>

Note you don't need ng-controller directive in your HTML because defining it in routes is enough
separating services
create services.js for example
angular.module(MODULE_NAME).factory('Users',function($http,$q) {
  return {
    getUsers:function(){
      var def = $q.defer();
      $http({url:'URL_HERE',method:'GET'}).then(function(res){
        def.resolve(res)
      },function(err){
        def.reject(err);
      })
    }
  }
})

using in controller
angular.module(MODULE_NAME).controller('MainCtrl',function($scope, Users) {  //Note Users is the name of the factory created above
   Users.getUsers().then(function(res){
     $scope.users=res;
   },function(err){
     $scope.error = err;
   })
});


text:
Q: Why does Heroku postgres take longer than local mysql? In my local development a query I make using ActiveRecord takes 1695ms including rendering the view, however on Heroku I get a request timeout with the same query, which means it takes more than 30s. Is there something I don't know about Heroku or Postgres that might cause this?
Here is the query:
Event.where(id: Details.select("event_id").where('email like \'%gmail%\''))

There are no indexes on the email attribute for the Details table.
Locally the explain_threshold is set to nil but I doubt it would have a problem with a 1.6s query anyway.
The amount of data in not terribly different, not like 1000 in one and 1000000 on the other, which is why I assume it should take about the same time.

A: The amount of data here is significant, because:
in (select ... where email like '%gmail%')

cannot use an index. It's a guaranteed seq scan on the entire table. The more rows you have, the slower it'll be.
Try changing the query a bit by using this trick:
http://postgres.cz/wiki/PostgreSQL_SQL_Tricks#LIKE_optimalization


text:
Q: onLocationUpdate not beign called in Service I'm developing an application which needs to retrieve user location for periods of time. I have used LocationListener interface in activities and it has worked fine, however when I implement it in my android Service it isn't called. Here's the onCreate method:
public void onCreate() {
    super.onCreate();
    turned= true;
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    locationManager = (LocationManager) this
            .getSystemService(LOCATION_SERVICE);
    String provider = locationManager.getBestProvider(criteria, true);
    locationManager
            .requestLocationUpdates(provider, 0, 0, this); ...}

I would really appreciate any help, Service seems fine because I send Toast and they are sent, but onLocationUpdate is never called.

A: EDIT: As Shobhit Puri said, it just need to be in the onStartCommand()
public int onStartCommand (Intent intent, int flags, int startId)
{
    super.onCreate();
    encendido = true;
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    locationManager = (LocationManager) this
            .getSystemService(LOCATION_SERVICE);
    String provider = locationManager.getBestProvider(criteria, true);
    locationManager
            .requestLocationUpdates(provider, 0, 0, this);
    return START_STICKY;
}


text:
Q: Dot products of self vectors in a matrix I would like to get the dot products of self vectors xi in a matrix
xi is the i-th row vector in matrix X

Here is my code
xi = np.diagonal(np.dot(x, x.T))

Is there a better way to do so? Because there are a lot of unnecessary computations

A: How about using np.einsum?
import numpy as np

x = np.arange(9).reshape(3, 3)
output = np.einsum('ij, ij -> i', x, x)
print(x)
print(output)
# [[0 1 2]
#  [3 4 5]
#  [6 7 8]]
# [  5  50 149]

A: Perform an element-wise squaring and then sum across the rows:
np.square(x).sum(axis=1)

Example:
>>> x = np.arange(9).reshape(3,3)
>>> np.diagonal(np.dot(x, x.T))
array([  5,  50, 149])
>>> np.square(x).sum(axis=1)
array([  5,  50, 149])


text:
Q: .NET - How can I get more information for an error in my program? Error: "The thread 0x566967f6 has exited with code 0 (0x0)" Maybe you can help me...
I am writing a program in Windows Mobile that connects to a mail-server and retrieves data from a POP3-server. I am using a third-party (free) socket available from here. I am using VS 2008 (in VB.NET) and the device-emulators.
I can connect without any problems and execute my various commands (such as logging in, STAT, LIST, TOP). However, when I use the RETR-command to download the e-mail, I get after a while an error which I can't track down. If I retrieve a short e-mail, it normally downloads the data without any problems. But if I try to retrieve an e-mail with an attachment (with more bytes to transfer), I generally get an "error" towards 70-80,000 bytes. However, when running the application on my real device, I still get an error but normally towards 400-500,000 although sometimes earlier.
Running this application on the desktop (same third-party socket but another .dll) works without any problems. I can download huge attachments easily. I doubt it is related to network-problems - for instance using Pocket Outlook to download e-mails with attachment from the same mail-server works.
The error does not show up in debugging mode - with this I mean that the code does not stop at a certain line. I have inserted a Try-Catch as well in my code but no error is shown. However, using the debug-output window, I note after a while a line that appears and which reads: "The thread 0x566967f6 has exited with code 0 (0x0)".
I believe the problem is related to the DLL-library (which is an ATL based COM-library) or more likely my way of coding this library but before writing to them, I wanted to see if I can track down the problem to this library and why it may cause my error/problem. In this way, I can furnish more information when I write to them. So, I am just wondering if there is a way in VS 2008 for me to get some more information in regard to my problem/error? Thank you.

A: Exit code 0 means no error occurred and that the thread terminated normally. If it's not supposed to be terminating try to figure out under what conditions it can and figure out which one is allowing the thread to exit prematurely.
The only reason I can think of why this might be occurring on a mobile device and not your desktop is something to do with buffers. My guess would be that the smaller, slower devices are having trouble keeping up with the speed of the incoming data and consequently the buffers are being overwritten.


text:
Q: Old vb.net application states that OLEDB.40 is not registered on this computer I am updating an older application, for which I had to dig out Visual Studio 2008. The application uses the JET Engine, 'Microsoft.Jet.OLEDB.4.0'
It has an interesting flaw - when I work with it, it out of nowhere gives the error that "The 'Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine."
Now I have had this so many times, that I know what to do - delete solution and check it out again.
This error is only when running/debugging from Visual Studio. The compiled EXE works all the time
I have checked the folders and tried to just reinstate the database etc etc, but I cannot see what is wrong. Checking updated files by date, there is nothing weird. Only 4 *.vb files. I cannot see any other change.
For some reason it just does not see the OLEDB.40 anymore, but the compiled exe works. Obviously the OLEDB.40 is there, but Visual Studio will not see it.
This error happens at random, from every 10 mins to every 2 days.
Every time I delete the solution and check it out again, and I can work again.
Any ideas?
LATEST: I tried checking the code out to a new place, copying 5 *.vb files and VS2008 can run/debug again.
Checking it out to the original location will not work, nor copying the new  checkout into the old place.
But checking it out in a new place and I am back up again...
The issue is related to the path


text:
Q: Connection issues to MySQL 5.5 I am trying to connect to an appliance that has a mySQL database running on it.
Let us call the appliance APPLIANCE1.
I am trying to connect to the database from SERVER1. SERVER1 has mySQL installed on it.
The command is simple enough:
mysql.exe --host=APPLIANCE --user=name --password=secret

I keep getting the following error:
ERROR 1045 (28000): Access denied for user 'name'@'SERVER1' (using password: YES)

Can anyone shine a light on why it keeps returning the following value: name@SERVER1. Is it not supposed to replace SERVER1 with the host you are trying to connect to?
Much appreciated.

A: No, it's the host you're connecting from.  This allows administrators to allow specific users to only login from specific hosts.


text:
Q: Cannot resolve symbol using App engine's sample code for Java Mail I have set up an app engine backend in my Android project using Android Studio successfully by following the hello world guide here. The app can communicate with the backend server. My next step is code the backend such that it can send emails. I am following the official guide here. However, I am facing an issue with the following import statements, which cannot be resolved.
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

I am really puzzled why this is the case as the guide specifically says "All of the JavaMail classes you need are included with the App Engine SDK. Do not add Oracle®'s JavaMail JARs to your app; if you do, the app will throw exceptions."
I have App Engine SDK included in the project, else the hello world program wouldn't have worked. I can't figure out why the import statements are not resolving.
Here is my build.gradle file for reference. Would appreciate your help.
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.google.appengine:gradle-appengine-plugin:1.9.14'
    }
}
repositories {
    jcenter();
}
apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'appengine'
sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7
dependencies {
    appengineSdk 'com.google.appengine:appengine-java-sdk:1.9.14'
    compile 'javax.servlet:servlet-api:2.5'
}
appengine {
    downloadSdk = true
    appcfg {
        oauth2 = true
    }
}

A: Okay I managed to solve the issue after a few hours by adding one extra line in the build.gradle file.
dependencies {
    appengineSdk 'com.google.appengine:appengine-java-sdk:1.9.18'
    compile 'com.google.appengine:appengine-api-1.0-sdk:1.9.18'
    compile 'javax.servlet:servlet-api:2.5'
}

So it turns out that simply having
appengineSdk 'com.google.appengine:appengine-java-sdk:1.9.18'

was not sufficient. I had the impression that it was sufficient because I could run the hello world program just fine (i.e. deploying to the backend using GAE's tools worked, which implies that the sdk dependency was registered). However, when I tried calling specific libraries from within the sdk itself within the Java code, they could not be resolved.
The fix was to add a compilation dependency.
compile 'com.google.appengine:appengine-api-1.0-sdk:1.9.18'

I was not able to find the information from the official docs though. In fact, I wouldn't have known how to phrase the compilation dependency properly if not for this article and the maven repo.
Hopefully this helps anyone using the GAE libraries in their code.


text:
Q: Indexing logs in Logstash using application ports I'm using ELK Stack, this dependency and config in order to log my APIs.
    <dependency>
        <groupId>com.github.piomin</groupId>
        <artifactId>logstash-logging-spring-boot-starter</artifactId>
        <version>1.3.0.RELEASE</version>
    </dependency>

And in properties:
logging.logstash.enabled: true
logging.logstash.url: 127.0.0.1:5000
logging.logstash.ignorePatterns: /(actuator|swagger|webjars).*
logging.logstash.logHeaders: true

I have several applications using different ports like ==> application A: localhost:9000, Application B: localhost:9001, ...
All the logs are sent to Logstash with the following config:
input {
   tcp {
    port => 5000
    codec => json
    type => "AppA"
  }
   tcp {
    port => 5000
    codec => json
    type => "AppB"

  }
}

filter {
       if [type] == "AppA" {
            mutate { add_field => { "[@metadata][target_index]" => "AppA" } }
      } else if [type] == "AppB" {
            mutate { add_field => { "[@metadata][target_index]" => "AppB" } }
      }
}

output {
    elasticsearch {
             hosts => ["localhost:9200"]
             index => "%{[@metadata][target_index]}"
                  }
}

But it does not work. I want to index them according to ports or names of applications. any solution?

A: Since you want to filter your events and send to different index based on the input they came, you just need to use conditionals in the output block, the same way you did in the filters block.
You need something like the following pipeline.
input {
    tpc {
        port => 5000
        type => "AppA"
    }
    tpc {
        port => 6000
        type => "AppB"
    }
}

filter {
    if [type] == "AppA" {
        filters for type AppA
    } else if [type] == "AppB" {
        filters for type AppB
    }
}

output {
    if [type] == "AppA" {
        elasticsearch {
            index for AppA
        }
    } else if [type] == "AppB" {
        elasticsearch {
            index for AppB
        }
    }
}


text:
Q: R Given a column, find duplicates of this column in a data.frame Given the following data:
questionTagMatrix <- data.frame( question1=c("0","1","0"), question2=c("1","0", "0"), question3=c("0","1","0"), question4=c("0","1","1")  )
rownames(questionTagMatrix)[1] <- "php"
rownames(questionTagMatrix)[2] <- "html"
rownames(questionTagMatrix)[3] <- "javascript"

newQuestion <- data.frame( newquestion=c("0","1","0") )
rownames(newQuestion)[1] <- "php"
rownames(newQuestion)[2] <- "html"
rownames(newQuestion)[3] <- "javascript"

How do I find all columns of questionTagMatrix equal to newQuestion?

A: You can use apply to find the columns:
questionTagMatrix[apply(questionTagMatrix, 2, function(x)
                                               all(x == as.matrix(newQuestion)))]

All columns of questionTagMatrix are compared with newQuestion. The result:
#            question1 question3
# php                0         0
# html               1         1
# javascript         0         0

A: A vectorized solution using colSums:
 questionTagMatrix[,colSums(questionTagMatrix == newQuestion)
                    ==nrow(questionTagMatrix)]

          question1 question3
php                0         0
html               1         1
javascript         0         0

PS newQuestion is a vector here :
newQuestion =c("0","1","0") ## not data.frame( newquestion=c("0","1","0") )

To get only questions names:
names(questionTagMatrix)[colSums(questionTagMatrix == newQuestion)
+                   ==nrow(questionTagMatrix)]
[1] "question1" "question3"


text:
Q: Как вывести два случайных не повторяющихся числа в СИ? Как вывести два случайных не повторяющихся числа в СИ в диапазоне от 0 до 10?
 srand(time(NULL));
 int a = rand()%9;
 int b = rand()%9;

Здесь числа случайные, но могут повторяться

A: Генерим первое, любое случайное от 0 до 9.
Генерим дополнительное случайное от 1 до 9.
Считаем второе случайное как сумма первого и дополнительного по модулю 10. Получаем также число от 0 до 9, причём гарантированно не равное первому случайному.
Т.е. приблизительно (в сях не силён)
int a = rand()%9;
int b = (a + 1 + rand()%8)%9;

A: int a = rand()%11; // 0 .. 10
int b = (a + 1 + rand()%10)%11; // 0 .. a - 1 , a + 1 .. 10

A: Поскольку исправлять предыдущего оратора не хочтся...
int a = rand()%9, b;
while((b = rand()%9)==a);

A: Если не использовать какую-нибудь функцию, которая сама так умеет, то просто проверять а и b на равенство:
int b = rand()%9;

int a = rand()%9;
while (a == b) {
    b = rand()%9;
}

A: Длинный вариант:
const int SIZE = 2;
int arr[SIZE];

int alreadyThere;

for (int i = 0; i < SIZE; )
{
alreadyThere = 0;
int newRanomValue = rand() % 10;

for (int j = 0; j < i; j++)
{
if (arr[j]==newRanomValue)
{
alreadyThere = 1;
break;
}
}

if (!alreadyThere)
{
arr[i] = newRanomValue;
i++;
}

}

for (int i = 0; i < SIZE; i++)
{
  printf([i]);
}


text:
Q: The email_from in Django send_mail function not working I put a contact form in my site, and I have this in my settings.py
# Email settings
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'myemail@gmail.com'
EMAIL_HOST_PASSWORD = '****'
EMAIL_PORT = 587

And this in my views.py
name = form.cleaned_data['name']
email = form.cleaned_data['email']
message = form.cleaned_data['message']
subject = 'Email from ' + name
content = name + '\r\n' + email + '\r\n\r\n' + message

send_mail(subject, content, email, ['me@myemail.com'])

It all works correctly, i get the email with all the information, but, the email comes from myemail@gmail.com even though the from_email parameter has the email var with the senders email.
It doesn't work that way or i'm doing something wrong?
I wanted to get the email from the sender, so y can just reply to it, like i do in PHP.
Thank you.

A: Gmail will not let you spoof where the email came from.
per user iAn in a similar post

The short answer - you can't.
Google rewrites the From and Reply-To headers in messages you send via it's SMTP service to values which relate to your gmail account.
The SMTP feature of gmail isn't intended to be an open or relay service. If it allowed any values for the From header, it would significantly dilute Google's standing with spam services, as there would be no way to verify the credentials of the sender.
You need to consider alternatives. How are you planning to host your script/application/website when it's finished: virtually every hosting solutions (shared/vps/dedicated server) will come pre-configured with an email transfer solution: be it sendmail or postfix on *nix, or IIS on Windows.
If you are intent on using gmail then you could:
Setup a dedicated "myapp@gmail.com" account
If you own the domain you are supposedly sending from, use the free gmail for domains, and setup a "myapp@mydomain.com" account.


text:
Q: active directory ldap login auth when password needs changing Let me explain my issue.
I have a PHP application using an LDAP connection to an Active Directory server to authenticate. If i make it so that a user needs to change their password at the next login it won't allow me to authenticate them before i allow the password change. I can detect that the password change is required but if i allowed the user to change it then i have no way to work out that the user is valid or not, which means that the system could be hacked by just knowing the username of a user that's password as expired.
This to me seems daft... is there something im missing..
Currently I am
binding to the server
checking if the password as expired or not
checking the authentication users details
This is what I get returned if the users account is set to change password on next login, auth as failed but there is a password change request.
Is there a specific order the requests need to be sent so i can auth the user before the password change it sent?
Thanks in advance

A: By marking the account as Must change password at next login there is effectively no password to authenticate so this doesn't translate to the web.
A better option is to compare the users' pwdLastSet attribute against the domain policy and enforce the change in the application not in AD.


text:
Q: Computer won't boot unless SSD is oriented a certain way I'm having a rather strange problem with my home build. It was functioning perfectly well until I put it in a storage locker (supposedly climate controlled) for a couple weeks and had it sitting in my new apartment for a month or so before setting it up (it has no wifi card, so I was using my laptop). Upon starting it, I noticed that the BIOS was taking way longer than usual to load, and that attempting to boot from my SSD would result in a boot error. According to setup, the SSD is being detected but it is not listed as the IDE1 Master. Also before entering setup the computer would usually list off the SSD and my CD drive (my two SATA drives) and then list "3rd Master Hard Disk Error" and prompt me to press F1. When I access the boot menu the SSD is usually (but not always) listed. Removing the SSD allowed BIOS to load normally. I checked the BIOS settings and verified that they were correct, and tried resetting them to defaults to no avail. I was able to successfully boot into DSL from a flash drive, but the SSD was not listed among the drives when I did so. I also was able to successfully boot a friend's computer from the SSD and checked that the main partition was marked as bootable, which it was, and ran fsck, which found no problems.
Here's where it gets weird, if it wasn't already. When I plugged the SSD back into my computer it booted just fine. After checking that everything was functioning, I decide to put back the screws holding the SSD in place (my case is home-built out of wood) and noticed that the SSD was upside-down relative to how the case was designed to hold it (it sits on its side, and when it is upside-down the SATA cable is in the way of a screw). Thinking nothing of this, I flip the SSD. My programs freeze immediately, with the exception of Windows Explorer which I assume is being run from RAM, and after a minute or so I get a BSOD. It then fails to boot. Flipping the SSD again allowed the computer to boot normally. It continued to work until the next time I booted it, when it booted fine but then froze and crashed in the same manner as before after ~15 minutes, without me touching the drive. It failed to boot afterwards until I tried several different orientations of the SSD, finally booting when I put it on end, but then crashed again after a few minutes. Trying different SATA connectors on the Motherboard sometimes gets it to run, but the CD drive seems to work fine from the SATA connector the SSD usually uses, except that it tries to open my arcade games in iTunes.
So here's my question: What the heck is going on, and how do I fix it?
Relevant computer stats:

*

*Hard Drive: Crucial RealSSD C300 2.5 64GB (IDE mode)

*Motherboard: ASRock M3A770DE

*OS: Windows 7 Professional OEM
Hypotheses/Stabs in the dark:

*

*Bad SATA or Power connector on SSD.

*Bad SATA cable.

*Bad-ish SATA connectors on the motherboard.

A: A connection within the drive is loose, and specific orientations as well as heat cause the connection to separate. You cannot fix this.

A: As you state when you reorient the SSD while the system is running and your system Freeze/BSOD, your issue sound like a bad SATA cable. It would be the first inexpensive item to scrutinize and change.
As a test - Swap the SATA cable from the CD drive to the SSD. use the port that the SSD was on, then the one that CD was on.


text:
Q: Visual Studio Code sh: 0: Can't open undefined/build.sh Recently I performed a clean install of Kubuntu 15.10 on my laptop and installed Visual Studio Code in order to code C#, F# and other Microsoft based languages.
Using the internal commandline I installed C# and F#. However, when I am trying to compile/run my code I get the following error:
open System;

public class Hello1
{
   public static void Main()
   {
      System.Console.WriteLine("Hello, World!");
   }
}

My Output:
sh: 0: Can't open undefined/build.sh

Screenshot:
http://i.imgur.com/j97uatj.png
I tried to Google the answer, but I wasnt able to find it.
Do you have any idea what I am missing?
Thanks!

A: Visual Studio Code does not include any tools to build C# or F#. It is just a text editor, like Sublime. It is not an IDE.
If you want to use Visual Studio Code to program for .NET in Linux, you need to decide if you want to use Mono or ASP.NET Core.
For ASP.NET Core you can find instructions here and check this and this too.
For installing Mono, check this page.
Note that for F# you need to use something like Ionide.io.
As per today there are the following options if you really need an IDE:

*

*MonoDevelop

*Xamarin Studio - a fork of MonoDevelop, supported by Xamarin

*The newest and brightest addition - JetBrains' Project Rider, which is planned for release later this year (Q4) but accessible for EAP right now

I personally think that Project Rider is the most promising tool, it has battle-tested products IdeaJ and Resharper under the bonnet and it is just a matter of time until it will become a de-facto the .NET IDE on Linux and Mac OS X. I would also prefer using it in Windows since it is much faster than Visual Studio.


text:
Q: Is a directed graph different from a flow graph? I'm trying to understand directed graphs in a more applied way, especially in the context of the dataflow programming paradigm. Is the following flow chart a directed graph?

Is a directed graph essentially a flow diagram? Or is a flow diagram a type of directed graph?

I have made a change to my question based on comments from users and additional reading. I believe the example I have shown is called a Flow Graph. Is that correct?
So now my question is: Is a flow graph a type of directed graph?

A: A directed graph like any mathematical object, is a well-defined object. It has a definition, so that handed any other mathematical object $X$, we can say whether or not $X$ is an example of a graph.
But what is the definition of a flow chart? Until you give a precise definition of flow chart, it's not a mathematical object and it's impossible to say how it compares to a directed graph. Furthermore, there isn't necessarily a correct definition of a flow chart; you get to define a flow chart however you need, depending on what you're thinking about. For example do you need to flow chart to "terminate," where flowing throw the chart you hit a terminal vertex? or can you have loops in your flow chart?


text:
Q: Migrating from .Net 4 to 5 changes the build task behavior and does not include `intermediate output` generated resources into the dll I'm migrating an WPF app from .Net Framework 4 to .Net 5.
That app rely on a (referenced project) library that allows some custom hlsl effects.
To compile hlsl files on the fly into ps files and include them in the generated dll file, i'm using: this build task.
This is working flawlessly using .Net Framework 4 using that csproj file (of the effect library project):
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <UsingTask TaskName="ShaderBuildTask.PixelShaderCompile" AssemblyName="ShaderBuildTask, Version=1.0.3072.18169, Culture=neutral, PublicKeyToken=44e467d1687af125" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProductVersion>9.0.21022</ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{22A99010-4E29-47AA-994E-6CCE9C28D45F}</ProjectGuid>
    <OutputType>Library</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>Comics.Effects</RootNamespace>
    <AssemblyName>Comics.Effects</AssemblyName>
    <TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
    <FileAlignment>512</FileAlignment>
    <FileUpgradeFlags>
    </FileUpgradeFlags>
    <OldToolsVersion>3.5</OldToolsVersion>
    <UpgradeBackupLocation />
    <PublishUrl>publish\</PublishUrl>
    <Install>true</Install>
    <InstallFrom>Disk</InstallFrom>
    <UpdateEnabled>false</UpdateEnabled>
    <UpdateMode>Foreground</UpdateMode>
    <UpdateInterval>7</UpdateInterval>
    <UpdateIntervalUnits>Days</UpdateIntervalUnits>
    <UpdatePeriodically>false</UpdatePeriodically>
    <UpdateRequired>false</UpdateRequired>
    <MapFileExtensions>true</MapFileExtensions>
    <ApplicationRevision>0</ApplicationRevision>
    <ApplicationVersion>1.0.0.%2a</ApplicationVersion>
    <IsWebBootstrapper>false</IsWebBootstrapper>
    <UseApplicationTrust>false</UseApplicationTrust>
    <BootstrapperEnabled>true</BootstrapperEnabled>
    <TargetFrameworkProfile />
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <Prefer32Bit>false</Prefer32Bit>
    <UseVSHostingProcess>false</UseVSHostingProcess>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <Prefer32Bit>false</Prefer32Bit>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
    <DebugSymbols>true</DebugSymbols>
    <OutputPath>bin\x64\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <DebugType>full</DebugType>
    <PlatformTarget>x64</PlatformTarget>
    <ErrorReport>prompt</ErrorReport>
    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
    <OutputPath>bin\x64\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <Optimize>true</Optimize>
    <DebugType>pdbonly</DebugType>
    <PlatformTarget>x64</PlatformTarget>
    <ErrorReport>prompt</ErrorReport>
    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
    <DebugSymbols>true</DebugSymbols>
    <OutputPath>bin\x86\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <DebugType>full</DebugType>
    <PlatformTarget>x86</PlatformTarget>
    <UseVSHostingProcess>false</UseVSHostingProcess>
    <ErrorReport>prompt</ErrorReport>
    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
    <OutputPath>bin\x86\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <Optimize>true</Optimize>
    <DebugType>pdbonly</DebugType>
    <PlatformTarget>x86</PlatformTarget>
    <ErrorReport>prompt</ErrorReport>
    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="System" />
    <Reference Include="System.Core">
    </Reference>
    <Reference Include="System.Xml.Linq">
    </Reference>
    <Reference Include="System.Data.DataSetExtensions">
    </Reference>
    <Reference Include="WindowsBase">
    </Reference>
    <Reference Include="PresentationCore">
    </Reference>
    <Reference Include="PresentationFramework">
    </Reference>
  </ItemGroup>
  <ItemGroup>
    <Compile Include="DenoiseEffect.cs" />
    <Compile Include="BilateralEffect.cs" />
    <Compile Include="UnsharpEffect.cs" />
    <Compile Include="AdjustEffect.cs">
    </Compile>
    <Compile Include="EffectLibrary.cs">
    </Compile>
    <Compile Include="Properties\AssemblyInfo.cs" />
    <PixelShader Include="AdjustEffect.fx" />
    <PixelShader Include="BilateralEffect.fx">
      <ShaderModel>3_0</ShaderModel>
    </PixelShader>
    <Service Include="{94E38DFF-614B-4cbd-B67C-F211BB35CE8B}" />
    <PixelShader Include="UnsharpEffect.fx">
      <ShaderModel>3_0</ShaderModel>
    </PixelShader>
  </ItemGroup>
  <ItemGroup>
    <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
      <Visible>False</Visible>
      <ProductName>.NET Framework 3.5 SP1</ProductName>
      <Install>true</Install>
    </BootstrapperPackage>
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <ItemGroup Condition="'$(BuildingInsideVisualStudio)'=='true'">
    <AvailableItemName Include="VertexShader">
      <Visible>false</Visible>
    </AvailableItemName>
    <AvailableItemName Include="PixelShader">
      <Visible>false</Visible>
    </AvailableItemName>
  </ItemGroup>
  <ItemGroup>
    <PixelShader Include="DenoiseEffect.fx" />
  </ItemGroup>
  <UsingTask TaskName="ShaderBuildTask.ShaderCompile" AssemblyName="ShaderBuildTask, Version=1.0.3072.18169, Culture=neutral, PublicKeyToken=44e467d1687af125" />
  <Target Name="VertexShaderCompile" Condition="'@(VertexShader)' != '' " BeforeTargets="Build">
    <ShaderCompile Sources="@(VertexShader)" ShaderProfile="vs_3_0" IntermediateOutputPath="$(IntermediateOutputPath)">
      <Output TaskParameter="Outputs" ItemName="Resource" />
    </ShaderCompile>
  </Target>
  <Target Name="PixelShaderCompile" Condition="'@(PixelShader)' != '' " BeforeTargets="Build">
    <ShaderCompile Sources="@(PixelShader)" ShaderProfile="ps_3_0" IntermediateOutputPath="$(IntermediateOutputPath)">
      <Output TaskParameter="Outputs" ItemName="Resource" />
    </ShaderCompile>
  </Target>
  <PropertyGroup>
    <PrepareResourcesDependsOn>VertexShaderCompile;PixelShaderCompile;$(PrepareResourcesDependsOn)</PrepareResourcesDependsOn>
  </PropertyGroup>
</Project>

But after migrating to .Net 5 the solution builds fine, the ps files are compiled into the obj directory, but the ps files aren't included into the dll, thus, making the wpf app launch and crash right after (as it needs the ps files).
Here is the new migrated csproj file:
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
  <UsingTask TaskName="ShaderBuildTask.ShaderCompile" AssemblyName="ShaderBuildTask, Version=1.0.3072.18169, Culture=neutral, PublicKeyToken=44e467d1687af125" />

  <PropertyGroup>
    <TargetFramework>net5.0-windows</TargetFramework>
    <EnableDefaultCompileItems>false</EnableDefaultCompileItems>
    <UseWPF>true</UseWPF>
    <UseWindowsForms>true</UseWindowsForms>
  </PropertyGroup>

  <ItemGroup>
    <Compile Include="DenoiseEffect.cs" />
    <Compile Include="BilateralEffect.cs" />
    <Compile Include="UnsharpEffect.cs" />
    <Compile Include="AdjustEffect.cs">
    </Compile>
    <Compile Include="EffectLibrary.cs">
    </Compile>

    <PixelShader Include="AdjustEffect.fx">
      <ShaderModel>2_0</ShaderModel>
    </PixelShader>
    <PixelShader Include="BilateralEffect.fx">
      <ShaderModel>3_0</ShaderModel>
    </PixelShader>
    <PixelShader Include="UnsharpEffect.fx">
      <ShaderModel>3_0</ShaderModel>
    </PixelShader>
    <PixelShader Include="DenoiseEffect.fx" />
  </ItemGroup>

  <UsingTask TaskName="ShaderBuildTask.ShaderCompile" AssemblyName="ShaderBuildTask, Version=1.0.3072.18169, Culture=neutral, PublicKeyToken=44e467d1687af125" />

  <Target Name="VertexShaderCompile" Condition="'@(VertexShader)' != '' " BeforeTargets="Build">
    <ShaderCompile Sources="@(VertexShader)" ShaderProfile="vs_3_0" IntermediateOutputPath="$(IntermediateOutputPath)">
      <Output TaskParameter="Outputs" ItemName="Resource" />
    </ShaderCompile>
  </Target>
  <Target Name="PixelShaderCompile" Condition="'@(PixelShader)' != '' " BeforeTargets="Build">
    <ShaderCompile Sources="@(PixelShader)" ShaderProfile="ps_3_0" IntermediateOutputPath="$(IntermediateOutputPath)">
      <Output TaskParameter="Outputs" ItemName="Resource" />
    </ShaderCompile>
  </Target>

  <PropertyGroup>
    <PrepareResourcesDependsOn>VertexShaderCompile;PixelShaderCompile;$(PrepareResourcesDependsOn)</PrepareResourcesDependsOn>
  </PropertyGroup>
</Project>

The only differences are the migration to .Net 5 and the removing of the run configurations for simplicity. Nothing else on the project has been modified.


text:
Q: Blazor dynamically generated table rows I created an sample c# blazor (server-side) app to practice a little.
I try to generate table rows dynamically for a calendar but i run into a problem there.

            Monday
            Tuesday
            Wednesday
            Thursday
            Friday
            Saturday
            Sunday

            @* currentDateTimeValues is a list with DateTime objects *@
            @foreach (var item in currentDateTimeValues)
            {
                @if (counter % 7 == 0 && counter > 0)
                {
                    @:

                }
                counter++;
                @item.ToString("dd.MM.yyyy")
            }

After 7 cells a new row should be created but it doesn't. The cells go straight ahead without linebreak.

Maybe you guys have any idea.
UPDATE:
In the meantime I've created a workaround because I think that blazor can't handle the

My currentDateTimeValues-List now contains week objects

            @* currentDateTimeValues is a list with Week objects *@
            @foreach (var week in currentDateTimeValues)
            {

                @week.Monday
                @week.Tuesday
                @week.Wednesday
                @week.Thursday
                @week.Friday
                @week.Saturday
                @week.Sunday

            }

A: I think the solution you are trying isn't possible in Blazor at the moment. Why not use two loops to create the calendar. Something like:
@while (counter < currentDateTimeValues.Length)
{

       @{
            var i = 0;
            if (i < 7 && counter + i < currentDateTimeValues.Length)
            {
                @currentDateTimeValues[counter + i].ToString("dd.MM.yyyy")
                i++;
            }
        }

    counter += 7;
}


text:
Q: Starting hotspot using console Ubuntu 16.04 I know how to create a hotspot using graphical interface but it seems like a lot of energy and resources get wasted just to keep my laptop on with all the GUI services running just to use as a hotspot. So I tried stopping the lightdm service, but then my hotspot too stopped.
I want to use my hotspot while lightdm service is stopped.
Any ideas or a better solution to conserve energy and resources just to keep my hotspot running using my laptop?


text:
Q: css not found (404) - it's adding another css to my path I have a normal HTML page on my IIS8 development machine. Very basic and doesn't contain any code yet.
To the HEAD I've added a css file deceleration I've created:
<link href="css/catalog.css" rel="stylesheet" />

When inspecting with either chrome or fiddler it reports a 404 - but not because the file isn't there - but because it's adding another css folder:
GET http://localhost/mywebsite/message/css/css/catalog.css 404 (Not Found)

which should actually be:
http://localhost/mywebsite/message/css/catalog.css

strange thing is that if I change the name of the folder to anything but CSS it works.
any ideas to why this is happening?
Thanks

A: Just use this and you'll be good to go:
<link href="catalog.css" rel="stylesheet" />

EDIT:
<link href="/catalog.css" rel="stylesheet" />


text:
Q: How to import specific error from boto? I am getting this exception (printing the class for debugging) when running my code:
An error occurred (DBInstanceNotFound) when calling the DescribeDBInstances operation: DBInstance <instance name> not found.
<class 'botocore.errorfactory.DBInstanceNotFoundFault'>

I would like to handle the exception properly like this:
from botocore.exceptions import DBInstanceNotFoundFault
from botocore.errorfactory import DBInstanceNotFoundFault
try:
    <fetch info about db instance>
except DBInstanceNotFoundFault as e:
    <handle error>

Unfortunately DBInstanceNotFoundFault does neither exist in botocore.exceptions nor in botocore.errorfactory.
I've cloned boto3 as well as botocore and grep'd for DBInstanceNotFoundFault but just can't find it.
How can I import it?

A: For boto3 exceptions, you don't actually import the error - rather you access it through the client. Check this out: https://github.com/boto/boto3/issues/1195#issuecomment-317108970
import boto3
rds = boto3.client('rds')
try:
    ...
except rds.exceptions.DBInstanceNotFoundFault:
    ...


text:
Q: Logging stack trace in log appender I would like to log the exception stack trace in stack-trace field of logstash log appender instead of being inside the message field
public void exceptionsCatcher(JoinPoint joinPoint, RuntimeException e) {
    ...
    log.error("exception  : {} ", e);

    ...
}

I searched throw community and just found solution with grok to filter out stack-trace from message field, what i would like is to set it at stack-trace field in application level and not in logstash filter .

A: You don't need extra configuration to do so just use proper overloaded method of your log provider, for example
    public void exceptionsCatcher(JoinPoint joinPoint, RuntimeException e) {
    ...
    log.error("exception : {} " + " some message description perhaps {}",
            e.getLocalizedMessage(), e.getMessage(), e);
    ...
}

The third marker will ingest stack trace into stack-trace attribute, find more about other overloaded methods in here.


text:
Q: Липкий горизонтальный скролл для таблицы Всем добра! Подскажите пожалуйста, есть вообще возможность сделать липкий горизонтальный скролл у таблицы? Есть большая таблица, снизу есть горизонтальный скролл, собственно, чтобы прокрутить таблицу в сторону, надо сначала промотать вниз до конца таблицы, передвинуть скроллинг, вернутся вверх, найти нужную строку, в общем неудобно... А так бы скроллинг всегда был снизу экрана, можно листать туда-сюда в любом месте
Пытаюсь сделать, как здесь но чёт не выходит:

  HEADER

MAIN CONTENT

  FOOTER

Стили
body{color:#fff; font-family:arial; font-weight:bold; font-size:40px; }
.main-container{ max-width:600px; margin:0 auto; border:solid 10px green; padding:10px; margin-top:40px;}
.main-container *{padding:10px;background:#aaa; border:dashed 5px #000;}
.main-container * + *{margin-top:20px;}
.main-header{
  height:50px; background:#aaa;
}
.main-content{
  min-height:1000px;
}

.main-footer{position:-webkit-sticky; position:sticky; bottom:0; border-color:red;}

Источник: https://codepen.io/elad2412/pen/MZZVjw

Добавил в оба класса, но изменений нет, что я делаю не так?

Либо какой-то может есть вариант, чтобы можно было двигать таблицу вправо/влево курсором мыши? Курсор типа cursor:grab, но это меняет только внешний вид курсора, без добавления функционала сдвигания таблицы


text:
Q: Can't get title from the first RICHEDIT60W child in Lync This code I do not get the first available RICHEDIT60W:
from pywinauto.application import Application
app = Application().connect(class_name='CommunicatorMainWindowClass')
window = app.window(class_name='CommunicatorMainWindowClass')

window.NetUINativeHWNDHost.NetUIHWND.print_control_identifiers()

print()
rich_edit = window.NetUINativeHWNDHost.NetUIHWND.NetUICtrlNotifySink.RICHEDIT60W
print("rich_edit:", rich_edit.WindowText())

Console:

Control Identifiers:

NetUIHWND - ''    (L162, T378, R562, B957)
['', '1', 'NetUIHWND', '0']
child_window(class_name="NetUIHWND")
   |
   | NetUICtrlNotifySink - ''    (L186, T408, R537, B425)
   | ['2', 'NetUICtrlNotifySink1', 'NetUICtrlNotifySink', 'NetUICtrlNotifySink0']
   | child_window(class_name="NetUICtrlNotifySink")
   |    |
   |    | RICHEDIT60W - '///'    (L186, T408, R537, B425)
   |    | ['RICHEDIT60W0', '///RICHEDIT60W', 'RICHEDIT60W1', '///', 'RICHEDIT60W']
   |    | child_window(title="///", class_name="RICHEDIT60W")
   |
   | RICHEDIT60W - '///'    (L186, T408, R537, B425)
   | ['RICHEDIT60W0', '///RICHEDIT60W', 'RICHEDIT60W1', '///', 'RICHEDIT60W']
   | child_window(title="///", class_name="RICHEDIT60W")
   |
   | NetUICtrlNotifySink - ''    (L184, T548, R515, B562)
   | ['3', 'NetUICtrlNotifySink2']
   | child_window(class_name="NetUICtrlNotifySink")
   |    |
   |    | RICHEDIT60W - 'qwerty'    (L184, T548, R515, B562)
   |    | ['RICHEDIT60W2', 'qwerty', 'qwertyRICHEDIT60W']
   |    | child_window(title="qwerty", class_name="RICHEDIT60W")
   |
   | RICHEDIT60W - 'qwerty'    (L184, T548, R515, B562)
   | ['RICHEDIT60W2', 'qwerty', 'qwertyRICHEDIT60W']
   | child_window(title="qwerty", class_name="RICHEDIT60W")
   |
   | NetUICtrlNotifySink - ''    (L162, T378, R162, B378)
   | ['4', 'NetUICtrlNotifySink3']
   | child_window(class_name="NetUICtrlNotifySink")

rich_edit: qwerty

By elements of the list, the first had to be "///" and not "qwerty"
What is the problem?
How to get the item with "///"?

A: Turned out to make so:
import pywinauto
window = pywinauto.findwindows.find_element(title_re='Microsoft Lync.*')
child = window.children()[3]
print(child.rich_text)  #  ///


text:
Q: Django-debug-toolbar not displaying (Can't find the .js and .css) and display is at "none"
Possible Duplicate:
django-debug-toolbar looking for assets by relative path?

So I just followed the instructions to install the django-debug-toolbar v0.9.4, and I can't make the toolbar appear in BOTH the admin and regular application. However, I can see it in the HTML source (via Chrome for example) and the display is set to "none". If I remove that style, it appears (without style and JS however) Also, it can't find the .js and .css.

Failed to load resource: the server responded with a status of 404 (NOT FOUND) 127.../machines/view/2/debug_toolbar/css/toolbar.min.css
Failed to load resource: the server responded with a status of 404 (NOT FOUND) 127.../machines/view/2/debug_toolbar/css/toolbar.min.js

Here are my settings so far relevant to this problem: http://dpaste.org/ar9ji/


text:
Q: how to detect an intersection when i hit the ground? Watch this image example:

Hi guys, I have a question about "Intersector", what I want is when I click the screen, I get the intersection, then I put a 3d modals on the ground according the intersection point. The problem was I can't get the intersection.
Here is my code
public Vector3 getIntersect(int screenX, int screenY) {
    Ray ray = cam.getPickRay(screenX, screenY);
    Vector3 ins = new Vector3();
    for (int i = 0; i < parentModels.size; ++i) {
        final GameObject go = parentModels.get(i);
        Intersector.intersectRayBounds(ray, go.bounds, ins);
    }
    return ins;
}

GameObject extends form ModelInstance.


text:
Q: How can I set a multiline UILabel inside UITableCell on Swift 3? I am trying to set a multiline UILabel, inside an UITableCell.
That UILabel has a proportional width taking as reference the screen of the device (with a multiplier). The text inside of it can change so I need to fit on the UILabel being able to multiline when the width of the text is higher than the space of the UILabel width.
I tried using:
myLabel.lineBreakMode = .byWordWrapping
myLabel.numberOfLines = 0
myLabel.sizeToFit()

but it is always displayed on one line truncating the text that overflows the UILabel width.
How can I make my UILabel to be multiline?
EDIT: I cannot put breaklines to my text because I retrieve my texts from my database.
Thanks in advance!

A: These two lines are necessary for calculating the cell height automatically. Put these in viewDidLoad.
self.tableView.estimatedRowHeight = 50.0
self.tableView.rowHeight = UITableViewAutomaticDimension

A: If you want a label to switch from one line to multiple lines, you either have to specify line breaks in the text of the string with \n or newline char, or you can set constraints for the width of the label, or you can set leading and trailing constraints for the label. If one of those methods is complete, the label will go to as many lines as it takes to hit the max number of lines or infinite if set to 0.

A: Finally I was able to make my multiline UILabel adding this code:
self.tableView.estimatedRowHeight = 50.0

and reducing the multiplier value. It seems that the text could not fit on the height of the UITableCell.


text:
Q: Java text field foucusing I have a default text set on my textfield, how does the program remove this text when the user focuses on the textfield. Vice-Versa, when the user isn't focused on the textfield the default text comes back.
I was thinking on adding an action event on the TF but that only works when the user taps the enter button whilst focused on the TF. Would a thread would work?

A: Consider adding a FocusListener to the JTextField. In the focusGained(FocusEvent e) method, you could check the JTextField's text and if it exactly matches the preview text, remove it. In the focusLost(FocusEvent e) method, you check if the JTextField is empty, and if so, re-add the default text.
myTextField.addFocusListener(new FocusListener() {
  public void focusGained(FocusEvent e){
    // get text from JTextField
    // if text matches default text, either select all, so user can keep it or change it
    // or delete it --- your choice
  }

  public void foucsLost(FocusEvent e){
    // check if JTextField's text is empty.
    // if so, cal setText(DEFAULT_TEXT) on the field
  }
});

A: You can call these functions on your any JTextFields
public void FocusGainedEmptyBox(JTextField txt)
{
   txt.setText(null);
}

public void FocusLostFillBox(JTextField txt)
{
   if(!txt.getText().equals(""))
   {
     txt.setText("I am Back");
   }
}

call FocusGainedEmptyBox(txtValue) on Focus Gained and FocusLostFillBox(txtValue) on Focus Lost.

A: Adding/removing text from the text field can cause problems if you ever need to use a DocumentListener on the text field to know when text changes.
For a different solution to this problem check out Text Prompt.

A: I think you want to do same as like HTML placeholder ,
 private void txtSearchStandardFocusLost(java.awt.event.FocusEvent evt) {
        // TODO add your handling code here:
        if (txtSearchStandard.getText().equals("")) {
            txtSearchStandard.setText(" Type Here to Search Standard");
            txtSearchStandard.setForeground(Color.GRAY);
        }

    }

    private void txtSearchStandardFocusGained(java.awt.event.FocusEvent evt) {
        // TODO add your handling code here:
        if (txtSearchStandard.getText().equals(" Type Here to Search Standard")) {
            txtSearchStandard.setText("");
        }

        txtSearchStandard.setForeground(Color.BLACK);
    }

But Keep in mind about this whenever you are trying to add some another event on this same TEXTFIELD


text:
Q: Django won't eat quicktime objects Django (1.2.5) won't play *.mov files, however it does take flv and mp4 files.. anything special about quicktime objects?
It says access denied or file not found, file is on the right path other file types work perfectly, the absolute domain does play the movie (its embedded in JW player on the site, who state they support mov format, H264 AAC)
what the...
tested in a local server with plain html.. 100% JW player bug.. too be continued

A: If you're doing things the right way, Django doesn't serve movie files, the web server (apache, nginx, cherokee, etc.) serve them. So the problem is probably on the side of your web server's configuration.

A: Are you sure the static files serving has been correctly configured? From the djangoproject file:
`(r'^site_media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/path/to/media'}),`


text:
Q: C# Private/Public Encryption using AES I am trying to figure out how to make public/private keys that are AES encrypted. I'd like to be able to use it like so:
byte[] BytesToEncrypt = { 0x01, 0x02, 0x03, 0x04, 0x05 };
byte[] PublicKey;
byte[] PrivateKey;
byte[] EncryptedBytes;
byte[] UnencryptedBytes;

PrivateKey = CreatePrivateKey();
PublicKey = CreatePublicKey(PrivateKey);
EncryptedBytes = EncryptBytes(PrivateKey);
// This line should return unencrypted bytes
UnencryptedBytes = UnencryptBytes(EncryptedBytes, PrivateKey);
// This line should also return the unencrypted bytes
UnencryptedBytes = UnencryptBytes(EncryptedBytes, PublicKey);

How can I implement something like this? I've seen public/private encryption, but all the examples I've seen seem to use RSA encryption. I want to use AES. Is this possible?

A: AES is an algorithm for symmetric-key encryption, so it doesn't make sense to talk about public and private AES keys. If your AES key is public there is no security at all.
You can encrypt an RSA public key using AES encryption if you wish, but it is unnecessary as it is not something you need to keep secret.
You can encrypt an RSA private key using AES encryption. This could be useful if you want to password protect your key so that if your computer is stolen they cannot use your key.
You can also use an asymmetric encryption to transfer a symmetric key to another party and then afterwards communicate with them using symmetric encryption.  TLS uses this principle. It can be useful because symmetric algorithms can be faster to compute, but sending a symmetric key to someone in plain text would be insecure so you need the asymmetric encryption to keep the symmetric key safe.

A: While AES encryption is symmetric, I assume that your goal is to encrypt data (and have to use AES for whatever reason), give that data to someone else, allow them to read it, but only if they have your public key.
You could consider this workflow:

*

*Generate an AES encryption key.

*Encrypt your data using AES encryption key.

*Generate a public and private key.

*Use the private key to encrypt your AES encryption key.

*Distribute the AES encrypted data, your public key, and your AES key as encrypted by the private key.

This is similar to what SSL does (not exactly though because the there is a handshake procedure with data being encrypted using public keys, not private keys), but might meet your needs.
This workflow ensures that your AES key can only be discovered if someone has your public key, but given that they then have the correct AES key, doesn't prevent someone from replacing your original data with other data. That's what public/private key data signing is for.


text:
Q: Redis store data in backup.db file I have RedisDB that exists in a Docker container. Database restored from dump.rdb file and everything works well (I can get all data that stored in Redis before) until Redis tries to save data in the background. Log here:
1:M 28 Jan 2021 11:28:28.035 * 100 changes in 300 seconds. Saving...
1:M 28 Jan 2021 11:28:28.349 * Background saving started by pid 21
21:C 28 Jan 2021 11:30:23.589 * DB saved on disk
21:C 28 Jan 2021 11:30:23.930 * RDB: 0 MB of memory used by copy-on-write

And after that, I see in the folder a new file: backup.db, and all data I get from this file (instead of dump.rdb).
redis.conf:
appendonly yes
appendfilename "appendonly.aof"
dbfilename dump.rdb
dir ./
save 900 1
save 300 10
save 60 10000

Docker run command:
docker run --name redis -p 6379:6379 -v /redis/data:/data -v /redis/config/redis.conf:/usr/local/etc/redis/redis.conf -d redis

dump.rdb file stored into /redis/data folder and redis.conf stored into /redis/config folder
Redis version: 6.0.10
Question: How to avoid creation backup.db file?


text:
Q: Posting a private photo on facebook I'm trying to give users the possibility to upload a photo from their local drive to Facebook. I'm using this blogpost(second scenario). It works fine, but I want to make the photo automaticly "private" (or upload it to a private album).
Extra info: I use this to upload the photo to a page (user is admin, of course), not a profile.
Also: I'm planning on changing to blogpost's code to PHP SDK friendly code, so anything on setting it private using the sdk is welcome as well.
Thanks!

A: For a user album you can do that:
When you create your album, you just have to add the privacy field (referenced here: https://developers.facebook.com/docs/reference/api/album/).
You can see the various possible values here: https://developers.facebook.com/docs/reference/api/privacy-parameter/
But for a page, even if you're admin, it seems you can't:

Note: The privacy parameter only applies for posts to the user's own timeline and is ultimately governed by the privacy ceiling a user has configured for an app. It does not apply to posts made by an app on behalf of a user to another user's timelines or to Pages, events, or groups. In those cases, such posts are viewable by anyone who can see the timeline or content in the group or event.


text:
Q: php compare array keys, not values I am successfully using the array_key_exists(), as described by php.net
Example:
<?php
$search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)) {
    echo "The 'first' element is in the array";
}
?>

But, take out the values, and it doesn't work.
<?php
$search_array = array('first', 'second');
if (array_key_exists('first', $search_array)) {
    echo "The 'first' element is in the array";
}
?>

Not sure how to only compare 2 arrays by their keys only.

A: In PHP, each element in a array has two parts: the key and the value.
Unless you manually say what keys you want attached to each value, PHP gives each element a numerical index starting at 0, incrementing by 1.
So the difference between
array('first','second')

and
array('first'=>1,'second'=>4)

is that the first doesn't have user-defined keys. (It actually has the keys 0 and 1)
If you were to do print_r() on the first, it would say something like
Array {
    [0] => "first",
    [1] => "second"
}

whereas the second would look like
Array {
    ["first"]  => 1,
    ["second"] => 2
}

So, to check if the key "first" exists, you would use
array_key_exists('first',$search_array);

to check if the the value "first" exists, you would use
in_array('first',$search_array);

A: The first example is an associative array: keys with values assigned. The second example is just a prettier way of saying:
array(0 => 'first', 1 => 'second')

For the second, you would need to use in_array. You shouldn't check for the presence of a key, which array_key_exists does, but rather the presence of a value, which in_array does.
if(in_array('first', $array))

A: in the second example, you didn't assign array keys - you just set up a basic "list" of objects
use in_array("first", $search_array); to check if a value is in a regular array

A: In your second example the keys are numeric your $search_array actually looks like this:
array(0=>'first', 1=>'second');

so they key 'first' doesnt exist, the value 'first' does. so
in_array('first', $search_array);

is the function you would want to use.

A: In PHP, if you are not giving key to array element they take default key value.Here you arrray will be internally as bellow
 $search_array = array(0=>'first', 1=>'second');

Anyway you can still fix this problem by using the array_flip function as below.
$search_array = array('first', 'second');
if (array_key_exists('first', array_flip($search_array))) {
    echo "The 'first' element is in the array";
}


text:
Q: Save Facebook credentials on React Native and Firebase I'm really new to React Native. My intention is that by storing the credentials provided by FBSDK's loginWithReadPermissions, the user won't have to log in each time the app launches, but just one time after it is first installed. Maybe store it somewhere I can check the credentials in componentWillMount().
My first question is: does the FBSDK do this automatically? If not, how can I do this?
I have this code for Facebook Auth:
facebookAuthentication(callback){
LoginManager.logInWithReadPermissions(['public_profile', 'user_likes', 'email']).then(
  function(result) {
    if (result.isCancelled) {
      alert('Inicio de sesión cancelado');
    } else {
      AccessToken.getCurrentAccessToken().then((accessTokenData) =>{
        const credential = Firebase.auth.FacebookAuthProvider.credential(accessTokenData.accessToken);
        Firebase.auth().signInWithCredential(credential).then((result) =>{
          return callback;
        }, (error) =>{
          console.log('Error en firebase' + error);
        });
      }, (error) =>{
        console.log('ACCESS TOKEN ERROR: ' + error);
      });
    }
  },
  function(error) {
    console.log('Login failed with error: ' + error);
  }
);

}
The code works perfectly, thanks in advance.

A: With React Native you can use Asyncstorage, which is basically what localstorage is for the web realm: a key-value pair mini-database.
Actually, you can retrieve the currently logged in user using Firebase's firebase.auth().currentUser. Maybe you can check on app startup if it returns a valid user object.