text:
Q: How do I connect to my lan devices remotely using openvpn? I have a linksys WRT32000ACM router which connects several devices on my LAN each running different services.  I would like to remotely connect to this network and access the services on those devices.  Since the default firmware on the router has OpenVPN installed, I figured that would be the easiest option.  If I enable OpenVPN, add a user, and download the generated .ovpn file.  I can connect a remote device (say an android phone with wifi off, running OpenVPN connect) to my router, but I cannot view any other devices on the network.
My remote device has an IP address of 172.19.13.2, when connected to the VPN, and can view the router's web ui at 172.19.13.1 but no other devices.  If I connect the other devices still on my LAN to OpenVPN the same way, then they will get the IP addresses 172.19.13.3, 172.19.13.4, 172.19.13.5, etc. but cannot see each other at those IP address. Also my remote device still cannot see them.
Do I need to make some changes to the generated .ovpn file before connecting a client?  I'm afraid that the changes I need to make are server side not client side, and Linksys doesn't provide many options to configure the server. I need to somehow specify at what address my LAN devices will appear on my remote openvpn client device. It won't be 172.19.13.* because they shouldn't need to be connected to the VPN and they won't be 192.168.1.*.
Below is a a sample of the .ovpn file I'm using.  Hopefully I just need to change something here:
client
dev tun
proto udp
remote <MY-IP-ADDRESS> 1194
tun-mtu 6000
# fragment 0 can be used to improve performance in some instances but
# breaks compatibility with some Android apps
# fragment 0
mssfix 0
resolv-retry infinite
nobind
persist-key
persist-tun
ns-cert-type server
auth-user-pass
verb 3
<ca>...</ca>
<cert>...</cert>
<key>...</key>


text:
Q: Google analytic for multiple pages having the same base URL The current method/code which I use for tracking my pages displays just one details in Google search.
I was wondering if there is any special method to display the results in the following manner? {Multiple links under one common name}

How can I do that? Is it possible?or this happens automatically depending upon the visits by the audience?
I searched in many blogs/tutorials but was unable to find an answer.

A: Yes you can do that. You should use Google Webmaster Tools: https://www.google.com/webmasters/tools/
Just register to google, add your domain to webmaster tools. Login and go to Configuration/Sitelinks.
"Sitelinks are automatically generated links that may appear under your site's search results.  If you don't want a page to appear as a sitelink, you can demote it. Only site owners and users with full permissions can demote sitelinks."

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to send data between Java and PHP (synchronously) I use PHP to generate the front-end, rendering the HTML, running some SQL queries on the database, etc. The SQL queries are becoming slower and slower and the only way to improve them is to make requests non-stateless. Currently, request causes some query to fetch data and return it via JSON to the client, but the improved query (no group by, barely any joins and sorting) would need to hold an object with the results of the previous requests: objects returned, their order, some of their attributes. Knowing what the previously returned objects were, any requests after that can be handled much faster and queries would become much simpler.
The question is: what is the most reliable way of running a Java service, which accepts the request from PHP and returns the results (JSON) synchronously, so that PHP can immediately parse the data and render the page? Would I be safe using JSON REST API over HTTP(S)? Should I look towards sockets? Could I create persistent connections from PHP without having to make a separate module in C?
P.S. The requests will happen between front-end server and Java server. They can be on the same machine or separate machines. Request might need to be load balanced in the future over a Java cluster.


text:
Q: realloc(): invalid next size: followed by a 32bit register so I've been writing an mtf encoder in C and I've been running into a realloc() error regardless of what I do. I've checked to see if there was an error in my logic (and there may be) by using print statements to see if I'm overstepping the bounds of my currently malloc'd array (adding a string past my original array size) and that doesn't seem to be the issue. I've used GDB and Valgrind and GDB gives me a cryptic message while Valgrind runs into a segmentation fault. This is my first time using dynamic memory and I'm pretty confused as to what the problem is, below are my code along with the GDB error:
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int count = 0;

move_to_front(int index, char** words){
    int i;
    char *t = words[index];

    for(i = index; i>1; i--){
       words[i] = words[i-1];
    }

    words[1] = t;

}

char** reallocate_words(char** words, int* words_size_pointer){
   printf("We're entering here\n");
   printf("%d", *words_size_pointer);
   int temp = *words_size_pointer;
   char** tempor;
   temp = temp*2;
   printf("%d", temp);
   tempor = (char**) realloc(words, temp);
   int i = *words_size_pointer;
   for(i; i<temp; i++){
       tempor[i] = (char*) malloc(120);
    }
   words_size_pointer = &temp;
   return tempor;

 }

void encode_word(int* words_size_pointer, FILE *f, char* word, char** words){
    if(count == 0){
        words[1] = word;
        fputs(words[1], f);
        count++;
    }
    int i;
    for(i=0; i<=count; i++){
        if(strcmp(words[i], word) == 0){
            break;
        }
    }
    if(i>=(*words_size_pointer)){
        printf("%d\n", i);
        words = reallocate_words(words, words_size_pointer);
        words[count+1] = word;
        count++;
        fputc(count+128, f);
        fputs(words[count], f);
        move_to_front(count, words);
    }
    if(i>count){
        words[count+1] = word;
        count++;
        fputc(count+128, f);
        fputs(words[count], f);
        move_to_front(count, words);
    }
    else{
        fputc(i+128, f);
        move_to_front(i, words);
    }

}

void sep_words(char** words, char *line, int* words_size_pointer, FILE *f){
    char* x;
    int i = 0;
    x = strtok(line, " ");
    while(x != NULL){
        encode_word(words_size_pointer,f, x, words);
        x = strtok(NULL, " ");
    }
}

void readline(FILE *f_two, FILE *f, char** words, int* words_size_pointer){
    char *line;
    size_t len = 0;
    ssize_t temp;
    int count;
    do{
    temp = getline(&line,&len,f);
    printf("%s", line);
    if(temp!= -1){
        sep_words(words, line, words_size_pointer, f_two);

    }
    }while(temp!=-1);

}

int main(int argc, char *argv[]){
    int x;
    int i;
    int j;
    x = strlen(argv[1]);
    char fi[x];
    char mtf[3] = "mtf";
    FILE *f;
    FILE *f_two;
    for(j = 0; j<(x-3); j++){
       fi[j] = argv[1][j];
    }
    strcat(fi, mtf);
    f = fopen(argv[1], "r");
    f_two = fopen(fi, "w");
    fputc(0xFA, f_two);
    fputc(0XCE, f_two);
    fputc(0XFA, f_two);
    fputc(0XDF, f_two);
    if(f == NULL){
        return 1;
    }

    char** words;
    words = (char **) malloc(20);
    for(i = 0; i<20; i++){
        words[i] = (char*) malloc(120);
    }
    int words_size = 20;
    int* words_size_pointer = &words_size;

    readline(f_two, f, words, words_size_pointer);
    return 0;
}

