问:
Multi-dimensional char array prints within function, but not when passed to another function
I am attempting to write data into a multi-dimensional array, and then pass the array as a const char** to another function.  When I print the char* locally in the function in which it is declared, everything works as expected.  But, when I try to print the array of char* in another function, they are all empty strings.

I am using the following code:

```<code>void my_print (const char** lines, unsigned int num)
{
    int i = 0;

    for (i = 0; i < num; i++) {
        fprintf(stderr, "lines[%d]:  %s", i, lines[i]);
    }
}

void my_func ()
{
    char cfg[2][200];
    unsigned int value = 5;

    snprintf(cfg[0], 200, "one two three\n");
    snprintf(cfg[1], 200, "my value = %u\n", value);

    fprintf(stderr, "lines[0] = %slines[1] = %s\n", cfg[0], cfg[1]);

    my_print((const char**) cfg, 2);
}
</code>```

This results in the following output:

```<code>lines[0] = one two three
lines[1] = my value = 5
lines[0]:
lines[1]:
</code>```

If instead, of the given my_func, I use the following:

```<code>void my_func ()
{
    char* cfg[2];
    unsigned int value = 5;

    cfg[0] = malloc(200);
    cfg[1] = malloc(200);
    snprintf(cfg[0], 200, "one two three\n");
    snprintf(cfg[1], 200, "my value = %u\n", value);

    fprintf(stderr, "lines[0] = %slines[1] = %s\n", cfg[0], cfg[1]);

    my_print((const char**) cfg, 2);
}
</code>```

Then, everything works, and I get:

```<code>lines[0] = one two three
lines[1] = my value = 5
lines[0]: one two three
lines[1]: my value = 5
</code>```

So, what is happening in the background here?  Why do I need to use malloc in order for my_print to be able to print my strings?

Thanks you

答:
An array is not a pointer

Arrays decay into pointers to their first elements, but that only happens at the first dimension.  So a 2D array does not decay into a pointer to a pointer, it only decays into a pointer to an array, so that is what you must pass to your function:

```<code>// lines is of type "pointer to array 200 of const char"
void my_print (const char (*lines)[200], unsigned int num)
</code>```

This line of code is very, very wrong:

```<code>my_print((const char**) cfg, 2);
</code>```

You probably inserted the cast to const char** to silence the compiler.  Do not do that -- the compiler is trying to tell you that you're doing something wrong!  Shutting it up is the wrong thing to do.  With the above change to the definition of my_print, you do not need any cast:

```<code>my_print(cfg, 2);
</code>```

Body:
I am attempting to write data into a multi-dimensional array, and then pass the array as a const char** to another function.  When I print the char* locally in the function in which it is declared, everything works as expected.  But, when I try to print the array of char* in another function, they are all empty strings.

I am using the following code:

void my_print (const char** lines, unsigned int num)
{
    int i = 0;

    for (i = 0; i < num; i++) {
        fprintf(stderr, "lines[%d]:  %s", i, lines[i]);
    }
}

void my_func ()
{
    char cfg[2][200];
    unsigned int value = 5;

    snprintf(cfg[0], 200, "one two three\n");
    snprintf(cfg[1], 200, "my value = %u\n", value);

    fprintf(stderr, "lines[0] = %slines[1] = %s\n", cfg[0], cfg[1]);

    my_print((const char**) cfg, 2);
}

This results in the following output:

lines[0] = one two three
lines[1] = my value = 5
lines[0]:
lines[1]:

If instead, of the given my_func, I use the following:

void my_func ()
{
    char* cfg[2];
    unsigned int value = 5;

    cfg[0] = malloc(200);
    cfg[1] = malloc(200);
    snprintf(cfg[0], 200, "one two three\n");
    snprintf(cfg[1], 200, "my value = %u\n", value);

    fprintf(stderr, "lines[0] = %slines[1] = %s\n", cfg[0], cfg[1]);

    my_print((const char**) cfg, 2);
}

Then, everything works, and I get:

lines[0] = one two three
lines[1] = my value = 5
lines[0]: one two three
lines[1]: my value = 5

So, what is happening in the background here?  Why do I need to use malloc in order for my_print to be able to print my strings?

Thanks you

Body:
An array is not a pointer

Arrays decay into pointers to their first elements, but that only happens at the first dimension.  So a 2D array does not decay into a pointer to a pointer, it only decays into a pointer to an array, so that is what you must pass to your function:

// lines is of type "pointer to array 200 of const char"
void my_print (const char (*lines)[200], unsigned int num)

This line of code is very, very wrong:

my_print((const char**) cfg, 2);

You probably inserted the cast to const char** to silence the compiler.  Do not do that -- the compiler is trying to tell you that you're doing something wrong!  Shutting it up is the wrong thing to do.  With the above change to the definition of my_print, you do not need any cast:

my_print(cfg, 2);


来源: stackexchange

问:
EJB injection into non managed objects
we are upgrading our web application to Oracle WebLogic 12c with EJB 3.x, and we got an issue.

This is the scenario...

We have a simple EJBs that we are going to call MyService, defined with its bean and local/remote interfaces defined by the EJB 3.x annotations.

Here is a pseudo code of the scenario:

```<code>class MyListener implements ServletContextListener {

    @EJB private MyService myService;

    public void contextInitialized(ServletContextEvent arg0) {
        // Here myService is correctly instantiated, so we do something...
    }

}
</code>```

Now we have to move the contextInitialized method logic inside an utility class, so the new scenario will be:

```<code>class MyUtility {

  @EJB private MyService myService;

  public void doSomething() {
      // Here myService is NULL!!!!!
  }

}

class MyListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent arg0) {
        new MyUtility().doSomething();
    }

}
</code>```

I have read a lot of documentation about that problem, and I discovered that only some kind of classes are scanned by the Application Server to resolve the injected EJBs ( Java EE 6, 5, 7 | List of managed beans or classes: EJBs , JSF beans and ..? ).

Is there a workaround to force the scanning of a custom class like mine with WebLogic?

Thank you very much.

答:
There is an option to wrap you Injection into a CDI-Component and to use this one in your code. CDI has the capability to work in standalone java, as soon as you configured it well.
Another helpful option can be the fact, that CDI supports EJB-injection too (in some usecases):
CDI.current().select(MyService.class).get();

BUT: EJBs has their own Transaction-Management. So I would prefer the wrapping into a cdi-component to get more controll in it.

ContentLicense: CC BY-SA 3.0

Title: EJB injection into non managed objects

Body:
we are upgrading our web application to Oracle WebLogic 12c with EJB 3.x, and we got an issue.

This is the scenario...

We have a simple EJBs that we are going to call MyService, defined with its bean and local/remote interfaces defined by the EJB 3.x annotations.

Here is a pseudo code of the scenario:

class MyListener implements ServletContextListener {

    @EJB private MyService myService;

    public void contextInitialized(ServletContextEvent arg0) {
        // Here myService is correctly instantiated, so we do something...
    }

}

Now we have to move the contextInitialized method logic inside an utility class, so the new scenario will be:

class MyUtility {

  @EJB private MyService myService;

  public void doSomething() {
      // Here myService is NULL!!!!!
  }

}

class MyListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent arg0) {
        new MyUtility().doSomething();
    }

}

I have read a lot of documentation about that problem, and I discovered that only some kind of classes are scanned by the Application Server to resolve the injected EJBs ( Java EE 6, 5, 7 | List of managed beans or classes: EJBs , JSF beans and ..? ).

Is there a workaround to force the scanning of a custom class like mine with WebLogic?

Thank you very much.


问:
unicode to string conversion swift
```<code>Es ist eines der Wahrzeichen
Bambergs: das Alte Rathaus, auch Insel- oder Brückenrathaus
genannt, das die frühere Herrschaftsgrenze zwischen der
bürgerlichen Inselstadt und der
</code>```

I want to convert all unicode to string from above string.

答:
We have the following method in our project:</p>

```<code>- (NSString *)convertHTMLToUnicode {
    NSArray *theHTMLEntities = @[@"&", @"Ä", /* more stuff */];
    NSArray *theUnicodeEntities = @[@"&", @"Ä", /* more stuff */];

    NSDictionary *theHTMLSource = [NSDictionary dictionaryWithObjects:theUnicodeEntities forKeys:theHTMLEntities];
    NSMutableString *theText = [NSMutableString stringWithString:self];
    for (NSString *theHtml in theHTMLEntities) {
        [theText replaceOccurrencesOfString:theHtml
                             withString:[theHTMLSource valueForKey:theHtml]
                                options:NSLiteralSearch
                                  range:NSMakeRange(0, theText.length)];
    }
    return theText;
}
</code>```

Title: unicode to string conversion swift

Body:
Es ist eines der Wahrzeichen
Bambergs: das Alte Rathaus, auch Insel- oder Brückenrathaus
genannt, das die frühere Herrschaftsgrenze zwischen der
bürgerlichen Inselstadt und der

I want to convert all unicode to string from above string.

Body:
We have the following method in our project:

- (NSString *)convertHTMLToUnicode {
    NSArray *theHTMLEntities = @[@"&amp;", @"&Auml;", /* more stuff */];
    NSArray *theUnicodeEntities = @[@"&", @"Ä", /* more stuff */];

    NSDictionary *theHTMLSource = [NSDictionary dictionaryWithObjects:theUnicodeEntities forKeys:theHTMLEntities];
    NSMutableString *theText = [NSMutableString stringWithString:self];
    for (NSString *theHtml in theHTMLEntities) {
        [theText replaceOccurrencesOfString:theHtml
                             withString:[theHTMLSource valueForKey:theHtml]
                                options:NSLiteralSearch
                                  range:NSMakeRange(0, theText.length)];
    }
    return theText;
}


问:
Basic Dragula Implementation
I am trying to get a simple Dragula implementation but it is refusing to work.  My code:

```<code><head>
<link href='drag3.css' rel='stylesheet' type='text/css' />
<link href='css/dragula.css' rel='stylesheet' type='text/css' />
<script src='drag3.js'></script>
</head>

<div class="container">
  <h1>Drag & Drop</h1>
  <p>Trying out <code>dragula.js</code>. Source <a href="https://github.com/bevacqua/dragula">here</a>.</p>
  <div class="left">
    <div id="drag-elements">
      <div>Element 1</div>
      <div>Element 2</div>
      <div>Element 3</div>
    </div>

    <div id="drop-target">
    </div>
  </div>
  <div class="right">
    <div id="display">Display</div>
  </div>
</div>

<script src='js/dragula.js'></script>
<script src='js/example.min.js'></script>
</code>```

Not sure what I am doing wrong, any help would be gratefully received!

The live code is here:

Dragula Implementation

答:
OK so I fixed it by simply moving the

