text:
Q: In built AEC Android performance Does anyone know if the in-built AEC that ships with Android post Jelly Bean works well? I am trying it and the output I get is very low in volume and very choppy. It does cancel all the speaker output but the leftover user input via mic is in pretty bad condition.
Just wanted to know if the AEC itself sucks or if I screwed up somewhere in the code. I could provide the generated audio file if someone wants to listen to it.

A: The built-in AEC might defer to a hardware based AEC, so it's really tough to say what performance you can expect. Note that the webrtc.org reference code has a built-in AEC that works very well, at some (software) processing cost.  If the Android device doesn't have hardware AEC anyway, that cost isn't cumulative.
Because of this, I don't think you can rely very much on consistent performance if you don't know the device beforehand.


text:
Q: Multiple data streams for web + app property I am new to google analytics and noticed that my firebase app was auto linked to a property in my google analytics account as type app + web.
In the data streams section of this property, I would like to ensure data comes through via two sources, www. and admin.. How do I achieve this? The UI on analytics only lets me link one web stream. I also don't seem to be able to edit this once it is set up.
I would actually prefer to set up two separate properties, as they are two different "apps", however in Firebase in Settings > Integrations > Manage you can only link one google property ID.
Both www. and admin. are hosting on the same firebase project, as separate web apps.
Where am I going wrong?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Database of bank accounts I'm creating a database for a 'bank' and was just unsure as to whether my method of   attaching accounts to customers was the most efficient. Here are a few of the enterprise rules:
-there are 2 types of account (current and savings)
-each account has a field for: balance, date of last access
-current accounts have overdraft
-savings accounts have interest_rate
-a customer can have as many accounts as they want
-an account can be 'subscribed' to unlimited people
I'm just not sure if the best method is just to have interest rate and overdraft in the account table to be set to null if it is the wrong account type.
Sorry if this question isn't put very well (I'm breaking my stackoverflow virginity here). Also, here is a link to the ER diagram have created so far: https://drive.google.com/file/d/0BwKmjTsIbwP0SE9Xbk1ycnkyV0E/edit?usp=sharing
Sorry that I couldn't post the image directly on here, it's just because I've got no rep...
Thanks in advance!

A: You take the information that you're given, and you normalize the data into relations.  That's why you use a relational database.
So let's start with customers.  We'll create a Customer table.  Generally, table names are singular.
Customer
--------
Customer ID
Customer name
Customer address
...

As you can see, all of the data in the Customer table is about the customer.
Next, we'll create an Account table.
Account
-------
Account ID
Account Type ID
Account balance
Account interest rate
Account overdraft
Account last access time stamp

All the data in the Account table came from your requirements statement.  The interest rate is set to zero for accounts with no interest.  The overdraft is set to zero for accounts with no overdraft.
Next, we'll create an Account Type table.
Account Type
------------
Account Type ID
Account Type

The data would be (0, Checking) and (1, Savings).  With an Account Type table, you can easily add new account types, like (2, Certificate of Deposit).
Next, even though you don't mention it, we'll create a Transaction table.  You'll need this to be able to print monthly statements.
Transaction
-----------
Transaction ID
Transaction time stamp
Transaction amount
Account ID

Ok, we've set up all of the entity type tables for banking.  Now, let's set up the relationship tables.
Customer and Account have a many to many relationship.  A customer can have many accounts, and an account can have many customers.
So, let's create a Customer Account table.
Customer Account
----------------
Customer ID
Account ID
Customer Account creation time stamp

The primary (clustering) key is (Customer ID, Account ID).  You'll also need a unique index on (Account ID, Customer ID)
I believe we're done creating tables.

*

*An account has an account type.

*A customer can have many accounts.

*An account can have many customers.

*An account can have many transactions.

*A transaction is posted to one account.


text:
Q: Show that $u(x,y)$ is constant. Let $u(x,y)$ be a harmonic function on domain s.t all the partial derivatives of $u(x,y)$ vanish at the same point of , then $u(x,y)$ is constant.
Now the thing is if the harmonic conjugate of $u(x,y)$ exists say $v(x,y)$ then $f=u+iv$ is analytic and $f^m(z)$ vanishes for all $z \in D$ then $f(z)$ is const so is $u(x,y)$.
But the question is I know that for a star shaped domain the harmonic conjugates exists not for any domain.. So what will be the solution of this?

A: A basic fact of elliptic regularity theory tells you that a function which is harmonic in a domain $D$ is also a real analytic function in $D$.
Therefore, if all partial derivatives of a harmonic function vanish simoultaneously at a given inner point of $D$, the Taylor expansion of the function centered at that point is null; thus the function itself is everywhere null in $D$ by Principle of Analytic Continuation.

A: For each $z\in D$ there is a star-shaped region $B$ with $z\in B\subset D$. (For example, a small enough open ball centered at $z$.) By your harmonic conjugate reasoning $u$ is constant on $B$. This (and the connectedness of $D$) is enough to show that $u$ is constant on all of $D$.


text:
Q: Estrutura de repetição que compara valores iguais e printe a correspondência Tenho dois arrays:
operador.tabela_perm possui ids de tela e o array telas possui além do id, o nome das telas.
Preciso criar uma estrutura de repetição que compare os dois arrays e printe o nome da tela.
Tentei algo como:
Meu array operador.tabela_perm:
(4) [1, 3, 9, 5]
0: 1
1: 3
2: 9
3: 5
length: 4

Meu array telas:
0: {id: 1, nome_tela: "Cadastrar Operador", created_at: null}
1: {id: 2, nome_tela: "Tipo do Produto", created_at: null}
2: {id: 3, nome_tela: "Produtos", created_at: null}
3: {id: 4, nome_tela: "Custos Fixos", created_at: null}
4: {id: 5, nome_tela: "Custos Variáveis", created_at: null}
5: {id: 6, nome_tela: "Custos Extras", created_at: null}
6: {id: 7, nome_tela: "Listagem dos Custos Fixos", created_at: null}

O array operador.tabela_perm possui como valores os IDS das telas.
O array telas possui id e nome, preciso printar o nome das telas que existem na tabela_perm.
    for(let i=0; i<this.operador.tabela_perm.length; i++){
      for(let j=0;j<this.operador.tabela_perm.length; j++){
        if(this.operador.tabela_perm[i] == this.telas[j].id){
          console.log(this.telas[j].nome_tela)
        }
      }
    }
  }

A: O que está acontecendo é que no seu segundo for, a condição de parada é this.operador.tabela_perm.length, que no eu exemplo é 4, então seu if só vai comparar até a posição 4 do array de telas, seu código deve ser assim:
for(let i = 0; i < this.operador.tabela_perm.length; i++) {
    for(let j = 0; j < this.telas.length; j++) {
        if(this.operador.tabela_perm[i] == this.telas[j].id) {
            console.log(this.telas[j].nome_tela)
        }
    }
}

A: Como você está utilizando Typescript, seria bacana você utilizar os recursos dele, como por exemplo os Arrow Functions, segue um exemplo de como ficaria a mesma solução acima citada.
tabela_perm.forEach((perm)=>{
  console.log(telas.find((telaName)=> telaName.id == perm).nome_tela)
})


text:
Q: Provided data source did not match an array, Observable, or DataSource at getTableUnknownDataSourceError I am new to Angular and Angular Material ,

Without Angular Materail it is working fine

    City
    State

      {{ varEmp?.address.city}}
      {{ varEmp?.address.state}}

With Angular Material it is not Working

  <ng-container matColumnDef="city">
     City
     {{element?.address.city}}
  </ng-container>

  <ng-container matColumnDef="state">
     State
     {{element?.address.state}}
  </ng-container>

In component I declared variable
displayedColumns: string[] = ['city','state'];

briefy described component code to reduce complexity

Json Object

{"address":
   {"city": "Karwar", "state": "Karnataka"}
}

A: I stumbled upon this issue as I had a static data source of json format and I needed to dump it in a mat-table.
The most common reason for this behavior is poor format of json data. The json data expected by mat-table should be in the format [{...}, {...}, {...}]. If you cannot change the format of the json data, simply convert the data to Array like this
var dataArr = new Array(jsonData));
and it would work.
Note - Converting it to array would add an extra layer of square brackets to the data. You might need to change the [dataSource] property in mat-table to dataArr[0].

A: Define the datasource of table as ;
this.dataSource = new MatTableDataSource<Address>(this.addressList);

A: You need to convert your data to an array.
[dataSource] for angular material mat-table, requires that an array of data is passed to it. Ensure that you have a well formatted array of your data before assigning to your data source

A: You could try edit the td tag and do not use ? after the element.
For example:
 {{element.address.city}}


text:
Q: Mysql get all string matches in single row field_id item_id value
-- ----
21  4139 {"repeat-test0":{"main":"test"},"repeat-test1":{"main":"test2"},"repeat-test2":{"main":"test3"}}
21  4140  {"repeat-test0":{"main":"testx"},"repeat-testx1":{"main":"testx2"},"repeat-test2":{"main":"test3"}}

I am ultimately trying to get the output to be:
field_id item_id value
-- ----
21  4139 test,test2,test3
21  4140 testx,testx2,testx3

I need something that will iterate through the different "repeat-testx' to get all of the values.
I have tried substring_index (below) - this can work - but I do not know how many of the repeats may exist in a single row.
Here is my current query:
SELECT DISTINCT
    substring_index( substring_index( `vdc_fields_values`.`value`, '"repeat-test0":{"main":"',-( 1 )), '"}', 1 ) AS `id0`,
    substring_index( substring_index( `vdc_fields_values`.`value`, '"repeat-test1":{"main":"',-( 1 )), '"}', 1 ) AS `id1`,
    substring_index( substring_index( `vdc_fields_values`.`value`, '"repeat-test2":{"main":"',-( 1 )), '"}', 1 ) AS `id2`,
    substring_index( substring_index( `vdc_fields_values`.`value`, '"repeat-test3":{"main":"',-( 1 )), '"}', 1 ) AS `id3`
FROM
    `vdc_fields_values`
WHERE
    (
    `vdc_fields_values`.`field_id` = 21
    AND `vdc_fields_values`.`item_id` =4139 )