And as for the GDB error:
    *** Error in `/file_loc/mtfcoding2': realloc(): invalid next size: 0x0000000000603490 ***
2040 \\This is due to print statements within my function.
Program received signal SIGABRT, Aborted.
0x00007ffff7a4acc9 in __GI_raise (sig=sig@entry=6)
    at ../nptl/sysdeps/unix/sysv/linux/raise.c:56
56  ../nptl/sysdeps/unix/sysv/linux/raise.c: No such file or directory.

Thank you for your time! :)

A: malloc and realloc require the number of bytes as argument. However you are writing code like:
char** words;
words = (char **) malloc(20);
for(i = 0; i<20; i++){
    words[i] = (char*) malloc(120);

You allocate 20 bytes but then you write 20 pointers (which probably takes 80 bytes).  To fix this you need to compute how many bytes are required to store the 20 pointers. A safe way of doing this is to use malloc as recommended by SO:
words = malloc(20 * sizeof *words);

You have the same problem in your realloc call.

This line has no effect: words_size_pointer = &temp; . Perhaps you meant *words_size_pointer = temp; . Make sure you clearly understand the difference between those two lines.
NB. There may be other errors.

A: Well, for starters, your move_to_front is dropping pointers. This one is a pretty bad memory leak, and given the nature of C and memory leaks, could be the cause of your segfault (for now). You should be doing this
for(i = index; i > 1; i--){
    char* tmp = words[i];
    words[i] = words[i-1];
    words[i-1] = tmp;
}

Otherwise, what you have done is overwritten the pointers from index to words[2] with the pointer at index. Also, you seem to like to start your words array at 1 instead of 0. Those off-by-one errors are gonna hurt ya too.
Also (as stated in my earlier comment), words_size_pointer = &temp; isn't quite right. Do this instead *words_size_pointer = temp;. The first way is only a local pointer re-assignment, but you want the change to be reflected in the caller's scope, so you must dereference the pointer and modify it.

A: It seems to be caused by your call to getline in your readline function.
char *line;
size_t len = 0;
...
temp = getline(&line,&len,f);

getline requires line to be NULL (in which case the value of len is ignored) or line must be a pointer returned by malloc, calloc, or realloc. If line is not NULL, and len isn't large enough, line is resized by calling realloc.  This is the crucial point: line points to some random address that wasn't returned by malloc, so getline attempts to use realloc to increase the buffer size because 0 bytes is just too small.
You also have a buffer overflow here:
char mtf[3] = "mtf";
...
for(j = 0; j<(x-3); j++){
   fi[j] = argv[1][j];
}
strcat(fi, mtf);

Because you made mtf only 3 bytes in size, it may or may not be followed immediately by a null terminator. When strcat is called, if mtf isn't followed immediately by a 0 byte in memory, you end up with something like sample.mtf\x1b\x01X as the output filename, assuming you don't write too far beyond the end of the fi array to crash the program with a SIGSEGV (segfault).  Any of the following will correct it:
char mtf[4] = "mtf";
//OR
char mtf[] = "mtf";
//OR
const char *mtf = "mtf";

However, because fi is only made up of x number of bytes, you'll end up writing to fi[x] with your null terminator that strcat adds.  This is a problem because char fi[x]; means you only have array indices 0 to x - 1 available.  Fix this part by using x = strlen(argv[1]) + 1.


text:
Q: Laravel spatie medialibrary upload not works with suPHP on server I have followed this instruction to enable users to upload avatar image.
It works perfectly on local. But when I uploaded code to server it does not work.
When I made public folder permission to 777, I get a 500 error.
How can I fix this?


text:
Q: php mailer not working with attachment in my php page i am sending mail from form. it's sending well but not sending with attachment. here's the code...
<form action="career.php" method="POST" class="form-horizontal companyInquiry">

                        <?php
                            if(isset($_SESSION['error'])) {
                                echo "
";
                                    foreach ($_SESSION['error'] as $err) echo "
$err
";
                                echo "
";
                                unset($_SESSION['error']);
                            }
                            if(isset($_SESSION['message'])) {
                                echo "

".$_SESSION['message']."

";
                                unset($_SESSION['message']);
                            }
                        ?>

                            We Have Current Openings For.

                            Experienced Graphics designer(2 to 3 year).

                            Experienced PHP developer(2 to 3 year).

                            Interested Candidate, Please fill below form with fresh resume.

                            Full Name

                                <input type="text" name="fullName" id="fullName" class="form-control" placeholder="Enter Your Full Name" value="<?php if(isset($_SESSION['values'])) echo $_SESSION['values']['fullName'];?>" />

                            Email

                                <input type="text" name="userEmail" id="userEmail" class="form-control" placeholder="Enter Your Email" value="<?php if(isset($_SESSION['values'])) echo $_SESSION['values']['userEmail'];?>" />

                            Contact No

                                <input type="text" name="userContact" id="userContact" class="form-control" placeholder="Enter Your Contact Number" value="<?php if(isset($_SESSION['values'])) echo $_SESSION['values']['userContact'];?>" />

                            Applied For

                                <select name="app_for" id="app_for">
                                    <option value="Graphics designer">Graphics designer</option>
                                    <option value="PHP developer">PHP developer</option>
                                </select>

                            About You

                                <textarea name="you" id="you" class="form-control" placeholder="Enter About You" style="border-radius:0"></textarea>

                            Your CV

                                <input type="file" name="cv" id="cv">

                                    Only .xls,.xlsx,.pdf and .PDF extentions are allowed.

                                <button type="submit" class="btn btn-default" name="send">Send</button>

                        <input type="hidden" name="company" value="<?php echo $_GET['com_id']; ?>" />
                    </form>

and my career.php file is.
<?php include_once("../../init.php");
date_default_timezone_set('Asia/Calcutta');
if($_SERVER['REQUEST_METHOD'] === 'POST') {
    require_once(CONNECT);
    require_once('../../public/includes/mailer/config/class.phpmailer.php');
    $inc = -1;
    if($_POST['fullName'] == '') {
        $inc++;$_SESSION['error'][$inc] = "FULL NAME IS REQUIRED";
    }
    if($_POST['userEmail'] == '') {
        $inc++;$_SESSION['error'][$inc] = "EMAIL IS REQUIRED";
    }
    if($_POST['userContact'] == '') {
        $inc++;$_SESSION['error'][$inc] = "CONTACT NO IS REQUIRED";
    }
    if($_POST['userEmail'] != '' && $_POST['userEmail'] != null) {
        if(!filter_var($_POST['userEmail'], FILTER_VALIDATE_EMAIL)) {
            $inc++;$_SESSION['error'][$inc] = "INVALID EMAIL";
        }
    }
    function inputs() {
        $_SESSION['values']['fullName'] = $_POST['fullName'];
        $_SESSION['values']['userEmail'] = $_POST['userEmail'];
        $_SESSION['values']['userContact'] = $_POST['userContact'];
        $_SESSION['values']['userMessage'] = $_POST['userMessage'];
        header("location:".SLASHES."career/");
    }
    if($inc > -1) inputs();
    else {
        $date = date('Y-m-d H:i:s');
        $mailBody =
            "message";
        $mail = new PHPMailer;
        $mail->isSMTP();
        $mail->Host = 'grimlock.secure-dns.net';
        $mail->SMTPAuth = true;
        $mail->Username = 'username';
        $mail->Password = 'password';
        $mail->SMTPSecure = 'tls';
        $mail->Port = 587;
        $mail->setFrom('jesadiyadivyesh@gmail.com', 'test');
        $mail->addReplyTo('jesadiyadivyesh@gmail.com', 'test');
        $mail->addAddress('jesadiyadivyesh@gmail.com', 'test');
        if($_FILES["cv"]["name"]) $mail->AddAttachment($_FILES["cv"]["tmp_name"],$_FILES["cv"]["name"]);
        $mail->WordWrap = 50;
        $mail->isHTML(true);
        $mail->Subject = "test";
        $mail->Body = $mailBody;
        $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
        if(!$mail->send()) {
            $_SESSION['error'][0] = "error in sending your data";
        }
        else{
            $_SESSION['message'] = "your data send successfully";
        }
        header("location:".SLASHES."career/");
    }
} else header("location:".SLASHES."career/");

?>

A: You don't set an attachment header (enctype).
Add to your form tag:
enctype="multipart/form-data"

And it should be like:
<form action="career.php" method="POST" enctype="multipart/form-data" class="form-horizontal companyInquiry">


text:
Q: How do I scrape data using ItemLoaders from a table using Scrapy? I am trying to extract data from the website "https://www.brickworkratings.com/CreditRatings.aspx". There is a table through which I can easily extract data through Scrapy Shell.
I wanted to use ItemLoaders as it is really powerful and gives a cleaner experience.
Here is my code below.
def start_requests(self):
    yield Request("https://www.brickworkratings.com/CreditRatings.aspx", self.parse_credit_rating_response)

def parse_credit_rating_response(self, response):
    table_rows = response.xpath('//*[@id="ContentPlaceHolder1_gvData"]//tr')
    for table_row in table_rows:
        loader = ItemLoader(SampleItem(), response=response)
        try:
            loader.get_xpath(table_row.xpath("td[1]//a/text()")[0].extract())
            # loader.add_value('company_name', 'test')
        except Exception as e:
            print(e)
        item = loader.load_item()
        print(item)
        yield item

I am getting the error,
"XPath error: Invalid expression in
                                                                        (Name of the Company)".

I believe my XPath is right but I don't think this is the way to use it. How do I use it correctly? I need to extract data from the table and wanted to use the more powerful ItemLoaders.
Any help will be appreciated, been stuck on it for a long time.

A: You need to specify the initial/parent selector when constructing the loader. It is then unnecessary to provide the response as well. And then you need to pass an XPath string to add_xpath instead of using get_xpath. Refer to the documentation.
Assuming your XPath is correct, here is an example:
# All added selectors will now be relative to table_row.
loader = ItemLoader(SampleItem(), selector=table_row)
# Just give it the XPath here.
loader.add_xpath("field_name", "td[1]//a/text()")

If you need to do additional processing, look at input/output processors.


text:
Q: Why is kernel mapped to the same address space as processes? This is a question to elaborate on this one: Why is kernel said to be in process address space?

This might be a silly question but it just popped up in my mind. All
  the text about process address space and virtual memory layout
  mentions that the process address space has space reserved for kernel.
  For e.g. on 32 bit systems the process address space is 4GB of which 1
  GB is reserved for kernel in Linux (Might be different on other OS).
I am just wondering why kernel is said to be in the process address
  space when a process cannot address the kernel directly. Why don't we
  say that the kernel has a separate address space than a process and
  why can't we have a different page table for kernel itself which is
  separate from the page tables of the processes?

Can I get an explanation with respect to Linux (Debian or Ubuntu) specific operating system?

A: Another important reason why we say kernel is in the process address space is that kernel can access the user code/data of the CURRENT process, i.e. the virtual address space 0~3G.
Sorry about my poor English. I am not a native English speaker.

A: Imagine what would happen if the kernel is not mapped in each process address space.It would
triple fault because say the timer interrupt occurs,then the processor calls the ISR routine
using IDT(Interrupt Descriptor Table).If the kernel is not mapped then the IDT address becomes
invalid and thus a triple fault will result.

A: To answer another part of the question - the kernel is mapped into every processes address space partially for efficiency/performance reasons (there are others too, I'm sure).
On most modern hardware, it is quicker to change the security level (thus allowing access to the pages that are otherwise protected, as mentioned in Alexey's answer) in order to perform system calls and other kernel provided functions than it is to change the security level and the entire virtual memory map, along with all the associated TLB cache flushes and everything else involved in a full context switch.
Since system calls can be fairly frequent events, the design that has evolved in Linux and many other places to try and minimize the overhead of utilizing kernel services, and mapping the kernel code and (at least some of the) data into each process is part of that.

A: A process "owns" the entire virtual address space here, the kernel and the user portions of it.
Its inability to peek and poke the kernel code and data is not due to different address spaces, it's due to different access rights/permissions set in the page tables. Kernel pages are set up in such a way that regular applications can't access them.
It is, however, customary to refer to the two parts of one whole thing as the kernel space and the user space and that can be confusing.


text:
Q: Check day of week and time I have been trying to figure out how to get between a day of week and time...I found this snippet of code:
function isBetween($from, $till, $input) {
 $f = DateTime::createFromFormat('!H:i', $from);
 $t = DateTime::createFromFormat('!H:i', $till);
 $i = DateTime::createFromFormat('!H:i', $input);
 if ($f > $t) $t->modify('+1 day');
 return ($f <= $i && $i <= $t) || ($f <= $i->modify('+1 day') && $i <= $t);
};

and I have managed to get it to check between two times and see if current matches using:
if (isBetween('22:30','02:00','23:00')){
 echo "true";
}

However I tried doing this
if (isBetween('22:30','02:00',date('H:i')){

but that just broke the site, I lack experience handling time and I basically want to check between 11pm monday to 2pm tuesday or 11pm monday to 5pm saturday and it has to do this check no matter what day of the year/month meaning I want it to be dynamic not static..
I've also tried:
if (date('H') < 14)

but it was very simplistic and I didn't know how to get something as complex as both date and hour+seconds

A: your missing 1 more closing )
if (isBetween('22:30','02:00',date('H:i'))){

You can just do like this:
function isBetween($from, $till, $input) {
 $f = date('H:i', strtotime($from));
 $fd= date('l', strtotime($from));
 $t = date('H:i', strtotime($till));
 $td= date('l', strtotime($till));
 $i = date('H:i', strtotime($input,'+8 hours'));
 $id= date('l', strtotime($input));
 $days = array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday');
 if(array_search($fd,$days)<array_search($id,$days) && array_search($td,$days)>array_search($id,$days)){
    return true;
 }elseif(array_search($fd,$days)==array_search($id,$days) && $f<$i){
    return true;
 }elseif(array_search($td,$days)==array_search($id,$days) && $t<$i){
    return true;
 }
 return false;
};

$from = 'Wednesday 12:00';
$till = 'Saturday 23:00';
$input = 'Friday 12:23';

if(isBetween($from,$till,$input)){
    echo "True";
}else{
    echo "not";
}

output = true;


text:
Q: get xml data from rss <rss version="2.0">
<channel>
<title>Report</title>
<link>...</link>
<description>Report</description>
<pubDate>Tue, 29 Oct 2013 23:57:00 +0800</pubDate>
<copyright>SMG-2009. All rights reserved.</copyright>
<image>...</image>
<item>
<title>Report</title>
<link>...</link>
<guid isPermaLink="false">http://Report</guid>
<description>
<![CDATA[
在 2013-10-30 00:00

 	 temperature:22

humidity:50%

Wind:South ; Speed: 12 km/hr

]]>
</description>
</item>
</channel>
</rss>

<?PHP
$weather = new DOMDocument();
          $weather -> load("abc.xml");
          $temp=$weather->getElementsByTagName('item')->item(0)->getElementsByTagName('description')->item(0)->childNodes->item(0)->nodeValue;
       //   $temp = iconv("UTF-8", "big5", $temp);

    $temp = explode("", $temp);

          $c = $temp[1];
          $h = $temp[2];

          echo $c . "----" . $h;

?>

//------------
Now What I want to retrieve is the $c for temperature and $h for humidity, but it fails, any advice on my code? Also the wind and speed as well.

A: Try:
$weather -> load("abc.xml");
$temp=$weather->getElementsByTagName('item')->item(0)->getElementsByTagName('description')->item(0)->nodeValue;

preg_match_all('/([^<]+)</', $temp, $matches);

$c = $matches[1][0];
$h = $matches[1][1];

echo $c . "----" . $h;


text:
Q: How to use multiple where conditions in Laravel Eloquent? This Query is working

    $conditions = [
        'status' => '1',
        'country' => "DK"
    ];
        $offers = Offers::where($conditions)->get();

How can i use LIKE %% in this
When i tried this in single condition , its working

      $offers = Offers::where('country' , 'LIKE' , '%DK%')->get();

A: Did you try this?
$conditions = [
    'status' => '1',
    'country' => "DK"
];
$offers = Offers::where('country' , 'LIKE' , '%DK%')->where($conditions)->get();

You can chain your where clauses as much as you want.

A: Actually you can use where multiple times so you can try something like:
$offers = Offers::where('country' , 'LIKE' , '%DK%')
    ->where('status', 1)
    ->get();

I didn't test this but you can try also like this: ( It might work but I'm note sure )
$conditions = [
    'status' => '1',
    'country' => "LIKE %DK%"
];
$offers = Offers::where($conditions)->get();


text:
Q: Not able to filter the model using the Ember.Select in Ember.js The use case is I am trying to filter the model using the Ember.Select, whenever the user clicks the button, the model gets filtered on the basis of the 'Designation' property.
Here's my Ember.Select:
{{view Ember.Select
       contentBinding="designations"
       optionValuePath="content.id"
       optionLabelPath="content.designation"
       selectionBinding="roles.selectedDesignation"}}
<button {{action 'filter'}}>Filter</button>

And Here's what I am doing in App.js,
App.TwodController = Ember.Controller.extend({
    filteredContent : Ember.computed.oneWay("content"),
    selectedDesignation : null,
    designations : [{
        designation : "Design",
        id : 1
    }, {
        designation : "Writer",
        id : 2
    }],
    actions : {
        filter : function() {
            var designation = this.get('roles.selectedDesignation');
            var filtered = this.get('content').filterProperty('designation', designation);
            this.set("filteredContent", filtered);
        }
    }
});

Here's the full JSBin, http://jsbin.com/iPUxuJU/2/edit
What I might be missing here?

A: You are missing something in selection binding
{{view Ember.Select
   contentBinding="designations"
   optionValuePath="content.id"
   optionLabelPath="content.designation"
   selectionBinding="selectedDesignation"}}
<button {{action 'filter'}}>Filter</button>

In controller logic:
App.TwodController = Ember.Controller.extend({
filteredContent : Ember.computed.oneWay("content"),
selectedDesignation : null,
designations : [{
    designation : "Design",
    id : 1
}, {
    designation : "Writer",
    id : 2
}],
actions : {
    filter : function() {
        var designation = this.get('selectedDesignation.designation');
        var filtered = this.get('content').filterProperty('designation', designation);
        this.set("filteredContent", filtered);
    }
}

});
Here is the working jsbin


text:
Q: Why i get java.lang.IllegalArgumentException: error at ::0 can't find referenced pointcut getLogging I get this exception on the title. I give some code following:
@Component("student")
public class Student {

    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void printSomething() {
//        get logging with aop
        System.out.println("student printed something");
//        get logging with aop
    }
}

@Aspect
@Component
public class StudentLogging {

    private final static Logger logger = Logger.getLogger(StudentLogging.class.getName());

    @Pointcut("execution(* aspectorientedprog.aopexample.Student.printSomething(..))")
    private void getLogging() {

    }

    @Around("getLogging()")
    public String aroundPrintSomething(ProceedingJoinPoint joinPoint) throws Throwable {
        logger.info("before printing something");
        Object o = joinPoint.proceed();
        logger.info("after printing something");
        return o.toString();
    }

}

public class AspectStudentTest {

    @Test
    public void aspect_student_test() {
        ApplicationContext context = new ClassPathXmlApplicationContext("aspect/aspect-conf.xml");
        Student student = context.getBean("student", Student.class);
        student.printSomething();
        System.out.println();
    }

}

my configuration file:
<context:annotation-config/>
<context:component-scan base-package="aspectorientedprog"/>
<aop:aspectj-autoproxy/>

I research something about this error, but all solutions are not worked, it was about AOP version. if i use only

@Around(execution("class"))

it is working truly but if i use the @Pointcut and @Around like above i got this problem...
thanks for your answers

A: Try with:
@Pointcut("execution(* aspectorientedprog.aopexample.Student.printSomething(..))")
    public void getLogging() {

    }


text:
Q: How to run db-migrate up on Dockerfile? When I run the following Dockerfile,in the middle of the process, after installing prisma, the RUN command db-migrate up is stopped. But when I used docker exec bin bash to run it, it worked without any problem. I don't think I can run the app before serving it. But there is a workaround like putting the migration commands as a service in docker-compose.yml. How to achieve it? or if there's any way to run those RUN commands of migration in this Dockerfile?

Dockerfile

FROM node:16.15.0-alpine

WORKDIR /app

COPY package*.json ./

# generated prisma files
COPY prisma ./prisma/

# COPY ENV variable
COPY .env ./

# COPY
COPY . .

RUN npm install

RUN npm install -g db-migrate

RUN npm install -g prisma

RUN db-migrate up

RUN prisma db pull

RUN prisma generate

EXPOSE 3000

CMD ["npm", "run", "dev"]

docker-compose.yml

version: '3.8'

services:
  mysqldb:
    image: mysql:5.7
    restart: unless-stopped
    env_file: ./.env
    environment:
      - MYSQL_ROOT_PASSWORD=$MYSQLDB_ROOT_PASSWORD
      - MYSQL_DATABASE=$MYSQLDB_DATABASE
    ports:
      - $MYSQLDB_LOCAL_PORT:$MYSQLDB_DOCKER_PORT
    volumes:
      - db:/var/lib/mysql
  auth:
    depends_on:
      - mysqldb
    build: ./auth
    restart: unless-stopped
    env_file: ./.env
    ports:
      - $NODE_LOCAL_PORT:$NODE_DOCKER_PORT
    environment:
      - DB_HOST=mysqldb
      - DB_USER=$MYSQLDB_USER
      - DB_PASSWORD=$MYSQLDB_ROOT_PASSWORD
      - DB_NAME=$MYSQLDB_DATABASE
      - DB_PORT=$MYSQLDB_DOCKER_PORT
    stdin_open: true
    tty: true

volumes:
  db:


text:
Q: OS X Application Keyboard Shortcuts I am making my first OS X application in Xcode, and I have no idea how to make a specified keyboard shortcut trigger some code (e.g. ⌘ Cmd+ C/⌘ Cmd+V). All I can find online is keyboard shortcuts in Xcode itself.
Thanks in advance

A: This is usually setup for you automatically. The MainMenu.xib by default has an Edit menu with these shortcuts bound, activating [firstResponder copy:] and [firstResponder paste:]. The first responder is item currently having keyboard focus, or it's parent view if it doesn't answer to those actions, up to the window at the top level.
For new shortcuts, Apple recommends that you have menu items associated to all those. If you do, you can set the shortcut in the interface builder using the attributes inspector. You then ctrl-drag from the menu item to the object you want to send the action to, e.g. the app delegate. You will have to create the target method first obviously. You should also use bindings to control when the menu item is enabled or not.
It's not recommended, but if you want to do this programmatically, without a menu item, you override the
- (BOOL)performKeyEquivalent:(NSEvent *)theEvent

method of the view or window in question. It will be called if it's in the responder chain when the key is pressed, and you return YES to indicate you've handled the event.


text:
Q: Save to a XML document using php problem Hey all. I'm trying to save A XML file using php. here is my code, the connection to the DB is okay and all, i can use $dom->saveXML() but the save function isn't saving nothing.
please help.
<?
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
  die ('Can\'t use db : ' . mysql_error());
}

// Select all the rows in the markers table

$query = "SELECT * FROM Listing_Arnona WHERE 1";
$result = mysql_query($query);
if (!$result) {
  die('Invalid query: ' . mysql_error());
}

// Iterate through the rows, adding XML nodes for each

while ($row = @mysql_fetch_assoc($result)){
  // ADD TO XML DOCUMENT NODE
  $node = $dom->createElement("marker");
  $newnode = $parnode->appendChild($node);
  $newnode->setAttribute("Price",$row['Price']);
  $newnode->setAttribute("PriceS", $row['Price']);
  $newnode->setAttribute("address", $row['street_name']);
  $newnode->setAttribute("NumRooms", $row['Room_Num']);
  $newnode->setAttribute("PROMO", $row['PROMO']);
}

$dom->formatOutput = true;
$test1 = $dom->saveXML(); // put string in test1
$dom->save('test1.xml'); // save as file

?>

A: The problem as everyone pointed out was the writing permissions. i opend a new folder name 'xml' with chmod 777 and changed the code to:
$dom->save('xml/test1.xml');

Thank you all.


text:
Q: Pass data into JQuery then HTML (multi-step) I am trying to allow a global function to be called and pass text into an alert box, which is set at the top of the page.
My code is:

And the message box is:

Help me!

I am not really sure how to do this..
I want to pass a type and a message. The class will be the type, and the message will do where the "Warning" goes.
So if I go somewhere in the page and go msg(warning, "help me!"); I want that to be translated like above.
Can you help? Thank you.

A: First of all, put an id attribute on the div so that it can be found easily. I will assume you are using alertbox as the id in the following function
Add the following to the end of the msg function:
var box=document.getElementById('alertbox');
box.setAttribute('class',type);
box.innerHTML=data;

It can probably be done shorter in jquery but I don't use jquery

A: function msg(type, data){
   var box=document.getElementById('alertbox');
    box.setAttribute('class',type);
    box.innerHTML=data;
    $('#alertbox').slideDown("slow").delay(1500).slideUp("slow");
}

Got it!


text:
Q: Can I use images such as from Tiananmen Square Protests to criticise the Chinese government on my profile page? Dear Stack Exchange Community,
As many of you know, for a long time I have been allowed to show images that criticise the Chinese government on my profile for several years, for which I'm thankful.
Furthermore, I believed that this had strong meta support in threads such as:

*

*User's political display name triggering government action against users who view it - what should I do?

*Are political avatars and profiles OK?
However, a recent interaction with the moderators has made me unsure about this, so I wanted to check what the community thinks.
Obviously, this is not meant to be a personal criticism of anyone, and I know mods have a lot of work on their plate already, and that this is a difficult subject, so I thought that it would be better to ask a larger audience.
Could you please give your opinion if the following should be allowed or not, supposing of course that they contain no gore, nudity, etc., the only shocking part being the political content:

*

*people imprisoned in Xinjiang concentration camps

*Tiananmen Square Protests

*Falun Gong (banned religion in China) and its persecution

*making fun of Chinese chairman Xi Jinping

*clearly labelled side-by-side comparisons between Nazi Germany and China, e.g.:

*

*prisoners in Xinjiang Concentration Camps and Nazi Concentration Camps

*Xi Jinping with the Young Pioneers of China and Hitler with Hitler Youth

*Chinese flag with stars replaced by Swastikas

If you believe all Nazi references should be banned but not anti-Chinese government ones, could you clarify the rationale, considering that all anti-Chinese government images are potentially offensive to some Chinese people, since they are censored in China?
Context
It started about a week ago. I had uploaded images of Nazi Germany next to images of the Chinese government to express my belief that the Chinese government is becoming more like the Nazi party, both of which I obviously disapprove of, as I think was clear from the context of the profile.
Quite simply, if all Nazi images are banned, even if to criticize the Nazis and other regimes, that's fine with me, just say that clearly "all images of Nazi Germany are banned regardless of context", and I'll promptly comply with the moderator instructions, as I always do.
The reason I'm writing this post, however, is that I don't feel that the moderators were able to give clear enough guidelines on what is allowed or not.
Without clearer guidelines, I really don't know if I can show anti-Chinese government images or not without being under constant risk of suspension, so I felt compelled to ask.
I was given a 7 days suspension, and below I summarize what I believe were the key points of the conversation.
The initial message from the mods was:

We note that you were previously contacted for part of your profile being offensive. It has been brought to our attention that a significant part of your profile is filled with shock pictures, nazi imagery and similar images.
We'd note that people do use this site at work, and while users have some freedom over the content of their profile, there are fairly obvious lines that shouldn't be crossed.
We do not recommend that you restore the content we removed - specifically the images without checking back with us.

to which I replied:

Could you clarify if the following types of images are OK or not:

*

*people imprisoned in Xinjiang concentration camps

*Tiananmen square protests

*making fun of Xi Jinping

*Falun Gong persecution

supposing that they show no explicit gore or violence?
All the above are considered highly shocking to many Chinese people, due in part to their strict censorship rules, and not suitable for the workplace in China.
I have been using such images for many years to criticize what I believe are terrible events in China, and the decision so far has been that I was allowed to use them.
The intent of the Nazi images is clearly to compare both regimes to criticize the Chinese Government, which I believe is following the same path as the Nazis (e.g. Concentration Camps in Xinjiang, no freedom of speech, etc.), to help prevent such abuses from happening again in the future.
I just want to clearly understand the rationale of of why anti-CCP images are OK, but anti-Nazi ones aren't, so I can follow your rules correctly and save everyone's time in the future by correctly deciding which images are OK or not.

to which they replied:

Could you clarify if the following types of images are OK or not:

Its not the 'topic' but rather the content.

I don't understand this. Are some images of Nazi Germany OK but others not? In that case, which are fine and which aren't? Can you give specific examples of fine vs not fine? What's the difference between "Nazi Germany content" and "Nazi Germany topic"?
And they further replied (emphasis mine):

I just want to clearly understand the rationale of of why anti-CCP images are OK, but anti-Nazi ones aren't, so I can follow your rules correctly and save everyone's time in the future by correctly deciding which images are OK or not.

We never said that. We gave specific examples of objectionable content. If you realise something isn't suitable - that it is something shocking, and not suitable for the workplace, as you seem to realise, it shouldn't be on your profile.

This is the key sentence that makes me understand that in their opinion all images censored by the Chinese government should not be posted.
Clearly, if a state censors a subject, it is de-facto illegal, and definitely not suitable for the workplace.
And any censored image is likely to be shocking to a part of the population, partly because the same state has made propaganda supporting this point of view, conditioning their people to think like that.
I then asked again for more specific guidelines, but there was no further reply after 7 days, so I felt it would be OK to bring this up here.
Thanks for your understanding.
Replies to selected comments about the validity of this question

You are preasking your closed question in the guise of a opinion based discussion

I believe the questions are not duplicates because each one is asking if a different specific thing is allowed or not, and I do not find it clear that one implies the other or not.
That question has top answer stating "it does not matter who the person is, including the president", Does the Be Nice policy require SE users to "be nice" to people who are not SE users (e.g. public figures)? which is a clear guideline I can understand and follow, even if I don't agree with it, so kudos for that answer.
But I don't see how that makes it clear if I can show Tiananmen pictures or not.

A: I recommend that images from Chinese history and news, or images criticising/mocking the Chinese government be allowed as long as they don't contain any gore, nudity, etc., i.e. the only potentially shocking aspect being their political implications.
While those may images inconvenience or offend some people, raising awareness of those events and ideas literally saves lives and prevents human rights violations, which is a more important goal in my opinion.
In this answer I do not wish to recommend or not if the side-by-side Nazi images are allowed or not, as I'd like to see what other people say instead.
However, whatever we decide, we should have clear and specific enough rules that people can reliably follow.
I believe that the guidelines:

*

*cannot be offensive to anyone

*must be suitable for work

are just too broad and subjective, and could be used to censor a very wide range of useful political speech.
If followed literally, they would basically forbid publishing anything that is censored in an authoritarian governments, therefore making us complicit with their actions.
Furthermore, I believe that the following meta threads already give strong support for allowing images which are potentially offensive and possibly not suitable for work, therefore contradicting those guidelines:

*

*User's political display name triggering government action against users who view it - what should I do? which clearly suggests that images that are not suitable for the workplace, to the point of being banned by the government, should be generally allowed

*Are political avatars and profiles OK? which shows a profile picture for "Free Palestine", therefore definitely not suitable for Israeli workplace

Even images in support of Western presidents can be considered offensive to some people who oppose them. E.g. I know closely people who would immediately stop being your friends if you showed support for Brazil's president Bolsanaro, and I suspect Trump/Biden.
Guidelines such as "any Nazi references must be clearly not supporting that ideology" and "all Nazi references in images are forbidden" however are good examples of specific enough guidelines if the community wants to set them.
If the community does decide to allow anti-Chinese government images, but forbid all Nazi references, I would like to point out two issues:

*

*it implicitly suggests that "we can offend some Chinese people, but we can't offend anyone from the West", which feels discriminatory, and is generally counter productive to the spread of freedom and democracy

*it prevents the dissemination of some potentially important political ideas. If a Government is truly acting more and more like the Nazis (which is of course a very subjective political opinion), it would be useful for people to know it

Those who forget the past are condemned to repeat it.

Replies to selected comments
(there were several comments originally, but mods now tend to delete most comments and replies)

Yes, I am concerned about Chinese politics too. No, Stack Exchange is not a billboard and your profile is no exception.

Profiles are always advertisements, be it for yourself, for you company, or for your beliefs and politics has been explicitly considered an allowed topic in the past: User's political display name triggering government action against users who view it - what should I do?

I think one group or another doesn't want their own complaint watered, promoted, or compared with a different complaint - they want their own complaint to be recognized exactly for what it is, not categorized as somewhat similar or in ways comparable to another - to retain their identity (a key component of their complaint). So don't bring up one specific category in the same breath as another, no https://en.wikipedia.org/wiki/Uyghur_genocide vs. https://en.wikipedia.org/wiki/Nazi_concentration_camps or anything else (and there's more than a few).

While current events are not as serious as in Nazi Germany perhaps, I do believe they are very serious, and possibly comparable to earlier stages of the Holocaust.
The goal of studying history is to predict it, and in doing so, comparisons are inevitable.
There has even been specific Jewish support of Uighurs, including in the context of the Holocaust: https://www.theguardian.com/world/2021/jan/24/jewish-leaders-use-holocaust-day-to-decry-persecution-of-uighurs "Jewish leaders use Holocaust Day to decry persecution of Uighurs"
My feeling is that this context it is clear enough that the goal of the comparison to highlight the importance of the Uighur issues, and not to reduce the important of the Holocaust.

If you cause enough complaints SE reserves the right not to promote your speech.

Although this rule satisfies my "clear/specific enough" criteria, it could also be used very unfairly, e.g. if I say "I'm Christian", and 1000 atheists flag the profile as offensive, should it come down? Similar cases would be "I'm homosexual/heterosexual" or "I vote for Trump/Biden".
I believe the answer is no.
I believe the only fair solution is to reply to those flags with a clear public guideline of what is allowed or not, e.g. "promoting your religion/sexual orientation/candidate is allowed".
And the best way to achieve such guidelines is through meta questions.
Without such guidelines, it becomes very risky to make any meaningful political statement, since any meaningful political statement will have opponents.
Offensive profiles - where to draw the line? says:

When a profile page or avatar has, or is likely to create a disruption, we need to be made aware of it and investigate. We might not take action in some cases, but we really do need to be aware of it.

The "We might not take action in some cases" accounts for those protected cases, which I'm trying to understand if the aforementioned issues are part of or not.

The mods and/or SE staff might not have clear guidelines in place yet, and I bet the last thing they want to do now is to figure out such guidelines to answer your question. If you have to ask, then I would refrain from adding any of that to your profile. Let's keep excessive politics out of SO.

This question attempts to help the community decide for the mods to factor out the work. Then in the future mods can just point all flags to specific answers, thus saving their time.

Politics should be posted on Twitter, not on Stack Overflow. (paraphrased)

Twitter is blocked in China, so posting there has no effect.
By limiting where freedom of speech can be used, you limit freedom of speech itself.

Nobody limits your free speech, we don't withhold you from going out on the street and yell whatever you want. Should SE allow everything on its platform, no. That is the same as you don't allow everything in your own house.

I never said the community has to allow anything to be posted. The community can decide to allow or forbid whatever they want.
But if the community decides to forbid talking about human rights violations, we become accomplices with them.
The Internet is the new street. E.g. instead of going to the streets to work, people are literally using the Internet.

The Chinese government most certainly needs to criticized, but why do you need to be tasteless (e.g., the profile picture)? You might achieve the opposite result.

Humor is one of the most powerful weapons against dictators: https://foreignpolicy.com/2013/04/05/why-dictators-dont-like-jokes/

And why do you leave out the tens of millions indirectly murdered by Mao Zedong in the 1960s (it didn't start in 1989)? Is it because you don't want people to compare now and then?

I can only fit 3k characters in my profile name, and recent events are more powerful than old ones. Even some Chinese today already recognize that Mao's government was bad.

Is "In Vladimir Putin We Trust" either in my profile page or as my previous display name offensive?

Should definitely be allowed in my opinion. If we want freedom of speech, we have to allow for people with possibly opposing views to ours to express their views as well.
However, user Intellectual Gymnastics Lover said it was removed from his profiles (in a now delete comment), so mods don't agree. He had moved it to his location to skirt around it, and down the profile went again after, but now for a year, after this post got a bit of attention due to this edit.
It would be good to have a meta thread for Putin, but realistically I don't think it would win, and would likely be deleted: even this question that has West-support got closed, had one deletion vote, and then was reopened before deletion.
The current general de-facto rule is in my observation/opinion: "if someone is widely disapproved of in the West, supporting them makes the profile go down". Even questions that are widely approved of in the West such as Xinjiang/Tiananmen don't have full support due to the part of people that are against politics of all kind on SO. So when you go against the mainstream opinion, you will generally lose any meta voting.
My opinion is similar to Elon Musk's:

By "free speech", I simply mean that which matches the law.
I am against censorship that goes far beyond the law.
If people want less free speech, they will ask government to pass laws to that effect.
Therefore, going beyond the law is contrary to the will of the people.

For the record, I am against the war in Ukraine. My current profile picture says "Putler Kaput" in Russian! But it is very hard to decide who is right or wrong in the world. Consider the Iraq war. 100k violent deaths minimum. Unclear UN legality at best. US/UK using intelligence to pressure UN leaders. Can I support George W. Bush on my profile?
Replies to parts of HolyBlackCat's answer

The mods and/or SE staff might not have clear guidelines in place yet, and I bet the last thing they want to do now is to figure out such guidelines to answer your inquiry.

As I argue in this answer above, this makes it very risky to post any political content on Stack Exchange, and greatly limits expression.

If you felt you needed to ask, then I would refrain from adding any of that to your profile.

This rule is too subjective and hard too determine without actually asking or just posting and risking a ban.

Let's stay professional and keep excessive politics out of SO/SE.

What is the rationale? Especially compared to the upside of saving lives/improving human rights.

~3 sentences max, calmly and politely expressing your opinion. No trigger words. Maybe a single link.

Setting arbitrary numerical like this does have the upside that it would limit how many decisions mods have to make at once.
However it also enormously limits freedom of expression.
And it does not clarify the crucial question: which content can go or not in those three paragraphs. Can I talk about Tiananmen? Can I talk about Falun Gong? Etc.
Everything censored by a dictatorship is likely to also be a trigger word.
If we only whitelisted a few subjects instead, this would allow for enormously greater freedom.

I think the caricature profile pic is ok, at least a tame one like yours.

(at the time of posting, this showed Xi Jinping photoshopped as Winnie the Pooh, a popular meme of the time)
Could you clarify pictures of peaceful students at Tiananmen or a person practicing Falun Gong are also tame enough?
I believe that all three would be equally offensive to many Chinese people, and all three are equally forbidden in China. Do you disagree?

I would remove anything political from your username. It gets obtrusive when people need to @ you in comments.

Currently very explicitly allowed at: User's political display name triggering government action against users who view it - what should I do?
Replies to Journeyman Geek's answer

It started about a week ago.

It didn't. You have more than one post asking about what's OK on a profile after it was moderated. Here's an [undeleted](User's political display name triggering government action against users who view it - what should I do? one)

It was not made clear in that answer that you are not allowed to ask if something is allowed on a profile or not.
The top answer actually gives a concrete yes/no answer, which I commend.
And they are not duplicates because you can't deduce the answer of this one from that one unrelated. Except perhaps for the winnie the poo subquestion, which https://meta.stackexchange.com/a/366173/200117 said is fine, in contradiction to that answer.
Below however you have made it clear that one is not allowed to ask, so I won't ask again.
However, this goes against several precedents, e.g.: User's political display name triggering government action against users who view it - what should I do? which is asking what is legal on a profile or not. It is also potentially unfair as it makes mods less accountable.

Could you please give your opinion if the following should be allowed or not, supposing of course that they contain no gore, nudity, etc., the only shocking part being the political content:

Of course, the old profile did and it was brought to our attention by the community.

Uploading images with those elements was a mistake, no complaints on that.
This question is explicitly about the mods refusing to explain if the ones that do not contain those elements are allowed or not, which  so I can correctly decide in the future.

All the above are considered highly shocking to many Chinese people, due in part to their strict censorship rules, and not suitable for the workplace in China.

You're aware its not suitable for work for many. You have said so, not us.

Exactly, like everything else censored by a dictatorship. Which has been explicitly allowed at User's political display name triggering government action against users who view it - what should I do? and which forbidding would mean being accomplices to a dictatorship.

Here's the tricky part here. You just filled your profile with DOZENS of shock pictures, after a previous warning for inappropriate personal attacks on a political figure. We're concerned any concrete suggestions of "what's OK and what's not" may result in trying to skirt the line, then sneaking past it, then doing a full cancan dance with a trained monkey on the other side.
As such, we decline to explicitly draw the out of bound markers for good taste and acceptability, but will let you know in an appropriate fashion should you cross it. You did and by quite a bit despite being warned previously.

As I mentioned earlier in the answer, not giving any suggestions allows mods to basically ban anything, which is unfair.

I'd suggest you stay deeply within the realm of supporting causes you believe in, as opposed to having a library of anti CCP propaganda

I care deeply about all anti-dictatorship causes, only I can decide that.

(which is amusingly similar to the pro CCP Chinese propaganda that we keep getting and spam-nuking)

If in their profiles, I recommend it should be kept as in mine. If outside of profile, should nuked as if I posted it.

Keep it short, constructive and to the point. Write it for humans - we're aware part of your goal is to try to convince the censorbots to block SE.

The images are made for humans. By limiting the number of images, you limit how much information I can give to Chinese people behind the firewall.
Anything that is censored in China can potentially trigger an SE block. The more information for humans, the more likely a block.
If something is not made for humans, it is is less likely to trigger a block than something made for humans.

A: It's worth looking at things in fuller context.

It started about a week ago.

It didn't. You have more than one post asking about what's OK on a profile after it was moderated. Here's an undeleted one

Could you please give your opinion if the following should be allowed or not, supposing of course that they contain no gore, nudity, etc., the only shocking part being the political content:

Of course, the old profile did and it was brought to our attention by the community.

All the above are considered highly shocking to many Chinese people, due in part to their strict censorship rules, and not suitable for the workplace in China.

You're aware its not suitable for work for many.  You have said so, not us.

people imprisoned in Xinjiang concentration camps

I don't think that would be safe for work for anyone.
Here's the tricky part here. You just filled your profile with DOZENS of shock pictures, after a previous warning for inappropriate personal attacks on a political figure. We're concerned any concrete suggestions of "what's OK and what's not" may result in trying to skirt the line, then sneaking past it, then doing a full cancan dance with a trained monkey on the other side.
As such, we decline to explicitly draw the out of bound markers for good taste and acceptability, but will let you know in an appropriate fashion should you cross it. You did and by quite a bit despite being warned previously.
While it's tempting to reply with the poster below -

I'd suggest you stay deeply within the realm of supporting causes you believe in, as opposed to having a library of anti CCP propaganda (which is amusingly similar to the pro CCP Chinese propaganda that we keep getting and spam-nuking) in your profile. Keep it short, constructive and to the point. Write it for humans - we're aware part of your goal is to try to convince the censorbots to block SE.
Keep it very much in mind that we have a diverse audience and many people use Stack Exchange at work, so if its something that the average person in most of the world may find distressing or shocking, it doesn't belong there.

A: The mods and/or SE staff might not have clear guidelines in place yet, and I bet the last thing they want to do now is to figure out such guidelines to answer your inquiry.
If you felt you needed to ask, then I would refrain from adding any of that to your profile.
Let's stay professional and keep excessive politics out of SO/SE. I too am not fond of the government of my country, but I don't advertise it here.

It's up to you of course, but if I were you, I would reduce the political part of the profile even further.
~3 sentences max, calmly and politely expressing your opinion. No trigger words. Maybe a single link.
I think the caricature profile pic is ok, at least a tame one like yours.
(edit: I could be underestimating how offensive it is to some. If you have doubts, then get rid of it.)
I would remove anything political from your username. It gets obtrusive when people need to @ you in comments.

A: If you are serious about academic questions and answers, keep professional and as scholarly as possible. If you join such a group to spam others, to woo supporters, or other purposes only of your personal interests, you may want to show more respect to others who value hard evidence and truth, with due patience to allow time for investigation, the same manner in problem solving.
Science is not advanced from media influence, majority voice, or repetition of hearsay.
Do the right thing in the right place.


text:
Q: laravel validating if passed params are not equal I'm creating an application that lets a user create blogposts in multiple language. Per language the have a tab that contains the different fields. They can define the title, content and the slug. When they save the blogpost, all the params are validated through a FormRequest class as following:
{
   "_method":"PUT",
   "_token":"eEDkVUU0cEcfAe3EQCiUIEdvCjTBqLFPT8CwW22D",
   "translations":{
      "nl":{
         "title":"A animi non est id repellat.nl",
         "slug":"veritatis-quos-iusto-eumnl",
         "content":"
ad-voluptate-sed-istenl<\/p>"
      },
      "en":{
         "title":"Velit dignissimos suscipit unde et quod.en",
         "slug":"cupiditate-in-quaerat-uten",
         "content":"
rem-corporis-aut-aten<\/p>"
      },
      "fr":{
         "title":"Mollitia reiciendis hic accusamus id dignissimos.fr",
         "slug":"voluptatem-iusto-quasi-rationefr",
         "content":"
accusantium-tempore-eos-nisifr<\/p>"
      },
      "de":{
         "title":"Esse quasi ut delectus molestiae rem.de",
         "slug":"voluptates-excepturi-labore-mollitiade",
         "content":"
earum-delectus-velit-distinctiode<\/p>"
      }
   }
}

Now i would like the slug to be unique but the normal unique rule doesnt work since the passed params arent added to the database yet. What would be the best way to validate the slugs, so the are all unique?

A: If you absolutely must let them create custom slugs for each, you could try using the different validation rule.
$this->validate($request, [
    'slug_field_1' => 'different:slug_field_2|different:slug_field_3|...',
    'slug_field_2' => 'different:slug_field_1|different:slug_field_3|...','
    ...
]);


text:
Q: adding subviews and constraints to UICollectionViewCell I'm writing my UI in code, and I'm trying to write the code for my UICollectionViewCell and add an UIImageView to it.
I need to create the UIImageView constraints in code.
What is the best practice for creating an imageView and constraints in an UIICollectionViewCell? e.i - in which UIICollectionViewCell creation method?

A: This is the way I am used to do what you're asking :

*

*Create my UICollectionViewController class:
 class MyCollectionController: UICollectionViewController {

     let cellId = "cellId"

     override func viewDidLoad() {
         super.viewDidLoad()

         collectionView.backgroundColor = .red
     }

     override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
         return 10
     }

 }

*Create your custom cell, let's call it MyCollectionCell :
 class MyCollectionCell: UICollectionViewCell {

     override init(frame: CGRect) {
         super.init(frame: frame)
         backgroundColor = .yellow
     }

     required init?(coder: NSCoder) {
         fatalError("init(coder:) has not been implemented")
     }
 }

*Declare programmatically your UIImageView (I prefer right before the init func) :
 let imageView: UIImageView = {
     let iv = UIImageView()
     iv.backgroundColor = .blue
     return iv
 }()

Don't forget the () to make sure the block of code is called!

*We need to add the imageView to the cell view and anchor it

To do so I always use an extension on UIView containing one function called anchor
extension UIView {

    func anchor(top: NSLayoutYAxisAnchor?, left: NSLayoutXAxisAnchor?, bottom: NSLayoutYAxisAnchor?, right: NSLayoutXAxisAnchor?, topPadding : CGFloat, leftPadding: CGFloat, bottomPadding: CGFloat, rightPadding: CGFloat, width: CGFloat, height: CGFloat) {

        self.translatesAutoresizingMaskIntoConstraints = false

        if let top = top {
            self.topAnchor.constraint(equalTo: top, constant: topPadding).isActive = true
        }

        if let left = left {
            self.leftAnchor.constraint(equalTo: left, constant: leftPadding).isActive = true
        }

        if let bottom = bottom {
            self.bottomAnchor.constraint(equalTo: bottom, constant: -bottomPadding).isActive = true
        }

        if let right = right {
            self.rightAnchor.constraint(equalTo: right, constant: -rightPadding).isActive = true
        }

        if width != 0 {
            self.widthAnchor.constraint(equalToConstant: width).isActive = true
        }

        if height != 0 {
            self.heightAnchor.constraint(equalToConstant: height).isActive = true
        }
    }
}

Now we can add the imageView and anchor it inside the init method of MyCollectionCell :
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .yellow

        addSubview(imageView)
        imageView.anchor(top: topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, topPadding: 3, leftPadding: 3, bottomPadding: 3, rightPadding: 3, width: 0, height: 0)
    }

*Let's use MyCollectionCell as the cellForItemAt for MyCollectionController

In viewDidLoad, register the cell with the right class (MyCollectionCell)
    let cellId = "cellId"

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView.backgroundColor = .red
        collectionView.register(MyCollectionCell.self, forCellWithReuseIdentifier: cellId)
    }

Dequeue cell as MyCollectionCell
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! MyCollectionCell

        return cell
    }

*When presenting MyCollectionController, you should see this result :


text:
Q: iPad 2 website sizing issue Ok before I start I will begin by saying I am NOT an experienced web developer!
I am writing this website: http://leydencarcentre.co.uk
It looks reasonable on a desktop browser, but I am struggling with getting an iPad (2) to display it properly.
On an iPad in portrait orientation the "Home" page is zoomed in a bit when you open it, but you can't zoom out to get the whole page width on the screen.  The "MOT" page is zoomed out completely so the full width fits in.
In landscape on the iPad they both look correct.
My site is basically 960px fixed width, but note I have tried to make it a bit responsive using media queries. (It's NOT a fluid layout, but there are slightly different div widths for different sizes - Desktop, Tablet, Phone).  I've made the main background different colours for each type of layout so you can see when the CSS for each media type kicks in.  (the desktop one is white, the tablet antique white, and the mobile Orange).
Can anyone help with this?  I've googled things like "iPad website width" and I can't make sense of what's the best way to go.
Any help on this particular iPad issue or advice on my CSS and layout greatfully received!
I know fully responsive fluid layouts are the talk of the town but I'm looking to get this site done pretty quickly.  Do I really need a fully fluid layout?
Thanks,
Paul

A: The easy fix:
<meta name="viewport" content="width=1000">

This will scale the iPad viewport to fit your page exactly (chrome told me body is 1000px wide).
In terms of mobile web good practices, I'd also add some scaling options so users can zoom in/out on different parts of the page.. something like:
<meta name="viewport" content="width=1000, minimum-scale=.5, initial-scale=1, maximum-scale=2.5">

A: I went with cale_b in the end as I tried many viewport settings and it either displayed OK on the iPad but not on Chrome under android or vice versa.
So I added a minimum height to my main body div.
Thanks cale_b


text:
Q: Why is my xml file having these after convert from excel? My xml file has these "x0020" after the first word and last word of a column in my excel file, any clue?
<root>
    <first_x0020_Name>John<first_x0020_Name>
    <last_x0020_Name>Doe<first_x0020_Name>
    <Age_x0020_Range>28<first_x0020_Name>
</root>

Here's my code to convert from excel to xml:
string PATH = @"C:file.xlsx";
        string connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + PATH + ";Extended Properties=Excel 12.0";
        OleDbConnection objConn = new OleDbConnection(connection);
        OleDbCommand objCmd = new OleDbCommand(string.Format(@"Select * From [Sheet1$]"), objConn);

        OleDbDataAdapter objDatAdap = new OleDbDataAdapter();
        objDatAdap.SelectCommand = objCmd;
        DataSet ds = new DataSet();
        objDatAdap.Fill(ds);
        string result;
        using (StringWriter sw = new StringWriter())
        {
            ds.DataSetName = "samples";
            DataTable ok = ds.Tables[0];
            ok.TableName = "sample";
            ds.WriteXml(sw);
            ds.WriteXml("C:/File.xml");
        }


text:
Q: order week number and resp. data in mysql starting with 51 and ending with week 12 I have got this query which shows snowdepth by weeknumber. There is no other date(ish) registration in the table other than wk, 1,2 3, etc.
SELECT
  res_id,
  wk,
  ROUND(templo, 0) AS templo,
  ROUND(temphi, 0) AS temphi,
  ROUND(snow_valley, 0) AS snow_valley,
  ROUND(snow_mountain, 0) AS snow_mountain
FROM
  sv_cond_vw_wk
GROUP BY res_id,
  wk
HAVING (res_id = 6)
  AND (wk = 51
    OR wk = 52
    OR wk = 52
    OR wk < 13)

It outpuths week 51 and 52 after week 12 but I would like to have it before week number 1:
51,52,1,2,3,4

A: You can use FIELD(wk,52,51) DESC in ORDER BY clause so that wk => 51 will appear first then wk => 52 and then rest ones
SELECT
  res_id,
  wk,
  ROUND(templo, 0) AS templo,
  ROUND(temphi, 0) AS temphi,
  ROUND(snow_valley, 0) AS snow_valley,
  ROUND(snow_mountain, 0) AS snow_mountain
FROM
  sv_cond_vw_wk
GROUP BY res_id,
  wk
HAVING (res_id = 6)
  AND (wk = 51
    OR wk = 52
    OR wk < 13)
ORDER BY FIELD(wk,52,51) DESC , wk


text:
Q: Using SyncLock to synchronize access to List(of T) I have a class that contains a List(of T) used in a multithreaded application.  I have three methods Get, Add and Remove where these access and modify the List(of T).  I was using SyncLock to lock m_List any time I queried it for the desired object as well as when I added or removed objects.  However I'm curious as to if there is a performance gain by simply locking m_List when I add an object or remove an object as opposed to when I'm searching for a desired object?
Public Shared sub Add(SomeObject as object)

     SyncLock ctype(m_List, IList).SyncRoot

         m_List.add(SomeObject)

     end SyncLock

end sub

Public Shared sub Remove(SearchString as string)

     SyncLock ctype(m_List, IList).SyncRoot

           m_List.RemoveAll(function(o as SomeObject) o.SomeProperty = SearchString)

     end SyncLock
end Function

Public Shared Function Get(SearchString as string) as SomeObject
     'The Commented out code is what I am thinking of removing...
     'SyncLock ctype(m_List, IList).SyncRoot

     Dim FoundObjectList = m_List.where(function(o as SomeObject) o.SomeProperty = SearchString)

    if FoundObjectList.count > 0 then

       If FoundObjectList(0).CreateDate < Now.AddMinutes(5) then
          Remove(FoundObjectList(0).SomeProperty)
          Return nothing
       end if
    else
         Return FoundObjectList(0)

    End if

   Return Nothing
'end SyncLock
end sub

A: If you try to iterate over the list and allow another thread to add an entry while you're doing so, you'll get an InvalidOperationException, it's as simple as that. My guess is that's not the behaviour you want.
List<T> simply doesn't support writing from one thread and reading from another at the same time - particularly not iterating over the list.


text:
Q: return part of a string I'm trying to return a certain part of a string. I've looked at substr, but I don't believe it's what I'm looking for.
Using this string:
/text-goes-here/more-text-here/even-more-text-here/possibly-more-here

How can I return everything between the first two // i.e. text-goes-here
Thanks,

A: $str="/text-goes-here/more-text-here/even-more-text-here/possibly-more-here";
$x=explode('/',$str);
echo $x[1];
print_r($x);// to see all the string split by /

A: <?php
$String = '/text-goes-here/more-text-here/even-more-text-here/possibly-more-here';

$SplitUrl = explode('/', $String);

# First element
echo $SplitUrl[1];  // text-goes-here

# You can also use array_shift but need twice
$Split = array_shift($SplitUrl);
$Split = array_shift($SplitUrl);

echo $Split;  // text-goes-here
?>

A: The explode methods above certainly work. The reason for matching on the second element is that PHP inserts blank elements in the array whenever it starts with or runs into the delimiter without anything else. Another possible solution is to use regular expressions:
<?php
$str="/text-goes-here/more-text-here/even-more-text-here/possibly-more-here";

preg_match('#/(?P<match>[^/]+)/#', $str, $matches);

echo $matches['match'];

The (?P<match> ... part tells it to match with a named capture group. If you leave out the ?P<match> part, you'll end up with the matching part in $matches[1]. $matches[0] will contain the part with the forward slashes like "/text-goes-here/".

A: Just use preg_match:
preg_match('@/([^/]+)/@', $string, $match);
$firstSegment = $match[1]; // "text-goes-here"

where
@    - start of regex (can be any caracter)
/    - a litteral /
(    - beginning of a capturing group
[^/] - anything that isn't a litteral /
+    - one or more (more than one litteral /)
)    - end of capturing group
/    - a litteral /
@    - end of regex (must match first character of the regex)


text:
Q: Show that if $T \in B(X,Y)$ and $x_n \rightarrow x$ weakly, then $Tx_n \rightarrow Tx$ weakly Suppose $T \in B(X,Y)$ and $x_n \rightarrow x$ weakly. Show that $Tx_n \rightarrow Tx$ weakly.
My attempt:
Let $y^* \in Y^*$. We want to show that $|y^*(Tx_n) - y^*(Tx)| < \epsilon$. Since $y^*$ is a bounded functional, we can assume that $\| y^* \|=1$. Note that
$$|y^*(Tx_n) - y^*(Tx)| = |y^*(Tx_n - Tx)| \leq \| T \| \| x_n - x \|_X $$
Note that $\| x_n - x \|_X = \sup \{ |x^*(x_n) - x^*(x)| : \| x^* \| \leq 1 \}$. Since $x_n \rightarrow x$ weakly, for all $x^* \in X^*$ and $\epsilon >0$, we have
$$|x^*(x_n) - x^*(x)| < \dfrac{\epsilon}{\| T \| +1}.$$
Hence,
$$|y^*(Tx_n) - y^*(Tx)| \leq \| T \| \| x_n - x \|_X < \epsilon.$$
I think something is wrong in my proof. It seems I am using the fact that a weakly convergent sequence is also strong convergent.
Can anyone help me to check?

A: You're not using the weak convergence of $x_n$ here.
The correct (and significantly easier) approach is to note that if $y^*$ is a bounded functional, then so is $y^*T$.


text:
Q: How to evaluate the passed prop to the styled component using react and typescript? i want to add a background color to the styled component div if state active is true.
i am doing it like so
function Main() {
    const [active, setActive] = useState(false);
    return (
        <ChildComponent
            active={active}/>
    );
}

const ChildComponent = styled.div<{ active?: boolean }>`
    height: 100%;
    ${({ active }) => active && 'background-color: grey';}