```<code> <script src='drag3.js'></script>
</code>```

to the end of the page.

Title: Basic Dragula Implementation

Body:
I am trying to get a simple Dragula implementation but it is refusing to work.  My code:

<link href='drag3.css' rel='stylesheet' type='text/css' />
<link href='css/dragula.css' rel='stylesheet' type='text/css' />

Drag & Drop

Trying out dragula.js. Source here.

Element 1

Element 2

Element 3

Display

Not sure what I am doing wrong, any help would be gratefully received!

The live code is here:

Dragula Implementation

Body:
OK so I fixed it by simply moving the

 <script src='drag3.js'></script>

to the end of the page.


问:
Fill an Input without selecting it before. HTML / JS?
I would like to fill an input without having to select it with my mouse before. Just using javascript and not Jquery .

What I mean is that they user just have ton type his answer and it goes directly into the input. Here is my HTML.

```<code><input id="inputresponse" name="response" type="text" value="" />
</code>```

I have searched everywhere but I can't find a clue. I guess we should use either keyup or keypress, but I can't find how.

Your help is highly appreciated, thanks !

答:
This should work:

```<code>$('#inputresponse').focus();
</code>```

Just setting this on your page will automatically focus on the input element and anything typed will be added within.

Body:
I would like to fill an input without having to select it with my mouse before. Just using javascript and not Jquery .

What I mean is that they user just have ton type his answer and it goes directly into the input. Here is my HTML.

<input id="inputresponse" name="response" type="text" value="" />

I have searched everywhere but I can't find a clue. I guess we should use either keyup or keypress, but I can't find how.

Your help is highly appreciated, thanks !

Body:
This should work:

$('#inputresponse').focus();

Just setting this on your page will automatically focus on the input element and anything typed will be added within.


问:
How to pass variable value to HTA
The following code in a batch file which gets the password from user Thru a HTA dialog box. It works fine. I want to pass a variable value !user[%%a]! to be displayed inside the pop up HTA dialog box so I can see
Enter password for User ID: "BATCH FILE USER VARIABLE"
in this window :

How can I do that?

```<code><!-- :
@setlocal enableextensions enabledelayedexpansion
:: PasswordSubmitter.bat
@echo off
set user[1]=me1
set user[2]=me2
set user[3]=me3

for /l %%a in (1,1,3)  do (
    set counter=%%a
    for /f "tokens=* delims=" %%p in ('mshta.exe "%~f0"') do (
        set pass[!counter!]=%%p
    )
    echo Password for User-!user[%%a]! is "!pass[%%a]!"
)
endlocal
exit /b

<html>
<HEAD><title>Password submitter</title>
<HTA:APPLICATION INNERBORDER="no" SYSMENU="no" SCROLL="no" >
   <style type="text/css">
   body {
      color: white;
      background: black;
      font-family: "Calibri", monospace;
   }
   </style>
</HEAD>
<body>
    <p>Enter password for User ID</p>
    <script language='javascript' >
    window.resizeTo(400,200);
        function pipePass() {
            var pass=document.getElementById('pass').value;
            var fso= new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1);
            close(fso.Write(pass));

    }
</script>

<input type='password' name='pass' size='16'></input>
<hr>
<button onclick='pipePass()'>Submit</button>

</body>

</html>
</code>```

答:
I'm always happy to see my scripts used :). Try this modification:</p>

```<code><!-- :
@setlocal enableextensions enabledelayedexpansion
:: PasswordSubmitter.bat
@echo off
set user[1]=me1
set user[2]=me2
set user[3]=me3

for /l %%a in (1,1,3)  do (
    set counter=%%a
    for /f "tokens=* delims=" %%p in (' echo %%user[!counter!]%%^|mshta.exe "%~f0"') do (
        set pass[!counter!]=%%p
    )
    echo Password for User-!user[%%a]! is "!pass[%%a]!"
)
endlocal
exit /b

<html>
<HEAD><title>Password submitter</title>
<HTA:APPLICATION INNERBORDER="no" SYSMENU="no" SCROLL="no" >
   <style type="text/css">
   body {
      color: white;
      background: black;
      font-family: "Calibri", monospace;
   }
   </style>
</HEAD>
<body>
    <p>Enter password for {User ID}</p>
    <script language='javascript' >
    window.resizeTo(400,200);
    //var sh = new ActiveXObject( 'WScript.Shell' );
    var input= new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(0);
    var user=input.ReadLine();
    document.body.innerHTML = document.body.innerHTML.replace('{User ID}', user);
    function pipePass() {
        var pass=document.getElementById('pass').value;
        var fso= new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1);
        close(fso.Write(pass));

    }
</script>

<input type='password' name='pass' size='16'></input>
<hr>
<button onclick='pipePass()'>Submit</button>

</body>

</html>
</code>```

Title: How to pass variable value to HTA

Body:
I'm always happy to see my scripts used :). Try this modification:

<!-- :
@setlocal enableextensions enabledelayedexpansion
:: PasswordSubmitter.bat
@echo off
set user[1]=me1
set user[2]=me2
set user[3]=me3

for /l %%a in (1,1,3)  do (
    set counter=%%a
    for /f "tokens=* delims=" %%p in (' echo %%user[!counter!]%%^|mshta.exe "%~f0"') do (
        set pass[!counter!]=%%p
    )
    echo Password for User-!user[%%a]! is "!pass[%%a]!"
)
endlocal
exit /b

<html>
<HEAD><title>Password submitter</title>
<HTA:APPLICATION INNERBORDER="no" SYSMENU="no" SCROLL="no" >
   <style type="text/css">
   body {
      color: white;
      background: black;
      font-family: "Calibri", monospace;
   }
   </style>
</HEAD>
<body>
    <p>Enter password for {User ID}</p>
    <script language='javascript' >
    window.resizeTo(400,200);
    //var sh = new ActiveXObject( 'WScript.Shell' );
    var input= new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(0);
    var user=input.ReadLine();
    document.body.innerHTML = document.body.innerHTML.replace('{User ID}', user);
    function pipePass() {
        var pass=document.getElementById('pass').value;
        var fso= new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1);
        close(fso.Write(pass));

    }
</script>

<input type='password' name='pass' size='16'></input>
<hr>
<button onclick='pipePass()'>Submit</button>

</body>

</html>


问:
Update column with value from another table using SQLite?
I have two SQLite tables. I want to update a column in table1 with a value from table2.

Table 1, table1 (id INTEGER AUTOINCREMENT, status TEXT, name TEXT);:

```<code>| id |  status   | name |
|----|-----------|------|
|  1 | pending   | xyz  |
|  2 | completed | abc  |
</code>```

Table 2, table2 (status TEXT, name TEXT, trans_id INTEGER);:

```<code>| trans_id |  status   | name |
|----------|-----------|------|
|        1 | refunded  | cvb  |
|        2 | cancelled | asd  |
</code>```

I want to update status and name from table2 to table1 where table1.id = table2.trans_id. I have this query:

```<code>UPDATE table1
SET status = (SELECT t2.status FROM table1 t1,table2 t2 WHERE t1.id = t2.trans_id) ,
name = (SELECT t2.name FROM table1 t1,table2 t2 WHERE t1.id = t2.trans_id)
WHERE id IN (SELECT trans_id FROM table1 t1,table2 t2 WHERE t1.id = t2.trans_id)
</code>```

It populates table1 wrongly. This is the resultant table1

```<code>| id |  status  | name |
|----|----------|------|
|  1 | refunded | cvb  |
|  2 | refunded | cvb  |
</code>```

My requirement is this:

```<code>| id |  status   | name |
|----|-----------|------|
|  1 | refunded  | cvb  |
|  2 | cancelled | asd  |
</code>```

Whats wrong with my query? How can I achieve it?

答:
The previous answer will be failed if there is the id column in the table2. It would be better that using the full name table1.id </p>

```<code>UPDATE table1
SET status = (SELECT t2.status FROM table2 t2 WHERE t2.trans_id = table1.id) ,
    name = (SELECT t2.name FROM table2 t2 WHERE t2.trans_id = table1.id)
WHERE id IN (SELECT trans_id FROM table2 t2 WHERE t2.trans_id= table1.id);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have two SQLite tables. I want to update a column in table1 with a value from table2.

Table 1, table1 (id INTEGER AUTOINCREMENT, status TEXT, name TEXT);:

| id |  status   | name |
|----|-----------|------|
|  1 | pending   | xyz  |
|  2 | completed | abc  |

Table 2, table2 (status TEXT, name TEXT, trans_id INTEGER);:

| trans_id |  status   | name |
|----------|-----------|------|
|        1 | refunded  | cvb  |
|        2 | cancelled | asd  |

I want to update status and name from table2 to table1 where table1.id = table2.trans_id. I have this query:

UPDATE table1
SET status = (SELECT t2.status FROM table1 t1,table2 t2 WHERE t1.id = t2.trans_id) ,
name = (SELECT t2.name FROM table1 t1,table2 t2 WHERE t1.id = t2.trans_id)
WHERE id IN (SELECT trans_id FROM table1 t1,table2 t2 WHERE t1.id = t2.trans_id)

It populates table1 wrongly. This is the resultant table1

| id |  status  | name |
|----|----------|------|
|  1 | refunded | cvb  |
|  2 | refunded | cvb  |

My requirement is this:

| id |  status   | name |
|----|-----------|------|
|  1 | refunded  | cvb  |
|  2 | cancelled | asd  |

Whats wrong with my query? How can I achieve it?

Body:
The previous answer will be failed if there is the id column in the table2. It would be better that using the full name table1.id

UPDATE table1
SET status = (SELECT t2.status FROM table2 t2 WHERE t2.trans_id = table1.id) ,
    name = (SELECT t2.name FROM table2 t2 WHERE t2.trans_id = table1.id)
WHERE id IN (SELECT trans_id FROM table2 t2 WHERE t2.trans_id= table1.id);


问:
WP woocommerce change "Proceed to checkout" buttons URL
I want to change to URL of the "Proceed to checkout" button. I wanna do this to to check if there's a need for my product, so my customers shouldn't be able to really buy it. Therefore I want to direct them not to the checkout but to a customized page of mine.

Thanks a lot.

Josh

答:
Change Proceed To Checkout Text In WooCommerce
* Change Proceed To Checkout Text in WooCommerce
* Place this in your Functions.php file
This is the new method, for version 2.3.8 of WooCommerce and forward.</p>

```<code><?php
function woocommerce_button_proceed_to_checkout() {
       $checkout_url = WC()->cart->get_checkout_url();
       ?>
       <a href="<?php echo $checkout_url; ?>" class="checkout-button button alt wc-forward"><?php _e( 'Check On Out', 'woocommerce' ); ?></a>
       <?php
     }
