text:
Q: ubuntu + nginx + laravel vue-material-dashboard I tried a lot to get the "Vue-material-dashboard Laravel" working. Here is the url to the project.
I manage to serve the thing, but when I try to login and it says: "Invalid credentials".
Looks like this:

As you can see below I also send them a ticket ;) But have not gotten help from them yet, so I decided to see if someone can help me here
Version of Vue-material-dashboard Laravel
latest
Reproduction link
Nginx file:
server {
    listen 8080;

    index index.php index.html index.htm;

    server_name example.com;

    return 301 https://example.com$request_uri;

}

server {
    listen 443 ssl;

    server_name example.com;
    root /data/vue-material-dashboard-laravel/laravel-json-api/public;

    ssl_certificate /etc/nginx/ssl/cert.pem;
    ssl_certificate_key /etc/nginx/ssl/key.pem;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";

    index index.php;

    charset utf-8;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }

   # location ~ /\.(?!well-known).* {
   #     deny all;
   # }
}

Operating System
Ubuntu
Device
server
Browser & Version
firefox, latest
Steps to reproduce

*

*I set all up according to documentation and run npm run build.

*I let nginx server the laravel/public folder. I use a rather minimal nginx configration in sites-enabled folder (see nginx code above)

What is expected?
I use the npm command, output tells me to look at http://example.com:8081
Everything looks fine and login should be working with default given login
What is actually happening?
I get some sort of backend, but cannot login.
It says: "Invalid credentials"
Solution
Do you maybe have a nice example of how nginx should server the app?
I could not find anything online. I tried running vue-material-dashboard over https by adding "vue.config.js":
module.exports = {
  devServer: {
    open: process.platform === 'darwin',
    host: '0.0.0.0',
    port: 8081, // CHANGE YOUR PORT HERE!
    https: true,
    hotOnly: false,
  },
}

Then indeed everything goes through https but login does still not work. Any ideas why? Seems api does not communicatie well with vue
Additional comments
If we can let it all work on a linux server we woudl want to go and buy the PRO version eventually (after we tested it and so on)


text:
Q: Segmentation fault (core dump) First reader-writer problem #include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <time.h>

int sleepval = 10, read_num = 0;
int readcnt = 0, writecnt = 0;
pthread_mutex_t mutex;
sem_t rw_mutex;

int randomGenerator(int high, int low){
    srand(time(0));
    return((rand() % (high - low + 1)) + 100);
}

void *reader(void *readno){
    pthread_mutex_lock(&mutex);
    read_num++;
    /* Block the writer if this is the first reader */
    if(read_num == 1){
        sem_wait(&rw_mutex);
    }
    pthread_mutex_unlock(&mutex);
    /* Read sleepval value and print */
    printf("Reader %03d reads %d\n", *((int *)readno), sleepval);
    readcnt++;
    sleep(sleepval / 1000);
    pthread_mutex_lock(&mutex);
    read_num--;
    /*Wake up writer if this is the last reader */
    if(read_num == 0){
        sem_post(&rw_mutex);
    }
    pthread_mutex_unlock(&mutex);
    int num = randomGenerator(500, 100);
    sleep(num / 1000);
}

void *writer(void *writeno){
    int num = randomGenerator(1000, 100);
    sleep(num / 1000);
    num = randomGenerator(50, 10);
    sem_wait(&rw_mutex);
    sleepval = num;
    printf("Writer %02d writes &d\n", *((int*)writeno), sleepval);
    writecnt++;
    sleep(sleepval / 1000);
    sem_post(&rw_mutex);
}

int main(int argc, char *argv[]){
    int r = atoi(argv[1]);
    int w = atoi(argv[2]);
    int second = 0;
    int i, id[100];
    if(r < 1 || r > 100 || w < 1 || w > 10){
        fprintf(stderr, "Usage: readwrite [read](1 - 100) [write](1 - 10)\n");
        exit(-1);
    }

    pthread_t read[100], write[10];
    pthread_mutex_init(&mutex, NULL);
    sem_init(&rw_mutex, 0 , 1);

    /* Create threads for readers */
    for(i = 0; i < r; i++){
        id[i] = i;
        pthread_create(&read[i], NULL, (void *)reader, (void *)&id[i]);
    }
    /* Create threads for writers */
    for(i = 0; i < w; i++){
        id[i] = i;
        pthread_create(&write[i], NULL, (void *)writer, (void *)&id[i]);
    }

    sleep(30); //wait for 30 seconds

    /* Signal threads to finish */
    for (i = 0; i < r; i++){
        pthread_join(read[i], NULL);
    }
    for (i = 0; i < w; i++){
        pthread_join(write[i], NULL);
    }

    /* Display number of occurred reads and writes */
    printf("\n==============================\n");
    printf("Number of reads  :\t%03d\n", readcnt);
    printf("Number of writes :\t%03d\n", writecnt);

    pthread_mutex_destroy(&mutex);
    sem_destroy(&rw_mutex);

    return 0;
}

This assignment is about solving the first reader-writer problem. I could compile it in linux using gcc  -lpthread -lrt. But when I try to run it using the given format readwrtie 100 10 I got the segmentation fault (core dump) and I don't know why. I tried running with valgrind a.out to see the problem and I couldnt understand. Please help me.
Memcheck, a memory error detector
==19787== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==19787== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==19787== Command: a.out
==19787==
==19787== Invalid read of size 1
==19787==    at 0x57E7AC: ____strtol_l_internal (in /lib/libc-2.12.so)
==19787==    by 0x57E50F: strtol (in /lib/libc-2.12.so)
==19787==    by 0x57AEB0: atoi (in /lib/libc-2.12.so)
==19787==    by 0x8048A32: main (in /gaia/class/student/maih/maih-asgmt3/a.out)
==19787==  Address 0x0 is not stack'd, malloc'd or (recently) free'd
==19787==
==19787==
==19787== Process terminating with default action of signal 11 (SIGSEGV)
==19787==  Access not within mapped region at address 0x0
==19787==    at 0x57E7AC: ____strtol_l_internal (in /lib/libc-2.12.so)
==19787==    by 0x57E50F: strtol (in /lib/libc-2.12.so)
==19787==    by 0x57AEB0: atoi (in /lib/libc-2.12.so)
==19787==    by 0x8048A32: main (in /gaia/class/student/maih/maih-asgmt3/a.out)
==19787==  If you believe this happened as a result of a stack
==19787==  overflow in your program's main thread (unlikely but
==19787==  possible), you can try to increase the size of the
==19787==  main thread stack using the --main-stacksize= flag.
==19787==  The main thread stack size used in this run was 10485760.
==19787==
==19787== HEAP SUMMARY:
==19787==     in use at exit: 0 bytes in 0 blocks
==19787==   total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==19787==
==19787== All heap blocks were freed -- no leaks are possible
==19787==
==19787== For counts of detected and suppressed errors, rerun with: -v
==19787== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 13 from 8)
Segmentation fault (core dumped)

A: In your writer function, change
printf("Writer %02d writes &d\n", *((int*)writeno), sleepval);
---------------------------^

to
printf("Writer %02d writes %d\n", *((int*)writeno), sleepval);
---------------------------^

In your main function, change
pthread_create(&read[i], NULL, (void *)reader, (void *)&id[i]);
pthread_create(&write[i], NULL, (void *)writer, (void *)&id[i]);

to
pthread_create(&read[i], NULL, reader, &id[i]);
pthread_create(&write[i], NULL, writer, &id[i]);