Output is:
id0 id1 id2 id3
-- ---- --- ---
test  test2 test3 {"repeat-test0":{"main":"test

A: You should save the data normalized. JSONm will be always a bother
Mysql 5.7 solution

CREATE TABLE A (val TEXT)

INSERT INTO A Values ('{"repeat-test0":{"main":"test"},"repeat-test1":{"main":"test2"},"repeat-test2":{"main":"test3"}}'),
('{"repeat-test0":{"main":"testx"},"repeat-testx1":{"main":"testx2"},"repeat-test2":{"main":"test3"}}')

SELECT REPLACE(REPLACE(REPLACE(JSON_EXTRACT(val, '$.*.main'),'[',''),'"',''),']','') FROM A

| REPLACE(REPLACE(REPLACE(JSON_EXTRACT(val, '$.*.main'),'[',''),'"',''),']','') |
| :---------------------------------------------------------------------------- |
| test, test2, test3                                                            |
| testx, test3, testx2                                                          |

db<>fiddle here
Mysql 8 Solution

CREATE TABLE A (val TEXT)

INSERT INTO A Values ('{"repeat-test0":{"main":"test"},"repeat-test1":{"main":"test2"},"repeat-test2":{"main":"test3"}}'),
('{"repeat-test0":{"main":"testx"},"repeat-testx1":{"main":"testx2"},"repeat-test2":{"main":"test3"}}')

SELECT REGEXP_REPLACE(JSON_EXTRACT(val, '$.*.main'),'[\\[\\]"]','') FROM A

| REGEXP_REPLACE(JSON_EXTRACT(val, '$.*.main'),'[\\[\\]"]','') |
| :----------------------------------------------------------- |
| test, test2, test3                                           |
| testx, test3, testx2                                         |

db<>fiddle here


text:
Q: PHPStan "Call to an undefined method" errors with symfony/phpunit-bridge PHPStan analysis combined with symfony/phpunit-bridge raises Call to an undefined method errors.

Is it possible to ignore these errors with simple PHPStan configuration?


text:
Q: Maintaining log stream after file name change I'm trying to log to a file and move it about every 30 seconds.  I'm using the os.rename function (which I do from a supervisord process) in python to move the current log to a timestamped log (which will then be processed by another python script) and then I continue to log to the old stream from my uwsgi server.
I've also tried the RotatingFileHandler and the timed version, but they don't seem to work properly.  I wasn't sure if that was a function of using it with the uwsgi server or not.
My question is, what is the simplest and most efficient way to continue logging to the same file name after the file it was "pointing to" has been moved?

A: Once Python opens a filehandle, it will continue to point to that file even if the file is renamed.  (This is OS specific behavior, but that is the POSIX defined behavior for Unix.)
Therefore you either need to do the log rotation from inside of the Python process, or else make the file that you write to be a named pipe that itself handles log rotation.  The latter is probably easier to set up.  http://www.linuxjournal.com/article/2156 is an old, but still relevant, article on how to do this under Unix.

A: I appreciate the help, but in the end the simplest method was just opening and closing the file in python for each write.  It may not be the most efficient, but its working.

A: At a very low level, it is necessary to open and close the files to change the file a logger is writing to.  This isn't an option, it is a necessity with how files really work.
The open() call takes a pathname and returns back a file descriptor.  This points to the file itself.  Modifications to the directory entry for the file are outside of this and the file descriptor really doesn't care.
A demonstration of this can be seen on a unix system -

*

*Fire up three shell windows and cd to /tmp in each of them

*In the first shell, cat > file.tmp

*In the second shell, tail -f file.tmp
At this point, anything you type in the cat window will appear on the tail window (hitting return may be required)

*In the third shell, mv file.tmp file.foo
You've moved the file, but if you keep typing in the cat window, it will still appear in the tail window.

*In the third shell, rm file.foo
And still, what you type in the cat window shows up in the tail window, even though there's no file in /tmp anymore.

In #2, a file was opened, created on the disk, and a file descriptor was used by the shell.  In #3, the file on the disk was opened for read, and it got back a file descriptor too.  The two processes are reading and writing to a file that they each access with their own file descriptor.  Moving the file on the disk doesn't affect these processes - they are still accessing the same file.  Whats more, even though the file is deleted from the directory entry, the file exists as a common place for those two processes (until they each close the file).
The only way to break the connection between a file descriptor and the file is to close the file and open a new file to get back a new file descriptor.

Many logging frameworks have a way of doing this open and close for you.  In Python (I admit I'm just reading the docs on this), the TimedRotatingFileHandler will rotate the log (and this is probably the important bit) on the next log after the time it is set to rotate.
Lets say you have a logger that spits out about one message every 10 minutes on the 5 (so 5, 15, 25, 35, 45, and 55).  You also have a log rotator that rotates on the hour.  The log file will not appear to be rotated until the 05 log message is written, then the logger realizes that it is after the time it needs to rotate and then rotates the log file, writing the new 05 message to a new file.
A not uncommon way to solve this (and get logs rotating when you want them to) is to log a message of high enough priority to cause the logs to rotate just after the time to rotate them.
The other thing to do is wait awhile.  Do you really need to move that log file now? Or can it sit for awhile?


text:
Q: 'My brother and his fiancee had been together for two years.' Why 'had been' not 'have been'? The past perfect refers to a time earlier than before now. It is used to make it clear that one event happened before another in the past. Ok, that's good.
So in this sentence 'my brother and his fiancee had been together for two years.' why 'had been' is used not 'have been'? I think 'have been' is more natural. Sometimes it is difficult for non-native speaker to understand past perfect. So, why does the author use 'had been' not 'have been'?

A: Looking at the complete text in the picture, there is no event in the past that "been together" can be placed before, so past perfect is incorrect in this context: it should be present perfect "have been", indicating that the two years extends until the present.
If some other event had occurred in the past and the two years was before that event, or the meeting had already occurred and this was an account of the meeting, the use of past perfect would be justified:

My brother announced his engagement on New Year's Eve: he and his fiancee had been together for two years. - the two years was before the announcement.
My brother and his fiancee had been together for two years. I couldn't wait to meet her. - account of a meeting that took place in the past

The later sentence "My parents already spent..." may be OK in American English, but British English would use present perfect for this too:

My parents have already spent time with her.

Present perfect is used when a past action is still in force or has some lasting effect, and in this case the lasting effect is that your parents have checked off spending time with her on their list of things to do.

A: The writer of this book was probably not very accurate. "Had been" seems to be incorrect; normally, it is used if one is in the context of the past tense already - like a 'past tense within the past tense'. Also, the book says, "our parents already spent time with her" - this should be, "our parents have already spent time with her," as a specific event is not being referenced.


text:
Q: Webpack: Copy javascript files to output directory without processing them I have a typescript project setup with webpack. This project also contains some javascript files that should be copied to the output directory without processing them in any way.
How can I achieve this?

A: I guess you can identify those file. May with some glob patter or by direct file name. Then use
copy-webpack-plugin

A: I wouldn't try to do that with WebPack...
Just copy the files with an npm script.
lets say somenthing like this in your package.json
"scripts": {
   "deldist": "rimraf ./assets/dist",
   "copy": "copy command here",
   "prod": "npm run deldist && cross-env NODE_ENV=production webpack --progress --hide-modules --display-error-details && npm run copy"
 },

...
then you could run
npm run prod


text:
Q: How do you compare date objects to strings in Objective-C? I have an array of dates in this format:
date: 2012-01-02,2012-03-17,2012-04-09,2012-05-07,2012-06-04,2012-08-06,2012-10-29,2012-12-25,2012-12-26.

I want to compare the dates with today's date, but I need some help.  This is my code.
NSArray *date =[dict12 objectForKey:@"ie_date_closed"];
NSLog(@"date:%@",date);
int i=date;
for (i=0; i<6; i++)
{
    NSComparisonResult result = [todaydate compare:date[i]];
    NSLog(@"result:%d",result);
}

A: Here is the code have a look at & try to implement your self using it :
for (i=0; i<[date count]; i++)
{
    NSDateformatter *format = Define Your date Format Here
    NSDate yourDate = [format dateFromString:[date objectAtIndex:i]];
    If ([YourDate compare:[NSDate date]] == NSOrderedSame)
    {
        NSLog(@"Both Dates are same");
    }
}

Note : I am not giving you whole readymade code but just for a hint so using it you can be able to implement what you want.
Hope this will help.

A: try it
 NSDate *firstTime;
    NSDate *nowTime;
   NSDate *localDate = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setTimeZone:[NSTimeZone   systemTimeZone]];
    dateFormatter.dateFormat = @"YYYY-MM-dd";
    NSString *str = [dateFormatter stringFromDate:localDate];

      NSArray *date =[dict12 objectForKey:@"ie_date_closed"];
      NSLog(@"date:%@",date);
     for (i=0; i<[date count]; i++)
{

     NSString *openTime =[NSString stringWithFormate:"%@"[date objectAtindex:i]];
    NSDateFormatter *dateComperFormatter1 = [[NSDateFormatter alloc] init];
    [dateComperFormatter1 setTimeZone:[NSTimeZone   systemTimeZone]];
    [dateComperFormatter1 setDateFormat:@"YYYY-MM-dd"];

    firstTime = [dateComperFormatter1 dateFromString:openTime];
    nowTime = [dateComperFormatter1 dateFromString:str];
    //    NSComparisonResult result;
    //   // has three possible values: NSOrderedSame,NSOrderedDescending, NSOrderedAscending
    //
    //    result = [nowTime compare:firstTime]; // comparing two dates

    NSComparisonResult result = [nowTime compare:firstTime];
  }

A: Try below code:-
NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
[formatter setDateFormat:@"yyyy-MM-dd"];
for (NSString *arrDt in date){
if ([arrDt isEqualToString:[formatter stringFromDate:[NSDate date]]]){
NSLog(@"Equal Date");}}

Note:- You need to set the dateFormat according to array object dates.


text: Q: Difference between "restricted" and "limited" I'm a non-native speaker of English. When I want to express the meaning of "Something,especially for some techniques, is not widely used yet " in my paper, which word would be better? I don't quite understand the difference between these two words. Could you help me, please?


text:
Q: Open unknown type of file .REF I need help opening some files I got.
I don't know the proper way to open it, all I know is that it's text based, as it's CAN-BUS info (Digits, 01 0F 3F 4D, etc [in example]). It may be encrypted some way I can't figure.
It's supposed to open with a external program to load this data.
Now the question is,
¿There is anyway to analyze it, metadata or whatever to decrypt it?
I don't know if it's permitted, but I will pay for a working solution as it's vital for my project right now.
I add some different files so you can analyze it.
http://www.racelogic.co.uk/_downloads/vbox/Vehicle_CAN_Files/Ford/2011%20Fiesta.REF
http://www.racelogic.co.uk/_downloads/vbox/Vehicle_CAN_Files/VAG/VW_CAN.REF
Example info in file in plain text:
    Racelogic Can Data File V1
   Unit serial number : 00000000
   xÚ30€  È  LxÚJM,Š÷IM+‰ÏHM͉.HMMÑ1440Ô‰×16Ò14Ó1Ð1Ð300òÌÍÌut!Th^qfzPo~I~Q~N¢ Z45 JxÚs+ÊÏ+‰ÏHMÍ)
   Ž.HMMÑ1440Ô‰×1±Ð14Ó1Ð1Ð300Ñ16273×Ñ…P¡yÅ™éy@µ¾ù%ùEù9‰: €D LxÚJM,ŠÊLÏ
   (‰ÏHM͉.HMMÑ1440Ô‰×14!=c#s3s]šWœ™žTë›_'_"Ÿ"¨ |2ª ;xÚ
   ðÕ152Љ×1±Ð14Ó1Ð1Ð342Õ16273×Ñ…P¡yÅ™éy©):¾ù%ùEù9‰: xšë FxÚsLNN͉HMI
  'ùÅ™%™ùy:¦F:ññ:ÆF:::z¦:†Fæ:º "4¯83=/5EÇ7¿$¿(?'Q ³IV

This is an example of a CanBus file. (Note that previous .ref file, might be other format:
 865         8   0  86   3 220  96  21 125   0
 929         8   0  27  32 128  24 134   4   0
 194         6 109   4   0 127 255   1
 326         8   0 255  64  12 255   0   3 130
 358         8   0  44   0  44   0  44 128   0
  70         8  16   0   0   0 128  32   0   0
 865         8   0  86   3 231  95  21 125   0
 929         8   0  27  32 128  24 133 244   0
 194         6 126   4   0 127 255   1
1378         2   0   0
 194         6 143   4   0 127 255   1
 865         8   0  87   3 237  95  21 126   0
 929         8   0  27  32 128  24 133 244   0

A: It may be encrypted some way I can't figure
These REF files are encoded by RaceLogic. You are supposed to purchase them, and provide a CAN01 serial number. Presumably they will provide you with a key to decode them when you have paid ...

It is also possible to import industry standard CAN database files with the ".DBC" file extension or to purchase encoded data set files from Racelogic with the .REF extension.

...

Each Racelogic encoded CAN database (REF file) is locked to a specific CAN01 serial number. When ordering a REF file it is important to
   specify the serial number of the CAN01 that it is to be used with.

Source Vehicle CAN Bus Interface


text:
Q: Mockito doReturn does not work as expected I'm trying to write some tests to validate a class that operates on files in the Context#getFilesDir() directory. I'm using java.nio.file.Files#createTempDirectory to create a directory to mock getFilesDir() output, then using Mockito to return it when getFilesDir is invoked.
Mockito seems to be creating a new temp directory every time even though I declare the result of createTempDirectory as a class variable and use it for my spy'd Context. This is causing tests to fail along with cleanup step because rather than one directory, I have six or seven which violates the required state for the class being tested.
Here's the link to my commit that shows the code I've written so far: https://github.com/msfjarvis/viscerion/commit/b1504d7206

A: Turns out Mockito was doing its job properly. The problem here was my poor understanding of JUnit. The @Before annotation runs the method before each test, which was not what I wanted, since I was looking for the method to run once when the class was being tested. The correct annotation for that was @BeforeClass which solves the proble. Huge thanks to this article that explained the differences.


text:
Q: snakemake batch creation of output Generating output based on changed input files in Snakemake is easy:
rule all:
    input: [f'out_{i}.txt' for i in range(10)]
rule make_input:
    output: 'in_{i}.txt'
    shell: 'touch {output}'
rule make_output_parallel:
    input: 'in_{i}.txt'
    output: 'out_{i}.txt'
    shell: 'touch {output}'

In this case, make_output will only run for instances where in_{i}.txt have changed.
But suppose the 'out_{i}.txt' cannot be generated in parallel and I want to generate them in a single step, like,
rule make_output_one_step:
    input: [f'in_{i}.txt' for i in range(10)]
    output: [f'out_{i}.txt' for i in range(10)]
    shell: 'touch {output}'

If only one of the in_{i}.txt files have changed, I don't need to regenerate all 10 of them.
How can I adjust make_output_one_step.output to generate only the needed files?

A: If you want some parts of the pipeline to not work in parallel for whatever reason (RAM, internet usage, IO, API limit, etc....) you can make use of resources.
rule all:
    input: [f'out_{i}.txt' for i in range(10)]

rule make_input:
    output: 'in_{i}.txt'
    shell: 'touch {output}'

rule make_output:
    input: 'in_{i}.txt'
    output: 'out_{i}.txt'
    resources: max_parallel=1
    shell: 'touch {output}'

And then you can call your pipeline like snakemake --resources max_parallel=1 --cores 10. In this case all the jobs of rule make_input will run in parallel, but only one instance of make_output will run in parallel.


text:
Q: Show that this piece-wise function defines a differentiable solution Show that
$y(x) = \begin{cases}-x^4 & x < 0, \\ x^4 & x \geqq 0 \end{cases}$
defines a differentiable solution of $xy'=4y$ for all $x$, but is not of the form $y(x)=Cx^4$.

A: Given your definition of y(x), we have that:
$$y'(x):$$$$=-4x^3, x < 0$$ $$=4x^3, x \geq 0$$
substitute these values into $xy'=4y$
for $x<0$ you have $x(-4x^3)=4(-x^4)$ which reduces to $x^4=x^4$
you take the same steps to verify for $x>0$.


text:
Q: Creating "placeholder" variables in Stata There is a series of regressions I want to run, and in each regression, I decide if I want a covariate or not. So for example, let's say I have a local macro with 10 covariates:
local covariates "`N' age `N' sex `N' age2 `N' job job2 `N'"

I want 10 regressions, each with one covariate in order as listed. However, the `N' terms are placeholders meant to show that I don't want a covariate in that regression. So when running the regressions, it looks something like:
forval i=1/10 {
    local cov `: word `i' of `covariates''
    if "`cov'" != "N" {
        reg y x `cov'
    }
    else {
        reg y x
    }
}

where y is an outcome, and x is another covariate that's included in every regression.
My issue is that Stata does not recognize the `N' placeholders. More specifically, it seems like the if "`cov'" != "N" condition filters out the placeholder variables from going to the reg y x `cov' step, but they don't go to the else condition to run reg y x. After some debugging, it seems like Stata simply doesn't realize that the length of covariates is 10: when I check the length of the macro, it returns 5, and when I print each term in the macro, it only returns 5 values. Since Stata thinks the length of the macro is 5, then it breaks once the forval loop hits i=6. Hence I only get 5 regressions of the form reg y x `cov' .
So, is there a clean way to include some sort of placeholder such that Stata will recognize the length of the macro, and thus run all 10 regressions?

A: This works for me:
sysuse auto, clear

local cov weight price N turn

foreach v of local cov {
    if "`v'" == "N" regress mpg i.foreign
    else regress mpg i.foreign `v'
}

You didn't provide a complete reproducible example. But your local macro cov contains 10 words if and only if when it is defined there is a local macro N defined and visible that contains one word.
Further, only if local macro N contains the word "N" will your code work as desired.
Indeed, it is hard to see why you use a local macro reference there at all.
It is not illegal to refer to a local macro that doesn't exist, but it will be evaluated as an empty string, and the consequence of that may be not what you want, as here. Here "doesn't exist" means previously defined within the same program, do-file or chunk of code in do-file editor.
Note that foreach provides a direct route to looping over the words of a local macro.
A simple if trite comment is that writing down ten statements for the ten regressions you do want will give code that is easier to write and easier to read....


text:
Q: Lazy-Pipe-Evaluation when using "Select" to export CSV file Intended Script Output: I want to export a CSV file with certain columns from a Microsoft SharePoint list.
Script-Outline:
Firstly, I fetch the list items in $items:
$query = New-Object Microsoft.SharePoint.Client.CamlQuery
$items = $list.GetItems($query)

The columns for the output CSV file are defined in a hashmap $h ($displayName => $internalName).
Now I create a new Hashtable for each column and add it to $selects:
$selects = @()
foreach ($h in $mapping.GetEnumerator()) {
     $selects += @{ L = $h.Name; E = { $_[$h.Value] } }
}

Then I exoprt the CSV file:
$items | Select-Object $selects | Export-Csv -Path $outputPath

Now the problem:
In E I defined an expression which will be calculated only when I need it (lazily, so when the Select is executed).
When this happens, the reference to the $h.Value attribute has been altered, because $h is being looped over.
Therefore, when the expression is evaluated, $h points to the last object that has been looped over (so the last element of the hashmap). This is the case for every select statement being evaluated in the pipe.
I could fix this by saving the reference of $h (or to its Value) in another variable.
But then I need a hard-coded number of variables.
How can I solve this problem?

A: Thanks to PetSerAl, here the tested&working code example:
foreach ($h in $mapping.GetEnumerator()) {
     $selects += @{ L = $h.Name; E = { $_[$h.Value] }.GetNewClosure() }
}

We can freeze the reference to $hinside the loop by using closures, as explained in this article.


text:
Q: Access to the path is denied in C# Visual Express 2010 I'm using Visual C# Express 10. I'm trying to create, open and write to a .avi file from another .avi file. I'm using Aforge dlls for y project. The following code was programmed in a button click.
OpenFileDialog toy = new OpenFileDialog();

            toy.Filter = "AVI files (*.avi)|*.avi|All files (*.*)|*.*";
            toy.Title = "Open an AVI file";
            toy.ShowDialog();
            string wish = toy.FileName;
            VideoFileReader reader = new VideoFileReader();
            VideoFileWriter writer = new VideoFileWriter();
            string fileName = @"C:\test.avi";
            FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate);

I'm getting error in above line
            // open video file
            reader.Open(wish);
            for (int i = 0; i < 100; i++)
            {
                Bitmap videoFrame = reader.ReadVideoFrame();
                int w = videoFrame.Width;
                int h = videoFrame.Height;
                writer.Open(@"C:\test.avi",w, h);
                videoFrame.Save(i + ".bmp");
                // dispose the frame when it is no longer required
                //videoFrame.Dispose();
            }
            reader.Close();

The error I receive is "Access to the path 'C:\test.avi' is denied".
I have tried a few solutions in StackOverflow which included changing permissions of C drive and using environmental folders. Please advise me on this.
EDIT:
Sorry for the delay. I cant write the log file as well. I'm trying to upload a pic
EDIT 2:
This is the exception. I got it from textbox and just typed it out. I replaced my name with xxxx though.
System.UnauthorizedAccessException: Access to the path 'C:\test.avi' is denied.
at System.IO._Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access,
Int32 rights, Boolean useRights, FileShare share, Int32 buffersize, FileOptions)
options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy,
Boolean useLongPath, Boolean checkHost)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access,
FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean
bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode)
at VideoFramesTest.Form1.OpenAndSave() in
C:\Users\XXXX\documents\visual studio
2010\projects\VideoFramestest\VideoFramestest\Form1.cs:line42

A: Ok. I solved my problem by doing this.
I changed the save file path to c:users....desktop
Apparently, we cant write directly in C:.
It also works if a new folder is created in C: (like C:\test\test.avi)
Thats the solution.
And also, I tried System.IO.File.Create(fileName). Works as well.
Good luck everyone.

A: My guess given your experience with c# would be you have test.avi open
a better thing to do would be to wrap your for loop in a try/catch like so:
for (int i = 0; i < 100; i++)
{
   try
   {

       Bitmap videoFrame = reader.ReadVideoFrame();
       int w = videoFrame.Width;
       int h = videoFrame.Height;
       writer.Open(@"C:\test.avi",w, h);
       videoFrame.Save(i + ".bmp");
       // dispose the frame when it is no longer required
       //videoFrame.Dispose();
   }
   catch (Exception ex)
   {
   //show my exception
   }
}

I would also suggest you also look at Using Statements to handle resources


text:
Q: How to specify "Target" of Mogenerator generated files? I have a xcode project with multiple targets (for logic and app unit tests).
I am also using core data with the mogenerator plugin to autogenerate source files from the .xcdatamodel.
The generate files are not being generated with any of the "target" flags selected. This causes build errors.
Is anyone aware of a solution to this. I would like to be able to indicate which targets the generated files should be included in.

A: I figured this one out. You can specify the target of the .xcdatamodel file using "Get Info". Whatever targets are specified for the model are also specified for the generated files.


text:
Q: How to set time out to this? I want it to automatically press the ok button after the window is opened for 20 seconds.
I don't know how exactly to do this.
code is:
window_NameInput.prototype.processHandling = function() {
    if (this.isOpen() && this.active) {

        if (Input.isRepeated('ok')) {
            this.processOk();
        }
    }
};

What I tried:
window_NameInput.prototype.processHandling = function() {
    if (this.isOpen() && this.active) {

       { setTimeout(function ()   if (Input.isRepeated('ok')) {
            this.processOk();
        } , 20000); }

    }
};

Edit:
I actually decided to use this code below. I want to call ok handler after window has been opened for 20 seconds.
Window_NameInput.prototype.processHandling = function() {
    if (this.isOpen() && this.active) {

   setTimeout(function(){

    this.callOkHandler();

},2000);

    }
};

But I got uncaught type error this.callokhandler is not a function
Any help is appreciated Thanks in advance

A: You've misplaced your if() condition before the function {.
Try:
window_NameInput.prototype.processHandling = function(){
  if (this.isOpen() && this.active) {
      setTimeout(function() {
        if (Input.isRepeated('ok')) {
          this.processOk();
        }
      }, 20000);
  }
};

Hope this helps,


text:
Q: Cannot find an initializer for type in swift struct PhoneP {
    var name = "Un-Name"
    var pphone = "Un-Phone"
    let NumOfDay = ""
    let date :NSDate = NSDate()
}

class PhoneManager: NSObject {

    var phones = [PhoneP]()

    func addPhone(name: String, phone: String, Nday: String){
        phones.append(PhoneP(name: name, pphone: phone, NumDay: Nday ,date: NSData()))
        //phones.append(Phone(name: name, pphone: phone, NumOfDay: Nday, date: NSDate()))
}

error: swift:28:23: Cannot find an initializer for type 'Phone' that accepts an argument list of type '(name: String, pphone: String, NumOfDay: String, date: NSDate)'

Why do I get this error?

A: numOfDay and date are constants which you already set. You won't be able to change them afterwards. Just use:
PhoneP(name: "name", pphone: "phone")

Or change your struct to:
struct PhoneP {
    var name = "Un-Name"
    var pphone = "Un-Phone"
    let NumOfDay: String
    let date: NSDate
}

You can then create the struct like:
PhoneP(name: "name", pphone: "phone", NumOfDay: "day", date: NSDate())

Also, you're adding NSData() to the type of NSDate, so that won't compile as well.
phones.append(PhoneP(name: name, pphone: phone, NumDay: Nday ,date: NSData()))


text:
Q: Why do OpenSSl Encription times vary with modifications to file? I have a ssl wrapper around GNU-Cash which decrypts my data file when opening GNU-Cash, and then re-encrypts it when I exit the app, overwriting the original encrypted file and then deletes the unencrypted one. What happens is if I make say 1 single change in GNU-Cash, the file re-encryption is a second or two, but if I make a lot of changes to the data, then the encryption takes significantly longer. It appears the time to create the new encrypted file is directly related to the changes made in the data file within.
I cannot see why it takes longer to encrypt a heavily modified file than the same one with only minor changes. My script does not remove the original encrypted data, just overwrites it upon exit from GNU-Cash. Does OpenSSl reference the old copy of the encrypted data file which it is over-writing?
I can post the whole thing if needed, but here are the Decrypt and Encrypt lines from the script:
openssl enc -d -aes-256-cbc -pbkdf2 -in ${DATA_FILE} -out ${DECRYPTED_FILE} -pass stdin <<EOPW &> /dev/null
${FILEPASS}
EOPW
openssl enc -e -aes-256-cbc -pbkdf2 -in ${DECRYPTED_FILE} -out ${DATA_FILE} -pass stdin <<EOPW &> /dev/null
${FILEPASS}
EOPW
Thanks.


text:
Q: How to save each row from csv file I want to save each row from a csv file. However, it is only printing the index column even though I sent the index column to false.
The following is my code:
def sizefcn(self):
        path1 = self.folder_path
        path2 = self.file_path
        path3 = Path(path2)
        file2=self.get_entry2()
        sizes = pd.read_csv(path3,header=None, index_col=False)
        for index, row in sizes.iterrows():
            size = row
            print(size)

I inputted a csv with 3 rows and no header, but it is giving me the index and the row so the output I get is
(0, 0    111
Name: 0, dtype: int64)
(1, 0    1111
Name: 1, dtype: int64)
(2, 0    121
Name: 2, dtype: int64)

but I want the output to be the numbers so : 111, 1111, 121.

A: I believe index_col takes an integer as a paramter. It defines which column in your csv you want to use as the index. Try omitting it entirely:
sizes = pd.read_csv(path3, header=None)

I should add that if you were to save this is a csv, you would want to include index=False. For example:
sizes.to_csv('outputfilename.csv', header=False, index=False)

Edit:
The for loop is also iterating over the index. Try this:
for index, row in sizes.iterrows():
    size = row
    print(size)

I'm not really sure what you're trying to do, but there might be a better way than writing a function for it considering the extensive functionality of pandas. Can you explain your problem in a little more detail?
From the provided description it seems like you want this:
for index, row in sizes.iterrows():
    size = row.to_list()
    print(size)

I tried this and it works for me:
In[]: df = pd.DataFrame({0:range(5), 1:range(5,10)})
In[]: df

Out[]:
   0  1
0  0  5
1  1  6
2  2  7
3  3  8
4  4  9

In[]: for index, row in df.iterrows():
          print(row.to_list())

Out[]:
[0, 5]
[1, 6]
[2, 7]
[3, 8]
[4, 9]


text:
Q: Is it possible for nhibernate to return a query as an IDictionary instead of an entity class? I have an entity Person:
public class Person
{
   public virtual int Id {get; set; }
   public virtual string FirstName { get; set; }
   public virtual string MiddleName { get; set; }
   public virtual string LastName { get; set; }
}

with the mappings:
public class PersonMap
{
   public PersonMap()
   {
       Table(TABLE_NAME);
       Id( x => x.Id);
       Map(x => x.FirstName).Not.Nullable();
       Map(x => x.LastName).Not.Nullable();
       Map(x => x.MiddleName).Not.Nullable();
    }
}

There are some stuations where I would like Nhibernate to return a dictionary instead of the entity:
IDictionary<string,string> person = session.Get(id);//????
string firstName = person["FirstName"];

Is this possible to without adding a different mapping?

A: session.CreateCriteria<Person>()
.SetResultTransformer(NHibernate.Transform.Transformers.AliasToEntityMap)
.List<Hashtable>();

something like this?

A: You don't need the DictionaryResultTransformer that DanP posted. AliasToEntityMapTransformer does the same thing, though neither will work on its own.  You'll get a dictionary of entities.
The only way I have found to do it is to project each property individually.  However you don't want to do that by hand because it will break whenever you change your mapping.  The solution is something like this:
var criteria = DetachedCriteria.For<Person>();
criteria.Add(Restrictions.Eq("Id", id));
var projectionList = Projections.ProjectionList();
var metadata = session.SessionFactory.GetClassMetadata(typeof(Person));
foreach (var name in metadata.PropertyNames)
{
    projectionList.Add(Projections.Property(name), name);
}
criteria
    .SetProjection(projectionList)
    .SetResultTransformer(Transformers.AliasToEntityMap);
var result = criteria.GetExecutableCriteria(session)
    .UniqueResult<IDictionary>()

In the above example, I am using a query to simulate a Get.  Of course, you can change this a bit and return a collection instead; just call List<T> instead of UniqueResult<T>.

A: You will need to define your own ResultTransformer implementation to have this working the way you need it. Below is a reference implementation that you can tweak as needed. There is a complete lack of error-checking, etc; so use with caution ;)
using System;
using System.Collections;
using NHibernate;
using NHibernate.Properties;
using NHibernate.Transform;

[Serializable]
public class DictionaryResultTransformer : IResultTransformer
{

        public DictionaryResultTransformer()
        {

        }

        #region IResultTransformer Members

        public IList TransformList(IList collection)
        {
                return collection;
        }

        public object TransformTuple(object[] tuple, string[] aliases)
        {
          var result = new Dictionary<string,object>();
          for (int i = 0; i < aliases.Length; i++)
          {
            result[aliases[i]] = tuple[i];
          }
          return result;
        }

        #endregion
}

A: No, but you can easily accomplish that by encapsulating the logic in a repository method.
public IDictionary<string, string> GetPersonDictionary(int id)
{
    var person = session.Get<Person>(id);
    var dict = new Dictionary<string, string>();
    dict.Add("FirstName", person.FirstName);
    /// etc.
    return dict;
}

You could also use reflection to populate the dictionary.

A: Look at this blog post:
http://sdesmedt.wordpress.com/2006/09/04/nhibernate-part-4-mapping-techniques-for-aggregation-one-to-many-mapping/
If you want a concrete example, check the samples of this nice tutorial. Look at the summaries that are not entities and have custom mapping logic:
http://www.codeproject.com/KB/architecture/NHibernateBestPractices.aspx
Or do a google search on SetResultTransformer that is available just for that, transform results in another objects or collections. Including IDictionnary.

A: You can do this by performing a client-side linq projection, see Diego's answer to this post.


text:
Q: how to defer compilation phase of the child directives unti the scope of parent directive has all data it requires I have the following html structure:
<my-parent-directive>
   <my-child-directive some-options="options">

And the controller for the myParentDirective which should instantiate $scope:
ng.module("some").directive("myParentDirective", ["someService", function(someService) {
    return {
        controller: function($scope) {
            someService.getData().then(function(options) {
                $scope.options = options;
            });
        }
    }
});

Since getData method is asynchronous and may take a while to return the options which are essential for the child directive I need to suspend compilation\linking phase for the child directive until the options have arrived. How can I do that?

A: Yes, actually its quite possible by manually inserting your child code inside the parent directive after the data received. Here is an short example:
app.directive('myParentDirective', ["someService", function(someService) {
    return {
        restrict: 'E',
        transclude: true,
        link: function($scope, element, attr, controller, transclude) {
            someService.getData().then(function(options) {
                 $scope.options = options;

                 // Grab the inner content of the directive
                 var innerContent = transclude($scope, function() {});
                 // And place it inside & recompile it
                 element.html(innerContent);
                 // For angular version 1.2.17 or lesser, compile the content
                 $compile(element.contents())($scope);
            });
        }
    };
}]);


text:
Q: How does Func Work? I am creating a Distinct extension method where I can pass in the criteria like the following.
persons.Distinct(p => p.Name);

I got the code from the web but I am having a hard time understanding the purpose of Func<T, TResult>. Also, when I say p => p.Name am I sending the String Name or am I sending the complete Person object? Here is the new Distinct method:
public static class ExtensionMethods
{
    public static IEnumerable<T> Distinct<T>(
        this IEnumerable<T> list, Func<T,object> checker)
    {
        return list.Distinct(new GenericComparer<T>(checker));
    }
}

public class GenericComparer<T> : IEqualityComparer<T>
{
    private Func<T, object> _checker;

    public GenericComparer(Func<T,object> checker)
    {
        _checker = checker;
    }

    public bool Equals(T x, T y)
    {
        return _checker(x).Equals(_checker(y));
    }

    public int GetHashCode(T obj)
    {
        return _checker(obj).GetHashCode();
    }
}

And here is the usage:
static void Main(string[] args)
{
    var persons = new List<Person>()
    {
        new Person() { Id = 1, Name = "Mary"},
        new Person() {Id = 2, Name="John"},
        new Person() { Id = 3, Name = "Mary"}
    };

    var uniquePersons = persons.Distinct(p => p.Name);

    foreach(var person in uniquePersons)
    {
        Console.WriteLine(person.Name);
    }
}

A: When you do this:
persons.Distinct(p => p.Name);

You're basically creating a function on the fly (using lambda expressions), that looks like this:
string theFunction(Person p)
{
    return p.Name;
}

This is a function that fits the signature of a Func<Person,String> delegate.  The Distinct method can take a delegate (basically a function pointer) which it uses to determine whether or not an element is distinct - in your case, only unique strings (returned by the function above) will be considered "distinct" elements.  This delegate is run on each element of your "persons" enumerable, and the results of those functions are used.  It then creates a sequence (IEnumerable<Person>) from those elements.

A: Func<T, TResult>

defines a function that accepts one parameter (of type T) and returns an object (of type TResult).
In your case, if you want a function that takes a Person object and returns a string...you'd want
Func<Person, string>

which is the equivalent of:
string Function(Person p)
{
    return p.Name;
}

A: You are getting back the distinct People, under the assumption that two People are the same if they have the same name
If you want a distinct set of names, you can use this:
IEnumerable<String> names = persons.Select(p => p.Name).Distinct();


text:
Q: Use selector to call function with parameters My Swift code looks like this:
class SystemClass {
    public init() {}
    func setXYZ(xyz: Float32) {
        // do something
    }
}

let callME: class = class()
class class {
  public init() {}
  func functionXYZ() {
    Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(SystemClass().setXYZ(xyz: 1.0)), userInfo: nil, repeats: true) // error code
  }
}

callME.functionXYZ()

I'd like to call the 'functionXYZ' and this is already working fine but calling the setXYZ function leads to errors because the selector failed.
How to edit the selector:
#selector(SystemClass().setXYZ(xyz: 1.0))

to call the setXYZ function with the given parameter?

A: EDIT: Updating to include pre-iOS 10.0 solution
In this case it'd be better to use the scheduledTimer function that takes a block, as this will allow you to pass arguments to your function:
Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { (timer) in
    SystemClass().setXYZ(xyz: 1.0)
}

For pre-iOS 10.0:
You can also pass userInfo in, including this default value, and then access that info from your inside your selector, like this:
Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(SystemClass().setXYZ(_:)), userInfo: 1.0, repeats: true)

To do this you'd also have to modify your setXYZ function signature to look like this:
@objc func setXYZ(_ sender: Timer) {
    if let xyz = sender.userInfo as? Float {
        print(xyz)
        // do something
    }
}


text:
Q: Toggle Windows 10 keyboard enabled/disabled state conditionally or programmatically So most information I've found online for disabling your laptop keyboard in Windows 10 is to go into Device Manager and uninstall the driver for your built-in keyboard so it will only use the input from your external one.
What I'd like to know is:

*

*Is there any other way to do this? This seems like a hack/workaround.

*Most information I've come across says that to re-enable your
built-in keyboard, you just restart your machine. Is there a faster
way to toggle the enabled/disabled state?

*Can I automate/script this process? It would be really cool if I
could write a program that toggles the state of the built-in keyboard
either with a button press or click, or if it detects a certain USB
device being plugged in.
EDIT
So this is what devcon says about my keyboard hardware:
HID\VID_320F&PID_500D&MI_00\7&FD25638&0&0000
    Name: HID Keyboard Device
    Hardware IDs:
        HID\VID_320F&PID_500D&REV_0100&MI_00
        HID\VID_320F&PID_500D&MI_00
        HID\VID_320F&UP:0001_U:0006
        HID_DEVICE_SYSTEM_KEYBOARD
        HID_DEVICE_UP:0001_U:0006
        HID_DEVICE

HID\VID_320F&PID_500D&MI_01&COL01\7&33A993FA&0&0000
    Name: HID Keyboard Device
    Hardware IDs:
        HID\VID_320F&PID_500D&REV_0100&MI_01&Col01
        HID\VID_320F&PID_500D&MI_01&Col01
        HID\VID_320F&UP:0001_U:0006
        HID_DEVICE_SYSTEM_KEYBOARD
        HID_DEVICE_UP:0001_U:0006
        HID_DEVICE

ACPI\MSNB1001\4&2B980D14&0
    Name: Standard PS/2 Keyboard
    Hardware IDs:
        ACPI\VEN_MSNB&DEV_1001
        ACPI\MSNB1001
        *MSNB1001
    Compatible IDs:
        *PNP0303

HID\VID_046D&PID_C52B&MI_00\7&DB720BD&0&0000
    Name: HID Keyboard Device
    Hardware IDs:
        HID\VID_046D&PID_C52B&REV_2411&MI_00
        HID\VID_046D&PID_C52B&MI_00
        HID\VID_046D&UP:0001_U:0006
        HID_DEVICE_SYSTEM_KEYBOARD
        HID_DEVICE_UP:0001_U:0006
        HID_DEVICE

If I do this:
C:\Windows\system32>devcon.exe disable HID_DEVICE_SYSTEM_KEYBOARD

I get:
HID\VID_320F&PID_500D&MI_00\7&FD25638&0&0000                : Disable failed
HID\VID_320F&PID_500D&MI_01&COL01\7&33A993FA&0&0000         : Disable failed
HID\VID_046D&PID_C52B&MI_00\7&DB720BD&0&0000                : Disable failed
No matching devices found.

I don't know why my built-in keyboard shows up 3 times either. The 4th keyboard is the USB one I don't want to disable.
I'm definitely running CMD as admin, and the devcon status and restart commands work properly.

A: The easiest way is to disable a device, e.g. "Standard PS/2 keyboard*, not to completely remove its drivers. And the simplest way to script this is with Microsoft's small command-line utility, devcon.exe.

*

*First, download devcon from Microsoft. For Windows 10, v. 1803 and later,

*

*Download the CAB file (just ~6 MB),

*Open the CAB file in Windows Explorer or 7-Zip,

*Extract the file filbad6e2cce5ebc45a401e19c613d0a28f and

*Rename that file to devcon.exe.

*Put devcon.exe in a location in PATH, e.g., %SystemRoot%\system32, or use the full path to devcon.exe in batch files.

*[For safety, you can check it in VirusTotal.]

*Find the ID of the keyboard device:

*

*Press Windows, type CMD, and press CtrlShiftEnter to open a CMD prompt as Administrator.

*Use cd to move to the folder holding devcon.exe.

*Enter the following to find the hardware ID's of all devices.
devcon.exe hwids *

*Copy all the CMD text withCtrlA.

*Paste the text into any text editor, such as Notepad, and search for keyb.

*There are multiple ID's for that device; pick one that is unique in that list, which is shown as <device-name>, below.

*Now you can create two very short scripts to disable and to enable the keyboard.

*

*Create a text file; insert into it devcon.exe disable "<device-name>", including quotation marks.

*Save the file and rename the text file to disable-keyboard.bat.

*Create a text file; insert into it devcon.exe enable "<device-name>", including quotation marks.

*Save the file and rename the text file to enable-keyboard.bat.

Now, just run one script (as Administrator) to disable he keyboard, and the the other to re-enable it. To make that easier yet, create shortcuts to the two scripts and set in Advanced properties to Run as Administrator.
Believe it or not, despite the long description, you can do this in just a few minutes.
N.B. Once you've disabled the keyboard, you'll need some way to run the re-enabling script *without use of the keboard.


text:
Q: How to get related contact role in SOQL-query? Salute.
I'm trying to add to the related contact list page an indication of the role of each indirect contact. In the standard page "Related Contacts" this field is, but how make it in custom - I don't understand.
Apparently, through an appeal to Account Contact Relationship? How to add it to a SOQL query?
public List<Contact> Contacts { get{
  return [SELECT Id, Name, Account.Name, Title, Email, Phone, Relations__c FROM
  Contact LIMIT 1000];
  } set;}

--
<apex:pageBlock title="Related Contacts">

   <apex:pageBlockButtons location="both">
     <apex:form >
        <apex:commandbutton action="{!URLFOR($Action.AccountContactRelation.AddRelation)}" value="New Related Contact"/>
     </apex:form>
   </apex:pageBlockButtons>

  <apex:pageBlockTable value="{!Contacts}" var="c">

      <apex:column headerValue="Name">
      <apex:outputLink value="/{!c.Id}">{!c.name}</apex:outputLink>
      </apex:column>
      <apex:column value="{!c.Account.Name}"/>
      <apex:column value="{!c.Title}"/>
      <apex:column value="{!c.Email}"/>
      <apex:column value="{!c.Phone}"/>
      <apex:column value="{!c.Relations__c}"/>

  </apex:pageBlockTable>
</apex:pageBlock>

A: The schema you are dealing with is:
Contact -> AccountContactRelation -< AccountId

where AccountContactRelation has a field Role

or
Contact -> AccountContactRole -< Account

where AccountContactRole has a field Roles (multi-picklist)

Since you are trying to display a list of Contacts and their roles on a single line of VF , you are gong to need a wrapper class in your controller. I'm assuming the first example schema. Same principle applies to second example schema
public class ContactWithRoles { // wrapper class
  public Contact contact {get; private set;}
  public ContactWithRoles (Contact c) {this.contact = c;}

  public String getRoles() { // concat 0+ roles into string
     String[] result = new List<String>();
     for (AccountContactRelation acr: contact.AccountContactRelations) {
        result.add(acr.Role);
     }
     return String.join(result,';');
  }
}

public ContactWithRoles[] contactsWithRoles { // VF page refers to this collection in pageBlockTable
  get {
     if (contactsWithRoles == null) {  // lazy load
        contactsWithRoles = new List<ContactWithRoles>();
        for (Contact c =  [SELECT Id, Name, Account.Name, Title, Email, Phone,
                             (SELECT Role FROM AccountContactRelations) // relationship query
                            FROM Contact LIMIT 1000]) {
            contactsWithRoles.add(c);
     }
     return contactsWithRoles;
  } private set;
}

VF markup
 <apex:pageBlockTable value="{!contactsWithRoles}" var="cwr">

   <apex:column headerValue="Name">
     <apex:outputLink value="/{!cwr.contact.Id}">{!cwr.contact.Name}</apex:outputLink>
    </apex:column>
    <apex:column value="{!cwr.contact.Account.Name}"/>
    ...
    <apex:column value="{!cwr.roles}"/>

A: This SOQL query works for me to get Contacts and Roles
SELECT Id, Name, Account.Name, (SELECT Roles FROM AccountContactRelations), Email FROM Contact where accountid='<some account id'


text:
Q: Backend technology for front-end technologies like Twitter Bootstrap This a noob alike question, but here we go.
I´ve read about Twitter Bootstrap (among other presentation frameworks), which gives the designer/programmer the tools to build easily the front end of a webapp.
What I don´t know is how to integrate that with a, for example, Java EE backend. I mean, do those presentation frameworks allow to integrate them with any backend technology (such as Java, PHP, Python, etc)? or are they linked to a specific technology?
I've built a few Java EE web applications using GWT for the presentation layer and Java in the server side; but as I´ve pointed before, I still don´t catch how it would be integrate Bootstrap with Java for example.
I know it´s a very general question but I´d appreciate any help.

A: If you are Java-minded, you may like Tobacco, which I made just for that: http://tobacco.noroutine.me/.
Basically it's maven project template with latest js libs and latest Twitter Bootstrap.
There are some similar things around like this. One which is closest to your needs may be resthub especially their Backbone stack may be of interest.

A: Twitter Bootstrap is a frontend toolkit, so it's basically css and HTML. That means it's not tied to any specific backend technology.
From the blog post announcing it:

At its core, Bootstrap is just CSS, but it's built with Less, a
  flexible pre-processor that offers much more power and flexibility
  than regular CSS. With Less, we gain a range of features like nested
  declarations, variables, mixins, operations, and color functions.
  Additionally, since Bootstrap is purely CSS when compiled via Less, we
  gain two important benefits:
First, Bootstrap remains very easy to implement; just drop it in your
  code and go. Compiling Less can be accomplished via Javascript, an
  unofficial Mac application, or via Node.js (read more about this at
  http://lesscss.org).
Second, once complied, Bootstrap contains nothing but CSS, meaning
  there are no superfluous images, Flash, or Javascript. All that
  remains is simple and powerful CSS for your web development needs.

What that means is that you can use it in any way you want. You can generate the markup server-side and serve it to the client (JSP for instance), you can serve a static fil from the server and add dynamic content via ajax (the backend could be servlets or some higher abstraction like Spring MVC or Jersey), or something in between like server-side generated "base" with some dynamic content/behavior via JavaScript/ajax. Another choice could be to drop the servlet container all together and use something like Play! Framework.
Edit:
I don't think Bootstrap creates the HTML elements for you, it creates the css using Less. You have to write the markup yourself on the server, and use the styles and idioms described in the docs: twitter.github.com/bootstrap/components.html You add dynamic values from java through technologies like JSP or template engines like Velocity, Freemarker, StringTemplate etc. Reading values from users is done by handling HTTP GET/POST actions and reading the attributes. Typically you handle a GET by

*

*Reading the parameters

*Select the template/JSP by the url

*Interpolate dynamic values calculated by java.

For instance if a user does a GET on ./order.html?orderId=1 you select the order.html template, interpolate values from orderService.getOrder(1). Have a look at the Freemarker examples to understand how a template engine work. You basically pass in a Map<String, Object> and the value associated by a ${key} is rendered in the page before it's sent to the browser.

A: as ebaxt said, Bootstrap is only a modular front end technology. Your question is about the visual part of a Java EE based application.
It will basically deal with MVC patterns and their implementation/technologies (EJB, Spring MVC).
And then you will finally deal with presentation technologies : writting in .jsp pages, using JSF or Struts or GWT technologies or (of course) BootStrap (like any other js and css code) to get visual results and accessibility. By doing this, you will get an entire well structured app.
Sorry for English mistakes if I have done some, I'm a french guy.

A: Here's an example.
It shows a simple webpage with bootstrap front-end integrated with java-backend service.
Or in another post it mentions integrate bootstrap with spring.


text:
Q: SAML - Parse Service Provider Metadata and extract details such as signing certificate and assertion consumer endpoint My application acts as an SAML IdP. For this, I am in the process of registering Service Providers with my application. For this, I connect to the SP Federation Metadata URL and download the XML.
Question is- is there any readily available java library which performs this tasks? Or do I need to extract the details manually using standard DOM APIs?
Note: My application maintains the user repository and their authentication and authorization details such as credentials, roles, operations, etc.
Hence can not really depend on third party IdPs such as ADFS or OneLogin.
Any help is much appreciated.

A: Thanks to codebrane for the pointers. I've figured out the way using opensaml libraries.
 private void init(String metadata) throws Exception {
       // parse metadata XML
        EntityDescriptorImpl entityDescriptor = parseMetaData(metadata);

        SPSSODescriptor spssoDescriptor = entityDescriptor.getSPSSODescriptor(SAMLConstants.SAML20P_NS);

        // get signing/encryption certificates
        List<KeyDescriptor> keyDescriptors = spssoDescriptor.getKeyDescriptors();
        for (KeyDescriptor keyDescriptor: keyDescriptors) {
            KeyInfo keyInfo = keyDescriptor.getKeyInfo();
            X509Certificate samlCertificate = keyInfo.getX509Datas().get(0).getX509Certificates().get(0);
            sigVerificationCertificate = KeyInfoSupport.getCertificate(samlCertificate);
        }

        // get SAML endpoints
        assertionConsumerServices = spssoDescriptor.getAssertionConsumerServices();
        singleLogoutServices = spssoDescriptor.getSingleLogoutServices();

        // TODO - extract organization name etc.
    }


text:
Q: ¿Por qué "\r\n\" en microcontroladores? Hice un curso básico HTML, haciendo pruebas con el navegador y nunca tuve que poner \r\n\ y he visto un ejemplo con un microcontrolador y sí que se pone \r\n\. Sé que \r\n\ es return and new line. Pero ¿Por qué cuando se escribe en HTML sobre un archivo *.c es necesario poner \r\n\ al final de cada línea?

*

*¿Es para que el compilador interprete que se acaba una línea en HTML y comienza otra?

*¿Alguien puede ser más específico o dar más información?

*¿Cuando es necesario ponerlo y con qué tipo de archivos?

*¿Por qué al hacer una página web no se pone, o muchas veces no se pone?

*¿Cuando es necesario ponerlo y cuando no? ¿Y para qué aplicaciones?

Ejemplo de función escrita en C con HTML con finales de línea con \r\n\:
const char systemPage[] = {
"<html><head><title>System Setting</title>\r\n\
<head>\r\n\
<style type=\"text/css\">\r\n\
body{background-color:orange}\r\n\
</style>\r\n\
</head>\r\n\
         .
         .
         .
};

Gracias por atender esta "curiosidad". Un saludo.

A:
¿Por qué cuando se escribe en HTML sobre un archivo *.c es necesario poner \r\n\ al final de cada línea?

El estándar HTML no entiende los saltos de línea. De hecho podría estar todo el HTML escrito en la misma línea y la página se seguiría mostrando correctamente.
Si alguien utiliza ese separador posiblemente sea por desconocimiento o costumbre, por "requisitos" del proyecto (es decir, que alguien con más poder de decisión ha dicho que tiene que ser así), o porque los editores que utiliza para verificar el HTML resultante trabajan mejor con esos saltos de línea (para visualizar el código ojo).


text:
Q: How to style a context menu background to OS default styling instead of transparent In my Firefox extension I have a tree that has a context menu assigned. The context menu displays and is functional, but the background is transparent. The row data of the tree shows through the context menu. How can I set it to the default OS context menu style?
My XUL treechildren tag with the menu assigned
<treechildren id="my_children" contextmenu="my_context">

</treechildren>

The XUL context menu
<popup id="my_context">
   <menuitem label="Start" oncommand="myApp.start()"/>
</popup>

I have noticed that the Tamper Data extension has this exact same problem.

A: The solution is really simple. From the documentation for the <xul:popup> tag:

The popup element is equivalent to the menupopup element which should be used instead.

Just replace <popup> by <menupopup>. The <popup> tag has been deprecated and unstyled for a while already, since Firefox 4 I think. You probably have it from a very outdated code example.


text:
Q: Submanifolds of $\mathbb{R}^{n}$ $X$ is a submanifold of $\mathbb{R}^{n}$ if and only if for all $p\in X$ exist an open set $U\subset\mathbb{R}^{n}$ and a $C^{\infty}$ map $r:U\rightarrow U$ such that $r\circ r=r$ and $X\cap U=r(U)$.
In the first way $\Rightarrow$ i think it is easy but in the second way $\Leftarrow$ i am not shure how to carry that to the definition of a submanifold.

A: The proof of this is given on the nLab here .
An interesting thing to note, as the page discusses, is that since every (finite-dimensional, Hausdorff, second countable) smooth manifold admits an embedding into $\mathbb{R}^n$ for some $n$, then in fact this construction completely characterizes all smooth manifolds, and the category of smooth manifolds can be seen to be the Karoubi envelope (idempotent-splitting completion) of the category of open subsets of Cartesian spaces. As explained in Remark 4.2 of the aforementioned article, this was advocated by Bill Lawvere as a nice way to immediately generalize many constructions on $\mathbb{R}^n$ to smooth manifolds in general, without having to tediously verify compatibility with coordinate changes.


text:
Q: What should I do during triaging if a question is already edited? I have just earned my privilege to review questions and help with triaging, so I started pitching in today.  I came across a question which in my opinion needed editing but was already edited.  Should I:

*

*Looks OK - ignores the fact that I feel the quality of the question could have been improved.

*Requires Editing - potentially duplicating work and if a second editor looks at it and concurs with the first editor then this is meaningless.

*Unsalvageable - Kind of an irrelevant option, but I can see a scenario where I feel the question is unsalvageable, but was already edited by someone who didn't.

*Skip - This - I assume - just throws it back on the heap for another triager to deal with who will likely have the same questions I did.

If this has been asked and answered already, I could use a link cause I couldn't really find anything with the search terms I used.

A: Whether the post has been edited is irrelevant.  If the post looks okay now, mark it as okay.  If the post needs editing in its current state, indicate that it needs editing.  If the post is unsalvageable, flag it as appropriate.


text:
Q: Files created by manage.py commands not chown'd from root user I'm using cookiecutter-django project template which includes nice docker-compose integration. However when I run a manage.py command that creates a file via docker-compose e.g:
sudo docker-compose -f dev.yml run django python manage.py dumpdata --output ./myapp/fixtures/data.json

the file is owned by root:root so I do not initially have write permissions on my host filesystem. I'm still learning about docker-compose and am struggling to find the tidiest way to chown any created files back to my local user.
I did try setting the user: flag in my django service in dev.yml like so..
  django:
    user: $USER

but this didn't take.
I also read about using
django:
  user: ${UID}

but this also fails with a warning
WARNING: The UID variable is not set. Defaulting to a blank string.

despite echo $UID returning the correct value. So for some reason, env variables are not being passed through properly, though I don't know how to go about debugging that. possibly related: https://github.com/docker/compose/issues/2613
edit: more updates.
so running docker-compose -f dev.yml run django env shows that $UID isn't present. I tried assigning it in entrypoint.sh but as that file is run by root, the $UID will be 0 at runtime. I'm out of ideas now as to how to pass the user ID in.


text:
Q: Wordpress menu deletes when trying to add a hook I'm trying to customize the default Wordpress menus. Added this to my functions.php file and it makes my menus disappear. What is wrong?
function custom_novice_menu($args) {
    $defaults = array(
        'container' => 'div'
    );
}

add_action('wp_nav_menu', 'custom_novice_menu');

Here is some documentation on wp_nav_menu()

A: wp_nav_menu is not an action, It is a filter, So you will need to write apply_filters for it and return $nav_menu from the callback function.


text:
Q: Opencv-3.1.0 on Ubuntu 16.04 I am trying to install opencv-3.1.0 on Ubuntu 16.04. However I face errors when trying to install from opencv.sh and cmake.

Please advise.

A: You can install opencv-3.1.0 from sources using CMake:

cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr/local
  /path_to_opencv_directory
make -j 8  #"-j 8" means you build opencv in parallel in 8 thread
sudo make install  #install opencv to standard directory (/usr/local/)

For full opencv installation description you can go there: opencv installation guide

P.S.: there is really no need to use any opencv.sh scripts. Everything should be installed intuitively and based on documentation.

A: According to this page, you can now install python on Ubuntu 16.04 as follows:
pip3 install opencv-python

for Python3. And
pip install opencv-python

for Python2.
I hope that helps someone, cheers.


text:
Q: Create div scrollable elements according to the number of elements in an String array I'm quiet new above all on Javascript technology. I want to create various div according to the number of string into an array of checked checkboxes but after my code it only displays one div every time... I must go through a jquery dialog to display it !
My JSP

My listContact.js
varPopup = $('#dialogMultiplesDeleteConfirmation').dialog({
        resizable : false,
        modal : true,
        autoOpen : false,
        width : 500,
        open: function(){
            var SuppressCheckboxItems = [];
            // I put into an array the different value of checked checkboxes
            $("input:checkbox[id=suppressCheckbox]:checked").each(function() {
                SuppressCheckboxItems.push($(this).val());
            });
            var z = document.createElement('div');
            // I suppress the ',' between each element
            var test = SuppressCheckboxItems.toString();
            var tab = test.split(",");
            for(var i = 0; i < tab.length; i++){
                    z.innerHTML = tab[i];
                    $('#listCurrentContact').html(z);
            }

A: You should use  $('#listCurrentContact').append(z);

A: Have you tried using .append instead of .html while concatenating your checkboxes to #listCurrentContact.
You can refer this document: https://www.w3schools.com/jquery/html_html.asp to see that .html() replaces the previous content with the new content whereas what you are trying to achieve here is appending the entire array of values to the div. Look at how .append() works in this link : https://www.javascripttutorial.net/javascript-dom/javascript-append/. Just to give you a brief overview, when you write a .append() on any element, it doesnot replace the previous content with the new content but instead attaches/concatenates the new content after the previous content.

A: Thanks to SaloniMishra Ive found the good answer. It just needed to change the .html() to .append() but with that if the customer just quit the jquery dialog and retry the previous elements stayed in the div so you need to clean every elements before to relaunch the function with the function removeChild()! Thanks all !
open : function() {
            var SuppressCheckboxItems = [];
            const currentDiv = document.getElementById('listCurrentContact');
            while (currentDiv.firstChild) {
                currentDiv.removeChild(currentDiv.lastChild);
            }
            $("input:checkbox[id=suppressCheckbox]:checked").each(function() {
                var z = document.createElement('div');
                z.innerHTML = $(this).attr("name");
                $("#listCurrentContact").append(z);
            });


text:
Q: PHP/HTML/JavaScript - Creating buttons with data attributes from PHP to HTML/JavaScript I have data in a PHP array I want to turn into buttons.
For simplicity, these buttons will console.log() their data on click.
Right now I'm using inline event handlers to do this.
How do I approach this problem using data attributes and no inline event handlers? I know how to create data attributes, but I don't know how to log the data and bind event listeners to the buttons.

<?php
$coordinates = array(
  first => array(
    "lat" => "64",
    "long" => "89"
  ),
  second => array(
    "lat" => "23",
    "long" => "11"
  ),
  third => array(
    "lat" => "35",
    "long" => "76"
  )
);
// Create buttons with inline event handlers
foreach($coordinates as $point) {
    echo "<button onclick='logData(".$point["lat"].", ".$point["long"].")'>Button</button>";
}

echo "

";
// Create buttons with data attributes. How do you log the data without inline event handlers?
foreach($coordinates as $point) {
    echo "<button data-lat=".$point["lat"]." data-long=".$point["long"].">Button</button>";
}

?>

A: Give each button a way to identify them, like a class attribute value.
foreach($coordinates as $point) {
  echo '<button class="point-button" data-lat="' . $point["lat"]. '" data-long="' . $point["long"] . '">Button</button>';
}

In JavaScript select all buttons that have that specific class and listen for the click event for each individual button.
The fired click event gives information about the element that is being clicked. That reference is stored in the target property of the event object.
Now that you have the clicked button, read out the dataset property of the button. It should have properties for every data-* attribute on the element, without the data- part in the name. So, for example, data-lat is represented as dataset.lat.
// Log function.
function logData(lat, long) {
  console.log(lat, long);
}

// Get all buttons with the point-button class.
const buttons = document.querySelectorAll('.point-button');

// Click event handler
function onButtonClick(event) {
  const currentButton = event.target;
  const lat = currentButton.dataset.lat;
  const long = currentButton.dataset.long;

  logData(lat, long);
}

// For each button, add an event listener for the click event.
// Call logData when a click happens.
buttons.forEach(button => {
  button.addEventListener('click', onButtonClick);
});

A: You can simply do like this

function hello(event){
  alert(event.dataset.lat)
}
<button onclick="hello(this)" data-lat="hello">
      save
</button>

in your case
foreach($coordinates as $point) {
  echo '<button class="point-button" data-lat="' . $point["lat"]. '" data-long="' . $point["long"] . '" onclick="loadData(this)">Button</button>';
}

and in js
function loadData(event) {
   const lat = event.dataset.lat
   const lon = event.dataset.long

   console.log(lat, long)

}


text:
Q: Variable data not retained to bind in HTML even after assigning data to it inside a subscribe() function I have below app-product.ts code written as below:
@Component({
   selector: 'app-product',
   template: `

{{products.prod_name | uppercase}} Details

Description: {{products.prod_desc}}

`
 })

export class ProductComponent {

   products:any = [];

   constructor(public rest: RestService){ this.getProducts() }

   getProducts() {
     this.products = [];
     this.rest.getProducts().subscribe((data: {}) => {
     console.log(data); // data is printing in console
      this.products = data; // tried keeping debugger here
   });
}

In the above code I am able to print the data in console but the variable products is not accessible in my template.
I also tried to keep a debugger at the point and I tried to print the products but it was showing as undefined every time.
Below is my angular service file for consuming REST API using Http Client as below:
@Injectable({
  providedIn: 'root'
})

export class CarApiService {

  getProducts(): Observable<any> {
    return this.http.get(endpoint + 'products').pipe(
    map(this.extractData));
  }
}

I also tried to analyse if there is any callback issues in the code but could not figure what is the real cause of this problem.
I also tried looking into few threads like:
component variables inside a RxJS subscribe() function are undefined
but could not find any help. Can anyone please help me out?

A: Since the service was in other module i had to create single sharing tree for access that return values.
So the code must be placed inside the export shared module block as below:
static forRoot(): ModuleWithProviders {
return {
  ngModule: SharedModule
};

}

A: Your are trying to use product in template (*ngIf="product") while the data is inside products variable.
and, you should call getProducts() function to fetch the values inside your array variable.
Import OnInit Interface and call the fucntion:
export class ProductComponent implements OnInit {

   products:any = [];

   constructor(public rest: RestService){}

   ngOnInit() {
          this.getProducts();
   }
   getProducts() {
     this.products = [];
     this.rest.getProducts().subscribe((data: {}) => {
     console.log(data); // data is printing in console
      this.products = data; // tried keeping debugger here
   });
}

update due comment
if you want show array in your template you have to iterate over the array:
template: `

{{product.prod_name | uppercase}} Details

Description: {{product.prod_desc}}

`

A: @Component({
   selector: 'app-product',
   template: `

{{product.prod_name | uppercase}} Details

Description: {{product.prod_desc}}

`
 })

export class ProductComponent {

   products:{}[] = [];

   constructor(public rest: RestService){ this.getProducts() }

   getProducts() {
     this.products = [];
     this.rest.getProducts().subscribe((data: {}[]) => {
     this.products = data;
     console.log(this.products); // this should not be undifind
   });
}

otherwise check your spelling


text:
Q: Event listeners in Codedui like Selenium I am trying to write the low level logging (my own html file) like clicking and entering text into the elements.
Is there any possible way to get those details after/before clicking the element like what we have in Selenium Event Listeners.

A: There are 2 ways that i would suggest.
(I) CodedUI Provides you QT.Agent32 to produce logs of your execution. To use it, follow the below steps.
1) Open the QTAgent32_40.exe.config file. By default, this file is located in :\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE.
2) Modify the value for EqtTraceLevel to the log level you want.(from level 1 to 4)
3) Save the file.
4) Open AppConfig File in codedUI Project, and paste this code under the config node.
<system.diagnostics>
<switches>
<add name="EqtTraceLevel" value="4"/>
</switches>
</system.diagnostics>

5) And in TestMethod enable this method like below,
LoggerOverrideState = HtmlLoggerState.AllActionSnapshot;

(II) Create Customized using File IO
1) Write a method to write the input in the newly created File (.txt or .excel or whatever). Say the method is Runlog(string input){} in a class called Report.cs
2) Let the input be whatever you intend to give. Example : clicked Submit button, Entered username.
3) Call this method with relevant input passing in it representing what action it has performed. Example: Report.Runlog("Clicked Submit Button");
4) Call this after every action. i know its a bit boring to call this after each action. but it's useful when you use a keyword driven framework.Hope it gives you an idea. Good luck!!


text:
Q: What type of RAM can I use to upgrade my system? My machine certainly isn't the newest one. It can handle most current games when I turn down the settings to medium/low. Core specs are (according to SiSoft Sandra):
CPU: Intel i5-2500
RAM: 4GB of RAM
Graphics: AMD Radeon HD 2850 1GB
I don't have any money to buy a new system, but I guess I can afford to upgrade my RAM to 8 or 12GB, hoping it will improve my performance a bit.
My problem is that I'm not that good when it comes to hardware and compatibility. I simply don't know if RAM I see in an online store will work in my machine. Please help me understand this.
SiSoft Sandra gives me the following details for my RAM:
Speichermodul
Hersteller : Kingston
Modell : 99U5458-005A01LF
Serialnummer : 112B8368
Typ : 4GB DIMM DDR3
Technologie : 8x(2048Mx8)
Geschwindigkeit : PC3-10700U DDR3-1334
Monitor Standard Timings : 9-9-9-25 4-34-10-5
Version : 1.00
Herstellungsdatum : Sonntag, 10. September 2017
Setze Takt @ 457MHz : 6-6-6-16 3-22-7-3
Setze Takt @ 533MHz : 7-7-7-19 3-26-8-4
Setze Takt @ 610MHz : 8-8-8-22 4-30-9-5
Setze Takt @ 686MHz : 9-9-9-25 4-34-10-5

Well, I guess I get the "DDR3" part, I can search for that in online stores. But it get's tricky after that. I see "1334" in the description of some RAM modules, but also "1334 low voltage" - are they compatible? Then it says "PC3-10700U". I can't find that in the stores (atelco.de for example) at all, the closest I see is "PC3-10667U". Did they just round up? And then there is a value for latency (I guess). CL7, CL9, CL2, CL10, ... what do I need?

Edit: As requested in the comments here are the mainboard information as shown by Sandra:
Hersteller : MSI
MP Unterstützung : Nein
MPS Version : 1.40
Modell : H61M-E33 (MS-7680)
Typ : Mainboard
Version : 2.0
System BIOS : 63-0100-000001-00101111-030211-Chipset
Anzahl von Speichersteckplätzen : 4
Maximal installierbarer Speicher : 32GB
A1_BANK0 - A1_DIMM0 : Kingston 99U5458-005.A01LF 112B8368 A1_AssetTagNum0 DIMM Synchron DDR3 4GB/64 @ 1.33GHz
A1_BANK1 - A1_DIMM1 : Leer
A1_BANK2 - A1_DIMM2 : Leer
A1_BANK3 - A1_DIMM3 : Leer

(sorry it's in German, but I think it should be understandable. If not, please ask and I will try and translate)

A: As long as you get at least 10667, you should be fine. I tend to get slightly faster and use it at lower ratings, as higher rated sticks tend to be more stable / compatible at lower speeds.
You shouldn't have to worry about CL7/CL9 etc. Just get a part that is DDR3 and PC-10667 or better, and install it. Your BIOS will usually recognize it when you install it and you're good to go - no fiddling, no hassle.


text:
Q: How do I automate authentication on a site that uses a third party like github or Facebook for login credentials when scraping? I am trying to scrape a webpage on codeeval.com that shows which challenges a user has completed and which ones are not completed. The page is https://www.codeeval.com/open_challenges/ The problem is that I use my github account to log into codeeval.com. I can't figure out how to authenticate my scraper through github so that I can get to that page. Currently I need to manually login and save the HTML file. I'd like to automate the process.
I'm using scrapy and python.


text:
Q: python curve_fit does not give reasonable fitting result I am trying to fit gaussian to a spectrum and the y values are on the order of 10^(-19). Curve_fit gives me poor fitting result, both before and after I multiply my whole data by 10^(-19). Attached is my code, it is fairly simple set of data except that the values are very small. If I want to keep my original values, how would I get a reasonable gaussian fit that would give me the correct parameters?
#get fits data
aaa=pyfits.getdata('p1.cal.fits')

aaa=np.matrix(aaa)
nrow=np.shape(aaa)[0]
ncol=np.shape(aaa)[1]

ylo=79
yhi=90
xlo=0
xhi=1023
glo=430
ghi=470

#sum all the rows to get spectrum
ysum=[]
for x in range(xlo,xhi):
sum=np.sum(aaa[ylo:yhi,x])
ysum.append(sum)

wavelen_pix=range(xhi-xlo)
max=np.max(ysum)
print "maximum is at x=", np.where(ysum==max)

##fit gaussian
#fit only part of my data in the chosen range [glo:ghi]
x=wavelen_pix[glo:ghi]
y=ysum[glo:ghi]
def func(x, a, x0, sigma):
    return a*np.exp(-(x-x0)**2/float((2*sigma**2)))

sig=np.std(ysum[500:1000]) #std of background noise

popt, pcov = curve_fit(func, x, sig)
print popt
#this gives me [1.,1.,1.], which is obviously wrong
gaus=func(x,popt[0],popt[1],popt[2])

aaa is a 153 by 1024 image matrix, partly looks like this:
matrix([[ -8.99793629e-20,   8.57133275e-21,   4.83523386e-20, ...,
-1.54811004e-20,   5.22941515e-20,   1.71179195e-20],
[  2.75769318e-20,   1.03177243e-20,  -3.19634928e-21, ...,
1.66583803e-20,  -9.88712568e-22,  -2.56897725e-20],
[  2.88121935e-20,   8.57964252e-21,  -2.60784327e-20, ...,
1.72335180e-20,  -7.61189937e-21,  -3.45333075e-20],
...,
[  1.04006903e-20,   1.61200683e-20,   7.04195205e-20, ...,
1.72459645e-20,   4.29404029e-20,   1.99889374e-20],
[  3.22315752e-21,  -5.61394194e-21,   3.28763096e-20, ...,
1.99063583e-20,   2.12989880e-20,  -1.23250648e-21],
[  3.66591810e-20,  -8.08647455e-22,  -6.22773168e-20, ...,
-4.06145681e-21,   4.92453132e-21,   4.23689309e-20]], dtype=float32)

A: You are calling curve_fit incorrectly, here is the usage
curve_fit(f, xdata, ydata, p0=None, sigma=None, absolute_sigma=False, check_finite=True, **kw)

*

*f is your function whose first arg is an array of independent variables, and whose subsequent args are the function parameters (such as amplitude, center, etc)

*xdata are the independent variables

*ydata are the dependedent variable

*p0 is an initial guess at the function parameters (for Guassian this is amplitude, width, center)

By default p0 is set to a list of ones [1,1,...], which is probably why you get that as a result, the fit just never executed because you called it incorrectly.
Try estimating the amplitude, center, and width from the data, then make a p0 object (see below for details)
init_guess = ( a_i, x0_i, sig_i) # same order as they are supplied to your function
popt, pcov = curve_fit(func, xdata=x,ydata=y,p0=init_guess)

Here is a short example
xdata = np.linspace(0, 4, 50)
mygauss = ( 10,2,0.5) #( amp, center, width)
y     = func(xdata, *mygauss  ) # using your func defined above
ydata = y + 2*(np.random.random(50)- 0.5) # add some noise to create fake data

Now I can guess the fit params
ai    = np.max( ydata) # guess the amplitude
xi    = xdata[ np.argmax( ydata)] # guess the position of center

Guessing the width is tricky, I would first find where the half max is located (there are two, but you only need to find one, as the Gaussian is symmetric):
pos_half = argmin( np.abs( ydata-ao/2 ) ) # subtract half the amplitude and find the minimum

Now evaluate how far this is from the center of the gaussian (xi) :
sig_i = np.abs( xi - xdata[ pos_half] ) # estimate the width

Now you can make make the initial guess
init_guess = (ai, xi sig_i)

and fit
params, variance = curve_fit( func, xdata=xdata, ydata=ydata, p0=init_guess)
print params
#array([ 9.99457443,  2.01992858,  0.49599629])

which is very close to mygauss. Hope it helps.

A: Forget about rescaling, or making linear changes, or using the p0 parameter, which usually don't work! Try using the bounds parameter in the curve_fit for n parameters like this:
a0=np.array([a01,...,a0n])
af=np.array([af1,...,afn])
method="trf",bounds=(a0,af)

Hope it works!
;)


text:
Q: Tkinter B1-Motion does not work when argument/argument added I am trying to make an object move. The function I have below does not work when I insert the argument 'rec'. The object does not move in move_rec. However, if I remove the argument the code works perfectly fine and I can drag the object. However, this requires a lot more lines of codes
def save_coords(e, rec):  #rec is last element of a stack

    global x0, x, y0, y

    x0, x, y0, y =  0, 0, 0, 0

    coordinate = mycanvas.coords(rec)

        x0, x, y0, y = coordinate[0], coordinate[2], coordinate[3], coordinate[1]
        if x0< 480:
          root.bind('<B1-Motion>', lambda event, stack= rec: move_rec(e, stack))

        #root.bind('<B1-Motion>', move_rec) #this one works but requires more lines of code

def move_rec(e, stack):
    if stack == left_stack[-1]:
       coordinates = mycanvas.coords(stack[-1])
        mycanvas.coords(stack[-1], e.x - ((coordinates[2]-coordinates[0])/2), e.y + 15, e.x + ((coordinates[2] - coordinates[0])/2), e.y - 15)

Basically, e.x becomes static when I add an argument. Any idea? Thanks


text:
Q: google-api-php-client apiAuthException refreshing OAuth2 I'm developing a PHP script to display a page with some charts and stats about my Analytics profile. I'm sending 3 or 4 ajax asynchronous calls to the server; the server then fetch data using google-api-php-client . There are about 10 requests to Google for each page refresh.
The problem is i'm getting totally random exceptions from the api:

Fatal error: Uncaught exception 'apiAuthException' with message 'Error
  refreshing the OAuth2 token, message: ' in apiOAuth2.php on line 242

One time i successfully get the data, one time not. This is very annoying because i cannot find why. What could be? The asynch calls maybe?
User quota is set to 1000 requests/second just to be sure. Eventually i get 'User quota exceded' from the api, something quite impossible.

A: I answer to myself because i found the problem (was my bad):

*

*I store the access token into an encrypted file

*Even if the access token should be offline it's not really offline: it expires but contains a refresh token that APIs will send to get a new fresh access token

*The new access token should be saved again into the file (i save it into __destruct() method of my wrapper class) and used for the next request (i was not saving it!)


text:
Q: Loading image dataset into memory with PIL (python) consumes too much memory I am using Google Colab (13 Gb RAM) and I am trying to load into memory 8000 JPG images (512x512), that on average are 150Kb each one.
I would expect that with all this would consume no more than 1.5GB in RAM, but actually consumes it all and Google Colab crashes.
What am I missing?
images = []
files = os.listdir(IMAGES_PATH)
for f in files:
  temp_image = Image.open(IMAGES_PATH + f)
  temp = np.array(temp_image.convert('RGB'), dtype='float32') / 255
  images.append(temp)

A: You are using:
512*512*8000  this is the matrix you get after your calculation, and a float is using 8kbytes, which means your memory use is:
512*512*8000*8 = 11,11GB
The original size of your image does not matter for this calculation, python is storing his on memory.


text:
Q: What will be different if the spring is not massless? In almost all text, it uses the massless spring as example to illustrate the idea of elastic potential energy. I wonder what's really being changed if we consider the mass of the spring? I saw a problem on a text regarding the non-massless spring. It is said that the stretched spring (don't know the length) has uniform density and mass $M$, the elastic constant k is also known. If we hold it vertical so it stretches naturally due to the gravity, what's the elastic potential will be. I am trying to understand this from physical point of view as follows but I don't know if it is correct or not since there might be some knowledge beyond undergraduate course I need to solve the problem
1) I think the spring is actually has the gravity acting on it's center of mass, so if we choose the (gravitational) potential reference to be zero (at where the hanging point), the gravitational potential is $Mgh$ where $h$ is the where the center of mass is .
2) From 1), can we say that the elastic potential energy is actually the same as the gravitational potential energy, so $$\frac{k}{2}(\Delta l)^2 = Mgh$$
So if we figure out $h$, we know the elastic potential energy. But the problem how to find the center of mass. I bring this to some senior students, some of them said the center of mass will not be changed, so the center of mass when the spring is not stretched and when it is naturally stretched will be the same, that's is to say, when it is not stretched, the center of mass is $l_0/2$ so $h=l_0/2$. Well, frankly, I don't see the point.
Someone show me the math to calculate the center of mass, which is an integral
$$
  h = l_c = \frac{1}{M}\int_0^L \frac{M}{l_0}xdx
$$
there he said $L$ is the fully-extended length and $l_0$ is the unstretched length, I don't know how to do the math but I plug that into mathematica and it gives
$$
  h = l_c = \frac{L^2}{2l_0}
$$
but if this is correct, we need to know the fully-extended length and original length to figure the center of mass. I don't think we get that information. So do we really need other knowledge to find the elastic potential energy for non-massless spring?

A: In general you can think massive springs as being a sequence of massless springs and masses connected in series. So you can compute the energy in each of these pairs spring-mass and then sum up (integrate).
I would take,
$$E_p=\int_0^L\frac12 \frac{k}{L} \left(\Delta x (x)\right)^2 dx$$
where $\Delta x$ is the displacement for each $x$. You can calculate it statically using the force for a small piece of spring located at $x$:
$$F(x)=k.\Delta x(x)$$
and $F(x)=m(x) g$, where $m(x)$ is the mass of the spring until $x$ (imagine the spring hanging and $x$ begins in the top and go downwards). It holds that $m(x)=\mu x$, where $\mu$ is the linear density $M/L$. Then
$$E_p=\int_0^L\frac12 \frac{k}{L} \left(F (x)\right)^2 dx$$
$$E_p=\int_0^L\frac12 \frac{k}{L} \left(\frac{Mg}{kL}x\right)^2 dx$$
$$E_p=\frac12 \frac{kM^2g^2}{L^3k^2} \int_0^L x^2 dx$$
$$E_p=\frac12 \frac{kM^2g^2}{L^3k^2} \frac13 L^3 $$
$$E_p=\frac{M^2g^2}{6k} $$

A: Hint: The change in position of 'centre of mass' is half of its extension.
Give it a try then come back, I will update the answer.


text:
Q: не работает в html {% if request.user.is_authenticated %} python django Имеется такой HTML код:
{% if user.is_authenticated %}
     Добро пожаловать, {{ user.username }} | Выход
 {% else %}
     Register | Login
 {% endif %}

*

*Не выводит что залогинен пользователь, хотя в админку заходит и показывает, что пользователь авторизован.

*Так:
{% if request.user.is_authenticated %}
тоже пробовал.

Может потому что это выводиться через tags.py и туда надо передать request?

A: Решил сам, просто если мы используем inclusion_tag, тогда надо передавать контест еще раз
@register.inclusion_tag('../templates/include/_nav.html', takes_context=True)
def navigation(context):
    #some code
    return context