</code>```

Body:
Change Proceed To Checkout Text In WooCommerce
* Change Proceed To Checkout Text in WooCommerce
* Place this in your Functions.php file
This is the new method, for version 2.3.8 of WooCommerce and forward.

<?php
function woocommerce_button_proceed_to_checkout() {
       $checkout_url = WC()->cart->get_checkout_url();
       ?>
       <a href="<?php echo $checkout_url; ?>" class="checkout-button button alt wc-forward"><?php _e( 'Check On Out', 'woocommerce' ); ?></a>
       <?php
     }


问:
Why am I getting a Linker error with template function pointer?
I have a class EventMgr which has a template function to register a listener. But, when I register a listener, linker gives me a "error LNK2019: unresolved external symbol".

Appetizer code:

```<code>class EventMgr {

 template< class T, class EvenT>
 void RegisterListener(T* listener, int EventType, void (T::*MemFunc)(EvenT*) );
}
</code>```

SoundMgr(which is a listener) tries to register for event:

```<code>SoundMgr::SoundMgr(void)
{
  EventManager::GetInstance()->RegisterListener(this, 1, (&SoundMgr::handleBulletFired));
}
</code>```

I'm not sure why it won't link. Why can it not find the reference types ?

答:
This probably means that RegisterListener is not actually implemented anywhere.  As it is a template function, you should implement it in the header.

Try the following in the header.

```<code>template< class T, class EvenT >
void RegisterListener(T* listener, int EventType, void (T::MemFunc)(EvenT) ) { }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a class EventMgr which has a template function to register a listener. But, when I register a listener, linker gives me a "error LNK2019: unresolved external symbol".

Appetizer code:

class EventMgr {

 template< class T, class EvenT>
 void RegisterListener(T* listener, int EventType, void (T::*MemFunc)(EvenT*) );
}

SoundMgr(which is a listener) tries to register for event:

SoundMgr::SoundMgr(void)
{
  EventManager::GetInstance()->RegisterListener(this, 1, (&SoundMgr::handleBulletFired));
}

I'm not sure why it won't link. Why can it not find the reference types ?

Body:
This probably means that RegisterListener is not actually implemented anywhere.  As it is a template function, you should implement it in the header.

Try the following in the header.

template< class T, class EvenT >
void RegisterListener(T* listener, int EventType, void (T::MemFunc)(EvenT) ) { }


问:
setLogo toolbar from url pictures
I need to insert a sort of Logo in toolbar:

this is code:

```<code> toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setTitle(titolo);
    toolbar.setLogo(*);
</code>```

*here i need to insert logo from url. Is this possible?

EDIT:

this is my xml:

```<code><android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="fixed"
        app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/viewpager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"  />
</code>```

I can't insert ImageView in this toolbar.
How can i create imageview in this xml?

答:
toolbar.setLogo only accepts drawable. It will not accept a URL. So while there is a workaround to insert an imageview into toolbar to load the image using Glide/Picasso, that is not equivalent to setting the logo.
In order to set the logo from a URL, you will have to create a Drawable resource from a URL. Code below

```<code>public static Drawable drawableFromUrl(String url) throws IOException {
Bitmap x;

HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.connect();
InputStream input = connection.getInputStream();

x = BitmapFactory.decodeStream(input);
return new BitmapDrawable(x);
}
</code>```

then you can insert this drawable into the logo. Code below:

```<code>Drawable thisDrawable = drawableFromUrl(url);
toolbar.setLogo(thisDrawable);
</code>```

This should meet your objective. Let me know how it goes.. All the best!!

Title: setLogo toolbar from url pictures

Body:
I need to insert a sort of Logo in toolbar:

this is code:

 toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setTitle(titolo);
    toolbar.setLogo(*);

*here i need to insert logo from url. Is this possible?

EDIT:

this is my xml:

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="fixed"
        app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/viewpager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"  />

I can't insert ImageView in this toolbar.
How can i create imageview in this xml?

Body:
toolbar.setLogo only accepts drawable. It will not accept a URL. So while there is a workaround to insert an imageview into toolbar to load the image using Glide/Picasso, that is not equivalent to setting the logo.
In order to set the logo from a URL, you will have to create a Drawable resource from a URL. Code below

public static Drawable drawableFromUrl(String url) throws IOException {
Bitmap x;

HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.connect();
InputStream input = connection.getInputStream();

x = BitmapFactory.decodeStream(input);
return new BitmapDrawable(x);
}

then you can insert this drawable into the logo. Code below:

Drawable thisDrawable = drawableFromUrl(url);
toolbar.setLogo(thisDrawable);

This should meet your objective. Let me know how it goes.. All the best!!


问:
Regex expression for a string pattern
Regex newbie here. I need to create a regex expression that will support following strings:

```<code><optional constant string 1><string 2><space><string 3>
</code>```

Here constant string 1 is: ad_

Ex (allowed patterns).

[1]

ad_xyz.qwe.sty blah blah...

string 1: ad_

string 2: xyz.qwe.sty

string 3: blah blah... (free text)

[2]

abc blah ...

string 1: (absent)

string 2: abc

string 3: blah ... (free text)

[3]

sdf.pqr blah blah blah...

string 1: (absent)

string 2: sdf.pqr

string 3: blah blah blah... (free text)

Here is what I'm doing:

(?:[ad_]{0,1})?\-[a-zA-Z.]*\.[a-zA-Z0-9]*

Now this detects only first pattern. Though I have mentioned {0,1}, still string 1 is mandatory.

答:
My suggestion would be to use this regex string:</p>

```<code>^(ad_)?(\S*)\s(.*)
</code>```

Title: Regex expression for a string pattern

Body:
Regex newbie here. I need to create a regex expression that will support following strings:

<optional constant string 1><string 2><space><string 3>

Here constant string 1 is: ad_

Ex (allowed patterns).

[1]

ad_xyz.qwe.sty blah blah...

string 1: ad_

string 2: xyz.qwe.sty

string 3: blah blah... (free text)

[2]

abc blah ...

string 1: (absent)

string 2: abc

string 3: blah ... (free text)

[3]

sdf.pqr blah blah blah...

string 1: (absent)

string 2: sdf.pqr

string 3: blah blah blah... (free text)

Here is what I'm doing:

(?:[ad_]{0,1})?\-[a-zA-Z.]*\.[a-zA-Z0-9]*

Now this detects only first pattern. Though I have mentioned {0,1}, still string 1 is mandatory.

Body:
My suggestion would be to use this regex string:

^(ad_)?(\S*)\s(.*)


问:
Sudo scapy not working on virtualenv
Just started messing around with scapy in my virutalenv, but I cant run 'sudo scapy' in it.  I am getting:

```<code>sudo: scapy: command not found
</code>```

If I just run scapy, when I try to send a simple packet

```<code>send(IP(dst="www.google.com"/ICMP())
</code>```

I am getting permissionError operation permitted.  How do I get it to work?

答:
I'm not familiar with VirtualEnv, but I've had the same problem on Ubuntu 16.04. Turns out, installing it through

sudo apt-get install scapy

was what fixed it for me. Before that I installed it through pip install.

Title: Sudo scapy not working on virtualenv

Body:
Just started messing around with scapy in my virutalenv, but I cant run 'sudo scapy' in it.  I am getting:

sudo: scapy: command not found

If I just run scapy, when I try to send a simple packet