Add a return statement to the reader and writer function.
Remove the unused variable second in the main function.
Try again.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can anyone explain this python statement using for loop with dictionaries? s=";".join(["%s=%s" % (k, v) for k, v in {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret" }.items()])
print(s)

.
Current output is:
server=mpilgrim;database=master;uid=sa;pwd=secret

.
thanks.

A: This is a list comprehension, it iterates over each element in the dictionary, where k and v will be the key and values respectively.
For each element the iteration will reproduce a string like "%s=%s" % (k, v) which means a key and a value will be conjoined by an = sign, producing database=master for example.
The list comprehension produces a list of these elements, and than each element is joined together by a ; sign using the join function.

A: The code for an intuitive understanding is:
result = ''
for k, v in {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret" }.items():
    string_ = k + "=" + v
    result = result+string_
print(result)

server=mpilgrimdatabase=masteruid=sapwd=secret

*

*your code, each of string_ variables is in list. (by using list comprehension)

*and then all string_ variables are attached with the =.  (by using .join)

print(",".join("abc"))  # use string
print(",".join(["a","b","c"])) # use list

a,b,c
a,b,c


text:
Q: How can I display my primary key as a column when using inner join? select StaffNo, SName, BranchName from STAFF  inner join BRANCH on staff.branchno = Branch.branchno;

I am trying to display BranchNo in the results from the above query, whenever I add BranchNo after branch name like this.
select StaffNo, SName, BranchName, Branchno from STAFF  inner join BRANCH on staff.branchno = Branch.branchno;

I get this error code ORA-00918: column ambiguously defined. To my understanding it is something to do with the fact that BranchNo is my primary key, is there a way I can get around this and display BranchNo in the query results? Many thanks.

A: Just prefix the ambiguous column name with the table it belongs to.
Actually, you should always prefix the columns in multi-table queries with the relevant table names; this makes the queries unambiguous for your database and for the readers
(and future maintainers) of the query.
For this, table aliases come handy (they make the query shorter).
Here is your updated query - I made a few assumptions on from which table each column comes from, that you might need to review:
select
    s.staffno,
    s.sname,
    b.branchname,
    s.branchno
from staff s
inner join branch b on s.branchno = b.branchno;


text:
Q: how to send data with form label element? I should send data with form when submit button pressed.This value should be invisible and I used <label name=r_id id=r_id style="visible:hidden"> 1 </div>
This is my form
   <form id="send_message" action="lib/send_message.php" method="post">

    <textarea name="message" cols="45" rows="3" id="message"></textarea>
    <label  name="r_id" id="r_id" style="visible:hidden"> 1 </label>

    <input type="submit" name="Submit" value="Submit">
    <input type="reset"    name="Submit2" value="Reset">

But in my .php file It shows only message ,id is empty.

I used  $message= $_POST['message'] and $r_ID=$_POST['r_id'] ;
EDIT
I should write that this label value must be change.And I am changing it with Jquery where the mouse clicked it gets  tags id.Can I change value attribute with Jquery ?

A: You're after a hidden input.
<input type="hidden" name="r_id" value="1"/>

A: input type="hidden"

are made for this and they won't appear if CSS are disabled (but of course they'll still appear in the HTML code)

A: LABELs are not form elements that can hold or send data.
They are captions tied to form elements.
<INPUT TYPE="hidden" name="r_id" id="r_id" VALUE="1"/>
This should do what you want.


text:
Q: How can I get the "Nanobar" plugin to go to 100% once all resources have been loaded? I'm having some trouble getting the Nanobar plugin to work.
I have used the code from the example found on this page http://nanobar.jacoborus.codes/
var options = {
  classname: 'my-class',
  id: 'my-id',
  target: document.getElementById('myDivId')
};

var nanobar = new Nanobar( options );

// move bar
nanobar.go( 30 ); // size bar 30%
nanobar.go( 76 ); // size bar 76%

// size bar 100% and and finish
nanobar.go(100);

The loading bar goes to 100% before the page has loaded all of its resources.
Does anyone have an idea how to make this great plugin work?
Thank you in advance.

A: Nanobar doesn't monitor page loading (unlike Pace for instance). Your code simply create a bar and grow it to 30, 76 then 100% length as soon as script have started.
To fit your needs, you must hook the sizing commands to some kind of loading events (readyState or load) relative to DOM (document, images...).
BUT, using it with load events is very limited because you'll have no grain control of the current loading state of page ressources (the total size and the downloaded size). Even if you're monitoring each ressource individually, you can only count ressources and add a 1/ressources_count * 100 length value to the bar.
A workaround is to use ajax (onprogress event) or fetch API (alas progress monitoring is still a bit scary) to load ressources (scripts, stylesheets, images...) dynamically. A global progress bar will then be pretty accurate but you may be facing CORS issues, concurrent ajax requests limitations and big big work to load a full page mainly with ajax !
Some libraries are trying to automate the whole process but it's rather a nice and informative loading animation than a precise and accurate loading progress bar (except for async requests).


text:
Q: Order Data using Pivot Function and Select specific columns on secondary table I'm writing a stored proc to return data from different tables into a single row with respective to a specific order, which are the properties of the primary key.
I have a table as shown below. I think the following table should be queried using the PIVOT Function.
   *Category Table*
-----------------------
| OrderNo | Category |                 /********************************/
-----------------------                      Available Categories
| A0001   | T-Shirt  |                               T-Shirts
| A0001   | Shorts   |                               Shorts
| A0001   | HeadCap  |                               HeadCap
| A0002   | Pants    |                               Pants
| A0002   | Jackets  |                               Jackets
| A0002   | TankTops |                               TankTops
| A0002   | Shorts   |                               Bags
| A0003   | Pants    |
| A0003   | Jackets  |
| A0003   | Bags     |
-----------------------

Another Table contains the order Properties i.e., OrderNo,ApprovedDate,TotalValue,Currency
                  *Ord_Property Table*
------------------------------------------------------
| OrderNo | ApprovedDate | TotalValue | ShipmentType |
------------------------------------------------------
| A0001   | 11/19/2019   |   68.50    |   Ground    |
| A0002   | 11/07/2019   |   240.00   |   2-Day     |
| A0003   | 10/31/2019   |   180.00   |   Ground    |
------------------------------------------------------

Output - When I ran the query specific to the order number, I'm trying to find any output as follows with columns for all the available categories in Table 1, along with the selected columns from the second Table.
------------------------------------------------------------------------------------------------------------------------
| OrderNo | ApprovedDate | TotalValue | ShipmentType | T-Shirt | Shorts | HeadCap | Pants | Jackets | TankTops | Bags |
------------------------------------------------------------------------------------------------------------------------
| A0001   | 11/19/2019   |   68.50    |   Ground     |    Y    |   Y    |    Y    |   N   |   N     | N        |  N   |
| A0002   | 11/07/2019   |   240.00   |   2-Day      |    N    |   Y    |    N    |   Y   |   Y     | Y        |  N   |
| A0003   | 10/31/2019   |   180.00   |   Ground     |    N    |   N    |    N    |   Y   |   Y     | N        |  Y   |

I tried select * from the second table and inner joined the first table on the OrderNo column. Along with the case statements in the Select list but the output is not as expected and instead of single row, it ends up Multiple columns.
Any suggestions will be appreciated.
SELECT OrderNo, ApprovedDate, TotalValue ,Currency
     , CASE WHEN Category = 'T-Shirt' THEN 'T-Shirt' END AS 'Requires_T-Shirt'
     , CASE WHEN Category = 'Shorts' THEN 'Shorts' END AS 'Requires_Shorts'
     , CASE WHEN Category = 'HeadCap' THEN 'HeadCap' END AS 'Requires_HeadCap'
     , CASE WHEN Category = 'Pants' THEN 'Pants' END AS 'Requires_Pants'
     , CASE WHEN Category = 'Jackets' THEN 'Jackets' END AS 'Requires_Jackets'
     , CASE WHEN Category = 'TankTops' THEN 'TankTops' END AS 'Requires_TankTops'
     , CASE WHEN Category = 'Bags' THEN 'Bags' END AS 'Requires_Bags'
FROM Ord_Property OP
INNER JOIN Category C ON C.OrderNo = OP.OrderNo
WHERE OP.ORDERNO =  @OrderNo

A: SELECT OrderNo, ApprovedDate, TotalValue ,Currency
     , MAX(CASE WHEN Category = 'T-Shirt' THEN 'Y' ELSE 'N' END) AS 'T-Shirt'
     , MAX(CASE WHEN Category = 'Shorts' THEN 'Y'ELSE 'N' END) AS 'Shorts'
     , MAX(CASE WHEN Category = 'HeadCap' THEN 'Y' ELSE 'N' END) AS 'HeadCap'
     , MAX(CASE WHEN Category = 'Pants' THEN 'Y' ELSE 'N' END) AS 'Pants'
     , MAX(CASE WHEN Category = 'Jackets' THEN 'Y'  ELSE 'N' END) AS 'Jackets'
     , MAX(CASE WHEN Category = 'TankTops' THEN 'Y'  ELSE 'N' END) AS 'TankTops'
     , MAX(CASE WHEN Category = 'Bags' THEN 'Y'  ELSE 'N'END) AS 'Bags'
FROM Ord_Property OP
INNER JOIN Category C
ON C.OrderNo = OP.OrderNo
WHERE OP.ORDERNO =  @OrderNo
GROUP BY OrderNo, ApprovedDate, TotalValue ,Currency

Try this Query......
Here i'm using CASE WHEN THEN Query...If records match then 'Y' else 'N'

A: Try this:
SELECT OrderNo, ApprovedDate, TotalValue ,Currency
     , MAX(CASE WHEN Category = 'T-Shirt' THEN 'T-Shirt' END) AS 'Requires_T-Shirt'
     , MAX(CASE WHEN Category = 'Shorts' THEN 'Shorts' END) AS 'Requires_Shorts'
     , MAX(CASE WHEN Category = 'HeadCap' THEN 'HeadCap' END) AS 'Requires_HeadCap'
     , MAX(CASE WHEN Category = 'Pants' THEN 'Pants' END) AS 'Requires_Pants'
     , MAX(CASE WHEN Category = 'Jackets' THEN 'Jackets' END) AS 'Requires_Jackets'
     , MAX(CASE WHEN Category = 'TankTops' THEN 'TankTops' END) AS 'Requires_TankTops'
     , MAX(CASE WHEN Category = 'Bags' THEN 'Bags' END) AS 'Requires_Bags'
FROM Ord_Property OP
INNER JOIN Category C
    ON C.OrderNo = OP.OrderNo
WHERE OP.ORDERNO =  @OrderNo
GROUP BY OrderNo, ApprovedDate, TotalValue ,Currency

A: Try this
No need for PIVOT here. Simple Aggregate(MAX) will give the result.
SELECT C.OrderNo, ApprovedDate, TotalValue ,Currency
     , MAX(CASE WHEN Category = 'T-Shirt' THEN 'Y' ELSE 'N' END) AS 'T-Shirt'
     , MAX(CASE WHEN Category = 'Shorts' THEN 'Y' ELSE 'N' END) AS 'Shorts'
     , MAX(CASE WHEN Category = 'HeadCap' THEN 'Y' ELSE 'N' END) AS 'HeadCap'
     , MAX(CASE WHEN Category = 'Pants' THEN 'Y' ELSE 'N' END) AS 'Pants'
     , MAX(CASE WHEN Category = 'Jackets' THEN 'Y' ELSE 'N' END) AS 'Jackets'
     , MAX(CASE WHEN Category = 'TankTops' THEN 'Y' ELSE 'N' END) AS 'TankTops'
     , MAX(CASE WHEN Category = 'Bags' THEN 'Y' ELSE 'N' END) AS 'Bags'
FROM Ord_Property OP
INNER JOIN Category C
    ON C.OrderNo = OP.OrderNo
WHERE OP.ORDERNO =  @OrderNo
GROUP BY C.OrderNo, ApprovedDate, TotalValue ,Currency

A: it returned multiple rows because you have multiple categories joined
SELECT OrderNo, ApprovedDate, TotalValue ,Currency
    , case when
        (select 1 from Category t1
            where t1.Category = 'T-Shirt' and t1.orderNo = OP.OrderNo) = 1
        then 'Y' else 'N' end AS 'Requires_T-Shirt'
    , case when
        (select 1 from Category t1
            where t1.Category = 'Shorts' and t1.orderNo = OP.OrderNo) = 1
        then 'Y' else 'N' end AS 'Requires_Shorts'
    , case when
        (select 1 from Category t1
            where t1.Category = 'HeadCap' and t1.orderNo = OP.OrderNo) = 1
        then 'Y' else 'N' end AS 'Requires_HeadCap'
    , case when
        (select 1 from Category t1
            where t1.Category = 'Pants' and t1.orderNo = OP.OrderNo) = 1
        then 'Y' else 'N' end AS 'Requires_Pants'
    , case when
        (select 1 from Category t1
            where t1.Category = 'Jackets' and t1.orderNo = OP.OrderNo) = 1
        then 'Y' else 'N' end AS 'Requires_Jackets'
    , case when
        (select 1 from Category t1
            where t1.Category = 'TankTops' and t1.orderNo = OP.OrderNo) = 1
        then 'Y' else 'N' end AS 'Requires_TankTops'
    , case when
        (select 1 from Category t1
            where t1.Category = 'Bags' and t1.orderNo = OP.OrderNo) = 1
        then 'Y' else 'N' end AS 'Requires_Bags'
FROM Ord_Property OP
WHERE OP.ORDERNO =  @OrderNo

You can also use sqlserver iif function
    , iif(max(iif(C.Category = 'T-Shirt' and C.orderNo = OP.OrderNo, 1, 0)) = 1, 'Y', 'N') as 'Requires_T-Shirt'
    , iif(max(iif(C.Category = 'Shorts' and C.orderNo = OP.OrderNo, 1, 0)) = 1, 'Y', 'N') as 'Requires_Shorts'
    , iif(max(iif(C.Category = 'HeadCap' and C.orderNo = OP.OrderNo, 1, 0)) = 1, 'Y', 'N') as 'Requires_HeadCap'
    , iif(max(iif(C.Category = 'Pants' and C.orderNo = OP.OrderNo, 1, 0)) = 1, 'Y', 'N') as 'Requires_Pants'
    , iif(max(iif(C.Category = 'Jackets' and C.orderNo = OP.OrderNo, 1, 0)) = 1, 'Y', 'N') as 'Requires_Jackets'
    , iif(max(iif(C.Category = 'TankTops' and C.orderNo = OP.OrderNo, 1, 0)) = 1, 'Y', 'N') as 'Requires_TankTops'
    , iif(max(iif(C.Category = 'Bags' and C.orderNo = OP.OrderNo, 1, 0)) = 1, 'Y', 'N') as 'Requires_Bags'


text:
Q: How can I write to a .csv file multiple times and keep the previous data using C++? As of now I am doing this:
std::ofstream file;
file.open("test.csv");
file << "Test case" << std::endl;
file.close()

The problem is the .csv file will get overwritten with new data, each time a programme is launched. So in this case each time I run the programme I would get one line of the text "Test case" instead of having this line added to the .csv file. Is there a way to keep the data consistent and just add them to the same file, while keeping the previous data, each time I run the programme?

A: You can specify a second parameter to open, for example file.open("test.csv", ios_base::app).
http://www.cplusplus.com/reference/fstream/ofstream/ofstream/
http://www.cplusplus.com/reference/fstream/filebuf/open/


text:
Q: React functional component does not update conditional styling for Font Awesome icon I can achieve conditional styling if I wrap the icon inside a span or div like this:
narrationIcon : {
    display: 'none'
}

<span className={`${props.narration ? '' : classes.narrationIcon}`}>

However when used like this only the initial styling is set:

<i className={`fas fa-volume fa-2x ${props.narration ? '' : classes.narrationIcon}`}>

Why is this? Is this due to Font Awesome generating svg under the hood?


text:
Q: Не отображается информация об объекте во View Здравствуйте, я только начинаю изучать ASP.NET MVC. У меня проблема с отображением деталей владельца, отображается имя, фамилия, а вот сведения о машине не отображаются. Делала по примеру из сайта Майкрософт по изучению ASP.NET.
    public class Owner
    {
    public int OwnerID { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public DateTime Birthday { get; set; }
    public int Experience { get; set; }
    public virtual ICollection<CarOwner> CarOwners { get; set; }
}
 public class Car
{

    public int CarID { get; set; }
    public string Model { get; set; }
    public string Mark { get; set; }
    public string Type { get; set; }
    public int Price { get; set; }
    public string YearofRelease { get; set; }
    public virtual ICollection<CarOwner> CarOwners { get; set; }
}
 public class CarOwner
{

    public int CarOwnerID { get; set; }
    public int OwnerID { get; set; }
    public int CarID { get; set; }
    //public decimal? Grade { get; set; }
    public virtual Car Car { get; set; }
    public virtual Owner Owner { get; set; }
}
  public class CarOwnersContext: DbContext
{
   public CarOwnersContext():base("CarOwnersContext")
    {

    }

        public DbSet<Owner> Owners { get; set; }
        public DbSet<CarOwner> CarOwners { get; set; }
        public DbSet<Car> Cars { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }

}
 public class CarOwnerInit:DropCreateDatabaseIfModelChanges<CarOwnersContext>
{
    protected override void Seed(CarOwnersContext context)
    {
        var owners = new List<Owner>
        {
            new Owner {Name="Sam", OwnerID=1, Surname="Lucky", Birthday=DateTime.Parse("1993-06-21"), Experience=3},
            new Owner { Name="Nick", Surname="May", Birthday=DateTime.Parse("1994-04-06"), Experience=5 }

        };
        owners.ForEach(s => context.Owners.Add(s));
        context.SaveChanges();

        var cars = new List<Car>
        {
            new Car {Model="gghguyg",CarID=2, Mark="ghffgy", Type="gghf", Price=7, YearofRelease="2001" },
            new Car {Model="gghguyg",CarID=4, Mark="ghffgy", Type="gghf", Price=77, YearofRelease="2011"  }

        };
        cars.ForEach(s => context.Cars.Add(s));
        context.SaveChanges();

        var carowners = new List<CarOwner>
        {
            new CarOwner { OwnerID=1, CarID=2,CarOwnerID=1},
            new CarOwner { OwnerID=2, CarID=4,CarOwnerID=2 }

        };
        carowners.ForEach(s => context.CarOwners.Add(s));
        context.SaveChanges();
    }
}
 Код для отображения подробностей о пользователе
   @model CarOwners.Models.Owner

   @{
   ViewBag.Title = "Details";
    }

Details

Owner

        @Html.DisplayNameFor(model => model.Name)

        @Html.DisplayFor(model => model.Name)

        @Html.DisplayNameFor(model => model.Surname)

        @Html.DisplayFor(model => model.Surname)

        @Html.DisplayNameFor(model => model.Birthday)

        @Html.DisplayFor(model => model.Birthday)

        @Html.DisplayNameFor(model => model.Experience)

        @Html.DisplayFor(model => model.Experience)

        @Html.DisplayNameFor(model => model.CarOwners)

                Course Title
                Grade

            @foreach (var item in Model.CarOwners)
            {

                        @Html.DisplayFor(modelItem => item.Car.Mark)

                        @Html.DisplayFor(modelItem => item.CarOwnerID)

            }

  @Html.ActionLink("Edit", "Edit", new { id = Model.OwnerID }) |
  @Html.ActionLink("Back to List", "Index")

A: Вообще говоря, здесь нужно уточнить, какую версию EF Вы используете. Насколько я понял и контекста задачи, для Вас будет актуальным организовать отношение многие-ко-многим между вашими сущностями Car и Owner. В настоящий момент EF может взять на себя задачу по созданию так называемой промежуточной таблицы, которая будет эту связь (M-M) обеспечивать. Следовательно, класс CarOwner - уже лишний. Ваши модели будут выглядеть примерно так:
public class Owner
{
    public int OwnerID { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public DateTime Birthday { get; set; }
    public int Experience { get; set; }
    public virtual ICollection<Car> Cars { get; set; }
}

public class Car
{
    public int CarID { get; set; }
    public string Model { get; set; }
    public string Mark { get; set; }
    public string Type { get; set; }
    public int Price { get; set; }
    public string YearofRelease { get; set; }
    public virtual ICollection<Owner> Owners { get; set; }
}

Поскольку коллекции помечены модификатором virtual, EF автоматически подтянет нужные объекты из других таблиц. При получении коллекции на экземпляре контекста вы получите готове объекты со всеми вложенными в них сущностями, в соответствии с отношениями, которые есть в БД. Раз уж используете CodeFirst, то используйте Migrations, это поможет следить за изменениями, которые вносятся в базу по мере изменения классов модели.

    @Html.DisplayNameFor(model => model.CarOwners)

Смысл этой строки лично мне, честно говоря, мало понятен. Неужели так написано в примере Microsoft?
В общем, после того, как добавите классы моделей и сгенерируете по ним базу, просто добавьте новый класс MVC-контроллера, к примеру:
public class OwnersController : Controller
{
    // GET: Owners
    public ActionResult Index(int id = 1)
    {
        var c = new CarOwnersContext();

         return View(c.Owners.ToList().Single(o => o.OwnerID==id));

    }
}

Такой контроллер будет возвращать во View в качестве модели экземпляр типа Owner с указанным id.
Ну а в самом View отображайте то, что вы хотите видеть о машине текущего владельца, например, так:
@Html.DisplayFor(model => model.Car.Type)


text:
Q: How to add users as site collection administrator group through code I am having various site collections and I want to add few users into administrator group. So that more people will have access to edit the groups. I can add users to the site collection administrators group through
Site Actions -> Site Collection Administrators (and add users)
But I want to add users into admin group through code? I didn't get much idea about it.
Any help is appreciated.
Thanks.

A: Check out this post.
Here is the example from the post:
//if the user is not a user on the site already
someSPWeb.AllUsers.Add("domain\\user","user@domain.com","The User",null);

SPUser spUser = someSPWeb.AllUsers["domain\\user"];

spUser.IsSiteAdmin = true;

spUser.Update();

A: There is a big difference with being site collection administrator. While the answer by MBsurf makes a user site admin, that will give him probably to much permissions. Using the code below you can retrieve the Owners group of a site and then add a user to that group:
// get the owners group based on permission
var ownerAssignment = (from a in site.RootWeb.RoleAssignments.OfType<SPRoleAssignment>()
where a.RoleDefinitionBindings.OfType<SPRoleDefinition>().
Contains(site.RootWeb.RoleDefinitions.GetByType(SPRoleType.Administrator))
select a).FirstOrDefault();

// get the assignment's SharePoint group
var adminGroup = (SPGroup)ownerAssignment.Member;
// you can now add a user to this group

A: The below property is more effective to retrieve the site (SPWeb) owner group:
SPWeb.AssociatedOwnerGroup
Regards,
Vinicius


text:
Q: multiply xml for single activity I have 1 activity that for diffrent input need to make change on the location of buttons on its XML file.
I try to do it by using setX to diffrent position but it didn't move.
I was thinking maybe to make several XML where have the some data include button ID and the only diffrent will be there position on the screen. But then I need to attach diffrent XML for the some activity.Is it possible and how this can be done?
Thanks a lot
Bar.

A: I found what was wrong with the code that don't move my image on the layout. So this is much easier than make several layouts.
If we want to change position of the image by setX(number), we have first to make a call of its parameters.
So it go this way:

*

*imageviewLeft.requestLayout(); // get its size parameters

*imageviewLeft.setX(number);
And then it calculates the right new position.
Remember that number units is pixel and can't express in dp,sp ect.
So to help translate from dp to px we can use this code:
private int dp2px(int dp) {
    float scale = getResources().getDisplayMetrics().density;
    int pixels = (int) (dp * scale + 0.5f);
    return pixels;
}


text:
Q: Running out of memory very quick with cudaMallocManaged I have a C code and I want to translate that code to work with CUDA.
Explaining the complete problem would be very complicated and long, thats a part of it, where I have the problem.
Now the problem is: I need to create four AVL trees (the data to insert inside the trees are read from a file (the actual file, smaller one, have 255000 rows, but can be at maximum with 12 millions of rows). After inserting the four values on each corresponding tree, each node of the different trees will have a list of different nodes (one different per tree) but first I need to solve the problem that I have.
The problem is the following, if I create three of them there is no problem but if I create the four, CUDA gives an error "Out of memory".
Note, there are 410 code lines, the memory reservations with the function cudaMallocManaged(...) are on lines: 90 (function main) and 164, 176 and 190 (function auxCrearIndiceAVL). So I think that there is the error of it, but if so I could not see it.
Also I am working on a computer on Windows with Visual Studio with two NVIDIA 680 GTX (2 GB) and 32 GB of RAM. So with those 4 structures I think that there is enought memory for the structures. I dont know if need to activate any options on the CUDA setup or ...
Thanks for all in advance to anyone looking at this. Manuel Luis Aznar
The code is the following:
#include "cuda_runtime.h"

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define TRUE 1
#define FALSE 0

#define CHECK(r) {_check((r), __LINE__);}

/* Estructuras y tipos */

enum { IZQUIERDO, DERECHO };

typedef struct _nodo_especial {
    double m2i;
    double m1o;
    double m2o;
    struct _tipo_nodo *dato_next_index;
    struct _nodo_especial *siguiente;
    struct _nodo_especial *next_index;
} nodoEspecial;

typedef nodoEspecial* pNodoEspecial;

typedef struct _tipo_nodo {
    double dato;
    int FE;
    struct _nodo_especial *list;
    struct _tipo_nodo *derecho;
    struct _tipo_nodo *izquierdo;
    struct _tipo_nodo *padre;
} tipoNodo;

typedef tipoNodo* pNodo;
typedef tipoNodo* Arbol;

typedef struct REGcrowd {
    double m1i, m2i, m1o, m2o, x, y, color; // crowding
} EstrellaCrowding;

typedef EstrellaCrowding* pEstrellaCrowding;
typedef EstrellaCrowding* ListaEstrellasCrowding;

typedef struct _nodo_recubrimiento {
    double dato;
    pNodo enlace;
} nodoRecubrimiento;

typedef nodoRecubrimiento* pNodoRecubrimiento;
typedef nodoRecubrimiento* ListaRecubrimiento;

typedef struct _indices {
    Arbol indiceM1i, indiceColor, indiceX, indiceY;
    int numeroEstrellasIndice;
    int numeroNodosM1i, numeroNodosColor, numeroNodosX, numeroNodosY;
    ListaRecubrimiento listaRecubrimiento;
} tipoIndice;

typedef tipoIndice* Indice;
typedef tipoIndice* pIndice;

pNodo auxCrearIndiceAVL(Arbol *a, double dat, int *contador);

__global__ void kernel(Indice indice);
void _check(cudaError_t r, int line);
void check_memory_cuda(void);
__host__ __device__ void InOrden(Arbol a, int *contador);

/* Funciones de equilibrado */
void Equilibrar(Arbol *a, pNodo nodo, int rama, int nuevo);
void RSI(Arbol *raiz, pNodo nodo);
void RSD(Arbol *raiz, pNodo nodo);
void RDI(Arbol *raiz, pNodo nodo);
void RDD(Arbol *raiz, pNodo nodo);

int Vacio(Arbol r);

int main(int argc, char *argv[]) {

    check_memory_cuda();

    //Indice indice = (pIndice)malloc(sizeof(tipoIndice));
    Indice indice;
    CHECK(cudaMallocManaged(&indice, sizeof(Indice)));
    indice->indiceM1i = NULL;
    indice->indiceColor = NULL;
    indice->indiceX = NULL;
    indice->indiceY = NULL;
    indice->listaRecubrimiento = NULL;
    indice->numeroEstrellasIndice = 0;
    indice->numeroNodosM1i = 0;
    indice->numeroNodosColor = 0;
    indice->numeroNodosX = 0;
    indice->numeroNodosY = 0;

    FILE *fcrowd;
    int i;
    EstrellaCrowding estrellaCrowding;
    fcrowd = fopen(argv[1], "r");
    for (i = 0; !feof(fcrowd); i++) {

        fscanf(fcrowd, "%lf %lf %lf %lf %lf %lf", &estrellaCrowding.m1i, &estrellaCrowding.m2i, &estrellaCrowding.m1o, &estrellaCrowding.m2o, &estrellaCrowding.x, &estrellaCrowding.y);

        estrellaCrowding.color = estrellaCrowding.m1i - estrellaCrowding.m2i;

        pNodo auxM1i = auxCrearIndiceAVL(&indice->indiceM1i, estrellaCrowding.m1i, &indice->numeroNodosM1i);
        pNodo auxColor = auxCrearIndiceAVL(&indice->indiceColor, estrellaCrowding.color, &indice->numeroNodosColor);
        pNodo auxX = auxCrearIndiceAVL(&indice->indiceX, estrellaCrowding.x, &indice->numeroNodosX);
        //pNodo auxY = auxCrearIndiceAVL(&indice->indiceY, estrellaCrowding.y, &indice->numeroNodosY);
    }
    fclose(fcrowd);

    check_memory_cuda();

    printf("Imprimiendo el recorrido en InOrden del arbol M1i CPU\n");
    int contador = 0;
    InOrden(indice->indiceM1i, &contador);

    printf("El numero de nodos del arbol M1i es CPU: %d\n", indice->numeroNodosM1i);
    printf("Raiz arbol M1i CPU: %lf\n", indice->indiceM1i->dato);

    printf("El numero de nodos del arbol Color es CPU: %d\n", indice->numeroNodosColor);
    printf("Raiz arbol Color CPU: %lf\n", indice->indiceColor->dato);

    printf("El numero de nodos del arbol X es CPU: %d\n", indice->numeroNodosX);
    printf("Raiz arbol X CPU: %lf\n", indice->indiceX->dato);

    //printf("El numero de nodos del arbol Y es CPU: %d\n", indice->numeroNodosY);
    //printf("Raiz arbol Y CPU: %lf\n", indice->indiceY->dato);

    kernel<<<1, 1>>>(indice);
    cudaDeviceSynchronize();

    return 0;
}

pNodo auxCrearIndiceAVL(Arbol *a, double dat, int *contador) {

    pNodo padre = NULL;
    pNodo actual = *a;

    /* Buscar el dato en el arbol, manteniendo un puntero al nodo padre */
    while (!Vacio(actual) && dat != actual->dato) {
        padre = actual;
        if (dat < actual->dato)
            actual = actual->izquierdo;
        else if (dat > actual->dato)
            actual = actual->derecho;
    }

    /* Si se ha encontrado el elemento, regresar sin insertar */
    if (!Vacio(actual))
        return actual;
    /* Si padre es NULL, entonces el arbol estaba vacio, el nuevo nodo sera el nodo raiz */
    else if (Vacio(padre)) {
        //(*a) = (Arbol)malloc(sizeof(tipoNodo));
        CHECK(cudaMallocManaged(&(*a), sizeof(tipoNodo), cudaMemAttachGlobal));
        (*a)->dato = dat;
        (*a)->izquierdo = (*a)->derecho = NULL;
        (*a)->padre = NULL;
        (*a)->FE = 0;
        (*a)->list = NULL;
        (*contador)++;
        return (*a);
    }
    /* Si el dato es menor que el que contiene el nodo padre, lo insertamos en la rama izquierda */
    else if (dat < padre->dato) {
        //actual = (Arbol)malloc(sizeof(tipoNodo));
        CHECK(cudaMallocManaged(&actual, sizeof(tipoNodo), cudaMemAttachGlobal));
        padre->izquierdo = actual;
        actual->dato = dat;
        actual->izquierdo = actual->derecho = NULL;
        actual->padre = padre;
        actual->FE = 0;
        actual->list = NULL;
        Equilibrar(a, padre, IZQUIERDO, TRUE);
        (*contador)++;
        return actual;
    }
    /* Si el dato es mayor que el que contiene el nodo padre, lo insertamos en la rama derecha */
    else {  /*if (dat > padre->dato) */
        //actual = (Arbol)malloc(sizeof(tipoNodo));
        CHECK(cudaMallocManaged(&actual, sizeof(tipoNodo), cudaMemAttachGlobal));
        padre->derecho = actual;
        actual->dato = dat;
        actual->izquierdo = actual->derecho = NULL;
        actual->padre = padre;
        actual->FE = 0;
        actual->list = NULL;
        Equilibrar(a, padre, DERECHO, TRUE);
        (*contador)++;
        return actual;
    }
}

__global__ void kernel(Indice indice) {

    printf("Imprimiendo el recorrido en InOrden del arbol M1i GPU\n");
    int contador = 0;
    InOrden(indice->indiceM1i, &contador);

    printf("El numero de nodos del arbol M1i es GPU: %d\n", indice->numeroNodosM1i);
    printf("Raiz arbol M1i GPU: %lf\n", indice->indiceM1i->dato);

    printf("El numero de nodos del arbol Color es GPU: %d\n", indice->numeroNodosColor);
    printf("Raiz arbol Color GPU: %lf\n", indice->indiceColor->dato);

    printf("El numero de nodos del arbol X es GPU: %d\n", indice->numeroNodosX);
    printf("Raiz arbol X GPU: %lf\n", indice->indiceX->dato);

    //printf("El numero de nodos del arbol Y es GPU: %d\n", indice->numeroNodosY);
    //printf("Raiz arbol Y GPU: %lf\n", indice->indiceY->dato);
}

void _check(cudaError_t r, int line) {
    if (r != cudaSuccess) {
        printf("CUDA error on line %d: %s\n", line, cudaGetErrorString(r), line);
        exit(0);
    }
}

void check_memory_cuda(void) {
    size_t free, total;
    cudaMemGetInfo(&free, &total);
    printf("CUDA Memory:\n\tFree ---> %llu\n\tTotal ----> %llu\n", free, total);
}

/* Recorrido de arbol en inorden, aplicamos la funcion func, que tiene
el prototipo:
void func(double*);
*/
__host__ __device__ void InOrden(Arbol a, int *contador)
{
    if (a->izquierdo) InOrden(a->izquierdo, contador);
    printf("%d ---> %lf\n", *contador, a->dato);
    (*contador)++;
    if (a->derecho) InOrden(a->derecho, contador);
}

/* Equilibrar árbol AVL partiendo del nodo nuevo */
void Equilibrar(Arbol *a, pNodo nodo, int rama, int nuevo)
{
    int salir = FALSE;

    /* Recorrer camino inverso actualizando valores de FE: */
    while (nodo && !salir) {
        if (nuevo)
        if (rama == IZQUIERDO) nodo->FE--; /* Depende de si añadimos ... */
        else                  nodo->FE++;
        else
        if (rama == IZQUIERDO) nodo->FE++; /* ... o borramos */
        else                  nodo->FE--;
        if (nodo->FE == 0) salir = TRUE; /* La altura de las rama que
                                         empieza en nodo no ha variado,
                                         salir de Equilibrar */
        else if (nodo->FE == -2) { /* Rotar a derechas y salir: */
            if (nodo->izquierdo->FE == 1) RDD(a, nodo); /* Rotación doble  */
            else RSD(a, nodo);                         /* Rotación simple */
            salir = TRUE;
        }
        else if (nodo->FE == 2) {  /* Rotar a izquierdas y salir: */
            if (nodo->derecho->FE == -1) RDI(a, nodo); /* Rotación doble  */
            else RSI(a, nodo);                        /* Rotación simple */
            salir = TRUE;
        }
        if (nodo->padre)
        if (nodo->padre->derecho == nodo) rama = DERECHO; else rama = IZQUIERDO;
        nodo = nodo->padre; /* Calcular FE, siguiente nodo del camino. */
    }
}

/* Rotación doble a derechas */
void RDD(Arbol *raiz, Arbol nodo)
{
    pNodo Padre = nodo->padre;
    pNodo P = nodo;
    pNodo Q = P->izquierdo;
    pNodo R = Q->derecho;
    pNodo B = R->izquierdo;
    pNodo C = R->derecho;

    if (Padre)
    if (Padre->derecho == nodo) Padre->derecho = R;
    else Padre->izquierdo = R;
    else *raiz = R;

    /* Reconstruir árbol: */
    Q->derecho = B;
    P->izquierdo = C;
    R->izquierdo = Q;
    R->derecho = P;

    /* Reasignar padres: */
    R->padre = Padre;
    P->padre = Q->padre = R;
    if (B) B->padre = Q;
    if (C) C->padre = P;

    /* Ajustar valores de FE: */
    switch (R->FE) {
    case -1: Q->FE = 0; P->FE = 1; break;
    case 0:  Q->FE = 0; P->FE = 0; break;
    case 1:  Q->FE = -1; P->FE = 0; break;
    }
    R->FE = 0;
}

/* Rotación doble a izquierdas */
void RDI(Arbol *a, pNodo nodo)
{
    pNodo Padre = nodo->padre;
    pNodo P = nodo;
    pNodo Q = P->derecho;
    pNodo R = Q->izquierdo;
    pNodo B = R->izquierdo;
    pNodo C = R->derecho;

    if (Padre)
    if (Padre->derecho == nodo) Padre->derecho = R;
    else Padre->izquierdo = R;
    else *a = R;

    /* Reconstruir árbol: */
    P->derecho = B;
    Q->izquierdo = C;
    R->izquierdo = P;
    R->derecho = Q;

    /* Reasignar padres: */
    R->padre = Padre;
    P->padre = Q->padre = R;
    if (B) B->padre = P;
    if (C) C->padre = Q;

    /* Ajustar valores de FE: */
    switch (R->FE) {
    case -1: P->FE = 0; Q->FE = 1; break;
    case 0:  P->FE = 0; Q->FE = 0; break;
    case 1:  P->FE = -1; Q->FE = 0; break;
    }
    R->FE = 0;
}

/* Rotación simple a derechas */
void RSD(Arbol *a, pNodo nodo)
{
    pNodo Padre = nodo->padre;
    pNodo P = nodo;
    pNodo Q = P->izquierdo;
    pNodo B = Q->derecho;

    if (Padre)
    if (Padre->derecho == P) Padre->derecho = Q;
    else Padre->izquierdo = Q;
    else *a = Q;

    /* Reconstruir árbol: */
    P->izquierdo = B;
    Q->derecho = P;

    /* Reasignar padres: */
    P->padre = Q;
    if (B) B->padre = P;
    Q->padre = Padre;

    /* Ajustar valores de FE: */
    P->FE = 0;
    Q->FE = 0;
}

/* Rotación simple a izquierdas */
void RSI(Arbol *a, pNodo nodo)
{
    pNodo Padre = nodo->padre;
    pNodo P = nodo;
    pNodo Q = P->derecho;
    pNodo B = Q->izquierdo;

    if (Padre)
    if (Padre->derecho == P) Padre->derecho = Q;
    else Padre->izquierdo = Q;
    else *a = Q;

    /* Reconstruir árbol: */
    P->derecho = B;
    Q->izquierdo = P;

    /* Reasignar padres: */
    P->padre = Q;
    if (B) B->padre = P;
    Q->padre = Padre;

    /* Ajustar valores de FE: */
    P->FE = 0;
    Q->FE = 0;
}

/* Comprobar si un árbol es vacío */
int Vacio(Arbol r)
{
    return r == NULL;
}

A: Yesterday evening and night I was doing some cudaMallocManaged(...) testing, before that I was thinking that Unified Memory was using the Device Memory and when it runs out of space in the device they starts using the Host memory.
That was not like this, with the Unified Memory System of CUDA 6 cudaMallocManaged(...), we can only allocate as much memory as the device have.
thanks very much to ArchaeaSoftware for its answer
thanks to whole people reading and I wish all of you to enjoy CUDA as much as you can
see you soon guys.
Manuel


text:
Q: Dart - How to set a variable as a type String of being a few specific options? I'm trying to set a variable as a String of being a few specific options. I'm writing or converting it from TypeScript and am trying to reproduce this:
let myVar: 'a' | 'b' | 'c';

String myVar;

... is as far as I can get.
How can I write this in Dart, please?


text:
Q: PHP, How to secure GET variable from URL Here is URL:
http://ex.com/members.php?id=5320
Here is code:
mysqli_query("SELECT * from members where id='$_GET[id]'");

which method is secure?

A: Use prepared statements and bind variables when you're using MySQLi
$stmt = $mysqli->prepare("SELECT * from members where id=?");
$stmt->bind_param('i', $_GET['id']);
$stmt->execute();

You may also wish to validate that $_GET['id'] is an integer first, and return an error message if it isn't rather than have all the overhead of a db query to return nothing.
Read this answer to a previous question to understand why yu should take this approach


text:
Q: C# lambda IN clause error I'm having issues creating an IN clause using C# and lambdas.
I have the following method GetUserList(string filtersByRoles)
The variable string filtersByRoles can hold a comma-delimited value such as: "1,2" or "1,2,3" or "1,3,4" etc...each number represents the unique number of a Role (in other words, RoleId).
I then have the following C# lambda query:
var query = _userRepository.GetUserList();

Which returns an IQueryable<User> where User is a table from my EntityFramework.
Once I verify if the filtersByRoles parameter is not null-or-empty, I need to make an IN clause such as:
if (!string.IsNullOrEmpty(filtersByRoles))
{
   //Convert *filtersByRoles* to an array of integers
   int[] myArray = filtersByRoles.Split(',').Select(x => int.Parse(x)).ToArray();

   //Make the IN clause
   query = query.Where(u => myArray.Contains(u.RoleId));
}

The above code compiles...but at RUNTIME it fails with the following error message:

LINQ to Entities does not recognize the method 'Boolean
  Contains[Int32](System.Collections.Generic.IEnumerable`1[System.Int32],
  Int32)' method, and this method cannot be translated into a store
  expression.

I've manage to find a workaround but it involves making a call to the .ToList() method which I believe fetches all the data from my database and then, adds a Where() clause.
But wouldn't that defeat the purpose or create some performance issues?
This is what I've done:
if (!string.IsNullOrEmpty(filtersByRoles))
{
      string[] myArray = filtersByRoles.Split(',');
      query = query.ToList().Where(u => myArray.Contains(u.RoleId.ToString())).AsQueryable();
}

I would prefer not to make the .ToList() call and avoid fetching all the data.
Is there another way to achieve this?
EDIT:
I'm using Entity Framework 1.0 and .NET Framework 3.5
Thanks
Sincerely
Vince

A: This is supported with EF 4 : http://blogs.msdn.com/b/alexj/archive/2009/03/26/tip-8-writing-where-in-style-queries-using-linq-to-entities.aspx

A: Here are my 2 cents:
Maybe the Dynamic LinQ will help solve your problem:
http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
You could build your Where clause as a string, say something like :
string sWhereClause = "1 = 1";
foreach(string rId in filtersByRoles.Split(','))
   sWhereClause += " OR RoleId = " + rId;

(I would suggest to use StringBuilder instead of +concat, but for the purpose of this answer, it doesn't matter)
and then
query = query.Where(sWhereClause);

I haven't tryed it though, but it sounds fair for solving your problem. Even though it looks like SQL injection... Well, improvements can be brought.
EDIT:
As a second thought I manage to come with this new idea:
string filterByRoles = "1,2,3";
query = query.Where(new Func<User, bool>(u => {
   return filterByRoles.Contains(u.RoleId.ToString());
})).AsQueryable();

This way, you can add whatever code you want in the Func{ ... } delegate, as long as it returns a boolean (I assumed here your TInput was a "User" class, of course change it to use the one corresponding to you needs).
Hope this helps!

A: Based on some of your replies, I've manage to pull up something like this:
int[] myArray = filtersByRoles.Split(',').Select(x => int.Parse(x)).ToArray();
int count = myArray.Count();
int role1;
int role2;
int role3;
int role4;

switch (myArray.Length)
{
    case 1:
        role1 = myArray[0];

        query = query.Where(u => u.RoleId.Equals(role1));
        break;

    case 2:
        role1 = myArray[0];
        role2 = myArray[1];

        query = query.Where(u => u.RoleId.Equals(role1)
                              || u.RoleId.Equals(role2));
        break;

    case 3:
        role1 = myArray[0];
        role2 = myArray[1];
        role3 = myArray[2];

        query = query.Where(u => u.RoleId.Equals(role1)
                              || u.RoleId.Equals(role2)
                              || u.RoleId.Equals(role3));
        break;

    case 4:
        role1 = myArray[0];
        role2 = myArray[1];
        role3 = myArray[2];
        role4 = myArray[3];

        query = query.Where(u => u.RoleId.Equals(role1)
                              || u.RoleId.Equals(role2)
                              || u.RoleId.Equals(role3)
                              || u.RoleId.Equals(role4));
        break;
}

When directly trying with the myArray[xxx]:
query = query.Where(u => u.RoleId.Equals(myArray[0]));

I was getting this:

The LINQ expression node type 'ArrayIndex' is not supported in LINQ to
  Entities.

Hence the creation of the 4 (integer) variables!
It now works but may need some optimization…
Thanks


text:
Q: SRCSET loading incorrect size when "sizes" is not specified As per the docs, when sizes is not specified in the image attribute, browser should automatically calculated the required size based on css rendering.
In that case, my image is 300px and the browser should choose 300px image. However, it's taking the 1024px image.
<html>
  <div style="width:300px">
    <img
      width="100%"
      src="https://staging.wpspeedmatters.com/wp-content/uploads/2019/11/migrating-birds-560x336.jpg"
      class="attachment-csco-medium-alternative size-csco-medium-alternative wp-post-image"
      alt=""
      srcset="
    https://staging.wpspeedmatters.com/wp-content/uploads/2019/11/migrating-birds-300x200.jpg   300w,
    https://staging.wpspeedmatters.com/wp-content/uploads/2019/11/migrating-birds-380x253.jpg   380w,
    https://staging.wpspeedmatters.com/wp-content/uploads/2019/11/migrating-birds-768x512.jpg   768w,
    https://staging.wpspeedmatters.com/wp-content/uploads/2019/11/migrating-birds-800x533.jpg   800w,
    https://staging.wpspeedmatters.com/wp-content/uploads/2019/11/migrating-birds-1024x683.jpg 1024w,
    https://staging.wpspeedmatters.com/wp-content/uploads/2019/11/migrating-birds-1160x773.jpg 1160w.
    https://staging.wpspeedmatters.com/wp-content/uploads/2019/11/migrating-birds.jpg          1500w,
    "
    />
  </div>
</html>

https://jsfiddle.net/khsyLxdr/

A: I believe you are incorrectly implementing the syntax. The (Number) w at the end.
Try changing it to 1X, 2X and so on. Also have you tried to specify the desired size on the CSS? Remember, HTML will display the image as-is unless you modify its properties.


text:
Q: Drawing created by incompatible version - Save will be prevented || Design Automation API We created a autocad plugin, that draws a border around the object present in dwg file.
It works fine for all the created using autocad.
We have a file created with autocad mechanical 2022, for which design automation gives error
" Drawing created by incompatible version - Save will be prevented "
Error Report Url
We using engine "Autodesk.Autocad+24_1"
We are not sure how to fix this issue, please suggest do we need to change to another engine or what coulod be the solution of it.


text:
Q: Catching ERROR_ALREADY_EXISTS and similar errors with CreateDirectory() I am looking to make a program using CreateDirectory(), RemoveDirectory(), and similar functions. One of the possible return errors from these commands ERROR_ALREADY_EXISTS. I want an if statement to catch this error and post a message on the screen and continue.

A: You need to call GetLastError () and check to see if the error condition meets ERROR_ALREADY_EXISTS; after calling CreateDirectory() and when it returns 0.


text:
Q: How to solve this multiple nested for loop EDIT: Big edit from ealier
I have achieved: the ultimate for-loop HELL.
What it does: scans an image and finds a 40 by 40 pixel square that has every pixel within it approximately the same color.
The problem: The code doesn't work as intended. Unsure why, but all my attempts to debug are in vain.
    jimp.read('jeffrey.png')
          .then(image => {
            console.log(jimp.intToRGBA(image.getPixelColor(0,0)))
            console.log(image.bitmap.width)
            console.log(image.bitmap.height)

                            var breakAll = false;
            var FINALX;
            var FINALY;
var doneCounter = 0;
            //40 by 40 pixels needed for qr code. Thisis barcode, so make it 40 by 80 or smthn, figure out that x thing.
            for(var x = 0; x < image.bitmap.width; x++) {
              var breakThis = false;
              console.log(x + " is x")
              if(breakAll == true) {
                    break;
                  }

              var verticalStart = 0;
              for(var y1 = verticalStart; y1 < image.bitmap.height; y1++) {
                if(breakAll == true) {
                    break;
                  }

                var tempStandardR = jimp.intToRGBA(image.getPixelColor(x,y1)).r;
                var tempStandardG = jimp.intToRGBA(image.getPixelColor(x,y1)).g;
                var tempStandardB = jimp.intToRGBA(image.getPixelColor(x,y1)).b;

                var verticalCounter = 0;

                for(var y2 = y1; y2 < image.bitmap.height; y2++) {
                  if(breakAll == true) {
                    break;
                  }
                  if(verticalCounter >= 40) {

                      //Then do X stuff
                      //horizcountertim

                      for(var y3 = y1; y3 < y1 + 40; y3++) {
                        if(breakAll == true) {
                          break;
                        }
                        breakThis = false;
                        var horizontalCounter = 0;
                        var tempStandardR3 = jimp.intToRGBA(image.getPixelColor(x,y3)).r;
                        var tempStandardG3 = jimp.intToRGBA(image.getPixelColor(x,y3)).g;
                        var tempStandardB3 = jimp.intToRGBA(image.getPixelColor(x,y3)).b;
                        for(var x2 = x; x2 < x + 41; x2++) {

                          if(breakAll == true) {
                            break;
                          }
                          console.log(doneCounter)
                           if(doneCounter >= 40) {
                              //SUCESS!!!!!!
                              //THE SPOT HAS BEEN FOUND AT (x minus 40, y minus 40).
                              //insert other image in this image at above coordinates. Wow I highly doubt this works.
                              console.log('SUCESS!!!!!!!!!')
                              FINALX = x2-40;
                              FINALY = y3-40;
                              breakAll = true;
                              break;
                            }
                           if(breakAll == true) {
                            break;
                          }
                          var tempStandardR4 = jimp.intToRGBA(image.getPixelColor(x2,y3)).r;
                          var tempStandardG4 = jimp.intToRGBA(image.getPixelColor(x2,y3)).g;
                          var tempStandardB4 = jimp.intToRGBA(image.getPixelColor(x2,y3)).b;
                          if((((tempStandardR3 - tempStandardR4) <= 20) && ((tempStandardR3 - tempStandardR4) >= -20)) && (((tempStandardG3 - tempStandardG4) <= 20) && ((tempStandardG3 - tempStandardG4) >= -20)) && (((tempStandardB3 - tempStandardB4) <= 20) && ((tempStandardB3 - tempStandardB4) >= -20))) {
                            horizontalCounter++;
                            if(horizontalCounter == 40) {
                              horizontalCounter = 0;
                              doneCounter++;
                              break;
                            }

                           // if((x2 - x >= 39) && (y3 - y1) >= 39) {

                            if(breakAll == true) {
                              break;
                            }
                          }
                          else {
                            horizontalCounter = 0;
                            verticalCounter = 0;
                            doneCounter = 0;
                            console.log('donecounter reset')
                            verticalStart = y3;
                            //y2 = y3;
                            breakThis = true;
                            break;
                          }
                        }
                        if(breakAll == true) {
                          break;
                        }
                        if(breakThis = true) {
                          break;
                        }

                      }
                    if(breakThis = true) {
                      breakThis = false;
                      break;
                    }
                  }
                  if(breakAll == true) {
                    break;
                  }
                   var tempStandardR2 = jimp.intToRGBA(image.getPixelColor(x,y2)).r;
                  var tempStandardG2 = jimp.intToRGBA(image.getPixelColor(x,y2)).g;
                  var tempStandardB2 = jimp.intToRGBA(image.getPixelColor(x,y2)).b;
                  if((((tempStandardR - tempStandardR2) <= 20) && ((tempStandardR - tempStandardR2) >= -20)) && (((tempStandardG - tempStandardG2) <= 20) && ((tempStandardG - tempStandardG2) >= -20)) && (((tempStandardB - tempStandardB2) <= 20) && ((tempStandardB - tempStandardB2) >= -20))) {
                    verticalCounter++;
                  }
                  else {
                    verticalCounter = 0;
                    verticalStart = y2;
                    console.log('lvl1 reset')
                    doneCounter = 0;
                    break;
                  }

                }
              }
            }
            console.log(' done');
            console.log(FINALX + " = x")
            console.log(FINALY + " = y")
          })
          .catch(err => {
            console.log(err);
          })

Each of the tempStandards are the RGB value for that individual pixel.
All of the for loops are to get a 40 by 40 open grid.
The issue I do see is a problem, but am baffled as to why, is doneCounter, that is supposed to ++ every time a horizontal counter has reached 40 and thus finished its horizontal check of one row of the 40 by 40 grid.
The issue when console logging doneCounter is, it console logs the same value twice, which makes no sense since its within the same for loop that has an if else statement that either adds to donecounter or resets it to 0.
EDIT: I scrapped the above code to try and remake it entirely to see if that would let it work, still failed though and not a clue as to why: Below is the updated attempt:
jimp.read('jeffrey.png')
          .then(image => {

            console.log(jimp.intToRGBA(image.getPixelColor(0,0)))
            console.log(image.bitmap.width)
            console.log(image.bitmap.height)
            var breakAll = false;
            var FINALX;
            var FINALY;
            var doneCounter = 0;
            var veritcalCounter = 0;
            var verticalStart = 0;
            var horizontalCounter = 0;
            var breakAll = false;
            var breakThis = false;
            //40 by 40 pixels needed for qr code. Thisis barcode, so make it 40 by 80 or smthn, figure out that x thing.
            for(var x = 0; x < image.bitmap.width; x++) {
              console.log(x)
              verticalCounter = 0;
              for(var y = 0; y < image.bitmap.height; y++) {
                var tempStandardR = jimp.intToRGBA(image.getPixelColor(x,verticalStart)).r;
                var tempStandardG = jimp.intToRGBA(image.getPixelColor(x,verticalStart)).g;
                var tempStandardB = jimp.intToRGBA(image.getPixelColor(x,verticalStart)).b;
                var tempStandardR2 = jimp.intToRGBA(image.getPixelColor(x,y)).r;
                var tempStandardG2 = jimp.intToRGBA(image.getPixelColor(x,y)).g;
                var tempStandardB2 = jimp.intToRGBA(image.getPixelColor(x,y)).b;
                if((((tempStandardR - tempStandardR2) <= 20) && ((tempStandardR - tempStandardR2) >= -20)) && (((tempStandardG - tempStandardG2) <= 20) && ((tempStandardG - tempStandardG2) >= -20)) && (((tempStandardB - tempStandardB2) <= 20) && ((tempStandardB - tempStandardB2) >= -20))) {
                  verticalCounter++;
                  if(verticalCounter == 40) {
                    verticalCounter = 0;
                    for(var y1 = y-40; y1 < y; y1++) {
                      horizontalCounter = 0;
                      for(var x1 = x; x1 < x+41; x1++) {
                        var tempStandardR3 = jimp.intToRGBA(image.getPixelColor(x,y1)).r;
                        var tempStandardG3 = jimp.intToRGBA(image.getPixelColor(x,y1)).g;
                        var tempStandardB3 = jimp.intToRGBA(image.getPixelColor(x1,y1)).b;
                        var tempStandardR4 = jimp.intToRGBA(image.getPixelColor(x1,y1)).r;
                        var tempStandardG4 = jimp.intToRGBA(image.getPixelColor(x1,y1)).g;
                        var tempStandardB4 = jimp.intToRGBA(image.getPixelColor(x1,y1)).b;
                        if((((tempStandardR3 - tempStandardR4) <= 20) && ((tempStandardR3 - tempStandardR4) >= -20)) && (((tempStandardG3 - tempStandardG4) <= 20) && ((tempStandardG3 - tempStandardG4) >= -20)) && (((tempStandardB3 - tempStandardB4) <= 20) && ((tempStandardB3 - tempStandardB4) >= -20))) {
                          if(x1 == x+40) {
                            doneCounter++;
                            if(doneCounter == 39) {
                              //SUCESS!!!!!!
                              //THE SPOT HAS BEEN FOUND AT (x minus 40, y minus 40).
                              //insert other image in this image at above coordinates. Wow I highly doubt this works.
                              console.log('SUCESS!!!!!!!!!')
                              FINALX = x;
                              FINALY = y1-40;
                              breakAll = true;
                              break;
                            }
                            break;
                          }
                        }
                        else {
                          verticalCounter = 0;
                          horizontalCounter = 0;
                          doneCounter = 0;
                          y = y1;
                          breakThis = true;
                          break;
                        }
                        if(breakAll == true) {
                          break;
                        }
                      }
                      if(breakThis == true) {
                        breakThis = false;
                        break;
                      }
                      if(breakAll == true) {
                        break;
                      }
                    }
                    if(breakAll == true) {
                      break;
                    }
                  }
                  if(breakAll == true) {
                    break;
                  }
                }
                else {
                  verticalCounter = 0;
                  verticalStart = 0;
                }
                if(breakAll == true) {
                  break;
                }
              }
              if(breakAll == true) {
                break;
              }
            }
            console.log(' done');
            console.log(FINALX + " = x")
            console.log(FINALY + " = y")
          })
          .catch(err => {
            console.log(err);
          })


text:
Q: ReactJS Background Image not Showing The code inside the image below suppose give me the background. But it did not work. I don't get it why?
Image to the problem

A: .sign-in-container does not get 100% elevation. Because React have Root and you component inside root div on DOM. Root's height is not 100%. It is "auto".
You have to use "height: 100vh" instead of height: "100%" this project.

A: In your stylesheet you should reset the margin and padding of the html and body tags and set the height and width respectively to 100vh and 100vw like this
* {
    margin: 0;
    padding: 0;
}

html, body {
    width: 100vw;
    height: 100vh;
}

#root {
    width: 100%;
    height: 100%;
}


text:
Q: What actually happens when a computer is deleted from Active Directory? If I open AD and then delete a computer, what will happen to that computer? Will it physically get removed from the domain? What would happen if I tried to log into the computer after it had been deleted?

A: Remember that you are not deleting a computer but a computer account
Just like deleting a user doesnt eject then from the building, deleting the computer account will just mean the computer can no longer access the domain.
Domain logins will fail because the domain controller won't talk to it. Computers need those accounts, with the right password, to access things like group policy shares.
But the computer will still think its on the domain, just like the guy about to be fired thinks he still works here.


text:
Q: How to store the image that was taken using camera in android to database using php I have two buttons in the activity,One for getting camera and the other for uploading images to server.I have used volley to do this in android.It shows error as below
E/AndroidRuntime: FATAL EXCEPTION: Thread-2147
                                                                       java.lang.OutOfMemoryError
                                                                           at java.lang.AbstractStringBuilder.enlargeBuffer(AbstractStringBuilder.java:94)
                                                                           at java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:132)
                                                                           at java.lang.StringBuilder.append(StringBuilder.java:124)
                                                                           at libcore.net.UriCodec.appendEncoded(UriCodec.java:119)
                                                                           at libcore.net.UriCodec.encode(UriCodec.java:133)
                                                                           at java.net.URLEncoder.encode(URLEncoder.java:57)
                                                                           at com.android.volley.Request.encodeParameters(Request.java:450)
                                                                           at com.android.volley.Request.getBody(Request.java:436)
                                                                           at com.android.volley.toolbox.HurlStack.addBodyIfExists(HurlStack.java:260)
                                                                           at com.android.volley.toolbox.HurlStack.setConnectionParametersForRequest(HurlStack.java:234)
                                                                           at com.android.volley.toolbox.HurlStack.performRequest(HurlStack.java:107)
                                                                           at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:96)
                                                                           at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:112)

when I click the upload button.Camera button is working fine.My android is as below:
Image.java
package com.login.sowmy.uspcar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class Image extends AppCompatActivity {
    Button btnimgupload, btncamera;
    ImageView imgliccard;
    private String encoded_string, cust_name;
    private Bitmap bitmap;
    private File file;
    private Uri file_uri;
    private static final int CAMERA_REQUEST = 1888;
    SharedPreferences shared;
    final String TAG = this.getClass().getName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image);
        imgliccard = (ImageView) findViewById(R.id.imglic);
        btncamera = (Button) findViewById(R.id.btncamera);
        btnimgupload = (Button) findViewById(R.id.btnupload);
        shared = getSharedPreferences("get", Context.MODE_PRIVATE);
        cust_name = shared.getString("key", null);
        btncamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                getFileUri();
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, file_uri);
                startActivityForResult(cameraIntent, CAMERA_REQUEST);

            }
        });
        btnimgupload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Encode_image().execute();
            }
        });
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
            //Bitmap photo = (Bitmap) data.getExtras().get("data");
            imgliccard.setImageURI(file_uri);

        }
    }

    public void getFileUri() {
        file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) +
                File.separator + cust_name + ".jpg");
        file_uri = Uri.fromFile(file);

    }

    public class Encode_image extends AsyncTask<Void, Void, Void> {
        @Override

        protected Void doInBackground(Void... params) {
            bitmap = BitmapFactory.decodeFile(file_uri.getPath());
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
            byte[] array = stream.toByteArray();
            encoded_string = Base64.encodeToString(array, 0);
            System.out.print("Step 1" +encoded_string);
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            makeRequest();
        }
    }

    private void makeRequest() {
        RequestQueue requestQueue= Volley.newRequestQueue(this);
        StringRequest request=new StringRequest(Request.Method.POST, "http://localhost/img_upload1.php", new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                Toast.makeText(getApplicationContext(), "error",Toast.LENGTH_SHORT).show();

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String,String> map=new HashMap<>();
                map.put("encoded_string",encoded_string);
                map.put("cust_name",cust_name);
                return map;
            }
        };
        requestQueue.add(request);
    }
}

My php file is as below
<?php
header('Content-type : bitmap; charset=utf-8');

if(isset($_POST["encoded_string"])) {
    $encoded_string=$_POST["encoded_string"];
    $cust_name=$_POST["cust_name"];
    $decoded_string =base64_decode($encoded_string);
    $path= 'android/'.$cust_name;

    $file=fopen($path,'wb');
    $is_written=fwrite($file,$decoded_string);
    fclose($file);

    if($is_written >0) {
        require 'connect.php';
        $query = "UPDATE cust_detail SET img_url=? WHERE cusname=? ";
        $params=array($path,$cust_name);
        $result = sqlsrv_query($conn,$query,$params);
        if( $result === false) {
            echo "Error in query preparation/execution.\n";
            die( print_r( sqlsrv_errors(), true));
        } else {
            echo "success";
        }
    }
    sqlsrv_close($conn);
}
?>

I have added the following in manifest file
<uses-feature
    android:name="android.hardware.camera2"
    android:required="true" />

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

I have added volley as below in build gradle
compile 'com.android.volley:volley:1.0.0'.

Can anyone please help me to how to uploads images using volley with php script?


text:
Q: Performance between substring and date cast SQL I have this SQL code that generate the same result. which one is most efficient?
SELECT SUBSTRING(transaccion_day, 1, 7) FROM my_table

SELECT to_char(to_date(transaccion_day,'YYYY-MM-DD'),'YYYY-MM') FROM my_table

*

*The content of transaccion_day is something like this: '2022-06-09'

*The result is something like: '2022-06'

A: It is most efficient with substring because in the second option you need to do two converts

A: If it has to be a text column (I hope not), then simply use a like query. It would utilize the existing index on the column. ie:
 SELECT * FROM my_table
where transaccion_day like '2022-06%';


text:
Q: Is it possible to make this border around image? I'm hoping to achieve a result like this and don't know where to start:

picture {
  position: relative;
  display: block;
  width: min-content;
}

img {
  display: block;
  padding: 6px;
}
<picture>

</picture>

A: This should get you started:
More info on 3D transforms
Pseudo elements

picture {
  position: relative;
  display: block;
  width: min-content;
}

img {
  display: block;
  padding: 6px;
  transform: translate(10px, 10px) perspective(100px) rotateX(10deg);
}

picture::before {
  content: '';
  display: block;
  position: absolute;
  width: calc(100% - 8px);
  height: calc(100% - 8px);
  border: 4px solid orange;
  border-radius: 6px;
}
<picture>

</picture>


text:
Q: "I like swimming breaststroke" or "I like swimming the breaststroke"? Tell me please if I need to use the before the types of swimming techniques when they are used as adverbs? For example:

I like swimming (the) breaststroke.
I prefer to swim (the) front crawl stroke.

If the sentences don't sound natural at all, how would a native English speaker say them?


text:
Q: Automate database creation with incremental name? I am trying to think through a script that I need to create. I am most likely going to be using php unless there would be a better language to do this with e.g. python or ror. I only know a little bit of php so this will definitely be a learning experience for me and starting fresh with a different language wouldn't be a problem if it would help in the long run.
What I am wanting to do is create a website where people can sign up for WordPress hosting. Right now I have the site set up with WHMCS. If I just leave it how it is I will have manually go in and install WordPress every time a customer signs up. I would like an automated solution that creates a database and installs WordPress as soon as the customer signs up. With WHMCS I can run a script as soon as a customer signs up and so far I understand how to create a database, download WordPress, and install WordPress. The only thing is I can't figure out how to make it work with more than one customer because with each customer there will be a new database. What I need the script to do is when customer A signs up,  the script will create a database name "customer_A" (that name is just an example) and when, lets say my second customer signs up, the script will create a database named "customer_B".
Is there a possible solution to this?
Thanks for the help

A: I did this yesterday.
my process was to add a row to a master accounts table, get the auto inc id, use that along with the company name to create the db name. so in my case the db's are
Root_1companyname1
Root_2companyname2
..
Root_ is optional of course.
Ask if you have any questions.


text:
Q: Credentials method failing on laravel I am trying to make a switcher in my website (made in laravel), i have solved a lot of problems and at now, i am getting error at the function
protected function credentials(Request $request)
    {
        return $request->only('email');

    }

My paths are like: localhost/es/password/email
I attach the code, thank you.
email.blade.php
@extends('layouts.app')

@section('content')

{{ __('Reset Password') }}

                    @if (session('status'))

                            {{ session('status') }}

                    @endif

                    <form method="POST" action="{{ route( 'password.email', app()->getLocale()) }}">
                        @csrf

                            {{ __('E-Mail Address') }}

                                <input id="email" type="email" class="form-control @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}" required autocomplete="email" autofocus>

                                @error('email')

                                        {{ $message }}

                                @enderror

                                <button type="submit" class="btn btn-primary">
                                    {{ __('Send Password Reset Link') }}
                                </button>

                    </form>

@endsection

web.php
Route::redirect('/', '/en');

Route::group(['prefix' => '{language}',
            'where' => ['language' => '[a-zA-Z]{2}']],
             function(){
    Route::get('/', 'HomeController@index')->name('home');
    Route::get('/home', 'HomeController@index')->name('home');

    Auth::routes(['verify' => true]);

    Route::get('/projects', 'projectsController@create')->name('projects');
    Route::post('/createProject', 'projectsController@store');
    Route::post('/modifyProject/{id}', 'projectsController@update');
    Route::get('/projects/{id}/delete', 'projectsController@destroy');

    Auth::routes();
    Route::get('/logout', '\App\Http\Controllers\Auth\LoginController@logout');

});

If you need something more of my app, say to this post and i will paste into in.
Regards

A: I have seemed that if i change the credentials functions to:
 protected function credentials(Request $request)
    {
        //dd($request);
        return $request->only('email', '#defaultLocale');
    }

the response of
  $response = $this->broker()->sendResetLink(
            $this->credentials($request)
        );

is passwords.throttle, and should be passwords.sent


text:
Q: Как на heroku выдать права доступа к файлу Node.js? Приложение Node.js загружаю на heroku. Запускаю приложение (heroku open) и получаю ошибку:
MyApp@0.0.0 start /app
app/fileNode.js
npm ERR! Linux 3.13.0-112-generic
sh: 1: app/fileNode.js: Permission denied

Загружаю и запускаю как описано в инструкции.
https://devcenter.heroku.com/articles/getting-started-with-nodejs
Из папки локального репозитория гит: git push heroku master
И затем запускаю: heroku open

A: Надо было создать Procfile. В этом и была проблема


text:
Q: Problem by merging columns in the table's heading I am trying to create two tables: one with two columns and the other one with three columns, in both cases the first row should be one cell merged over all columns. Besides, the content of this first cell is spanning over more than one line. Here is my solution at the moment, but it works only for a fixed column number:
\documentclass{scrreprt}

\usepackage{booktabs}

\usepackage{tabularx}
\newcolumntype{b}{X} %type big
\newcolumntype{s}{>{\hsize=0.99\hsize}X} %type small. Above 1 does not make any difference
\newcommand{\heading}[1]{\multicolumn{2}{p{\textwidth}}{#1}} %For the cases where I am main author
%\newcommand{\heading}[1]{\multicolumn{3}{p{\textwidth}}{#1}} %For the cases where I am not main author

\usepackage[table,xcdraw]{xcolor}
\renewcommand{\arraystretch}{1.2} %(or 1.3). based on the advice in https://www.inf.ethz.ch/personal/markusp/teaching/guides/guide-tables.pdf

\usepackage{csquotes}

\usepackage{siunitx}
\sisetup{detect-all}

\usepackage{pifont}
\newcommand{\xmark}{\ding{55}}

\begin{document}
This is my template for tables: documentation of authorship for the cumulative thesis.
\begin{table}[h!]
\centering
%\caption{My caption}
%\label{my-label}
\begin{tabularx}{\textwidth}{bs}
\toprule %requires the booktabs package.
%\multicolumn{2}{p{\textwidth}}{[ref] M. Name and L. Author, \enquote{Long title of a nice article reporting cool but complicated research}, \textit{Fancy journal} \textbf{2016}, \textit{13}, 001--007}  \\
\heading{[ref] M. Name and L. Author, \enquote{Long title of a nice article     reporting cool but complicated research} \textbf{2016}, \textit{13}, 001--007}\\
\midrule
Author                          & M. Name \\
\midrule %requires the booktabs package
Development of the concept      & \xmark   \\
\rowcolor[HTML]{C0C0C0}
Preparation of the figures      & \xmark  \\
Preparation of the manuscript   & \xmark  \\ %\cmark \xmark require the pifont package and newcommand thing: http://tex.stackexchange.com/questions/42619/x-mark-to-match-checkmark
\rowcolor[HTML]{C0C0C0}
Correction of the manuscript    & \xmark   \\
\midrule
Proposed publication equivalent & \num{1}  \\
\bottomrule
\end{tabularx}
\end{table}

\end{document}

for the case with two columns and:
\documentclass{scrreprt}

\usepackage{booktabs}

\usepackage{tabularx}
\newcolumntype{b}{X} %type big
\newcolumntype{s}{>{\hsize=0.99\hsize}X} %type small. Above 1 does not make any difference
%\newcommand{\heading}[1]{\multicolumn{2}{p{\textwidth}}{#1}} %For the cases where I am main author
\newcommand{\heading}[1]{\multicolumn{3}{p{\textwidth}}{#1}} % For the cases where I am not main author

\usepackage[table,xcdraw]{xcolor}
\renewcommand{\arraystretch}{1.2} %(or 1.3). based on the advice in https://www.inf.ethz.ch/personal/markusp/teaching/guides/guide-tables.pdf

\usepackage{csquotes}

\usepackage{siunitx} %possible package for units
\sisetup{detect-all}

\usepackage{pifont}
\newcommand{\xmark}{\ding{55}}

\begin{document}

This is my template for tables: documentation of authorship for the cumulative thesis.

\begin{table}[h!]
\centering
%\caption{My caption}
%\label{my-label}
\begin{tabularx}{\textwidth}{bss}
\toprule
%\multicolumn{3}{p{\textwidth}}{[ref] F. Author, M. Name and L. Author,         \enquote{Long title of a nice article reporting cool but complicated research}, \textit{Fancy journal} \textbf{2016}, \textit{13}, 001--007}  \\
\heading{[ref] F. Author, M. Name and L. Author, \enquote{Long title of a nice article reporting cool but complicated research}, \textit{Fancy journal}     \textbf{2016}, \textit{13}, 001--007}\\
\midrule
Author                          & F. Author & M. Name \\
\midrule
Development of the concept      & \xmark  & \\
\rowcolor[HTML]{C0C0C0}
Programmation of the algorithm  & \xmark & \xmark  \\
Data acquisition                & \xmark &  \\
\rowcolor[HTML]{C0C0C0}
Data analysis                   & \xmark & \xmark \\
Preparation of the manuscript   & \xmark & \\ %\cmark \xmark require the pifont package and newcommand thing: http://tex.stackexchange.com/questions/42619/x-mark-to-match-checkmark
\rowcolor[HTML]{C0C0C0}
Correction of the manuscript    & \xmark  & \xmark  \\
\midrule
Proposed publication equivalent & \num{1} & \num{0,5} \\
\bottomrule
\end{tabularx}
\end{table}

\end{document}

for the case with three columns.
Does anybody know how to programm this heading command so that it works for any column number?
Also, I have other minor aesthetic problems: the content of the table is spreading out on the right side, especially the grey lines are very obvious but also the title is too wide. Is there a way to fix this?
Does anybody understand why the point between first name and last name is visible in the heading but not in the first row (like M. Name and M Name)?
Finally I am not yet satisfied with the fixed cell width solution here, the columns end up too much on the right, maybe somebody has a suggestion how to make it prettier?
I would be super grateful for help, comments, suggestions!

A: I'm not sure what caused the periods to disappear, as I am not that familiar will all the packages being used.  Whatever the cause, using c instead of s fixed it.
\documentclass{scrreprt}

\usepackage{booktabs}

\usepackage{tabularx}
\newcolumntype{b}{X} %type big
%\newcolumntype{s}{>{\hsize=0.99\hsize}X} %type small. Above 1 does not make any difference
%\newcommand{\heading}[1]{\multicolumn{2}{p{\textwidth}}{#1}} %For the cases where I am main author
\newcommand{\heading}[1]{\multicolumn{3}{p{\dimexpr\textwidth-2\tabcolsep}}{#1}} % For the cases where I am not main author

\usepackage[table,xcdraw]{xcolor}
\renewcommand{\arraystretch}{1.2} %(or 1.3). based on the advice in https://www.inf.ethz.ch/personal/markusp/teaching/guides/guide-tables.pdf

\usepackage{csquotes}

\usepackage{siunitx} %possible package for units
\sisetup{detect-all}

\usepackage{pifont}
\newcommand{\xmark}{\ding{55}}

\begin{document}

This is my template for tables: documentation of authorship for the cumulative thesis.

\begin{table}[h!]
\centering
%\caption{My caption}
%\label{my-label}
\begin{tabularx}{\textwidth}{bcc}
\toprule
%\multicolumn{3}{p{\textwidth}}{[ref] F. Author, M. Name and L. Author,         \enquote{Long title of a nice article reporting cool but complicated research}, \textit{Fancy journal} \textbf{2016}, \textit{13}, 001--007}  \\
\heading{[ref] F. Author, M. Name and L. Author, \enquote{Long title of a nice article reporting cool but complicated research}, \textit{Fancy journal}     \textbf{2016}, \textit{13}, 001--007}\\
\midrule
Author                          & F. Author & M. Name \\
\midrule
Development of the concept      & \xmark  & \\
\rowcolor[HTML]{C0C0C0}
Programmation of the algorithm  & \xmark & \xmark  \\
Data acquisition                & \xmark &  \\
\rowcolor[HTML]{C0C0C0}
Data analysis                   & \xmark & \xmark \\
Preparation of the manuscript   & \xmark & \\ %\cmark \xmark require the pifont package and newcommand thing: http://tex.stackexchange.com/questions/42619/x-mark-to-match-checkmark
\rowcolor[HTML]{C0C0C0}
Correction of the manuscript    & \xmark  & \xmark  \\
\midrule
Proposed publication equivalent & \num{1} & \num{0,5} \\
\bottomrule
\end{tabularx}
\end{table}

\end{document}


text:
Q: Putting txt File Into Array is Starting at 12th Element I'm writing a program in C, in which I am reading the data from a .txt file, and my goal is to put each element from the .txt file into an array. When I compile and run the program, the values of 50, 55, and 0 are returned. These are the ASCII values (I'm not sure why the elements are being stored as ASCII codes, but that's okay for now) for 2, 7, and 0 (meaning nothing was initialized since we reached the end of the .txt file. Why is my program not reading the .txt file from the beginning??
...
int main(int argc, char *argv[]){
FILE *inputFile;
char *input = argv[1];
char magicSquareArray[257];

inputFile = fopen(input, "r");

if (inputFile == 0){
    printf("Cannot open file for reading!\n");
    return -1;
}

fscanf(inputFile, "%s", magicSquareArray);
while (!feof(inputFile)){
    fscanf(inputFile, "%s", magicSquareArray);
}

printf("%i\n", magicSquareArray[0]);
int sideSize = magicSquareArray[0];
int squareSize = sideSize * sideSize;
printf("%i\n", squareSize);

fclose(inputFile);

The text file:
3
4,3,8
9,5,1
2,7,6

A: Perhaps you want the code such as the following.
(However, I think in the following manner.
To prepare an array read the first number,
To assign a numerical value to read into it.)
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]){
    FILE *inputFile;
    char *input = argv[1];
    char magicSquareArray[257];
    int ch, len;
    inputFile = fopen(input, "r");

    if (inputFile == 0){
        printf("Cannot open file for reading!\n");
        return -1;
    }
    len = 0;
    while((ch = fgetc(inputFile)) != EOF && len < sizeof(magicSquareArray)-1){
        magicSquareArray[len++] = ch;
    }
    magicSquareArray[len] = 0;
    fclose(inputFile);

    printf("%c\n", magicSquareArray[0]);
    int sideSize = atoi(magicSquareArray);
    int squareSize = sideSize * sideSize;
    printf("%i\n", squareSize);

    return 0;
}


text:
Q: What data does InactivityMonitor of ActiveMQ see for checking connection availability? I met the following exception yesterday.

org.apache.activemq.transport.InactivityIOException: Channel was
inactive for too (>30000) long: tcp://127.0.0.1......

The exception was thrown while a queue session's commit method was being performed. I found out when the exception is thrown on the official website of activeMQ. It says:

Connections are monitored by:

*

*Ensuring data is read from the connection during the specified time period (Max Inactivity Duration).

*Writing a KeepAliveInfo message to
the connection if no normal activemq traffic is sent across the
connection during the specified time period.

and

Using the default values; if no data has been written or read from the
connection for 30 seconds, the InactivityMonitor kicks in. The
InactivityMonitor throws an InactivityIOException and shuts down the
transport associated with the connection.

I understand what it says, I think. But I don't get what data is needed to be sent for InactivityIOException not to be thrown. I think the data does not mean normal queue massages.
What is the data exactly?
And in addtion, what does the following words mean??

*

*KeepAliveInfo message

*normal activemq traffic

Thanks in advance.

A: The data on the wire is any bytes traveling back and forth from client to broker.  The inactivity monitor tracks how long it's been since the last time some bytes have been sent or received, this can be any data, as it implies that the connection is not in a half closed state or the remote is hung etc.
Normally the regular flow of messages either to or from the broker will suffice to keep the connection active but when things get quiet the inactivity monitor starts to send KeepAliveInfo packets to the broker and the broker will respond in kind, this acts as a PING and PONG to ensure that the socket connection is still alive and well.
In your case it seems the client could not get any data back from the broker and it decided that the connection or broker must be faulty.  You'd need to investigate the logs of both broker and client to try and see what was happening around the time this happened.


text:
Q: .htaccess ignore certain directories but pass subdomain existing .htaccess file
RewriteEngine on
RewriteBase /

# if not https, redirect
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# parse the subdomain as a variable we can access
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{HTTP_HOST} !^app
RewriteCond %{HTTP_HOST} ^([^\.]+)\.([^\.]+)\.([^\.]+)$
RewriteRule ^(.*)$ /$1?sub=%1

# ignore any .cfm|.html|.asp|.ico files and certain directories
RewriteRule ^(php|images|css|js|xyz|(.*)\.php|(.*)\.html|(.*)\.asp|(.*)\.ico)($|/) - [L]

# map all requests to the 'path' get variable in index.cfm
RewriteRule ^index\.php$ - [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?path=$1 [L,QSA]

=======
currently its doing this:

https://hello.domain.com --> https://hello.domain.com/index.php?sub=hello
https://hello.domain.com/dir1/15 --> https://hello.domain.com/index.php?path=dir1/15&sub=hello
https://hello.domain.com/index.php --> https://hello.domain.com/index.php
https://hello.domain.com/images/logo.png --> https://hello.domain.com/images/logo.png

what needs to happen:

1. https://hello.domain.com/index.php --> https://hello.domain.com/index.php?sub=hello

(currently sub=hello is not being appended)
2. https://hello.domain.com/process/generate.php --> https://hello.domain.com/process/generate.php?sub=hello

("/process" directory needs to be ignored, but "sub=hello" still needs to be passed)
Basically all i need some additions to the rules to make sure #1 & #2 are also working. No changes of existing rules should happen.
Thanks in advance!

A: Your full .htaccess:
RewriteEngine on
RewriteBase /

# if not https, redirect
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# ignore any .cfm|.html|.asp|.ico files and certain directories
RewriteRule ^(php|images|css|js|xyz|(.*)\.html|(.*)\.asp|(.*)\.ico)($|/) - [L]

# parse the subdomain as a variable we can access
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{HTTP_HOST} !^app
RewriteCond %{HTTP_HOST} ^([^.]+)\.[^.]+\.[^.]+$
RewriteRule ^(.*)$ index.php?sub=%1&path=$1 [L,QSA]

%{ENV:REDIRECT_STATUS} is an internal variable that is set to 200 after first internal rewrite.


text: Q: Is there any relationship between the (orthonormal) eigenvectors of $X^TX$ and $XX^T$? Specifically, suppose $X$ is an $n \times p$ matrix such that $v_1, \ldots, v_p$ are orthonormal eigenvectors (w/ associated eigenvalues $\lambda_1, \ldots, \lambda_p$) of $X^TX$. Can any assumptions be made about the eigenvectors or eigenvalues of $XX^T$?


text:
Q: Why is #+ used for multiline comments in the Advanced Bash-Scripting Guide I noticed in the Advanced Bash-Scripting Guide, that multiline comments are denoted as #+ rather than simply #. E.g. here.
(there is also a #% used in that particular example, denoting something like a bullet list(?), but this is literally the only location in the document where this is used, whereas the #+ syntax is used extensively)
I was wondering if this is some sort of convention, or if there is a particular reason for it other than the fact it just looks nice.
I note that it specifically seems to denote lines that are meant to be a continuation on a single line, rather than multi-line comments in general, so I'm wondering if it was simply done internally for parsing / documentation generation.
Has anyone else encountered this out in the wild before? Does anyone actually use this style?


text:
Q: xcode programming, which folder I should put my .xib file in? I forgot how to link my .xib file to my xcode project, been busy, forgot lots of things.
I appreciate the quick answers, that will save my jumping into apple docs.

A: .xib files are usually put in the Resources folder, although it doesn't matter too much.


text:
Q: Please assist me to escalate this issue Please assist me to escalate this issue
Is the above sentence correct?
or
Should I use 'in' or 'on' or 'with' in place of 'to'?

A: "in escalating" is better.
Or: "help me escalate".