`;

This works fine. but instead of just passing string grey to background color i want to pass props like below.
const ChildComponent = styled.div<{ active?: boolean }>`
    height: 100%;
    ${({ active }) => active && 'background-color:'${(props: any) =>
    props.theme.colors.grey.light3}};

`;

This is not the right syntax to do it. could someone help me fix this thanks.

A: You can nest template literals within template literals as long as they're located inside an interpolated expression block (${...}).
So your code should look like this:
const ChildComponent = styled.div<{ active?: boolean }>`
    height: 100%;
    ${({ active, ...props }) => active && `background-color: ${(props: any) =>
    props.theme.colors.grey.light3}`};

`;


text:
Q: connecting to database in c++ In php I create a config file that opens a connection to the database and then I use that file in all my other files in order to open a connection also. But I can't seem to find a way to do the same thing with c++. I can connect to the database but I can't use it as a class because I have a main() inside it and I can't seem to make it work without the main. This is my code:
// Standard C++ includes
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;

// Include the Connector/C++ headers
#include "cppconn/driver.h"
#include "cppconn/exception.h"
#include "cppconn/resultset.h"
#include "cppconn/statement.h"

// Link to the Connector/C++ library
#pragma comment(lib, "mysqlcppconn.lib")

// Specify our connection target and credentials
const string server   = "localhost";
const string username = "root";
const string password = "";

int main()
{
    sql::Driver     *driver; // Create a pointer to a MySQL driver object
        sql::Connection *dbConn; // Create a pointer to a database connection object
        sql::Statement  *stmt;   // Create a pointer to a Statement object to hold our SQL commands
        sql::ResultSet  *res;    // Create a pointer to a ResultSet object to hold the results of any queries we run

    // Try to get a driver to use to connect to our DBMS
    try
    {
        driver = get_driver_instance();
    }
    catch (sql::SQLException e)
    {
        cout << "Could not get a database driver. Error message: " << e.what() << endl;
        system("pause");
        exit(1);
    }

    // Try to connect to the DBMS server
    try
    {
        dbConn = driver->connect(server, username, password);
    }
    catch (sql::SQLException e)
    {
        cout << "Could not connect to database. Error message: " << e.what() << endl;
        system("pause");
        exit(1);
    }

    stmt = dbConn->createStatement();

    // Try to query the database
    try
    {
        stmt->execute("USE test");

        res = stmt->executeQuery("SELECT * FROM users");

    }
    catch (sql::SQLException e)
    {
        cout << "SQL error. Error message: " << e.what() << endl;
        system("pause");
        exit(1);
    }

    sql::ResultSetMetaData *res_meta = res -> getMetaData();
    int columns = res_meta -> getColumnCount();

    while (res->next())
    {
        for (int i = 1; i <= columns; i++) {
                cout << res->getString(i) << " | " ;
                }
         cout << endl;
    }

    delete res;
    delete stmt;
    delete dbConn;
    return 0;
}

A: You need to create a class (e.g class DBConnector)and declare functions in header file.
For example this piece of code can go into one function:
sql::Driver* DBConnector::GetDriverInstance()
{
try
    {
        m_driver = get_driver_instance();
    }
    catch (sql::SQLException e)
    {
        cout << "Could not get a database driver. Error message: " << e.what() << endl;
        system("pause");
        exit(1);
    }
    return m_driver;
}

Here sql::Driver *m_driver is expected to be declared as a member variable of class in header file. You might need to read more about classes and member functions and variables before actually going ahead with code.
Other than this, you need to take very good care of memory management. I would suggest you read more and use smart pointers like std::shared_ptr.


text:
Q: PHP exec_shell via input string I can use shell_exec this way:
$output = shell_exec('ls -lart');
echo "
$output
";

but this did'nt work:
$job = 'ls -lart';
$output = shell_exec($job);
echo "
$output
";

Is'nt it possible to give a string to shell_exec?

A: Work. Error was not shell_exec, but wrong concatination of two string given to it ...


text:
Q: when all I get is EOF from a net.TCPConn, how do I know if the connection has been dropped? The godocs say:
"EOF is the error returned by Read when no more input is available. Functions should return EOF only to signal a graceful end of input. If the EOF occurs unexpectedly in a structured data stream, the appropriate error is either ErrUnexpectedEOF or some other error giving more detail."
and in my program I would love love to get ErrUnexpectedEOF, but I don't. I always get just EOF even when the client terminates in the middle of sending a file.
so, i'm stuck. Successful files that transfer 100% of the way thru send EOF at end. And files that quit 50% thru with error also send EOF as the error. I do not know the total size of the file before the transfer.
Is there any more information I could get from the net.TCPConn to know was this a full file or not?

A: TCP is a streaming protocol; a stream of bytes. That's why file transfer protocols invented/implemented upon TCP, like FTP (File Transfer Protocol).
But (not recommended/thought experiment) if you can send your files in chunks that does not contain a certain character/byte (like base64 + \n as that certain character), then you can use that certain character as delimiter.
Now if we handle our connections using a function similar to this:
func (srv *Server) handler(conn net.Conn) {
    //...

    defer srv.closeConnection(conn, nil)

    reader := bufio.NewReader(conn)
    writer := bufio.NewWriter(conn)

    //...

    conn.SetDeadline(time.Now().Add(conf.ClientTimeout))

    for {
        select {
        case <-conf.QuitSignal:
            return
        default:
            line, err := reader.ReadBytes('\n')
            if err != nil {
                return
            }

            //...
        }

        conn.SetDeadline(time.Now().Add(conf.ClientTimeout))
    }
}

func (srv *Server) closeConnection(conn net.Conn, err error) {
    conn.Close()
    //...
}

From the documentation of Reader.ReadBytes we read ReadBytes returns err != nil if and only if the returned data does not end in delimiter. This way we can recognize a broken chunk.


text:
Q: Why doesn't the copy constructor work when I return an automatic variable from function? In the below example I want to find out why the copy constructor isn't called when I return an automatic variable from the doit() function. I understand that the first version of handler is called because we have a temporary object but can't figure out why the copy constructor isn't called while creating that temporary object (copies everything from s to a temporary object).
#include <iostream>
using namespace std;

class S{
    public:
        S(){std::cout<<"Constructor\n";}
        S(const S& s){std::cout<<"Copy Constructor\n";}
        ~S(){std::cout<<"Destructor\n";}
};

S doit(){
    S s;
    return s;
}

void handler(S&& r){
    std::cout<<"Here\n";
}
void handler(const S& r){
    std::cout<<"Here2\n";
}

int main() {
    handler(doit());
}

A: Actually, there is a constructor being called in your code according to the rules of the language. However, the compiler has optimized that out and so you don't see the call. If you compile with -fno-elide-constructors you should see the copy-constructor being invoked.
Note that the copy-constructor will only be invoked because the defaulted move-constructor is suppressed. If you add that back like this:
S(S&&) = default;

then this move-constructor will be called instead. Here's a demo.


text:
Q: Optimal buying strategy with multiple shops and items I'm working on a program to "optimally" buy magic cards. On the site each user has a "mini-shop", think eBay without the auctions.
The users enters a list of cards he wants to buy, I then fetch all offers from the site and print an "optimal" shopping list. Optimal meaning cheapest. Prices differ in the shops and also postage changes depending on how many cards you buy.
I would like to implement some algorithm which creates that list for me. I have written one, which works(I think), but I have no idea how good it works.
So my question is this: Can this problem be solved by some existing algorithm? It would need to deal with ~1000 offers for EACH card (normally 40-60 cards, so around 50k different offers)
Can somone point me in the correct direction on this?

A: The "partition" or "bin packing" problems (which are both mappable to what you want to do) is known to be NP-complete. Thus, the only way to make SURE that you have the optimal solution is to try all possible solutions and pick the best way.
If the user wants to buy 1,000 cards, trying all possible options is not computationally feasible, so you need to use heuristics.


text:
Q: How to move the drop down box to top I have used kendo-ui to implement drop down menus in my blog as you can see i want to move the box to upwards without effecting the posts. when i added the code margin-top:20px;  but it does no works any other way to move the box to upwards.
like

<!doctype html>

    <link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.2.607/styles/kendo.common-material.min.css" />
    <link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.2.607/styles/kendo.material.min.css" />
    <link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.2.607/styles/kendo.default.mobile.min.css" />

T-shirt Size

            <select id="size" placeholder="Select size..." style="width: 300px;" >
              <option />X-Small
              <option />Small
              <option />Medium
              <option />Large
              <option />X-Large
              <option />2X-Large
            </select>

</!doctype>

A:

<!doctype html>

    <link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.2.607/styles/kendo.common-material.min.css" />
    <link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.2.607/styles/kendo.material.min.css" />
    <link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.2.607/styles/kendo.default.mobile.min.css" />

T-shirt Size

            <select id="size" placeholder="Select size..." style="width: 300px;" >
              <option />X-Small
              <option />Small
              <option />Medium
              <option />Large
              <option />X-Large
              <option />2X-Large
            </select>

</!doctype>

A: <!doctype html>

<link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.2.607/styles/kendo.common-material.min.css" />
<link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.2.607/styles/kendo.material.min.css" />
<link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.2.607/styles/kendo.default.mobile.min.css" />

T-shirt Size

        <select id="size" placeholder="Select size..." style="width: 300px;" >
          <option />X-Small
          <option />Small
          <option />Medium
          <option />Large
          <option />X-Large
          <option />2X-Large
        </select>

A: solved i added margin-top:20px; to my .post so posts are now appeard in down


text:
Q: IGraphM on Apple Silicon? I recently got a new laptop with Apple's M1 Max processor and now the IGraphM installer
Get["https://raw.githubusercontent.com/szhorvat/IGraphM/master/IGInstaller.m"]

returns

FYI, I ran this in Mathematica version 13.0.1 on macos 12.3.1.
So what I'd like to ask:

*

*Is it possible to install IGraphM on the M1 architecture? (Given the fact that it runs on ARM-based machines like RaspberryPi, the answer is probably "yes".)

*How to install it and make it run?

A: Release 0.6 with Apple Silicon support is out now.
(Version 0.5.x does not support Apple Silicon, but you can run the Intel version of Mathematica even on ARM Macs.)


text:
Q: If I own a domain do I own all of its sub domains? If I own a domain do I own all of its sub domains?
For example if I purchase example.com, do I automatically  own mail.example.com, blog.example.com, etc?
If I do not own the sub domains, can anyone buy mail.example.com if I own example.com? Do I have a right of first sale if someone tries to buy one of my sub domains?
Finally, do the answers to the above questions apply to all domains in all TLDs, like .org, .net, .ca, .name, etc?
Thank you.
EDIT: According to the .name agreement registration restrictions at
http://www.icann.org/en/about/agreements/registries/name/appendix-11-25mar11-en.htm
an individual can register a .name domain only if the domain matches the eligibility requirements. There are several eligibility requirements, one of which is that a .name domain must be the real name or identifier of an individual. So, for example, firstname.lastname.name and firstnamelastname.name are both valid. However, lastname.name is not valid because it does not identify an individual. If I registered lastname.name, someone else could mount a challenge based on the eligibility requirements and register otherfirstname.lastname.name. So I do not in fact control the sub domains.
Am I reading that right? Are there similar restrictions on ownership of subdomains in other TLDs?

A: Yes, you own and control the entire namespace below the domain you purchase, because DNS is hierarchical.  Creating mail.example.com and blog.example.com is just a matter of adding entries to the DNS zone that you control.
Since you asked about the name. domain, I'll address that specifically: You cited its eligibility requirements and have confused this with domain control. If you aren't eligible to have the domain to begin with, then the point is moot.
In the case of name. and a few other top level domains, it may be valid to register a second-level, third-level or a fourth-level name, depending on that domain's individual eligibility requirements. For instance, us. allows second-level registrations to anyone, but for historical reasons, there exist many second-level registrations corresponding to U.S. states which are registered to state government agencies, and where the third or fourth level is further delegated to agencies within those states.


text:
Q: Cordova missing cordova_plugins.json file. Have added it but still getting error I have just started a Cordova/Phonegap 2.0.7 project. All is going well but when I test in a browser I get the message:
MLHttpRequest cannot load file://localhost/~~~/www/cordova_plugins.json. Cross origin requests are only supported for HTTP. cordova-2.7.0.js:6410

I searched SO and found that this is a common bug and to just add a blank file name cordova_plugins.json to the www folder. I have done this but the error persists.
On top of this I also get a Failed to Load resource error for a file
file://localhost/!gap_exec?1368772098759
and I have no idea what it is.
I have not added any plugins to the project yet but am retrieving data via JSON with a small JQuery script. I am also using JQuery Mobile.
Would anyone know how to remedy this at all?
Thanks!

A: This issue seems to be fixed in the next release: https://github.com/apache/cordova-js/pull/25


text:
Q: имя таблицы как параметр sql Может кто подскажет ответ на такую задачу:
Есть таблицы в базе данных, которые имеют названия table15, table14...table00. Необходимо написать хранимую процедуру, которая в качестве одного из параметра должна получать год, по которому и должна определяться таблица для выполнения запросов.
Динамический SQL использовать при этом не получается, так как код процедуры большой! Есть какое то решения для данной задачи?

A: Необходимо объединить все таблицы (table15...) в один view с добавлением уникального идентификатора (в данном случае, последние 2 цифры года) в качестве дополнительной колонки.
При запросе в процедуре делать join переданного в процедуру года и уникального идентификатора года. Тем самым из view будут получены записи только определенной таблицы.
Упрощенный пример:
declare @t1 table (id int)
declare @t2 table (id int)

insert into @t1 values(1)
insert into @t1 values(2)
insert into @t1 values(3)

insert into @t2 values(4)
insert into @t2 values(5)
insert into @t2 values(6)

select * from
(select 1 as Id, * from @t1
 union all
 select 2, * from @t2) t
where Id = 1


text:
Q: Is reference counting thread safe For example consider
class ProcessList {
private
   std::vector<std::shared_ptr<SomeObject>> list;
   Mutex mutex;
public:
   void Add(std::shared_ptr<SomeObject> o) {
       Locker locker(&mutex); // Start of critical section. Locker release so will the mutex - In house stuff
       list.push_back(std::make_shared<SomeObject>(o).
   }

   void Remove(std::shared_ptr<SomeObject> o) {
       Locker locker(&mutex); // Start of critical section. Locker release so will the mutex - In house stuff
       // Code to remove said object but indirectly modifying the reference count in copy below
   }

   void Process() {
       std::vector<std::shared_ptr<SomeObject>> copy;

       {
           Locker locker(&mutes);
           copy = std::vector<std::shared_ptr<SomeObject>>(
                list.begin(), list.end()
           )
       }
       for (auto it = copy.begin(), it != copy.end(); ++it) {
           it->Procss(); // This may take time/add/remove to the list
       }
    }
};

One thread runs Process. Multiple threads run add/remove.
Will the reference count be safe and always correct - or should a mutex be placed around that?

A: Yes, the standard (at §20.8.2.2, at least as of N3997) that's intended to require that the reference counting be thread-safe.
For your simple cases like Add:
void Add(std::shared_ptr<SomeObject> o) {
    Locker locker(&mutex);
    list.push_back(std::make_shared<SomeObject>(o).
}

...the guarantees in the standard are strong enough that you shouldn't need the mutex, so you can just have:
void Add(std::shared_ptr<SomeObject> o) {
    list.push_back(std::make_shared<SomeObject>(o).
}

For some of your operations, it's not at all clear that thread-safe reference counting necessarily obviates your mutex though. For example, inside of your Process, you have:
   {
       Locker locker(&mutes);
       copy = std::vector<std::shared_ptr<SomeObject>>(
            list.begin(), list.end()
       )
   }

This carries out the entire copy as an atomic operation--nothing else can modify the list during the copy. This assures that your copy gives you a snapshot of the list precisely as it was when the copy was started. If you eliminate the mutex, the reference counting will still work, but your copy might reflect changes made while the copy is being made.
In other words, the thread safety of the shared_ptr only assures that each individual increment or decrement is atomic--it doesn't assure that manipulations of the entire list are atomic as the mutex does in this case.
Since your list is actually a vector, you should be able to simplify the copying code a bit to just copy = list.
Also note that your Locker seems to be a subset of what std::lock_guard provides. It appears you could use:
std::lock_guard<std::mutex> locker(&mutes);

...in its place quite easily.

A: It will be an overhead to have a mutex for reference counting.
Internally, mutexes use atomic operations, basically a mutex does internal thread safe reference counting. So you can just use atomics for your reference counting directly instead of using a mutex and essentially doing double the work.

A: Unless your CPU architecture have an atomic increment/decrement and you used that for reference count, then, no, it's not safe; C++ makes no guarantee on the thread safety of x++/x-- operation on any of its standard types.
Use atomic<int> if your compiler supports them (C++11), otherwise you'll need to have the lock.
Further references:

*

*https://www.threadingbuildingblocks.org/docs/help/tbb_userguide/Atomic_Operations.htm


text:
Q: Validate dates before conversion, aka. ISDATE() equivalent DB2 version is 9.7.0.7
I have a flat file, and need to validate fully prior to insert into a  production table.  For analysis, I've parsed it into a table where all columns are VARCHAR.
One of the tasks is to validate dates.  I need to be able to locate the specific invalid dates, to report on the scope (frequency) and solution (reason).
I use ISDATE() in Sybase and SQL Server, which returns a 1 for a valid date, and a 0 for an invalid date.  In Teradata, I left join to the SYS_CALENDAR table in the system catalog. It's been about 15 years since I've last been in a DB2 environment, but I believe analogs to either do not exist.
In this DB2 environment my role is limited to QA, meaning I cannot create T-SQL procedures or UDFs.
This thread is clever and makes me think there may be some Common Table Expression logic that could be employed in a query:
ISDATE equivalent of DB2
That one falls short as a solution, however, because it only considers format - the presence of an invalid (but properly formatted) date like '2016-04-31' or '2016-02-30' will raise an error and the query will return no rows.
I need to return all rows, identifying if each is valid or invalid (or just return the invalid rows for investigation, even) - so doing a CAST or CONVERT, or inserting into a formatted table in a test environment won't work.
Is there an analog to ISDATE(), SYS_CALENDAR, or another solution that gets to the same end product of a row-wise presentation of dates that can't be cast to DATE, prior to performing that conversion/insert?

A: You can do it with the PureXML extension as follows:
SELECT
 XMLCAST(XMLQUERY('string($D) castable as xs:date' PASSING mycolumn as D ) AS INT)
FROM
 mytable

which will return 1 or 0.


text:
Q: Is it possible to drag and drop some content between two browser windows using JQuery or another method? Basically, I have a popup window and I want ability to drag and drop an html item back to parent opener window. For example, if there is an image on the popup window which is draggable (and basically a handler only), once I drop it in the drop-zone of the parent window I just need to copy a hidden ID and/or maybe name of the Image from the popup to the parent window.
I can see plenty of examples on same page drag and drop but across windows? Is it possible? Both these windows have same website opened so I suppose there shouldn't be any cross-site issue thing?
Could you point me to the right direction? Anything not clear please ask.
EDIT
Is HTML5 an option?
Another EDIT
Is there another way to achieve above? i.e. different method than drag and drop - I am interested in transferring some data between one window to another here. Any ideas will be appreciated.

A: You are after the HTML5 Drag and Drop API
A pretty good description: DnD Basics
You can even drag and drop stuff between Firefox and Chrome. Safari is missing the drop event, should be out in the next release (6 if I'm right). Opera & IE is not supporting it yet.