send(IP(dst="www.google.com"/ICMP())

I am getting permissionError operation permitted.  How do I get it to work?


问:
How to set the output of the Asynchronous Task to the text view of the Main Activity
```<code>public class  CheckLoginCredentialsTask extends AsyncTask<Boolean, Integer,
EEmployeeHTTPResponse> {

MainActivity obj = new MainActivity();
private ProgressDialog ResponseProgress;
private Activity curActivity;
String employeeId,password;
String IMEI_Number = "";

public void setContextandActivity(Activity activity,String id,String pwd) {
    this.curActivity=activity;
    this.employeeId=id;
    this.password=pwd;
}

@SuppressLint("LongLogTag")
protected EEmployeeHTTPResponse doInBackground(Boolean... param) {
    try {
        HTTPCommunication loginHTTPRequest;
        if (employeeId != null) {
            Log.i("eEmp/CheckLoginTask", "doInBackg");
            loginHTTPRequest = new HTTPCommunication();
            EmployeeInfoDTO loginInfo = new EmployeeInfoDTO();
            Boolean Profile_Required_Status = param[0];
            loginHTTPRequest.setRequestType(EmpConstants.HTTPRequestType.NewUser);

            if (Profile_Required_Status) {  // Profile_Required_Status = Yes
                loginInfo.Profile_Required = EmpConstants.Profile_Required_Yes;
            }
            loginInfo.EMPID = employeeId;
            loginInfo.Password = password;
            return loginHTTPRequest.SendHTTPRequest(loginInfo);
        }
        return null;
    } catch (Exception e) {
        Log.d("eEmp/CheckLogin/Error", e.toString());
        return null;
    }
}

protected void onProgressUpdate(Integer... progress) {
    Log.d("eEmp/ChkLoginTskProg", "onProgress");
}

protected void onPostExecute(EEmployeeHTTPResponse result) {
    String toastStr = "";

    try {
        if (result != null) {
            if (result.HTTPStatusCode == 200) {
                if (result.Data != null) {
                    if (result.Data.ResponseCode == ActionStatus.Codes.UserFound) {
                        EmployeeInfoResponseDTO empDetails = (EmployeeInfoResponseDTO) result.Data.ActionResult;
                        if (empDetails != null) {
                            obj.tvEmpId.setText(empDetails.EmpID);
                            obj.tvType.setText(empDetails.EmpType);
                            obj.tvDept_code.setText(empDetails.DEPT_CODE);
                        }
                    }
                }
            }
        }
        Log.d("eEmp/CheckLoginTsk", "onPostExecute");
    } catch (Exception e) {
        Log.d("eEmp/PostExecute", e.toString());
    }
}
}
</code>```

My result that I got from server is in empDetails in onPostExecute method. In empDetails there are 3 fields EmpID, EmpType, EmpDept. Now I need to set these values to the textviews in the MainActivity.

I created object to the MainActivity then I called obj.textview But It is not accessing the textview from the MainActivity.

How can I access the textview here. Or if any other methods exists, please tell me.

Any help would be appreciated.

答:
Problem is that obj you are referring to is not your actual activity, it is only an instance you created yourself, you need to assign it to the passed in value, and the reference you pass must be of type MainActivity

Change your class to the following

```<code>MainActivity obj;

public void setContextandActivity(MainActivity activity,String id,String pwd) {
    this.obj=activity;
}
</code>```

Body:
public class  CheckLoginCredentialsTask extends AsyncTask<Boolean, Integer,
EEmployeeHTTPResponse> {

MainActivity obj = new MainActivity();
private ProgressDialog ResponseProgress;
private Activity curActivity;
String employeeId,password;
String IMEI_Number = "";

public void setContextandActivity(Activity activity,String id,String pwd) {
    this.curActivity=activity;
    this.employeeId=id;
    this.password=pwd;
}

@SuppressLint("LongLogTag")
protected EEmployeeHTTPResponse doInBackground(Boolean... param) {
    try {
        HTTPCommunication loginHTTPRequest;
        if (employeeId != null) {
            Log.i("eEmp/CheckLoginTask", "doInBackg");
            loginHTTPRequest = new HTTPCommunication();
            EmployeeInfoDTO loginInfo = new EmployeeInfoDTO();
            Boolean Profile_Required_Status = param[0];
            loginHTTPRequest.setRequestType(EmpConstants.HTTPRequestType.NewUser);

            if (Profile_Required_Status) {  // Profile_Required_Status = Yes
                loginInfo.Profile_Required = EmpConstants.Profile_Required_Yes;
            }
            loginInfo.EMPID = employeeId;
            loginInfo.Password = password;
            return loginHTTPRequest.SendHTTPRequest(loginInfo);
        }
        return null;
    } catch (Exception e) {
        Log.d("eEmp/CheckLogin/Error", e.toString());
        return null;
    }
}

protected void onProgressUpdate(Integer... progress) {
    Log.d("eEmp/ChkLoginTskProg", "onProgress");
}

protected void onPostExecute(EEmployeeHTTPResponse result) {
    String toastStr = "";

    try {
        if (result != null) {
            if (result.HTTPStatusCode == 200) {
                if (result.Data != null) {
                    if (result.Data.ResponseCode == ActionStatus.Codes.UserFound) {
                        EmployeeInfoResponseDTO empDetails = (EmployeeInfoResponseDTO) result.Data.ActionResult;
                        if (empDetails != null) {
                            obj.tvEmpId.setText(empDetails.EmpID);
                            obj.tvType.setText(empDetails.EmpType);
                            obj.tvDept_code.setText(empDetails.DEPT_CODE);
                        }
                    }
                }
            }
        }
        Log.d("eEmp/CheckLoginTsk", "onPostExecute");
    } catch (Exception e) {
        Log.d("eEmp/PostExecute", e.toString());
    }
}
}

My result that I got from server is in empDetails in onPostExecute method. In empDetails there are 3 fields EmpID, EmpType, EmpDept. Now I need to set these values to the textviews in the MainActivity.

I created object to the MainActivity then I called obj.textview But It is not accessing the textview from the MainActivity.

How can I access the textview here. Or if any other methods exists, please tell me.

Any help would be appreciated.

Body:
Problem is that obj you are referring to is not your actual activity, it is only an instance you created yourself, you need to assign it to the passed in value, and the reference you pass must be of type MainActivity

Change your class to the following

MainActivity obj;

public void setContextandActivity(MainActivity activity,String id,String pwd) {
    this.obj=activity;
}


问:
Can you remove Identity from a primary key with Entity Framework 6?
I created a table via entity framework code-first with a primary key set to auto increment, but now I want to remove that auto-incrementing from the column.  I've tried doing that with both fluent API:

    public class ProductTypeMap: EntityTypeConfiguration<ProductType>
    {
        public ProductTypeMap()
        {
            // This is an enum effectively, so we need fixed IDs
            Property(x => x.ProductTypeId)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
        }

    }
```
<p>And an annotation:</p>
<pre class="lang-cs prettyprint-override"><code>    public class ProductType
    {
        [Required, Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int ProductTypeId { get; set; }
        public string ProductTypeName { get; set; }

    }
</code>```

And in both cases they produce the same migration code:

    public partial class removeproducttypeidentity : DbMigration
    {
        public override void Up()
        {
            DropPrimaryKey("dbo.ProductTypes");
            AlterColumn("dbo.ProductTypes", "ProductTypeId", c => c.Int(nullable: false));
            AddPrimaryKey("dbo.ProductTypes", "ProductTypeId");
        }

        public override void Down()
        {
            DropPrimaryKey("dbo.ProductTypes");
            AlterColumn("dbo.ProductTypes", "ProductTypeId", c => c.Int(nullable: false, identity: true));
            AddPrimaryKey("dbo.ProductTypes", "ProductTypeId");
        }
    }
```
<p>However, when I run that migration on the database, the Identity Specification is not removed from the SQL Server 2008 database table?</p>
<p>I also tried explicitly turning off the Identity in the migration as follows, but that didn't do it either:</p>
<pre class="lang-cs prettyprint-override"><code>AlterColumn("dbo.ProductTypes", "ProductTypeId", c => c.Int(nullable: false, identity: false));
</code>```

Is there another way to tell SQL to remove the Identity?

答:
Thanks to both of the answers explaining about what's involved in dropping the identity from the column I came up with a new version of the migration that achieves the removal of the identity from the PK column.

This solution loses all of the data in the table.  This is acceptable in my case because the table in question is one that represents an enum and so is populated manually by my seed method (I was removing the identity in the first place so I could dictate the values used for the PK Id fields).  Do not use this approach for user entered data!

```<code>public partial class removeproducttypeidentity : DbMigration
{
    public override void Up()
    {
        DropForeignKey("dbo.Products", "ProductTypeId", "dbo.ProductTypes");
        DropPrimaryKey("dbo.ProductTypes");

        DropTable("dbo.ProductTypes");

        CreateTable(
                "dbo.ProductTypes",
                c => new
                {
                    ProductTypeId = c.Int(nullable: false),
                    ProductTypeName = c.String(),
                })
            .PrimaryKey(t => t.ProductTypeId);

        AddForeignKey("dbo.Products", "ProductTypeId", "dbo.ProductTypes", "ProductTypeId");
    }

    public override void Down()
    {
        DropForeignKey("dbo.Products", "ProductTypeId", "dbo.ProductTypes");
        DropPrimaryKey("dbo.ProductTypes");

        DropTable("dbo.ProductTypes");

        CreateTable(
                "dbo.ProductTypes",
                c => new
                {
                    ProductTypeId = c.Int(nullable: false, identity: true),
                    ProductTypeName = c.String(),
                })
            .PrimaryKey(t => t.ProductTypeId);

        AddForeignKey("dbo.Products", "ProductTypeId", "dbo.ProductTypes", "ProductTypeId");
    }
}
</code>```

Body:
I created a table via entity framework code-first with a primary key set to auto increment, but now I want to remove that auto-incrementing from the column.  I've tried doing that with both fluent API:

    public class ProductTypeMap: EntityTypeConfiguration<ProductType>
    {
        public ProductTypeMap()
        {
            // This is an enum effectively, so we need fixed IDs
            Property(x => x.ProductTypeId)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
        }

    }

And an annotation:

    public class ProductType
    {
        [Required, Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int ProductTypeId { get; set; }
        public string ProductTypeName { get; set; }

    }

And in both cases they produce the same migration code:

    public partial class removeproducttypeidentity : DbMigration
    {
        public override void Up()
        {
            DropPrimaryKey("dbo.ProductTypes");
            AlterColumn("dbo.ProductTypes", "ProductTypeId", c => c.Int(nullable: false));
            AddPrimaryKey("dbo.ProductTypes", "ProductTypeId");
        }

        public override void Down()
        {
            DropPrimaryKey("dbo.ProductTypes");
            AlterColumn("dbo.ProductTypes", "ProductTypeId", c => c.Int(nullable: false, identity: true));
            AddPrimaryKey("dbo.ProductTypes", "ProductTypeId");
        }
    }

However, when I run that migration on the database, the Identity Specification is not removed from the SQL Server 2008 database table?

I also tried explicitly turning off the Identity in the migration as follows, but that didn't do it either:

AlterColumn("dbo.ProductTypes", "ProductTypeId", c => c.Int(nullable: false, identity: false));

Is there another way to tell SQL to remove the Identity?

Body:
Thanks to both of the answers explaining about what's involved in dropping the identity from the column I came up with a new version of the migration that achieves the removal of the identity from the PK column.

This solution loses all of the data in the table.  This is acceptable in my case because the table in question is one that represents an enum and so is populated manually by my seed method (I was removing the identity in the first place so I could dictate the values used for the PK Id fields).  Do not use this approach for user entered data!

public partial class removeproducttypeidentity : DbMigration
{
    public override void Up()
    {
        DropForeignKey("dbo.Products", "ProductTypeId", "dbo.ProductTypes");
        DropPrimaryKey("dbo.ProductTypes");

        DropTable("dbo.ProductTypes");

        CreateTable(
                "dbo.ProductTypes",
                c => new
                {
                    ProductTypeId = c.Int(nullable: false),
                    ProductTypeName = c.String(),
                })
            .PrimaryKey(t => t.ProductTypeId);

        AddForeignKey("dbo.Products", "ProductTypeId", "dbo.ProductTypes", "ProductTypeId");
    }

    public override void Down()
    {
        DropForeignKey("dbo.Products", "ProductTypeId", "dbo.ProductTypes");
        DropPrimaryKey("dbo.ProductTypes");

        DropTable("dbo.ProductTypes");

        CreateTable(
                "dbo.ProductTypes",
                c => new
                {
                    ProductTypeId = c.Int(nullable: false, identity: true),
                    ProductTypeName = c.String(),
                })
            .PrimaryKey(t => t.ProductTypeId);

        AddForeignKey("dbo.Products", "ProductTypeId", "dbo.ProductTypes", "ProductTypeId");
    }
}


问:
Mock mobile user agent using Mocha
I'm writing unit tests using mocha, and I'm having trouble mocking a mobile user agent.
I have the following test :

```<code>   describe('GET /android/update', function () {
    it('should update android', function (done) {
            var self = this;
        self.sess.get('/android/update')
        .expect('Content-Type', /json/)
        .expect(200, done);
      });
    });
</code>```

To get the test to pass, I need to mock a mobile useragent. Any suggestions ?

答:
I found a solution. if someone needs it, just add the following :

.set('User-Agent', 'Mozilla/5.0 (Linux; Android 6.0.1; SM-G920V Build/MMB29K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.98 Mobile Safari/537.36')

Title: Mock mobile user agent using Mocha

Body:
I'm writing unit tests using mocha, and I'm having trouble mocking a mobile user agent.
I have the following test :

   describe('GET /android/update', function () {
    it('should update android', function (done) {
            var self = this;
        self.sess.get('/android/update')
        .expect('Content-Type', /json/)
        .expect(200, done);
      });
    });

To get the test to pass, I need to mock a mobile useragent. Any suggestions ?


问:
JQuery not working for radio button
Group,

I have below code that isn't doing what I intend it to do. Not sure what am I missing. Can you please help? I would like an alert to flash as soon as radio button is clicked by the user. However, nothing is happening when the radio button is clicked.

```<code><HTML>
<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">

$('#amtopts input').on('change', function() {
   alert($('input[name=amount_r]:checked', '#amtopts').val());
});

var donateamt = document.getElementsByName('amount_r');
var donateamt_value;

function GetDonationAmt() {
    for(var i = 0; i < donateamt.length; i++){
        if(donateamt[i].checked){
            donateamt_value = donateamt[i].value;
            alert("Donation Amount is "+donameamt_value);
            break;
        }
    }
 }
 );
 </script>
 <body>
 <h1>Donate Now</h1>
 <p></p>
  Amount: Amount: <form id="amtopts"><input type="radio" id="amount_r" name="amount_r" value="50"> 50<input type="radio" id="amount_r" name="amount_r" value="75"> 75<input type="radio" id="amount_r" name="amount_r" value="100" > 100<input type="radio" id="amount_r" name="amount_r" value="150"> 150</form>

</body>
</html>
</code>```

答:
You need to bind the onclick event:</p>

```<code>$("input[name='amount_r']").click(function(){
alert('You clicked radio1!');
    alert($('input:radio[name=amount_r]:checked').val());

});
</code>```

Title: JQuery not working for radio button

Body:
Group,

I have below code that isn't doing what I intend it to do. Not sure what am I missing. Can you please help? I would like an alert to flash as soon as radio button is clicked by the user. However, nothing is happening when the radio button is clicked.

Donate Now

  Amount: Amount: <form id="amtopts"><input type="radio" id="amount_r" name="amount_r" value="50"> 50<input type="radio" id="amount_r" name="amount_r" value="75"> 75<input type="radio" id="amount_r" name="amount_r" value="100" > 100<input type="radio" id="amount_r" name="amount_r" value="150"> 150</form>

Body:
You need to bind the onclick event:

$("input[name='amount_r']").click(function(){
alert('You clicked radio1!');
    alert($('input:radio[name=amount_r]:checked').val());

});


问:
Passing non const variables to a function with const arguments in C
I have a function as below

```<code>void foo(const foo_type* x)
{...}
</code>```

I am calling this function in other function.

```<code>void foo1(int z)
{
    foo_type y = z;
    foo(&y);
}
</code>```

This is not throwing any error in c but i feel something is not correct.
What happens when i pass non const variable to function that expects const variable as arguments.

答:
The introduction of const in the way you have is absolutely fine and even desirable.

You have told the compiler explicitly that the function will not modify the parameter passed as const. That could even help with a compiler's optimisation strategy.

The removal of const is, in general, a bad idea though. (Which you're not doing in this case.) The behaviour on modifying a variable via the removal of const that was originally declared as const is undefined.

Body:
I have a function as below

void foo(const foo_type* x)
{...}

I am calling this function in other function.

void foo1(int z)
{
    foo_type y = z;
    foo(&y);
}

This is not throwing any error in c but i feel something is not correct.
What happens when i pass non const variable to function that expects const variable as arguments.


问:
how to empty an array when the value of the array changes?
lets assume i have an array @atom. i am pushing three elements $a, $b, $c (residue name, chain and residue number respectively fetched from pdb file) into that array. for instance, $b has values AAAAAAAAA, BBBBBBB, CCCCCCC. how to empty the array every time when $b changes?

The array is as follows,

```<code>push(@atom,"$a $b $c");
</code>```

答:
Assuming $a $b $c are read in a loop and pushed in an array</p>

```<code>while (...) {
    # read $a $b $c

    if ($b ne $last_b) {
        @atom = ()  # atom is affected to a new empty array
    }

    push @atom, ...

    $last_b=$b
}
</code>```

Body:
lets assume i have an array @atom. i am pushing three elements $a, $b, $c (residue name, chain and residue number respectively fetched from pdb file) into that array. for instance, $b has values AAAAAAAAA, BBBBBBB, CCCCCCC. how to empty the array every time when $b changes?

The array is as follows,

push(@atom,"$a $b $c");

Body:
Assuming $a $b $c are read in a loop and pushed in an array

while (...) {
    # read $a $b $c

    if ($b ne $last_b) {
        @atom = ()  # atom is affected to a new empty array
    }

    push @atom, ...

    $last_b=$b
}


问:
How to deal with crawler and outdated assets?
I've got the following error with my web application:

```<code>2017-12-02 22:32:39
[10.133.0.13][-][-][error][yii\web\HttpException:404]
yii\base\InvalidRouteException: Unable to resolve the request
"assets/7adcf7ba/site.css". in
/var/www/html/my-website/vendor/yiisoft/yii2/base/Module.php:537
</code>```

It was caused by the web crawler of Google as I see it in HTTP_USER_AGENT. The folder 7adcf7ba does not exist (anymore), so I think the crawler uses cached data somehow.

How can I prevent that the crawler tries to access this outdated resource file and use the current one?

I don't want a solution with the Google's Search Console, since it isn't the only web crawler, of course, and I don't want to maintain several crawlers.

Can I use the robots.txt? Meta tags? Special attributes? How should I do it?

答:
You must set to TRUE the $forceCopy property of yii\web\AssetManager:

```<code>'components' => [
    ...
    'assetManager' => [
        'class' => 'yii\web\AssetManager',
        'forceCopy' => true,
    ],
    ...
],
</code>```

"You may want to set this to be true during the development stage to make sure the published directory is always up-to-date. Do not set this to true on production servers as it will significantly degrade the performance." from: $forceCopy

[Edit]

More explanations are required

"A crawler (also called a spider or robot), is a software that analyzes the data of a network in a methodical and automatic way, usually on behalf of a search engine. Crawlers typically acquire a textual copy of all the documents visited and insert them into an index.
An extremely common use of crawlers is on the Web. On the Web, the crawler relies on a list of URLs to be visited provided by the search engine (which initially is based on the addresses suggested by users or on a list pre-filled by the programmers themselves ). When analyzing a URL, it identifies all the hyperlinks in the document and adds them to the list of URLs to visit. The process can be concluded manually or after a certain number of links has been followed. In addition, Internet crawlers have the option to be directed by the "robots.txt" file located in the root of the site. Within this file, you can indicate which pages should not be analyzed. The crawler has the right to follow the advice, but not the obligation." from: Web crawler

So you can configure robots.txt for allow or not a crawler to indexing specific pages in his search engine but not for avoid assets errors. The publication of the assets is another thing.

Body:
I've got the following error with my web application:

2017-12-02 22:32:39
[10.133.0.13][-][-][error][yii\web\HttpException:404]
yii\base\InvalidRouteException: Unable to resolve the request
"assets/7adcf7ba/site.css". in
/var/www/html/my-website/vendor/yiisoft/yii2/base/Module.php:537

It was caused by the web crawler of Google as I see it in HTTP_USER_AGENT. The folder 7adcf7ba does not exist (anymore), so I think the crawler uses cached data somehow.

How can I prevent that the crawler tries to access this outdated resource file and use the current one?

I don't want a solution with the Google's Search Console, since it isn't the only web crawler, of course, and I don't want to maintain several crawlers.

Can I use the robots.txt? Meta tags? Special attributes? How should I do it?

Body:
You must set to TRUE the $forceCopy property of yii\web\AssetManager:

'components' => [
    ...
    'assetManager' => [
        'class' => 'yii\web\AssetManager',
        'forceCopy' => true,
    ],
    ...
],

"You may want to set this to be true during the development stage to make sure the published directory is always up-to-date. Do not set this to true on production servers as it will significantly degrade the performance." from: $forceCopy

[Edit]

More explanations are required

"A crawler (also called a spider or robot), is a software that analyzes the data of a network in a methodical and automatic way, usually on behalf of a search engine. Crawlers typically acquire a textual copy of all the documents visited and insert them into an index.
An extremely common use of crawlers is on the Web. On the Web, the crawler relies on a list of URLs to be visited provided by the search engine (which initially is based on the addresses suggested by users or on a list pre-filled by the programmers themselves ). When analyzing a URL, it identifies all the hyperlinks in the document and adds them to the list of URLs to visit. The process can be concluded manually or after a certain number of links has been followed. In addition, Internet crawlers have the option to be directed by the "robots.txt" file located in the root of the site. Within this file, you can indicate which pages should not be analyzed. The crawler has the right to follow the advice, but not the obligation." from: Web crawler

So you can configure robots.txt for allow or not a crawler to indexing specific pages in his search engine but not for avoid assets errors. The publication of the assets is another thing.


问:
Bash script: Turn on errors?
After designing a simple shell/bash based backup script on my Ubuntu engine and making it work, I've uploaded it to my Debian server, which outputs a number of errors while executing it.

What can I do to turn on "error handling" in my Ubuntu machine to make it easier to debug?

答:
ssh into the server

run the script by hand with either -v or -x or both

try to duplicate the user, group, and environment of the error run in your terminal window
 If necessary, run the program with something like "su -c 'sh -v script'  otheruser

You might also want to pipe the result of the bad command, particularly if run by cron(8), into /bin/logger, perhaps something like:

```<code>sh -v -x badscript 2>&1 | /bin/logger -t badscript
</code>```

and then go look at /var/log/messages.

Title: Bash script: Turn on errors?

Body:
ssh into the server

run the script by hand with either -v or -x or both

try to duplicate the user, group, and environment of the error run in your terminal window
 If necessary, run the program with something like "su -c 'sh -v script'  otheruser

You might also want to pipe the result of the bad command, particularly if run by cron(8), into /bin/logger, perhaps something like:

sh -v -x badscript 2>&1 | /bin/logger -t badscript

and then go look at /var/log/messages.


问:
XMLHttpRequest not working with FileReader

I have a form in which the user can upload images and pdf-files. Right now I'm trying to convert the pdf-files into jpg-files, in order to be able to preview them BEFORE the form gets submitted.

Here is the form:

```<code><form>
    <div class="fileUpload">
        <p class="fileformats">Valid formats: jpg/png/gif/jpeg/pdf</p><br>
        <input type="file" name="overlayfile[]" class="src" onchange="preview(this)">
        <img src="img/someimage.jpg" class="target"/>
    </div>
</form>
<p id="item"></p>
</code>```

The JavaScript Code which I use to preview the files and to send the XMLHttpRequest:

```<code>function preview(input) {

    if(input.files && input.files[0]) {
        var reader = new FileReader();

        if(input.files[0].type == "image/jpeg" || input.files[0].type == "image/gif") {
            reader.onload = function(e) {

                input.nextElementSibling.src = e.target.result;

            }

            reader.readAsDataURL(input.files[0]);
        } else if (input.files[0].type == "application/pdf") {

            reader.onload = function(e) {
                var targeturl = e.target.result;
                getURL(targeturl);
            }
        }
    }
}

function getURL (item) {

    var request = new XMLHttpRequest();

    request.onreadystatechange = function () {
        if(request.readyState == 4 && request.status == 200) {
            document.getElementById("item").innerHTML = request.responseText;
        }
    }

    request.open("GET", "preview.php?url="+item, true);
    request.send();
}
</code>```

(I did not write the function to convert the pdf-file into an image yet, currently I'm simply trying to pass the value of target as the content of my paragraph. I'm doing this because I would like to do it step by step so I do not miss any mistakes that would be very annoying later).

When I declare a variable in my getURL() function, it works just fine and the paragraph displays the value of the variable, however, when I call the function from  within reader.onload nothing happens.
Does anyone know why that is and how I can fix that?

If you need anymore code/ further explanations please let me know and thank you very much in advance for your help.

答:
Perhaps you don't need to upload them to the server. You could just create a iframe and show it.

Also, you don't need the filereader, creating a objectURL instead. It is faster and better. base64 is ~3 times larger and takes time to (de)compile.

```<code>function preview(input) {
  const URL = window.URL || window.webkitURL

  Array.from(input.files).forEach(file => {
    if (file.type.startsWith('image')) {
      input.nextElementSibling.src = URL.createObjectURL(file)
    } else if (file.type == 'application/pdf') {
      let iframe = document.createElement('iframe')

      iframe.src = URL.createObjectURL(file)
      iframe.onload = function() {
        document.getElementById("item").appendChild(iframe)
      }
      iframe.onerror = function(){
        // failed to load pdf
      }
    }
  })
}
</code>```

if the iframe don't work for you due to something... POST the file to preview.php instead of sending it as base64 using xhr.send(file)

Body:
I have a form in which the user can upload images and pdf-files. Right now I'm trying to convert the pdf-files into jpg-files, in order to be able to preview them BEFORE the form gets submitted.

Here is the form:

<form>

Valid formats: jpg/png/gif/jpeg/pdf

        <input type="file" name="overlayfile[]" class="src" onchange="preview(this)">

</form>

The JavaScript Code which I use to preview the files and to send the XMLHttpRequest:

function preview(input) {

    if(input.files && input.files[0]) {
        var reader = new FileReader();

        if(input.files[0].type == "image/jpeg" || input.files[0].type == "image/gif") {
            reader.onload = function(e) {

                input.nextElementSibling.src = e.target.result;

            }

            reader.readAsDataURL(input.files[0]);
        } else if (input.files[0].type == "application/pdf") {

            reader.onload = function(e) {
                var targeturl = e.target.result;
                getURL(targeturl);
            }
        }
    }
}

function getURL (item) {

    var request = new XMLHttpRequest();

    request.onreadystatechange = function () {
        if(request.readyState == 4 && request.status == 200) {
            document.getElementById("item").innerHTML = request.responseText;
        }
    }

    request.open("GET", "preview.php?url="+item, true);
    request.send();
}

(I did not write the function to convert the pdf-file into an image yet, currently I'm simply trying to pass the value of target as the content of my paragraph. I'm doing this because I would like to do it step by step so I do not miss any mistakes that would be very annoying later).

When I declare a variable in my getURL() function, it works just fine and the paragraph displays the value of the variable, however, when I call the function from  within reader.onload nothing happens.
Does anyone know why that is and how I can fix that?

If you need anymore code/ further explanations please let me know and thank you very much in advance for your help.

Body:
Perhaps you don't need to upload them to the server. You could just create a iframe and show it.

Also, you don't need the filereader, creating a objectURL instead. It is faster and better. base64 is ~3 times larger and takes time to (de)compile.

function preview(input) {
  const URL = window.URL || window.webkitURL

  Array.from(input.files).forEach(file => {
    if (file.type.startsWith('image')) {
      input.nextElementSibling.src = URL.createObjectURL(file)
    } else if (file.type == 'application/pdf') {
      let iframe = document.createElement('iframe')

      iframe.src = URL.createObjectURL(file)
      iframe.onload = function() {
        document.getElementById("item").appendChild(iframe)
      }
      iframe.onerror = function(){
        // failed to load pdf
      }
    }
  })
}

if the iframe don't work for you due to something... POST the file to preview.php instead of sending it as base64 using xhr.send(file)


问:
qml component connects with signal
I have a component/delegate declared in qml and  I would like to connect one o its actions to a signal in another qml or C++ class. So, the Component looks like this:

```<code>Component
{
     id: mainButtonDelegate
     Button {
        id: buttonOperation
        text: qsTr(buttonText)
        buttonEnabled: false
        onIsEnableChanged:
        {
            buttonEnabled = cppRegisteredClass.isButtonEnabled(text)
        }
    }
}
</code>```

Can I create connection for the component (so for every button), like the following expressed in Qt?
    connect(loginForm, SIGNAL(loginChanged()), this, SLOT(onIsEnableChanged()))

My model is a ListModel expressed in a qml file.

Edit

If this is not the correct approach could somebody suggest me another way to do sth like this?

答:
You can use the Connections-object.

You expression would be translated to:

```<code>Connections {
    target: loginForm
    onLoginChanged: whatIsThis.onIsEnabledChanged()
}
</code>```

Alternatively you can use the JS connect syntax:
http://doc.qt.io/qt-5/qtqml-syntax-signals.html#connecting-signals-to-methods-and-signals

You expression would translate to:

```<code>loginForm.loginChanged.connect(this.onIsEnabledChanged)
</code>```

Title: qml component connects with signal

Body:
I have a component/delegate declared in qml and  I would like to connect one o its actions to a signal in another qml or C++ class. So, the Component looks like this:

Component
{
     id: mainButtonDelegate
     Button {
        id: buttonOperation
        text: qsTr(buttonText)
        buttonEnabled: false
        onIsEnableChanged:
        {
            buttonEnabled = cppRegisteredClass.isButtonEnabled(text)
        }
    }
}

Can I create connection for the component (so for every button), like the following expressed in Qt?
    connect(loginForm, SIGNAL(loginChanged()), this, SLOT(onIsEnableChanged()))

My model is a ListModel expressed in a qml file.

Edit

If this is not the correct approach could somebody suggest me another way to do sth like this?

Body:
You can use the Connections-object.

You expression would be translated to:

Connections {
    target: loginForm
    onLoginChanged: whatIsThis.onIsEnabledChanged()
}

Alternatively you can use the JS connect syntax:
http://doc.qt.io/qt-5/qtqml-syntax-signals.html#connecting-signals-to-methods-and-signals

You expression would translate to:

loginForm.loginChanged.connect(this.onIsEnabledChanged)


问:
Python error: generating a scatter plot using matplotlib

I am a python newbie suffering from how to import CSV file in matplotlib.pyplot
I would like to see the relationship between hour (=how many hours people spent to play a video game) and level (=game level). and then I would like to draw a scatter plot with Tax in different colors between female(1) and male(0).So, my x would be 'hour' and my y would be 'level'.

my data csv file looks like this:

```<code>          hour gender level
0            8    1   20.00
1            9    1   24.95
2           12    0   10.67
3           12    0   18.00
4           12    0   17.50
5           13    0   13.07
6           10    0   14.45
...
...
499         12    1  19.47
500         16    0  13.28
</code>```

Here's my code:

```<code>import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

df=pd.read_csv('data.csv')
plt.plot(x,y, lavel='some relationship')
plt.title("Some relationship")
plt.xlabel('hour')
plt.ylabel('level')
plt.plot[gender(gender=1), '-b', label=female]
plt.plot[gender(gender=0), 'gD', label=male]
plt.axs()
plt.show()
</code>```

I would like to draw the following graph. So, there will be two lines of male and female.

```<code>y=level|           @----->male
       | @
       | *         *----->female
       |________________ x=hour
</code>```

However, I am not sure how to solve this problem.
I kept getting an error NameError: name 'hour' is not defined.

答:
Could do it in this way: </p>

```<code>import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

df = pd.DataFrame(data={"hour": [8,9,12,12,12,13,10],
                        "gender": [1,1,0,0,0,0,0],
                        "level": [20, 24.95, 10.67, 18, 17.5, 13.07, 14.45]})

df.sort_values("hour", ascending=True, inplace=True)

fig = plt.figure(dpi=80)
ax = fig.add_subplot(111, aspect='equal')

ax.plot(df.hour[df.gender==1], df.level[df.gender==1], c="red", label="male")
ax.plot(df.hour[df.gender==0], df.level[df.gender==0], c="blue", label="female")
plt.xlabel('hour')
plt.ylabel('level')
</code>```

Body:
I am a python newbie suffering from how to import CSV file in matplotlib.pyplot
I would like to see the relationship between hour (=how many hours people spent to play a video game) and level (=game level). and then I would like to draw a scatter plot with Tax in different colors between female(1) and male(0).So, my x would be 'hour' and my y would be 'level'.

my data csv file looks like this:

          hour gender level
0            8    1   20.00
1            9    1   24.95
2           12    0   10.67
3           12    0   18.00
4           12    0   17.50
5           13    0   13.07
6           10    0   14.45
...
...
499         12    1  19.47
500         16    0  13.28

Here's my code:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

df=pd.read_csv('data.csv')
plt.plot(x,y, lavel='some relationship')
plt.title("Some relationship")
plt.xlabel('hour')
plt.ylabel('level')
plt.plot[gender(gender=1), '-b', label=female]
plt.plot[gender(gender=0), 'gD', label=male]
plt.axs()
plt.show()

I would like to draw the following graph. So, there will be two lines of male and female.

y=level|           @----->male
       | @
       | *         *----->female
       |________________ x=hour

However, I am not sure how to solve this problem.
I kept getting an error NameError: name 'hour' is not defined.

Body:
Could do it in this way:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

df = pd.DataFrame(data={"hour": [8,9,12,12,12,13,10],
                        "gender": [1,1,0,0,0,0,0],
                        "level": [20, 24.95, 10.67, 18, 17.5, 13.07, 14.45]})

df.sort_values("hour", ascending=True, inplace=True)

fig = plt.figure(dpi=80)
ax = fig.add_subplot(111, aspect='equal')

ax.plot(df.hour[df.gender==1], df.level[df.gender==1], c="red", label="male")
ax.plot(df.hour[df.gender==0], df.level[df.gender==0], c="blue", label="female")
plt.xlabel('hour')
plt.ylabel('level')


问:
Videojs HLS m3u8 files are not playing in iOS devices and safari browser
I am able to play the m3u8 files in the PC and android devices, but i am not able to play those files in the iOS mobile devices and safari browser,
I disabled the overrideNative to 'true' for the android devices, so its working in the android.
but we should not disable the native for iOS and safari, because iOS Safari uses a native player,
so I have set the overridnative false for the iOS. but its not working.
I am following new videojs versions.

videojs : 6.4.0

videojs contrib hls: 5.12.2

videojs flash: 2.0.1

Example

```<code> <!DOCTYPE html>
    <html>
    <head>
    <meta charset=utf-8 />
    <title>videojs-contrib-hls</title>

    <link href="https://unpkg.com/video.js@6.4.0/dist/video-js.css" rel="stylesheet">
    <script src="https://unpkg.com/video.js@6.4.0/dist/video.js"></script>
    <script src="https://unpkg.com/videojs-flash@2.0.1/dist/videojs-flash.js"></script>
    <script src="https://unpkg.com/videojs-contrib-hls@5.12.2/dist/videojs-contrib-hls.js"></script>

    </head>
    <body>
      <h1>Video.js Example Embed</h1>
      <video id="my_video_1" class="video-js vjs-default-skin" controls preload="auto" width="600" height="268"
       data-setup='{}'>
        <source src="https://d2zihajmogu5jn.cloudfront.net/bipbop-advanced/bipbop_16x9_variant.m3u8" type="application/x-mpegURL">
      </video>
      <script>
        let videojshls= videojs('my_video_1', {  html5: {
        nativeAudioTracks: false,
        nativeVideoTracks: false,
        hls: {
          debug: true,
          overrideNative: false
        }
       }});
      </script>
    </body>
    </html>
</code>```

example jsfiddle

please can anyone help me. thanks

答:
Try this http://jsfiddle.net/fxfktztx/1/. It works for me.

```<code>var overrideNative = false;

var player = videojs('example-video', {
  html5: {
    hls: {
      overrideNative: overrideNative
    },
    nativeVideoTracks: !overrideNative,
    nativeAudioTracks: !overrideNative,
    nativeTextTracks: !overrideNative
  }
});
player.play();
</code>```

As far I know, videojs options should be passed when the player is initialised, either with data-setup attribute or directly into the constructor as I did in the example above.

Body:
I am able to play the m3u8 files in the PC and android devices, but i am not able to play those files in the iOS mobile devices and safari browser,
I disabled the overrideNative to 'true' for the android devices, so its working in the android.
but we should not disable the native for iOS and safari, because iOS Safari uses a native player,
so I have set the overridnative false for the iOS. but its not working.
I am following new videojs versions.

videojs : 6.4.0

videojs contrib hls: 5.12.2

videojs flash: 2.0.1

Example

 <!DOCTYPE html>

    <meta charset=utf-8 />
    <title>videojs-contrib-hls</title>

    <link href="https://unpkg.com/video.js@6.4.0/dist/video-js.css" rel="stylesheet">

Video.js Example Embed

      <video id="my_video_1" class="video-js vjs-default-skin" controls preload="auto" width="600" height="268"
       data-setup='{}'>
        <source src="https://d2zihajmogu5jn.cloudfront.net/bipbop-advanced/bipbop_16x9_variant.m3u8" type="application/x-mpegURL">
      </video>

example jsfiddle

please can anyone help me. thanks

Body:
Try this http://jsfiddle.net/fxfktztx/1/. It works for me.

var overrideNative = false;

var player = videojs('example-video', {
  html5: {
    hls: {
      overrideNative: overrideNative
    },
    nativeVideoTracks: !overrideNative,
    nativeAudioTracks: !overrideNative,
    nativeTextTracks: !overrideNative
  }
});
player.play();

As far I know, videojs options should be passed when the player is initialised, either with data-setup attribute or directly into the constructor as I did in the example above.


问:
How to Send a Form post Using Ajax in Laravel 5.4
I'm trying to send a form with a POST method but I'm getting a query exception error.

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'post_id'
  cannot be null (SQL: insert into comments (comment, approved,
  user_id, post_id, updated_at, created_at) values (sdfsdfsdff,
  1, 1, , 2017-12-04 07:18:13, 2017-12-04 07:18:13))

'sdfsdfsdff' is the comment that I'm trying to send to the "comment system", 1 is the user id, the blank space is where the post id should be.

Controller

```<code><?php

$this->validate($request, [
    'comment' => 'required'
]);

$post = Post::find($post_id);
$comment = new Comment();
$comment->comment = $request->comment;
$comment->approved = true;
$comment->user_id = auth()->id();
$comment->post_id = $request->id;
$comment->save();

return response()->json([
    'comment' => $comment->comment,
    'user_id' => $comment->user_id,
    'post_id' => $comment->post_id,
    'post_slug' => $post->slug,
    'success' => true
]);
</code>```

Ajax code in the view

```<code>var urlPostComment = '{{ url('comments/store') }}';

$('.send').click(function(e){
   e.preventDefault();
   var dataSerialize = $('#comment-new').serialize();

   $.ajax({
      method: 'post',
      url: urlPostComment,
      data: dataSerialize,
      dataType: 'json', // <- La coma
      success: function (data) {
         console.log(data); // <- Revisar JSON en la consola del navegador
         if( data.success )
         {
            $('#comment-post').append(
               '<p class="store-comment">' + data.comentario + '</p>'
            );
         }

      }, // <- La coma
      error: function () {
         console.log('Error en el AJAX');
      }, // <- La coma
      complete: function () {
         console.log('Termino el ajax');
      }
   });
});
</code>```

Form

```<code><div class="row">
    <div class="col-xs-8 col-md-offset-2 form-create">
        {!! Form::open(['route' => ['comments.store', $post->id], 'method' => 'POST', 'id' => 'add-comment']) !!}
        <p class="error text-center alert alert-danger hidden"></p>
        {{ Form::label('comment', ' Comentario', ['class' => 'glyphicon glyphicon-comment pull-right label-space', 'id' => 'comment-create']) }}
        {{ Form::textarea('comment', null, ['class' => 'form-control comment-text', 'id' => 'comment-new', 'placeholder' => 'Escribe tu comentario']) }}
        <p class="error text-center alert alert-danger hidden"></p>
        {{ Form::submit('Agregar Comentario', ['class' => 'comment-message-guest-button send']) }}
        {!! Form::close() !!}
    </div>
</div>
</code>```

Comments HTML

```<code><div class="row">
        @foreach ($post->comments as $comment)
            <section class="comment-list">
                <article class="row">
                    <div class="col-md-3 col-sm-3 hidden-xs">
                        <figure class="thumbnail">
                            <img class="img-responsive" src="/uploads/avatars/{{ $comment->user->profilepic  }}"/>
                            <figcaption class="text-center">{{ $comment->user->name }}</figcaption>
                        </figure>
                    </div>
                    <div class="col-md-8 col-sm-8">
                        <div class="panel panel-default arrow left">
                            <div class="panel-body">
                                <header class="text-left">
                                    <div class="comment-user"><i class="fa fa-user"></i> {{ $comment->user->name }}
                                    </div>
                                    <time class="comment-date" datetime="{{ $comment->created_at->diffForHumans() }}"><i
                                                class="fa fa-clock-o"></i> {{ $comment->created_at->diffForHumans() }}
                                    </time>
                                </header>
                                <div id="comment-post" data-commentid="{{ $comment->id }}">
                                    <p id="display-comment"
                                       class="store-comment" {{ $comment->id }} {{ $post->id }}>{{ $comment->comment }}</p>
                                </div>
                            </div>

                            <div class="panel-footer list-inline comment-footer">
                                @if(Auth::guest())
                                    No puedes responder ningún comentario si no has ingresado.
                                @else
                                    @if(Auth::user() == $comment->user)
                                        <a href="#" data-toggle="modal" data-target="edit-comment" class="edit-comment">Editar</a>
                                        <a href="#" data-toggle="modal" data-target="delete-comment"
                                           class="delete-comment">Eliminar</a>
                                    @endif
                                    @if(Auth::user() != $comment->user)
                                        <a href="#">Responder</a>
                                    @endif
                                @endif
                            </div>
                        </div>
                    </div>
                </article>
            </section>
        @endforeach
</div>
</code>```

The main error:

POST http://localhost:8000/comments/store 500 (Internal Server Error)
  "from google chrome console"

In my comments table in the database, I do have the foreign key that worked perfectly when I wasn't using Ajax, so I don't think that's a relationship problem. Thank you in advance.

答:
I assume that your route looks like this

```<code>Route::post('comments.store/{id}', ...);
</code>```

You can access the route parameter {id} in your request by

```<code>$request->route('id');
</code>```

But since you're inside a controller, you can just access the parameter in your store function

```<code>public function store($id) {
    echo $id;
}
</code>```

Body:
I'm trying to send a form with a POST method but I'm getting a query exception error.

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'post_id'
  cannot be null (SQL: insert into comments (comment, approved,
  user_id, post_id, updated_at, created_at) values (sdfsdfsdff,
  1, 1, , 2017-12-04 07:18:13, 2017-12-04 07:18:13))

'sdfsdfsdff' is the comment that I'm trying to send to the "comment system", 1 is the user id, the blank space is where the post id should be.

Controller

<?php

$this->validate($request, [
    'comment' => 'required'
]);

$post = Post::find($post_id);
$comment = new Comment();
$comment->comment = $request->comment;
$comment->approved = true;
$comment->user_id = auth()->id();
$comment->post_id = $request->id;
$comment->save();

return response()->json([
    'comment' => $comment->comment,
    'user_id' => $comment->user_id,
    'post_id' => $comment->post_id,
    'post_slug' => $post->slug,
    'success' => true
]);

Ajax code in the view

var urlPostComment = '{{ url('comments/store') }}';

$('.send').click(function(e){
   e.preventDefault();
   var dataSerialize = $('#comment-new').serialize();

   $.ajax({
      method: 'post',
      url: urlPostComment,
      data: dataSerialize,
      dataType: 'json', // <- La coma
      success: function (data) {
         console.log(data); // <- Revisar JSON en la consola del navegador
         if( data.success )
         {
            $('#comment-post').append(
               '
' + data.comentario + '
'
            );
         }

      }, // <- La coma
      error: function () {
         console.log('Error en el AJAX');
      }, // <- La coma
      complete: function () {
         console.log('Termino el ajax');
      }
   });
});

Form

        {!! Form::open(['route' => ['comments.store', $post->id], 'method' => 'POST', 'id' => 'add-comment']) !!}

        {{ Form::label('comment', ' Comentario', ['class' => 'glyphicon glyphicon-comment pull-right label-space', 'id' => 'comment-create']) }}
        {{ Form::textarea('comment', null, ['class' => 'form-control comment-text', 'id' => 'comment-new', 'placeholder' => 'Escribe tu comentario']) }}

        {{ Form::submit('Agregar Comentario', ['class' => 'comment-message-guest-button send']) }}
        {!! Form::close() !!}

Comments HTML

        @foreach ($post->comments as $comment)

                            user->profilepic  }}"/>

{{ $comment->user->name }}

 {{ $comment->user->name }}

                                    <time class="comment-date" datetime="{{ $comment->created_at->diffForHumans() }}"> {{ $comment->created_at->diffForHumans() }}
                                    </time>

id }}">

id }} {{ $post->id }}>{{ $comment->comment }}

                                @if(Auth::guest())
                                    No puedes responder ningún comentario si no has ingresado.
                                @else
                                    @if(Auth::user() == $comment->user)
                                        Editar
                                        Eliminar
                                    @endif
                                    @if(Auth::user() != $comment->user)
                                        Responder
                                    @endif
                                @endif

        @endforeach

The main error:

POST http://localhost:8000/comments/store 500 (Internal Server Error)
  "from google chrome console"

In my comments table in the database, I do have the foreign key that worked perfectly when I wasn't using Ajax, so I don't think that's a relationship problem. Thank you in advance.

Body:
I assume that your route looks like this

Route::post('comments.store/{id}', ...);

You can access the route parameter {id} in your request by

$request->route('id');

But since you're inside a controller, you can just access the parameter in your store function

public function store($id) {
    echo $id;
}


问:
Return internal class calling object function
I'm testing with Kotlin and I'm writing a small library to be imported and used by a test App project.

In the library project I marked my classes as internal because I don't want them to be visible for the App project, but I would like to have a single entry point for the library, and for that I am using a Kotlin object like shown below

```<code>LIBRARY

object Library {
   fun getComponent() = AwesomeComponent()
}

internal class AwesomeComponent() {
   // some implementation
}

TEST APP

class MainActivity : AppCompatActivity() {

   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      val component = Library.getComponent()
   }
}
</code>```

The problem is that this doesn't compile because the function in the Library object returns an internal type and therefore need to be marked as internal as well, but doing so would hide the function from the TestApp.

Another option would be to not have the internal modifier at all so the TestApp can see the Library method, but then it can also see the classes inside the Library project

Is there an easy solution that I am overlooking here or does it need to go through re-planning of packages and structure of the Library project? (not sure how to do it in that case)

答:
You have to publish some sort of public API for the app module to be able to use the component that the getComponent() method returns. If you want to publish minimal information about your library, you can have it return an interface that contains only the publicly available method calls to the library, and make your class implement that interface:

```<code>object Library {
    fun getComponent(): IAwesomeComponent = AwesomeComponent()
}

interface IAwesomeComponent {
     // methods you want to call on the component in the app module
}

internal class AwesomeComponent(): IAwesomeComponent {
    // implementations of the interface methods
}
</code>```

Body:
I'm testing with Kotlin and I'm writing a small library to be imported and used by a test App project.

In the library project I marked my classes as internal because I don't want them to be visible for the App project, but I would like to have a single entry point for the library, and for that I am using a Kotlin object like shown below

LIBRARY

object Library {
   fun getComponent() = AwesomeComponent()
}

internal class AwesomeComponent() {
   // some implementation
}

TEST APP

class MainActivity : AppCompatActivity() {

   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      val component = Library.getComponent()
   }
}

The problem is that this doesn't compile because the function in the Library object returns an internal type and therefore need to be marked as internal as well, but doing so would hide the function from the TestApp.

Another option would be to not have the internal modifier at all so the TestApp can see the Library method, but then it can also see the classes inside the Library project

Is there an easy solution that I am overlooking here or does it need to go through re-planning of packages and structure of the Library project? (not sure how to do it in that case)

Body:
You have to publish some sort of public API for the app module to be able to use the component that the getComponent() method returns. If you want to publish minimal information about your library, you can have it return an interface that contains only the publicly available method calls to the library, and make your class implement that interface:

object Library {
    fun getComponent(): IAwesomeComponent = AwesomeComponent()
}

interface IAwesomeComponent {
     // methods you want to call on the component in the app module
}

internal class AwesomeComponent(): IAwesomeComponent {
    // implementations of the interface methods
}


问:
not able to send messages with Multicastsocket over my local network
I am using the example server and client from this website. I have the client on my laptop and the server on my other laptop.

When I run them the server doesn't receive anything. When I run the server and client on the same laptop (doesn't matter which one) the server is able to receive messages. What might be the problem here?

One laptop has W7 and the other W10

答:
I suggest you test multicast connectivity between your two machines using an existing program (without programming anything in Java). Are they in the same subnet?

I haven't used multicast in the last 10 years, but a quick search yields many results.


问:
Function to check if parameter is still the same
I have a loop that has a function inside. my target here is to check if the current data inside the loop are still the same for example my array is like this

var data = ['test1','test1','test1','test2'];

now I will check them if the data on that array inside the loop are currently the same. for example like this.

```<code>for (var i = 0; i < data.length; i++) {
    var value = data[i][0];
    console.log(checkifcurrent(value));
}
</code>```

my problem here is to return checkifcurrent(value) if it still the same like this

```<code>function checkifcurrent(value) {
    if (currentvalue is still the same as the last one) {
        console.log(same);
    } else {
        console.log(not same);
    }
}
</code>```

I hope you understand tysm for understanding

答:
```<code>var isSame = (function () {
  var previous;
  return function(value){
    var result = value === previous;
    previous = value;
    return result;
  }
})();
</code>```

Body:
I have a loop that has a function inside. my target here is to check if the current data inside the loop are still the same for example my array is like this

var data = ['test1','test1','test1','test2'];

now I will check them if the data on that array inside the loop are currently the same. for example like this.

for (var i = 0; i < data.length; i++) {
    var value = data[i][0];
    console.log(checkifcurrent(value));
}

my problem here is to return checkifcurrent(value) if it still the same like this

function checkifcurrent(value) {
    if (currentvalue is still the same as the last one) {
        console.log(same);
    } else {
        console.log(not same);
    }
}

I hope you understand tysm for understanding


问:
Merge maps and make values as array
```<code>public class MapCheck {
    public static void main(String[] args) {
        Map<String, String> data = new HashMap<String, String>();
        data.put("John", "Taxi Driver");
        data.put("Mark", "Professional Killer");
        Map<String, String> data1 = new HashMap<String, String>();
        data1.put("John", "Driver");
        data1.put("Mark", "Murderer");
        Map<String, String> data3 = new HashMap<String, String>();
        data3.putAll(data);
        data3.putAll(data1);
        System.out.println(data3);
    }
}
</code>```

I have few maps which contains same key, their values are different. I want to merge them. But when I merge them with the usual putAll() it gives me only the value of the key which was inserted latest.

Output from above code is  {John=Driver, Mark=Murderer}

Is there a method which will get me all the values associated with the key and give me as a array like

```<code>{John=[Taxi Driver, Driver], Mark=[Professional Killer, Murderer]}
</code>```

答:
You can produce a Map<String, List<String>> quite easily with Java 8 Streams:

```<code>Map<String, List<String>>
    merged =
        Stream.of(data,data1) // create a Stream<Map<String,String> of all Maps
              .flatMap(map->map.entrySet().stream()) // map all the entries of all the
                                                     // Maps into a
                                                     // Stream<Map.Entry<String,String>>
              .collect(Collectors.groupingBy(Map.Entry::getKey, // group entries by key
                                             Collectors.mapping(Map.Entry::getValue,
                                                                Collectors.toList())));
</code>```

The output Map:

```<code>{John=[Taxi Driver, Driver], Mark=[Professional Killer, Murderer]}
</code>```

Title: Merge maps and make values as array

Body:
public class MapCheck {
    public static void main(String[] args) {
        Map<String, String> data = new HashMap<String, String>();
        data.put("John", "Taxi Driver");
        data.put("Mark", "Professional Killer");
        Map<String, String> data1 = new HashMap<String, String>();
        data1.put("John", "Driver");
        data1.put("Mark", "Murderer");
        Map<String, String> data3 = new HashMap<String, String>();
        data3.putAll(data);
        data3.putAll(data1);
        System.out.println(data3);
    }
}

I have few maps which contains same key, their values are different. I want to merge them. But when I merge them with the usual putAll() it gives me only the value of the key which was inserted latest.

Output from above code is  {John=Driver, Mark=Murderer}

Is there a method which will get me all the values associated with the key and give me as a array like

{John=[Taxi Driver, Driver], Mark=[Professional Killer, Murderer]}

Body:
You can produce a Map<String, List<String>> quite easily with Java 8 Streams:

Map<String, List<String>>
    merged =
        Stream.of(data,data1) // create a Stream<Map<String,String> of all Maps
              .flatMap(map->map.entrySet().stream()) // map all the entries of all the
                                                     // Maps into a
                                                     // Stream<Map.Entry<String,String>>
              .collect(Collectors.groupingBy(Map.Entry::getKey, // group entries by key
                                             Collectors.mapping(Map.Entry::getValue,
                                                                Collectors.toList())));

The output Map:

{John=[Taxi Driver, Driver], Mark=[Professional Killer, Murderer]}


问:
auto generate hyperlink column for c# gridview
I have a query, output of which populates a gridview. The columns of gridview are not fixed, i.e except for 1st columns rest column count can vary.

Output table structure is roughly:

```<code>    name | week1 | week2
    stu1 | 23    | 0
    stu2 | 45    | 6
</code>```

The column count varies because week no is not static.
Is it possible to generate hyperlink in the cells where cell value is greater than zero? And if possible then how to get the row and column index on clicking the digit and redirecting to another page for details?

答:
you can do it in RowDataBound event , as given in msdn : GridView.RowDataBound Event</p>

```<code>  void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
  {
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
      for(var cell in e.Row.Cells)
      {
       int val = 0;
       if(int.TryParse(cell.Text,out val)
       {
        //you can have hyper link here
        if(val > 0)
        cell.Text = "<a href='void(0);'>" + cell.Text + "</a>";
       }
      }

    }
  }
</code>```

Body:
I have a query, output of which populates a gridview. The columns of gridview are not fixed, i.e except for 1st columns rest column count can vary.

Output table structure is roughly:

    name | week1 | week2
    stu1 | 23    | 0
    stu2 | 45    | 6

The column count varies because week no is not static.
Is it possible to generate hyperlink in the cells where cell value is greater than zero? And if possible then how to get the row and column index on clicking the digit and redirecting to another page for details?

Body:
you can do it in RowDataBound event , as given in msdn : GridView.RowDataBound Event

  void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
  {
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
      for(var cell in e.Row.Cells)
      {
       int val = 0;
       if(int.TryParse(cell.Text,out val)
       {
        //you can have hyper link here
        if(val > 0)
        cell.Text = "<a href='void(0);'>" + cell.Text + "</a>";
       }
      }

    }
  }