问:
How to pass some data in chunks inside html table in jQuery
I have html like

```<code><table id="library_info_tbl">
  <thead>
    <th>Call No.</th>
    <th>Book</th>
    <th>Accession No.</th>
    <th>Status</th>
  </thead>
  <tbody>
    <tr><td>12<td><td>ffyuyudf</td><td>61</td><td>Lost</td></tr>
    <tr><td>12<td><td>ffyuyudf</td><td>62</td>Damaged</tr>
    <tr><td>12<td><td>ffyuyudf</td><td>63</td>Damaged</tr>
    <tr><td>13<td><td>abcdef</td><td>72</td>Lost</tr>
    <tr><td>13<td><td>abcdef</td><td>73</td>Lost</tr>
     ...
  </tbody>
</table>

</code>```

I am trying to tweak the below lines

```<code>         $('#library_info_tbl tbody tr').each(function() {

                var statusarray = [];
                var callno = $(this).find("td:first-child").html();
                var accessionno = $(this).find("td:nth-child(2)").html();
                var status = $(this).find("td:last-child").html();
                var callnotouse = "";

                if(callno is similar)
                {
                    var innerarray = {};
                        innerarray = {
                            status: status,
                            accessionno: accessionno
                       };
                       statusarray.push(innerarray);
                       callnotouse = callno;
                }

                if(statusarray.length)
                {
                    $.ajax({
                        url: 'index.php?action=savestatus',
                        type: 'POST',
                        dataType: 'JSON',
                        data: {callno:callnotouse,statusarray:statusarray},
                      ...
                }
              continue;
          });
</code>```

for achieving statusarray and callnotouse in order to pass them in ajax call. Basically I want the code should work like first it should check similar call numbers in table for e.g in the above table.

It should first fetch on the basis of callno 12 and the innerarray or statusarray should contain data like

```<code>              status: Lost,
              accessionno: 61

              status: Damaged,
              accessionno: 62

               status: Damaged,
               accessionno: 63

              callnotouse = 12
</code>```

These data should get passed to ajax call (which will get saved in the database). After that, in the same of the loop of table it should take callno 13

```<code>          status: Lost,
          accessionno: 72

          status: Lost,
          accessionno: 73

          callnotouse = 13
</code>```

Then it should get passed to ajax call and so. Basically I am not able to tweak the above code on the basis of similar callno.

答:
Working code

```<code>var libraryInfos = [];

$("#library_info_tbl tbody tr").each(function(){
  var tds = $("td", this);
  var callNo = tds.first().html();

  if(typeof libraryInfos[callNo] == 'undefined'){
    libraryInfos[callNo] = [];
  }

  libraryInfos[callNo].push({
    status: $(tds[4]).html(),
    accessionNo: parseInt($(tds[3]).html())
  });
});

$.each(libraryInfos, function(callNo, statusArr){
  if(statusArr){
    var reqData = { callno: callNo, statusarray: statusArr };

    $.ajax({
      url: 'index.php?action=savestatus',
      type: 'POST',
      dataType: 'JSON',
      data: reqData
    });

    console.log(reqData);
  }
});
</code>```

Demo: https://jsbin.com/mamezit/5/edit?html,js,console,output

ContentLicense: CC BY-SA 4.0

Body:
I have html like

    Call No.
    Book
    Accession No.
    Status

12ffyuyudf	61	Lost

12ffyuyudf	62	Damaged

12ffyuyudf	63	Damaged

13abcdef	72	Lost

13abcdef	73	Lost

     ...

I am trying to tweak the below lines

         $('#library_info_tbl tbody tr').each(function() {

                var statusarray = [];
                var callno = $(this).find("td:first-child").html();
                var accessionno = $(this).find("td:nth-child(2)").html();
                var status = $(this).find("td:last-child").html();
                var callnotouse = "";

                if(callno is similar)
                {
                    var innerarray = {};
                        innerarray = {
                            status: status,
                            accessionno: accessionno
                       };
                       statusarray.push(innerarray);
                       callnotouse = callno;
                }

                if(statusarray.length)
                {
                    $.ajax({
                        url: 'index.php?action=savestatus',
                        type: 'POST',
                        dataType: 'JSON',
                        data: {callno:callnotouse,statusarray:statusarray},
                      ...
                }
              continue;
          });

for achieving statusarray and callnotouse in order to pass them in ajax call. Basically I want the code should work like first it should check similar call numbers in table for e.g in the above table.

It should first fetch on the basis of callno 12 and the innerarray or statusarray should contain data like

              status: Lost,
              accessionno: 61

              status: Damaged,
              accessionno: 62

               status: Damaged,
               accessionno: 63

              callnotouse = 12

These data should get passed to ajax call (which will get saved in the database). After that, in the same of the loop of table it should take callno 13

          status: Lost,
          accessionno: 72

          status: Lost,
          accessionno: 73

          callnotouse = 13

Then it should get passed to ajax call and so. Basically I am not able to tweak the above code on the basis of similar callno.

Body:
Working code

var libraryInfos = [];

$("#library_info_tbl tbody tr").each(function(){
  var tds = $("td", this);
  var callNo = tds.first().html();

  if(typeof libraryInfos[callNo] == 'undefined'){
    libraryInfos[callNo] = [];
  }

  libraryInfos[callNo].push({
    status: $(tds[4]).html(),
    accessionNo: parseInt($(tds[3]).html())
  });
});

$.each(libraryInfos, function(callNo, statusArr){
  if(statusArr){
    var reqData = { callno: callNo, statusarray: statusArr };

    $.ajax({
      url: 'index.php?action=savestatus',
      type: 'POST',
      dataType: 'JSON',
      data: reqData
    });

    console.log(reqData);
  }
});

Demo: https://jsbin.com/mamezit/5/edit?html,js,console,output


来源: stackexchange

问:
Python pyexcelerate library writing multiple sheets to same workbook?
I am trying to write multiple sheets into one workbook and I'm using pyexcelerate to utilize it's optimized writing time.

Here's my current code to write to a workbook:

```<code>def df_to_excel(df, path, sheet_name='Sheet 1'):
    data = [df.columns.tolist(), ] + df.values.tolist()
    wb = Workbook()
    wb.new_sheet(sheet_name, data=data)
    wb.save(path)
</code>```

now this works perfectly fine if i only need one sheet; however, if i write in multiple sheet, only the last sheet will be kept (all sheets generated before will be replaced).

I want to keep all the sheets (with diff names ofc), and I looked into their github page, but I cannot find info on such capability:
https://github.com/kz26/PyExcelerate

I also looked into a few other stackoverflow posts but they are using different packages:

Writing resutls into 2 different sheets in the same Excel file

xlwt create dynamic number of worksheets based on input

creating multiple excel worksheets using data in a pandas dataframe

any help is appreciated!

答:
If you want to save different variable in different sheet of one excel file faster and also want header and index of the pandas.dataframe in the excel file. You can do something as follows,</p>

```<code>    import timeit
    from pyexcelerate import Workbook

    def to_Excel(data, fileName):
        start_time = timeit.default_timer()
        wb = Workbook()
        for key in data.keys():
            ws = wb.new_sheet(key)
            frame = data[key]
            frame = frame.transpose()
            frame.reset_index(level=0, inplace = True)
            frame = frame.transpose()
            frame.reset_index(level=0, inplace = True)
            row_num = frame.shape[0]
            col_num = 1
            for col_name, col_series in frame.iteritems():
                ws.range((1,col_num), (row_num,col_num)).value = [[x] for x in col_series]
                col_num += 1
        wb.save(fileName)
        end_time = timeit.default_timer()
        delta = round(end_time-start_time,2)
        print("Took "+str(delta)+" secs")
</code>```

<p>'data' is a dictionary variable. The 'key' of 'data' works as 'sheet name' and data type of each key value should be in pandas dataframe. </p>

ContentLicense: CC BY-SA 3.0

Body:
I am trying to write multiple sheets into one workbook and I'm using pyexcelerate to utilize it's optimized writing time.

Here's my current code to write to a workbook:

def df_to_excel(df, path, sheet_name='Sheet 1'):
    data = [df.columns.tolist(), ] + df.values.tolist()
    wb = Workbook()
    wb.new_sheet(sheet_name, data=data)
    wb.save(path)

now this works perfectly fine if i only need one sheet; however, if i write in multiple sheet, only the last sheet will be kept (all sheets generated before will be replaced).

I want to keep all the sheets (with diff names ofc), and I looked into their github page, but I cannot find info on such capability:
https://github.com/kz26/PyExcelerate

I also looked into a few other stackoverflow posts but they are using different packages:

Writing resutls into 2 different sheets in the same Excel file

xlwt create dynamic number of worksheets based on input

creating multiple excel worksheets using data in a pandas dataframe

any help is appreciated!

Body:
If you want to save different variable in different sheet of one excel file faster and also want header and index of the pandas.dataframe in the excel file. You can do something as follows,

    import timeit
    from pyexcelerate import Workbook

    def to_Excel(data, fileName):
        start_time = timeit.default_timer()
        wb = Workbook()
        for key in data.keys():
            ws = wb.new_sheet(key)
            frame = data[key]
            frame = frame.transpose()
            frame.reset_index(level=0, inplace = True)
            frame = frame.transpose()
            frame.reset_index(level=0, inplace = True)
            row_num = frame.shape[0]
            col_num = 1
            for col_name, col_series in frame.iteritems():
                ws.range((1,col_num), (row_num,col_num)).value = [[x] for x in col_series]
                col_num += 1
        wb.save(fileName)
        end_time = timeit.default_timer()
        delta = round(end_time-start_time,2)
        print("Took "+str(delta)+" secs")

'data' is a dictionary variable. The 'key' of 'data' works as 'sheet name' and data type of each key value should be in pandas dataframe.


问:
Location of the table space files?
How can I find the directory in which oracle stores it's table space files?

When I do: select * from dba_data_files; or select * from v$datafile; then I get some paths like that:

```<code>+DATA01/fu/datafile/bar_ts01_data.260.264360912
</code>```

But what means +DATA01? And where is that exactly in the file system?

答:
In that table, the file_name field should give the full path to the datafile.

Also, try select * from v$datafile; and that view should help as well.

Title: Location of the table space files?

Body:
How can I find the directory in which oracle stores it's table space files?

When I do: select * from dba_data_files; or select * from v$datafile; then I get some paths like that:

+DATA01/fu/datafile/bar_ts01_data.260.264360912

But what means +DATA01? And where is that exactly in the file system?


问:
Take the mean of values in a list if a duplicate is found
I have 2 lists which are associated with each other. E.g., here, 'John' is associated with '1', 'Bob' is associated with 4, and so on:

```<code>l1 = ['John', 'Bob', 'Stew', 'John']
l2 = [1, 4, 7, 3]
</code>```

My problem is with the duplicate John. Instead of adding the duplicate John, I want to take the mean of the values associated with the Johns, i.e., 1 and 3, which is (3 + 1)/2 = 2. Therefore, I would like the lists to actually be:

```<code>l1 = ['John', 'Bob', 'Stew']
l2 = [2, 4, 7]
</code>```

I have experimented with some solutions including for-loops and the "contains" function, but can't seem to piece it together. I'm not very experienced with Python, but linked lists sound like they could be used for this.

Thank you

答:
I believe you should use a dict. :)

```<code>def mean_duplicate(l1, l2):
    ret = {}
    #   Iterating through both lists...
    for name, value in zip(l1, l2):
        if not name in ret:
            #   If the key doesn't exist, create it.
            ret[name] = value
        else:
            #   If it already does exist, update it.
            ret[name] += value

    #   Then for the average you're looking for...
    for key, value in ret.iteritems():
        ret[key] = value / l1.count(key)

    return ret

def median_between_listsElements(l1, l2):
    ret = {}

    for name, value in zip(l1, l2):
        #   Creating key + list if doesn't exist.
        if not name in ret:
            ret[name] = []
        ret[name].append(value)

    for key, value in ret.iteritems():
        ret[key] = np.median(value)

    return ret

l1 = ['John', 'Bob', 'Stew', 'John']
l2 = [1, 4, 7, 3]

print mean_duplicate(l1, l2)
print median_between_listsElements(l1, l2)
# {'Bob': 4, 'John': 2, 'Stew': 7}
# {'Bob': 4.0, 'John': 2.0, 'Stew': 7.0}
</code>```

Body:
I have 2 lists which are associated with each other. E.g., here, 'John' is associated with '1', 'Bob' is associated with 4, and so on:

l1 = ['John', 'Bob', 'Stew', 'John']
l2 = [1, 4, 7, 3]

My problem is with the duplicate John. Instead of adding the duplicate John, I want to take the mean of the values associated with the Johns, i.e., 1 and 3, which is (3 + 1)/2 = 2. Therefore, I would like the lists to actually be:

l1 = ['John', 'Bob', 'Stew']
l2 = [2, 4, 7]

I have experimented with some solutions including for-loops and the "contains" function, but can't seem to piece it together. I'm not very experienced with Python, but linked lists sound like they could be used for this.

Thank you

Body:
I believe you should use a dict. :)

def mean_duplicate(l1, l2):
    ret = {}
    #   Iterating through both lists...
    for name, value in zip(l1, l2):
        if not name in ret:
            #   If the key doesn't exist, create it.
            ret[name] = value
        else:
            #   If it already does exist, update it.
            ret[name] += value

    #   Then for the average you're looking for...
    for key, value in ret.iteritems():
        ret[key] = value / l1.count(key)

    return ret

def median_between_listsElements(l1, l2):
    ret = {}

    for name, value in zip(l1, l2):
        #   Creating key + list if doesn't exist.
        if not name in ret:
            ret[name] = []
        ret[name].append(value)

    for key, value in ret.iteritems():
        ret[key] = np.median(value)

    return ret

l1 = ['John', 'Bob', 'Stew', 'John']
l2 = [1, 4, 7, 3]

print mean_duplicate(l1, l2)
print median_between_listsElements(l1, l2)
# {'Bob': 4, 'John': 2, 'Stew': 7}
# {'Bob': 4.0, 'John': 2.0, 'Stew': 7.0}


问:
Room Empty Db after application restart
I am trying to use Room for my new app. But whenever I restart my app, I am unable to retrieve the old data. It looks like my app is creating a new instance of the database every time, but I am not sure why. Here are my classes based on MVP pattern.

Edit: I just checked again and I can see that the auto-generated Id for the Entity (MyModel) doesn't get reset to 1 but when I retrieve data I only get collection inserted in that session.

Dao

```<code>@Dao
public interface MyDao {

      @Insert(onConflict = OnConflictStrategy.REPLACE)
      List<Long> insertModels(List<MyModel> models);

      @Query("SELECT * FROM MyModel")
      List<MyModel> getModels();
}
</code>```

Database

```<code>@Database(entities = {MyModel.class}, version = 1)
public abstract class MyDatabase extends RoomDatabase {
    public abstract MyDao myDao();
}
</code>```

DatabaseModule

```<code>@Module
public class DatabaseModule {

    @Provides
    @Singleton
    MyDatabase provideMyDatabase(Application context) {
        return Room.databaseBuilder(context.getApplicationContext(), MyDatabase.class, "MyDB").build();
    }

    @Provides
    @Singleton
    MyDao provideMyDao(MyDatabase myDatabase) {
        return myDatabase.myDao();
    }
}
</code>```

Data Source

```<code>@Singleton
public class MyDataSource {

    MyDao mMyDao;

    @Inject
    public MyDataSource(@NonNull MyDao myDao) {
        mMyDao = myDao;
    }
}
</code>```

Repository

```<code>@Singleton
public class MyRepository {

    private final MyDataSource mMyDataSource;

    @Inject
    MyRepository(@Local MyDataSource myDataSource) {
        mMyDataSource = myDataSource;
    }
}
</code>```

ApplicationComponent

```<code>@Singleton
@Component(modules = {AndroidSupportInjectionModule.class, ApplicationModule.class, DatabaseModule.class})
public interface ApplicationComponent extends AndroidInjector<MyApp> {

    @Component.Builder
    interface Builder {

        @BindsInstance
        Builder application(Application application);

        ApplicationComponent build();
    }
}
</code>```

App

```<code>public class MyApp extends DaggerApplication {

    private ApplicationComponent mApplicationComponent;

    @Override
    protected AndroidInjector<? extends DaggerApplication> applicationInjector() {
        mApplicationComponent = DaggerApplicationComponent.builder().application(this).build();
        return mApplicationComponent;
    }
}
</code>```

答:
i just saw the google example and how they did it, and i realized that you need to fix:

```<code>@Module public class DatabaseModule {

@Provides
@Singleton
MyDatabase provideMyDatabase(Application context) {
    return Room.databaseBuilder(context.getApplicationContext(), MyDatabase.class, "MyDB").build();
}

@Provides
@Singleton
MyDao provideMyDao(MyDatabase myDatabase) {
    return myDatabase.myDao();
}
</code>```

}

to check if database already exist, with this code:

```<code>  /**
 * Check whether the database already exists and expose it via {@link #getDatabaseCreated()}
 */
private void updateDatabaseCreated(final Context context) {
    if (context.getDatabasePath(DATABASE_NAME).exists()) {
        setDatabaseCreated();
    }
}

private void setDatabaseCreated(){
    mIsDatabaseCreated.postValue(true);
}

public LiveData<Boolean> getDatabaseCreated() {
    return mIsDatabaseCreated;
}
</code>```

anyway here is a link to github google sample about this:
https://github.com/googlesamples/android-architecture-components/blob/master/BasicSample/app/src/main/java/com/example/android/persistence/db/AppDatabase.java

Title: Room Empty Db after application restart

Body:
I am trying to use Room for my new app. But whenever I restart my app, I am unable to retrieve the old data. It looks like my app is creating a new instance of the database every time, but I am not sure why. Here are my classes based on MVP pattern.

Edit: I just checked again and I can see that the auto-generated Id for the Entity (MyModel) doesn't get reset to 1 but when I retrieve data I only get collection inserted in that session.

Dao

@Dao
public interface MyDao {

      @Insert(onConflict = OnConflictStrategy.REPLACE)
      List<Long> insertModels(List<MyModel> models);

      @Query("SELECT * FROM MyModel")
      List<MyModel> getModels();
}

Database

@Database(entities = {MyModel.class}, version = 1)
public abstract class MyDatabase extends RoomDatabase {
    public abstract MyDao myDao();
}

DatabaseModule

@Module
public class DatabaseModule {

    @Provides
    @Singleton
    MyDatabase provideMyDatabase(Application context) {
        return Room.databaseBuilder(context.getApplicationContext(), MyDatabase.class, "MyDB").build();
    }

    @Provides
    @Singleton
    MyDao provideMyDao(MyDatabase myDatabase) {
        return myDatabase.myDao();
    }
}

Data Source

@Singleton
public class MyDataSource {

    MyDao mMyDao;

    @Inject
    public MyDataSource(@NonNull MyDao myDao) {
        mMyDao = myDao;
    }
}

Repository

@Singleton
public class MyRepository {

    private final MyDataSource mMyDataSource;

    @Inject
    MyRepository(@Local MyDataSource myDataSource) {
        mMyDataSource = myDataSource;
    }
}

ApplicationComponent

@Singleton
@Component(modules = {AndroidSupportInjectionModule.class, ApplicationModule.class, DatabaseModule.class})
public interface ApplicationComponent extends AndroidInjector<MyApp> {

    @Component.Builder
    interface Builder {

        @BindsInstance
        Builder application(Application application);

        ApplicationComponent build();
    }
}

App

public class MyApp extends DaggerApplication {

    private ApplicationComponent mApplicationComponent;

    @Override
    protected AndroidInjector<? extends DaggerApplication> applicationInjector() {
        mApplicationComponent = DaggerApplicationComponent.builder().application(this).build();
        return mApplicationComponent;
    }
}

Body:
i just saw the google example and how they did it, and i realized that you need to fix:

@Module public class DatabaseModule {

@Provides
@Singleton
MyDatabase provideMyDatabase(Application context) {
    return Room.databaseBuilder(context.getApplicationContext(), MyDatabase.class, "MyDB").build();
}

@Provides
@Singleton
MyDao provideMyDao(MyDatabase myDatabase) {
    return myDatabase.myDao();
}

}

to check if database already exist, with this code:

  /**
 * Check whether the database already exists and expose it via {@link #getDatabaseCreated()}
 */
private void updateDatabaseCreated(final Context context) {
    if (context.getDatabasePath(DATABASE_NAME).exists()) {
        setDatabaseCreated();
    }
}

private void setDatabaseCreated(){
    mIsDatabaseCreated.postValue(true);
}

public LiveData<Boolean> getDatabaseCreated() {
    return mIsDatabaseCreated;
}

anyway here is a link to github google sample about this:
https://github.com/googlesamples/android-architecture-components/blob/master/BasicSample/app/src/main/java/com/example/android/persistence/db/AppDatabase.java


问:
Routing back with param in Angular2
In my Angular2 project I have two pages A and B.
Page B has parameters, for example  http://localhost:4001/pageB/bw0600 has parameter bw0600.

When user push the button back  (<-) in the browser, he hast to be able to go to the previous page A (this works fine) and the parameters (in this case bw0600 should be there too. So, the address of page A should look like

http://localhost:4001/pageA/bw0600

So i need maybe somehow to overwrite the usual behaviour of router back (I don't have button (just  (<-) in the browser) , so I can't write the function and bind it to element button)...

How could I solve this?

答:
If you set the parameter to pageA and then forwarded them to pageB, the back button would then go to the correct, parameterized pageA.

As in: pageA => pageA/bw0600 => pageb/bw0600

You could also store the data, and then have pageA always look for the data in localstore or in a shared service when it is loaded.

Title: Routing back with param in Angular2


问:
Python RegEx clean-up randomly placed new lines
I got the following text and wish to do some regex clean up of the new lines

```<code>Quality risk management. A systematic process for the assessment, control,
communication and review of risks to quality across the lifecycle. (ICH Q9)

Simulated agents. A material that closely approximates the physical and, where
practical, the chemical characteristics, e.g. viscosity, particle size, pH etc., of the product
under validation.

State of control. A condition in which the set of controls consistently provides assurance
of acceptable process performance and product quality.

Traditional approach. A product development approach where set points and operating
ranges for process parameters are defined to ensure reproducibility.

Worst Case. A condition or set of conditions encompassing upper and lower processing
limits and circumstances, within standard operating procedures, which pose the greatest
chance of product or process failure when compared to ideal conditions. Such conditions
do not necessarily induce product or process failure.

User requirements Specification (URS). The set of owner, user and engineering
requirements necessary and sufficient to create a feasible design meeting the intended
purpose of the system.
</code>```

This almost works:
    re.sub(r'\w(?

but it also removes last and first character... How do I avoid this?

Here is the same example on regex101:

https://regex101.com/r/5uEsJR/1

答:
Since your reges is matching \w before and after \n and it is not being put back in replacement, it gets lost.

You can use lookarounds as:

```<code>re.sub(r'(?<=\w)\n(?=\w)', ' ')
</code>```

RegEx Demo

(?<=\w): Assert that we have a word character before

\n: Match a line break character

(?=\w): Assert that we have a word character next

Body:
I got the following text and wish to do some regex clean up of the new lines

Quality risk management. A systematic process for the assessment, control,
communication and review of risks to quality across the lifecycle. (ICH Q9)

Simulated agents. A material that closely approximates the physical and, where
practical, the chemical characteristics, e.g. viscosity, particle size, pH etc., of the product
under validation.

State of control. A condition in which the set of controls consistently provides assurance
of acceptable process performance and product quality.

Traditional approach. A product development approach where set points and operating
ranges for process parameters are defined to ensure reproducibility.

Worst Case. A condition or set of conditions encompassing upper and lower processing
limits and circumstances, within standard operating procedures, which pose the greatest
chance of product or process failure when compared to ideal conditions. Such conditions
do not necessarily induce product or process failure.

User requirements Specification (URS). The set of owner, user and engineering
requirements necessary and sufficient to create a feasible design meeting the intended
purpose of the system.

This almost works:
    re.sub(r'\w(?

but it also removes last and first character... How do I avoid this?

Here is the same example on regex101:

https://regex101.com/r/5uEsJR/1

Body:
Since your reges is matching \w before and after \n and it is not being put back in replacement, it gets lost.

You can use lookarounds as:

re.sub(r'(?<=\w)\n(?=\w)', ' ')

RegEx Demo

(?<=\w): Assert that we have a word character before

\n: Match a line break character

(?=\w): Assert that we have a word character next


问:
How to get dom element value in the page using jquery
Let say I have two fields with id "name" and "address". I want to show the actual value in the div message when I show it to user. And I did

```<code><input type="text" id="name" value="MyName" />
<input type="text" id="address" value="myaddress" />

<div style="visibility:hidden">
    <div>Your name is $(name)</div>
    <div>Your address is $(address)</div>
</div>
</code>```

I tried

```<code><div style="visibility:hidden">
    <div>Your name is <script>$("input[id=name]").val()</script></div>
    <div>Your address is <script>$("input[id=address]").val())</script></div>
</div>
</code>```

I am getting empty name and address.

Questtion is how can I fix it, is there any better approach? like

```<code><div style="visibility:hidden">
    <div>Your name is <script>GetValue(name)</script></div>
    <div>Your address is <script>GetValue(address)</</script></div>
</div>
</code>```

and use jquery to replace values?

答:
.val() returns the value, but doesn't write it to the DOM. You can get it to work by using document.write:

```<code><div style="visibility:hidden">
    <div>Your name is <script>document.write($("input[id=name]").val());</script></div>
    <div>Your address is <script>document.write($("input[id=address]").val());</script></div>
</div>
</code>```

But a way better approach would be more along the lines of

```<code><div style="visibility:hidden">
    <div id="name-div"></div>
    <div id="address-div"></div>
</div>

<script>
$("#name-div").text("Your name is " + $("#name").val());
$("#address-div").text("Your address is " + $("#address").val());
</script>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Let say I have two fields with id "name" and "address". I want to show the actual value in the div message when I show it to user. And I did

<input type="text" id="name" value="MyName" />
<input type="text" id="address" value="myaddress" />

Your name is $(name)

Your address is $(address)

I tried

Your name is

Your address is

I am getting empty name and address.

Questtion is how can I fix it, is there any better approach? like

Your name is

Your address is

and use jquery to replace values?

Body:
.val() returns the value, but doesn't write it to the DOM. You can get it to work by using document.write:

<div style="visibility:hidden">
    <div>Your name is <script>document.write($("input[id=name]").val());</script></div>
    <div>Your address is <script>document.write($("input[id=address]").val());</script></div>
</div>

But a way better approach would be more along the lines of

<div style="visibility:hidden">
    <div id="name-div"></div>
    <div id="address-div"></div>
</div>

<script>
$("#name-div").text("Your name is " + $("#name").val());
$("#address-div").text("Your address is " + $("#address").val());
</script>


问:
Oracle Insert All vs Insert
In Oracle I came across two types of insert statement

1) Insert All: Multiple entries can be inserted using a single sql statement

2) Insert : One entry will be updated per insert.

Now I want to insert around 100,000 records at a time. (Table have 10 fields with includes a primary key). I am not concerned about any return value.

I am using oracle 11g.

Can you please help me with respect to performance which is better "Insert" or "Insert All".

答:
I know this is kind of a Necro but it's pretty high on the google search results so I think this is a point that worth making.

Insert All can give dramatic performance benefits if you are building a web application because it is a single SQL statement that requires only one round trip to your database. In most cases although far from all cases. the majority of the cost of a query is actually latency. Depending on what framework you are using, this syntax can help you avoid unnecessary round trips.

This might seem incredibly obvious but I have seen many, many production web applications in large companies that have forgotten this simple fact.

Title: Oracle Insert All vs Insert


问:
Applying some mathematical operation to a signal in SIMULINK
Good day,

I need some help in some mathematical operations in SIMULINK. I have a signal coming from a block. The signal always has the first few entries
as 9999. Then, the next entry is a value between 0 and 200, say: 100. After that, all other remaining entries are back to 9999. This is always the nature of signal, except that the value: 100 may change its value or location in different simulations but it always has one or more values of 9999 before it, and all other entries after it are also 9999.

This is an example of the signal coming from a block:

```<code>S=[9999 75 9999 9999 9999]
</code>```

Another example:

```<code>S=[9999 9999 9999 100 9999 9999 9999 9999 9999]
</code>```

I want to pass this signal to another block or MATLAB Function in SIMULINK so that once the value (75 in the first example or 100 in the second example) is read, it will stay forever till the end of simulations.

Therefore, the desired output for the first example is:

```<code>Y=[9999 75 75 75 75]
</code>```

And for the second example is:

```<code>Y=[9999 9999 9999 100 100 100 100 100 100]
</code>```

So all remaining 9999’s are replaced by that value.

I tried to use a MATLAB Function with some if-else statements. Also, I tried using blocks of delay and comparisons, but I wasn’t able to get the desired output.

Is there a solution to that either using MATLAB Function or using some SIMULINK blocks ?

Regards

答:
Check the following, with initializing Memory block with 9999

and the result,

zoomed results,

Body:
Good day,

I need some help in some mathematical operations in SIMULINK. I have a signal coming from a block. The signal always has the first few entries
as 9999. Then, the next entry is a value between 0 and 200, say: 100. After that, all other remaining entries are back to 9999. This is always the nature of signal, except that the value: 100 may change its value or location in different simulations but it always has one or more values of 9999 before it, and all other entries after it are also 9999.

This is an example of the signal coming from a block:

S=[9999 75 9999 9999 9999]

Another example:

S=[9999 9999 9999 100 9999 9999 9999 9999 9999]

I want to pass this signal to another block or MATLAB Function in SIMULINK so that once the value (75 in the first example or 100 in the second example) is read, it will stay forever till the end of simulations.

Therefore, the desired output for the first example is:

Y=[9999 75 75 75 75]

And for the second example is:

Y=[9999 9999 9999 100 100 100 100 100 100]

So all remaining 9999’s are replaced by that value.

I tried to use a MATLAB Function with some if-else statements. Also, I tried using blocks of delay and comparisons, but I wasn’t able to get the desired output.

Is there a solution to that either using MATLAB Function or using some SIMULINK blocks ?

Regards


问:
AspNetCore v2.0 — Render razor-views in another project for integration tests
I want to write integration test for my web-application. I used Microsoft.AspNetCore.TestHost.TestServer to communicate with controllers via url. But views cannot be rendered. In response I get error-message:

One or more compilation references are missing. Ensure that your
  project is referencing 'Microsoft.NET.Sdk.Web' and the
  'PreserveCompilationContext' property is not set to false.

In my .csproj I tried to change project-sdk on Microsoft.NET.Sdk.Web, I tried to add <PreserveCompilationContext>true</PreserveCompilationContext>. Also I tried to rewrite the code as described in Microsoft-docs (here in here).
But I still have the same error-message.

Steps to Reproduce:

Create test-project "WebApplication1.IntegrationTests".

Add reference on WebApplication-project.

Add nuget-package "Microsoft.AspNetCore.TestHost"

Send get-request to "/Home/Index" via TestServer.

Read response with error-message.

```<code>using WebApplication1;
using Microsoft.AspNetCore.TestHost;
using System.Net.Http;
using System.Threading.Tasks;

namespace WebApplication1.IntegrationTests
{
    public class Program
    {
        public static void Main(string[] args)
        {
            // Path to contentRoot folder.
            var contentRootPath = @"..\..\..\..\WebApplication1";

            var builder = new WebHostBuilder()
                .UseStartup<Startup>()
                .UseEnvironment(EnvironmentName.Development)
                .UseContentRoot(contentRootPath);

            var server = new TestServer(builder);
            var client = server.CreateClient();

            var response = client.GetAsync("/Home/Index").Result;
            var responseString = response.Content.ReadAsStringAsync().Result;
        }
    }
}
</code>```

Rendered responseString in browser:

答:
If you're using AspNetCore v2.0 you should instantiate your webhost in your program file like so

```<code>public static IWebHost BuildWebHost(string[] args) {
     return WebHost.CreateDefaultBuilder(args) //<-- See what this does
            .UseStartup<Startup>()
            .Build();
    }
</code>```

Then insure that your project has preservecompilationcontext set to true like you apparantly did. Also i'm assuming that you're targeting the .Net 4.6.x runtime.

Body:
I want to write integration test for my web-application. I used Microsoft.AspNetCore.TestHost.TestServer to communicate with controllers via url. But views cannot be rendered. In response I get error-message:

One or more compilation references are missing. Ensure that your
  project is referencing 'Microsoft.NET.Sdk.Web' and the
  'PreserveCompilationContext' property is not set to false.

In my .csproj I tried to change project-sdk on Microsoft.NET.Sdk.Web, I tried to add <PreserveCompilationContext>true</PreserveCompilationContext>. Also I tried to rewrite the code as described in Microsoft-docs (here in here).
But I still have the same error-message.

Steps to Reproduce:

Create test-project "WebApplication1.IntegrationTests".

Add reference on WebApplication-project.

Add nuget-package "Microsoft.AspNetCore.TestHost"

Send get-request to "/Home/Index" via TestServer.

Read response with error-message.

using WebApplication1;
using Microsoft.AspNetCore.TestHost;
using System.Net.Http;
using System.Threading.Tasks;

namespace WebApplication1.IntegrationTests
{
    public class Program
    {
        public static void Main(string[] args)
        {
            // Path to contentRoot folder.
            var contentRootPath = @"..\..\..\..\WebApplication1";

            var builder = new WebHostBuilder()
                .UseStartup<Startup>()
                .UseEnvironment(EnvironmentName.Development)
                .UseContentRoot(contentRootPath);

            var server = new TestServer(builder);
            var client = server.CreateClient();

            var response = client.GetAsync("/Home/Index").Result;
            var responseString = response.Content.ReadAsStringAsync().Result;
        }
    }
}

Rendered responseString in browser:

Body:
If you're using AspNetCore v2.0 you should instantiate your webhost in your program file like so

public static IWebHost BuildWebHost(string[] args) {
     return WebHost.CreateDefaultBuilder(args) //<-- See what this does
            .UseStartup<Startup>()
            .Build();
    }

Then insure that your project has preservecompilationcontext set to true like you apparantly did. Also i'm assuming that you're targeting the .Net 4.6.x runtime.


问:
Connected component initial render fails because Redux state is not yet populated from server
I am using Redux thunk and axios to make server calls and modify the state depending on the result.

The problem is that when I use a connected component, and its initial state depends on data from the server, it does not render (the connected props are empty)

```<code>render () (<div>{this.props.someData}</data>) // empty, or error, if nested

...

const mapStateToProps = state => ({
  someData: state.someData
})
</code>```

I also tried this:

```<code>componentWillMount = () => {
  this.setState({
    someData: this.props.someData
  })
}
</code>```

And used state in render, but it didn't help.

Is there a way to wait for the server response before rendering or some other solution?

答:
Typically you would use the Component.defaultProps object to initialize your props. So in your case, something like this will set your someData prop to an initial value before axios receives the data.

class MyComponent extends React.Component {
  // ... your implementation
}

MyComponent.defaultProps = {
    someData: [] // empty array or whatever the data type is
};```

Edit: docs

Body:
I am using Redux thunk and axios to make server calls and modify the state depending on the result.

The problem is that when I use a connected component, and its initial state depends on data from the server, it does not render (the connected props are empty)

render () (
{this.props.someData}</data>) // empty, or error, if nested

...

const mapStateToProps = state => ({
  someData: state.someData
})

I also tried this:

componentWillMount = () => {
  this.setState({
    someData: this.props.someData
  })
}

And used state in render, but it didn't help.

Is there a way to wait for the server response before rendering or some other solution?

Body:
Typically you would use the Component.defaultProps object to initialize your props. So in your case, something like this will set your someData prop to an initial value before axios receives the data.

class MyComponent extends React.Component {
  // ... your implementation
}

MyComponent.defaultProps = {
    someData: [] // empty array or whatever the data type is
};

Edit: docs


答:
I have created a jsfiddle here: http://jsfiddle.net/7se87/</p>

```<code>$("input").keyup(function () {
    var spanclass = $(this).attr('id');
    var value = $(this).val();
    $("span."+spanclass).text(value);
}).keyup();

<input type="text" id="name" value="MyName" />
<input type="text" id="address" value="myaddress" />

<div style="display:block;">
    <div>Your name is <span class='name'></span></div>
    <div>Your address is <span class='address'></span></div>
</div>
</code>```

Title: How to get dom element value in the page using jquery

Body:
I have created a jsfiddle here: http://jsfiddle.net/7se87/

$("input").keyup(function () {
    var spanclass = $(this).attr('id');
    var value = $(this).val();
    $("span."+spanclass).text(value);
}).keyup();

<input type="text" id="name" value="MyName" />
<input type="text" id="address" value="myaddress" />

<div style="display:block;">
    <div>Your name is <span class='name'></span></div>
    <div>Your address is <span class='address'></span></div>
</div>


问:
Make sticky object stop being sticky
I'm about to make a portfolio for my exam. For that we have some articles we have to make for it. Therefore ive made a homepage, which shows the subjects that ive been writing about, and when you click on one of them, you come down to the article instantly.
On the left side there is a new menu which is sat as sticky, and scrolls with the page. The menu only contains the subjects that im going through for that single

My problem is, that the menu KEEPS on scrolling with the page, when it should stop after the article has ended, so a new chapter menu can appear. How do I do that?

Edit: I was on my phone when i wrote it.. But here is the code for the MENU on HTML, CSS and Jquery

  /*** Left Menu ***/
    var navLeftPos = $('#left_menu').offset().top;
    //console.log(navLeftPos)
    $(window).on('scroll', function () {
        console.log($(window).scrollTop())
        if (navTopPos <= $(window).scrollTop()) {
            $('#left_menu').addClass('left_menu')
        }
        if (navTopPos <= $(window).scrollTop() ) {
            $('#left_menu').addClass('left_menu')
        }
        else {
            $('#left_menu').removeClass('left_menu');
        }
    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/*** Menu sidebar ***/

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu {
    float:left;
    width: 30%;
    padding: 1.5% 1.5% 1.5% 5%;
    background-color: #C4E1AC;
}

div#wrapper div#underlayer div#ComputerensHistorie section.left_menu {
    position: fixed;
    top: 105px;
    left: 0;
}

/***** Overskrift *****/

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu h2 {
    font-family: Frank Ruhl Libre;
    letter-spacing: 2px;
}

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu svg {
    width: 60%;
    margin-bottom: 15px;
}

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu svg .cls-1 {
    stroke-width: 0.5px;
}

/***** Animations understreg *****/

svg#understreg_et line#streg_tre {
    stroke: #3A8540;
    animation: backandforth 12s linear infinite;
}

svg#understreg_et line#streg_to {
    stroke: #fff;
    animation: backandforth 4s linear infinite;
}

svg#understreg_et line#streg_et {
    stroke: #245328;
    animation: backandforth 6s linear infinite;
}

@keyframes backandforth {
    0% {
        transform: scaleX(1);
    }
    25% {
        transform: scaleX(0.8)
    }
    50% {
        transform: scaleX(0.5);
    }
    80% {
        transform: scaleX(0.8);
    }
    100% {
        transform: scaleX(1);
    }
}

/**** Introduktion *****/

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu p {
    font-size: 13px;
    line-height: 150%;
    padding-top: 15px;
    font-family: roboto;
}

/**** Navigation ****/

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu nav {
    font-size: 13px;
    line-height: 150%;
    margin-top: 10%;
}

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu nav ul {}

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu nav ul li {
    list-style-type: none;
}

div#wrapper div#underlayer div#ComputerensHistorie section.left_menu nav ul li.links {
    margin-left: 20px;
    font-family: roboto;
}

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu nav ul li a {
    text-decoration: none;
    line-height: 150%;
    color: black;
    font-family: roboto;
    font-size: 0.9em;
}

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu nav ul li a:hover {
    color: #3f824f;
}

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu nav ul ul {
    margin-left: 15px;
}

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu nav ul li h2 {
    font-size: 14px;
    text-transform: uppercase;
    border-bottom: 1px solid #000;
    margin-bottom: 10px;
    font-family: roboto;
    padding-left: 5px;
    letter-spacing: 0.5px;
    width: auto;
}</code>```

Computerens historie

                    <svg id="understreg_et" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 72 8"><defs></defs><title>streg</title><line id="streg_tre" class="cls-1" y1="1" x2="60" y2="1"/><line id="streg_to" class="cls-1" x1="72" y1="4" x2="29" y2="4"/><line id="streg_et" class="cls-1" x1="11" y1="7" x2="46" y2="7"/></svg>

Vores dagligdag er konstant præget af den elektroniske verden, der omgiver os derhjemme, på gaden, arbejdet - alle steder!

Vi forsker hele tiden i hvordan vi kan optimere vores elektroniske viden, hvordan vi kan få det til at se smarter ud og ikke mindst mere praktisk.

Men hvordan startede det hele egentlig?

Kapitler

Lommeregneren som Grundsten

Antikythera - Den tidligste "computer"

Stamfaderen

Den tidlige computer

Konrad Zuse

Z3 Computeren

Referencer

                ```

答:
You will be counting the height or the article.

```<code>var h = $('articile').height();
</code>```

And then You will tell your page to change the css of the element to relative after you scroll more then article's height

```<code>$(window).scroll(function(){
  if(window).scrollTop() > h){
    $('navbar').css('position','relative');
  }
});
</code>```

If you share some code I'll helping you better.

Title: Make sticky object stop being sticky

Body:
I'm about to make a portfolio for my exam. For that we have some articles we have to make for it. Therefore ive made a homepage, which shows the subjects that ive been writing about, and when you click on one of them, you come down to the article instantly.
On the left side there is a new menu which is sat as sticky, and scrolls with the page. The menu only contains the subjects that im going through for that single

My problem is, that the menu KEEPS on scrolling with the page, when it should stop after the article has ended, so a new chapter menu can appear. How do I do that?

Edit: I was on my phone when i wrote it.. But here is the code for the MENU on HTML, CSS and Jquery

  /*** Left Menu ***/
    var navLeftPos = $('#left_menu').offset().top;
    //console.log(navLeftPos)
    $(window).on('scroll', function () {
        console.log($(window).scrollTop())
        if (navTopPos <= $(window).scrollTop()) {
            $('#left_menu').addClass('left_menu')
        }
        if (navTopPos <= $(window).scrollTop() ) {
            $('#left_menu').addClass('left_menu')
        }
        else {
            $('#left_menu').removeClass('left_menu');
        }
    });

/*** Menu sidebar ***/

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu {
    float:left;
    width: 30%;
    padding: 1.5% 1.5% 1.5% 5%;
    background-color: #C4E1AC;
}

div#wrapper div#underlayer div#ComputerensHistorie section.left_menu {
    position: fixed;
    top: 105px;
    left: 0;
}

/***** Overskrift *****/

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu h2 {
    font-family: Frank Ruhl Libre;
    letter-spacing: 2px;
}

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu svg {
    width: 60%;
    margin-bottom: 15px;
}

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu svg .cls-1 {
    stroke-width: 0.5px;
}

/***** Animations understreg *****/

svg#understreg_et line#streg_tre {
    stroke: #3A8540;
    animation: backandforth 12s linear infinite;
}

svg#understreg_et line#streg_to {
    stroke: #fff;
    animation: backandforth 4s linear infinite;
}

svg#understreg_et line#streg_et {
    stroke: #245328;
    animation: backandforth 6s linear infinite;
}

@keyframes backandforth {
    0% {
        transform: scaleX(1);
    }
    25% {
        transform: scaleX(0.8)
    }
    50% {
        transform: scaleX(0.5);
    }
    80% {
        transform: scaleX(0.8);
    }
    100% {
        transform: scaleX(1);
    }
}

/**** Introduktion *****/

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu p {
    font-size: 13px;
    line-height: 150%;
    padding-top: 15px;
    font-family: roboto;
}

/**** Navigation ****/

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu nav {
    font-size: 13px;
    line-height: 150%;
    margin-top: 10%;
}

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu nav ul {}

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu nav ul li {
    list-style-type: none;
}

div#wrapper div#underlayer div#ComputerensHistorie section.left_menu nav ul li.links {
    margin-left: 20px;
    font-family: roboto;
}

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu nav ul li a {
    text-decoration: none;
    line-height: 150%;
    color: black;
    font-family: roboto;
    font-size: 0.9em;
}

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu nav ul li a:hover {
    color: #3f824f;
}

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu nav ul ul {
    margin-left: 15px;
}

div#wrapper div#underlayer div#ComputerensHistorie section#left_menu nav ul li h2 {
    font-size: 14px;
    text-transform: uppercase;
    border-bottom: 1px solid #000;
    margin-bottom: 10px;
    font-family: roboto;
    padding-left: 5px;
    letter-spacing: 0.5px;
    width: auto;
}

Computerens historie

                    <svg id="understreg_et" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 72 8"><defs></defs><title>streg</title><line id="streg_tre" class="cls-1" y1="1" x2="60" y2="1"/><line id="streg_to" class="cls-1" x1="72" y1="4" x2="29" y2="4"/><line id="streg_et" class="cls-1" x1="11" y1="7" x2="46" y2="7"/></svg>

Vores dagligdag er konstant præget af den elektroniske verden, der omgiver os derhjemme, på gaden, arbejdet - alle steder!

Vi forsker hele tiden i hvordan vi kan optimere vores elektroniske viden, hvordan vi kan få det til at se smarter ud og ikke mindst mere praktisk.

Men hvordan startede det hele egentlig?

Kapitler

Lommeregneren som Grundsten

Antikythera - Den tidligste "computer"

Stamfaderen

Den tidlige computer

Konrad Zuse

Z3 Computeren

Referencer

Body:
You will be counting the height or the article.

var h = $('articile').height();

And then You will tell your page to change the css of the element to relative after you scroll more then article's height

$(window).scroll(function(){
  if(window).scrollTop() > h){
    $('navbar').css('position','relative');
  }
});

If you share some code I'll helping you better.


问:
Adding a delay to inline onmouseover
I am working on a page which allows you to view items on a google map. You can hover over a business address and it will move the map to that location and open an infowindow.  It works perfectly, but the onmouseover event is inline because every onmouseover has a different id, which is set by a php variable.

The problem is, I need to find a way to add a delay to the onmouseover event, so that the user has to hover over the item for a couple of seconds before the onmouseover is triggered.

I've looked around at some possible solutions, but nothing seems to add the delay.

The onmouseover link looks like this...

```<code><a onmouseover="javascript:triggerClick(<?php echo $id; ?>)" href="<?php echo $listingurl; ?>">
</code>```

Any suggestions would be appreciated.

答:
OK, I made it work thanks to this thread... this is what it looks like now and it works...

```<code><a onmouseover="setTimeout(function(){ javascript:triggerClick(<?php echo $id; ?>); }, 1000);" href="<?php echo $listingurl; ?>">
</code>```

Thanks

Title: Adding a delay to inline onmouseover

Body:
I am working on a page which allows you to view items on a google map. You can hover over a business address and it will move the map to that location and open an infowindow.  It works perfectly, but the onmouseover event is inline because every onmouseover has a different id, which is set by a php variable.

The problem is, I need to find a way to add a delay to the onmouseover event, so that the user has to hover over the item for a couple of seconds before the onmouseover is triggered.

I've looked around at some possible solutions, but nothing seems to add the delay.

The onmouseover link looks like this...

<a onmouseover="javascript:triggerClick(<?php echo $id; ?>)" href="<?php echo $listingurl; ?>">

Any suggestions would be appreciated.

Body:
OK, I made it work thanks to this thread... this is what it looks like now and it works...

<a onmouseover="setTimeout(function(){ javascript:triggerClick(<?php echo $id; ?>); }, 1000);" href="<?php echo $listingurl; ?>">

Thanks


问:
Concurrent requests handling on Google App Engine
I was experimenting with concurrent request handling on few platforms.

The aim of the experiment was to have a broad measure of the capacity bounds of some selected technologies.

I set up a Linux VM on my machine with a basic Go http server (the vanilla http.HandleFunc of the http default package).
The server would then compute a modified version of the fasta algorithm that restricted threads and processes to 1, and return the result. N was set to 100000.
The algorithm runs in roughly 2 seconds.
I used the same algorithm and logic on a Google App Engine project.

The algorithm is written using the same code, just the handler set up is done on init() instead of main() as per GAE requirements.

On the other end an Android client is spawning 500 threads each one issuing in parallel a GET request to the fasta computing server, with a request timeout of 5000 ms.

I was expecting the GAE application to scale and answer back to each request and the local Go server to fail on some of the 500 requests but results were the opposite:
the local server correctly replied to each request within the timeout bounds while the GAE application was able to handle just 160 requests out of 500. The remaining requests timed out.

I checked on the Cloud Console and I verified that 18 GAE instances were spawned, but still the vast majority of requests failed.

I thought that most of them failed because of the start-up time of each GAE instance, so I repeated the experiment right after but I had the same results: most of the requests timed out.

I was expecting GAE to scale to accomodate ALL the requests, believing that if a single local VM could successfully reply to 500 concurrent requests GAE would have done the same, but this is not what happened.

The GAE console doesn't show any error and correctly reports the number of incoming requests.

What could be the cause of this?
Also, if a single instance could handle all the incoming requests on my machine by virtue of only goroutines, how come that GAE needed to scale so much at all?

答:
Thanks everyone for their help.
Many interesting points and insights have been made by the answers I had on this topic.

The fact the the Cloud Console were reporting no errors led me to believe that the bottleneck was happening after the real request processing.

I found the reason why the results were not as expected: bandwidth.

Each response had a payload of roughly 1MB and thus responding to 500 simultaneous connections from the same client would clog the lines, resulting in timeouts.
This was obviously not happening when requesting to the VM, where the bandwith is much larger.

Now GAE scaling is in line with what I expected: it successfully scales to accomodate each incoming request.


问:
Content of unmatched string
I am parsing input from stdin, which is in the following format:

```<code>1
2
3
done
</code>```

My current code is:

```<code>while(<> =~ /(\d+)/) {
    # do something with $1
}
# I want to access the line following the last number here
</code>```

which is fine for the 1st part of the file (with the list of numbers).
However, I would like the content of the line immediately following the last number.

Is there any elegant way to do it?

Title: Content of unmatched string

Body:
I am parsing input from stdin, which is in the following format:

1
2
3
done

My current code is:

while(<> =~ /(\d+)/) {
    # do something with $1
}
# I want to access the line following the last number here

which is fine for the 1st part of the file (with the list of numbers).
However, I would like the content of the line immediately following the last number.

Is there any elegant way to do it?

Body:
while (<>) {
    chomp;
    last if !/^\d+\z/;

    ... $_ ...
}

die("Premature EOF") if !defined($_);

... $_ ...


问:
Can't get Share Button aligned!
I'm trying to align the share, like and tweet button horizontally but I can't get the share button right. I tried adding vertical align top, changing the height and display:inline but it always remains more or less 10px belowe the others. What should I do to get them all aligned?

```<code><div style='vertical-align: top;'>

<a expr:share_url='data:post.url' name='fb_share'/>

<a class='twitter-share-button' data-count='horizontal' data-lang='es' data-related=':' data-via='' expr:data-text='data:post.title' expr:data-url='data:post.url' href='http://twitter.com/share' rel='nofollow'/>

<iframe allowTransparency='true' expr:src='"http://www.facebook.com/plugins/like.php?href=" + data:post.url + "&layout=button_count&show_faces=false&width=100&action=like&font=arial&colorscheme=light"' frameborder='0' scrolling='no' style='border:none; overflow:hidden; width:110px; height:20px;'/>
</div>

<script src='http://static.ak.fbcdn.net/connect.php/js/FB.Share' type='text/javascript'>
</script>

<script src='http://platform.twitter.com/widgets.js' type='text/javascript'>
</script>
</code>```

Thanks

答:
An easier method than styling these elements individually, is to sandwich them inside
 tags--allowing you to position the parent
 easily, and also float the
 tags (creating the 'inline' effect you're after.)

jsFiddle didn't like the facebook APIs, so I used 3 twitter buttons instead; the code looks like:

```<code><ul class="social_network">
    <li>
        <a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="">Tweet</a>
    </li>

    <li>
        <a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="">Tweet</a>
    </li>

    <li>
        <a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="">Tweet</a>
    </li>
</ul>
</code>```

With some very simple CSS (including a subtle outline so you can see the boundaries of the
 elements:

```<code>.social_network {
    position : relative;
    list-style-type : none;
}
.social_network li {
    float : left;
    border : 1px solid rgba(0,0,0,.1);
    padding : 6px;
    margin : 2px;
}
</code>```

You can find an example of the above here: http://jsfiddle.net/kgFaW/

This should put you in the right direction. Let me know if you run into any issues with the Facebook APIs.

Title: Can't get Share Button aligned!

Body:
I'm trying to align the share, like and tweet button horizontally but I can't get the share button right. I tried adding vertical align top, changing the height and display:inline but it always remains more or less 10px belowe the others. What should I do to get them all aligned?

Thanks

Body:
An easier method than styling these elements individually, is to sandwich them inside <li> tags--allowing you to position the parent <ul> easily, and also float the <li> tags (creating the 'inline' effect you're after.)

jsFiddle didn't like the facebook APIs, so I used 3 twitter buttons instead; the code looks like:

<ul class="social_network">
    <li>
        <a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="">Tweet</a>
    </li>

    <li>
        <a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="">Tweet</a>
    </li>

    <li>
        <a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="">Tweet</a>
    </li>
</ul>

With some very simple CSS (including a subtle outline so you can see the boundaries of the <li> elements:

.social_network {
    position : relative;
    list-style-type : none;
}
.social_network li {
    float : left;
    border : 1px solid rgba(0,0,0,.1);
    padding : 6px;
    margin : 2px;
}

You can find an example of the above here: http://jsfiddle.net/kgFaW/

This should put you in the right direction. Let me know if you run into any issues with the Facebook APIs.


问:
Sum integer list when next integer is the same value
So I need to have a code that checks one integer, and checks if the integer after it is the same value. If so, it will add the value to x.

```<code>input1 = [int(i) for i in str(1234441122)]
x= 0
</code>```

So my code currently gives the result [1, 2, 3, 4, 4, 4, 1, 1 ,2 ,2]. I want it to give the result of x = 0+4+4+1+2.
I do not know any way to do that.

答:
You can try this:

```<code>s = str(1234441122)
new_data = [int(a) for i, a in enumerate(s) if i+1 < len(s) and a == s[i+1]]
print(new_data)
final_data = sum(new_data)
</code>```

Output:

```<code>[4, 4, 1, 2]
11
</code>```

Body:
So I need to have a code that checks one integer, and checks if the integer after it is the same value. If so, it will add the value to x.

input1 = [int(i) for i in str(1234441122)]
x= 0

So my code currently gives the result [1, 2, 3, 4, 4, 4, 1, 1 ,2 ,2]. I want it to give the result of x = 0+4+4+1+2.
I do not know any way to do that.

Body:
You can try this:

s = str(1234441122)
new_data = [int(a) for i, a in enumerate(s) if i+1 < len(s) and a == s[i+1]]
print(new_data)
final_data = sum(new_data)

Output:

[4, 4, 1, 2]
11


问:
TypeError: null is not an object (evaluating '*')
For the below code:

```<code>var item = cartModel.getlist()[index];
if((item.isDepo()) {
    // Some code
} else if(!permission.hasPermissionToVoidSKU()) {
    // Some code
} else if(item.sku.indexOf(mposConstants.RESTOCK_FEE_SKU) > -1){
                // Some code
}
</code>```

I'm getting this error:

TypeError: null is not an object (evaluating 'item.sku.indexOf')

If item object is null, the error is something different (see below). In what scenario will this error be thrown?

Update:

If item.sku is null, the error is:

[FATAL] [] [-] ["TypeError: Cannot read property 'indexOf' of null

If item is null, the error is:

[FATAL] [] [-] ["TypeError: Cannot read property 'isDepo' of null

Body:
For the below code:

var item = cartModel.getlist()[index];
if((item.isDepo()) {
    // Some code
} else if(!permission.hasPermissionToVoidSKU()) {
    // Some code
} else if(item.sku.indexOf(mposConstants.RESTOCK_FEE_SKU) > -1){
                // Some code
}

I'm getting this error:

TypeError: null is not an object (evaluating 'item.sku.indexOf')

If item object is null, the error is something different (see below). In what scenario will this error be thrown?

Update:

If item.sku is null, the error is:

[FATAL] [] [-] ["TypeError: Cannot read property 'indexOf' of null

If item is null, the error is:

[FATAL] [] [-] ["TypeError: Cannot read property 'isDepo' of null

Body:
Based on this answer and others, it sounds like you're getting that error because a function is called before the DOM element it references or acts upon has been loaded.

In the snippet of code you provided, I don't see a direct reference to any DOM elements, but I would suggest calling your script after your HTML has finished rendering (i.e. by putting any <script> tags at the end of your HTML, or by using a $(document).ready() call if you use jQuery).


问:
Python - Why backup variable inside loop is being updated if I don't change it value inside?
I want to set the values of matrix W in Wo.
Then, I will go inside a loop and do operations with W. At the end of the loop, I want to restore it to Wo, but I am getting the opposite result, Wo is becoming Wo.

How is that possible? How can I accomplish what I want? I have also tried defining Wo as a global but no result

```<code>W = np.random.rand(5, 10)
global Wo
Wo = W # Back up for the initial values of W

for k in range(0, K):

  for j in range(0, m):       # For every hidden node

    for i in range(0, n):        # For every connection

      # Operations (W get changed)
      W = Wo
</code>```

Then, if I check the value of Wo has been modified, in a way that Wo == W is always True.

What am I missing?

Thanks in advance

答:
All items in Python are references so if you change one reference other will change too

```<code>l = []
global l_global
l_global = l

for i in range(1, 10):
  l.append(i)

print(l)
print(l_global)
</code>```

Does it make sense now for your case?

Body:
I want to set the values of matrix W in Wo.
Then, I will go inside a loop and do operations with W. At the end of the loop, I want to restore it to Wo, but I am getting the opposite result, Wo is becoming Wo.

How is that possible? How can I accomplish what I want? I have also tried defining Wo as a global but no result

W = np.random.rand(5, 10)
global Wo
Wo = W # Back up for the initial values of W

for k in range(0, K):

  for j in range(0, m):       # For every hidden node

    for i in range(0, n):        # For every connection

      # Operations (W get changed)
      W = Wo

Then, if I check the value of Wo has been modified, in a way that Wo == W is always True.

What am I missing?

Thanks in advance

Body:
All items in Python are references so if you change one reference other will change too

l = []
global l_global
l_global = l

for i in range(1, 10):
  l.append(i)

print(l)
print(l_global)

Does it make sense now for your case?


问:
Error(389/703 with Wildfly 11 server
When i'm want to start a wildfly server, I write in terminal /opt/wildfly11/bin$ sudo ./standalone.sh
But after that I get several mistakes, such below:

=========================================================================

JBoss Bootstrap Environment

JBOSS_HOME: /opt/wildfly11

JAVA: java

JAVA_OPTS:  -server -Xms64m -Xmx512m -XX:MetaspaceSize=96M
  -XX:MaxMetaspaceSize=256m -Djava.net.preferIPv4Stack=true -Djboss.modules.system.pkgs=org.jboss.byteman -Djava.awt.headless=true

=========================================================================

12:45:34,953 INFO  [org.jboss.modules] (main) JBoss Modules version
  1.6.1.Final WARNING: An illegal reflective access operation has occurred WARNING: Illegal reflective access by
  org.wildfly.security.manager.GetAccessibleDeclaredFieldAction
  (jar:file:/opt/wildfly11/modules/system/layers/base/org/wildfly/security/elytron-private/main/wildfly-elytron-1.1.6.Final.jar!/)
  to field java.security.AccessControlContext.context WARNING: Please
  consider reporting this to the maintainers of
  org.wildfly.security.manager.GetAccessibleDeclaredFieldAction WARNING:
  Use --illegal-access=warn to enable warnings of further illegal
  reflective access operations WARNING: All illegal access operations
  will be denied in a future release

389 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-7)
  MSC000001: Failed to start service
  org.wildfly.management.http.extensible:
  org.jboss.msc.service.StartException in service
  org.wildfly.management.http.extensible: java.net.BindException: Адресу
  вже використано /127.0.0.1:9990   at
  org.jboss.as.server//org.jboss.as.server.mgmt.UndertowHttpManagementService.start(UndertowHttpManagementService.java:340)
    at
  org.jboss.msc//org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:2032)
    at
  org.jboss.msc//org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1955)
    at
  java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
    at
  java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
    at java.base/java.lang.Thread.run(Thread.java:844)

12:45:44,***703 ERROR [org.jboss.as.controller.management-operation]
  (Controller Boot Thread) WFLYCTL0013: Operation ("add") failed -
  address: ([
      ("core-service" => "management"),
      ("management-interface" => "http-interface") ]) - failure description: {"WFLYCTL0080: Failed services" =>
  {"org.wildfly.management.http.extensible" => "java.net.BindException:
  Адресу вже використано /127.0.0.1:9990"}} 12:45:44,**715 ERROR
  [org.jboss.as.controller.management-operation] (Controller Boot
  Thread) WFLYCTL0013: Operation ("add") failed - address: ([
      ("core-service" => "management"),
      ("management-interface" => "http-interface") ]) - failure description: {"WFLYCTL0080: Failed services" =>
  {"org.wildfly.management.http.extensible" => "java.net.BindException:
  Адресу вже використано /127.0.0.1:9990"}}*****  WildFly Full
  11.0.0.Final (WildFly Core 3.0.8.Final) stopped in 32ms

答:
It seems to me, that your port is used by an other application. (google translate :) ) you can check it with a command:

```<code>netstat -tulpn | grep :9990
</code>```

You can set a port offset to wildfly by setting system property:

```<code>bin/standalone.sh -Djboss.socket.binding.port-offset=100
</code>```

But be aware you need to specify port when connection to CLI after:

```<code>bin/jboss-cli.sh --controller=localhost:10090 -c
</code>```

Also any other service will be using port increased by 100 in such case.

Title: Error(389/703 with Wildfly 11 server

Body:
It seems to me, that your port is used by an other application. (google translate :) ) you can check it with a command:

netstat -tulpn | grep :9990

You can set a port offset to wildfly by setting system property:

bin/standalone.sh -Djboss.socket.binding.port-offset=100

But be aware you need to specify port when connection to CLI after:

bin/jboss-cli.sh --controller=localhost:10090 -c

Also any other service will be using port increased by 100 in such case.


问:
How to query huge MySQL databases?
I have 2 tables, a purchases table and a users table. Records in the purchases table looks like this:

```<code>purchase_id | product_ids | customer_id
---------------------------------------
1           | (99)(34)(2) | 3
2           | (45)(3)(74) | 75
</code>```

Users table looks like this:

```<code>user_id  | email              | password
----------------------------------------
3        | joeShmoe@gmail.com | password
75       | nolaHue@aol.com    | password
</code>```

To get the purchase history of a user I use a query like this:

```<code>mysql_query(" SELECT * FROM purchases WHERE customer_id = '$users_id' ");
</code>```

The problem is, what will happen when tens of thousands of records are inserted into the purchases table. I feel like this will take a performance toll.

So I was thinking about storing the purchases in an additional field directly in the user's row:

```<code>user_id | email              | password  | purchases
------------------------------------------------------
1       | joeShmoe@gmail.com | password  | (99)(34)(2)
2       | nolaHue@aol.com    | password  | (45)(3)(74)
</code>```

And when I query the user's table for things like username, etc. I can just as easily grab their purchase history using that one query.

Is this a good idea, will it help better performance or will the benefit be insignificant and not worth making the database look messier?

I really want to know what the pros do in these situations, for example how does amazon query it's database for user's purchase history since they have millions of customers. How come there queries don't take hours?

EDIT

Ok, so I guess keeping them separate is the way to go. Now the question is a design one:

Should I keep using the "purchases" table I illustrated earlier. In that design I am separating the product ids of each purchase using parenthesis and using this as the delimiter to tell the ids apart when extracting them via PHP.

Instead should I be storing each product id separately in the "purchases" table so it looks like this?:

```<code>purchase_id | product_ids | customer_id
---------------------------------------
1           | 99          | 3
1           | 34          | 3
1           | 2           | 3
2           | 45          | 75
2           | 3           | 75
2           | 74          | 75
</code>```

答:
Nope, this is a very, very, very bad idea.

You're breaking first normal form because you don't know how to page through a large data set.

Amazon and Yahoo! and Google bring back (potentially) millions of records - but they only display them to you in chunks of 10 or 25 or 50 at a time.

They're also smart about guessing or calculating which ones are most likely to be of interest to you - they show you those first.

Which purchases in my history am I most likely to be interested in?  The most recent ones, of course.

You should consider building these into your design before you violate relational database fundamentals.

Title: How to query huge MySQL databases?

Body:
I have 2 tables, a purchases table and a users table. Records in the purchases table looks like this:

purchase_id | product_ids | customer_id
---------------------------------------
1           | (99)(34)(2) | 3
2           | (45)(3)(74) | 75

Users table looks like this:

user_id  | email              | password
----------------------------------------
3        | joeShmoe@gmail.com | password
75       | nolaHue@aol.com    | password

To get the purchase history of a user I use a query like this:

mysql_query(" SELECT * FROM purchases WHERE customer_id = '$users_id' ");

The problem is, what will happen when tens of thousands of records are inserted into the purchases table. I feel like this will take a performance toll.

So I was thinking about storing the purchases in an additional field directly in the user's row:

user_id | email              | password  | purchases
------------------------------------------------------
1       | joeShmoe@gmail.com | password  | (99)(34)(2)
2       | nolaHue@aol.com    | password  | (45)(3)(74)

And when I query the user's table for things like username, etc. I can just as easily grab their purchase history using that one query.

Is this a good idea, will it help better performance or will the benefit be insignificant and not worth making the database look messier?

I really want to know what the pros do in these situations, for example how does amazon query it's database for user's purchase history since they have millions of customers. How come there queries don't take hours?

EDIT

Ok, so I guess keeping them separate is the way to go. Now the question is a design one:

Should I keep using the "purchases" table I illustrated earlier. In that design I am separating the product ids of each purchase using parenthesis and using this as the delimiter to tell the ids apart when extracting them via PHP.

Instead should I be storing each product id separately in the "purchases" table so it looks like this?:

purchase_id | product_ids | customer_id
---------------------------------------
1           | 99          | 3
1           | 34          | 3
1           | 2           | 3
2           | 45          | 75
2           | 3           | 75
2           | 74          | 75


答:
The following will work. Zip together adjacent pairs and only take the first elements if they are the same as the second ones:

```<code>>>> lst = [1, 2, 3, 4, 4, 4, 1, 1, 2, 2]
>>> sum(x for x, y in zip(lst, lst[1:]) if x == y)
11
</code>```

While this should be a little less [space-]efficent in theory (as the slice creates an extra list), it still has O(N) complexity in time and space and is well more readable than most solutions based on indexed access. A tricky way to avoid the slice while still being concise and avoiding any imports would be:

```<code>>>> sum((lst[i] == lst[i-1]) * lst[i] for i in range(1, len(lst)))  # Py2: xrange
11
</code>```

This makes use of the fact that lst[i]==lst[i-1] will be cast to 0 or 1 appropriately.

Title: Sum integer list when next integer is the same value

Body:
The following will work. Zip together adjacent pairs and only take the first elements if they are the same as the second ones:

>>> lst = [1, 2, 3, 4, 4, 4, 1, 1, 2, 2]
>>> sum(x for x, y in zip(lst, lst[1:]) if x == y)
11

While this should be a little less [space-]efficent in theory (as the slice creates an extra list), it still has O(N) complexity in time and space and is well more readable than most solutions based on indexed access. A tricky way to avoid the slice while still being concise and avoiding any imports would be:

>>> sum((lst[i] == lst[i-1]) * lst[i] for i in range(1, len(lst)))  # Py2: xrange
11

This makes use of the fact that lst[i]==lst[i-1] will be cast to 0 or 1 appropriately.


问:
How to speed up exporting in Google Earth Engine?
I need to download a bunch of Landsat images from Google Earth Engine, and I'm doing it in its Python API with

```<code>task = ee.batch.Export.image(IMAGE, NAME, config=CONFIG)
task.start()
</code>```

Though it's working, the speed is extremely slow. The size of my images is around 70kb, but each takes 4 min or longer. Currently this happens in a for loop, so how can I, if possible, pack up multiple images as one task? Or other ways to speed up this process?

答:
The startup costs for an export are pretty high.  If you're just exporting tiny pieces, you might be able to do it with image.getThumbnail for RGB visualized images, or image.getDownloadURL() for raw numbers.

The getThumbnail() function will give you a PNG or JPEG and getDownloadURL() will give you a zipfile with the bands as individual geotiffs.  Note that both are unreliable for large downloads or images that take a lot of computation.  Since the image starts being computed once you access the resulting URL, there's no way to communicate failure; if something goes wrong, you just get a empty/corrupt file.

Body:
I need to download a bunch of Landsat images from Google Earth Engine, and I'm doing it in its Python API with

task = ee.batch.Export.image(IMAGE, NAME, config=CONFIG)
task.start()

Though it's working, the speed is extremely slow. The size of my images is around 70kb, but each takes 4 min or longer. Currently this happens in a for loop, so how can I, if possible, pack up multiple images as one task? Or other ways to speed up this process?


问:
retreiving instagram story for logged in user via instagram omniauth
I am building ruby on rails application which uses instagram omniauth for user authentication. How can I pull user story from Instagram API with data about story viewers?

I am using following gems to enable Instagram Omniauth:

```<code>gem 'devise'
gem 'omniauth'
gem 'omniauth-instagram'
gem 'instagram'
</code>```

答:
They're still no way to get User's Stories data with the Instagram Public API, even if you're authenticated.

As you can see in the documentation, The media endpoint only returns items of type Images, Videos and Carousel.

Body:
I am building ruby on rails application which uses instagram omniauth for user authentication. How can I pull user story from Instagram API with data about story viewers?

I am using following gems to enable Instagram Omniauth:

gem 'devise'
gem 'omniauth'
gem 'omniauth-instagram'
gem 'instagram'


问:
Modifying Page controls from Xslt helper function class in Sitecore
Within an xslt render I call the following

```<code><xsl:value-of select="di:inject()"/>
</code>```

The corresponding class retrieves the current page object and attempts to modify the page header

public class XslHelper : Sitecore.Xml.Xsl.XslHelper
{
    public void inject()
    {
        Page page = HttpContext.Current.Handler as Page;

        // page.GetType().FullName tells me that I have successfully got the reference

        page.Header.Controls.Add(new HtmlLink { Href = "/style.css" });
    }
}
```

However the header does not get updated? Why is this and is there another way to achieve the same result?

EDIT: We ended up extending the XslRender template and storing dependencies there instead, which can then be picked up and added to the session by overriding the InsertRenderings class in the renderLayout pipeline. The session object can then be accessed on Page_Load in the layout, which can access the header of the page.

答: You'd probably be better off just having all your classes in a single static CSS file. The additional overhead of HTTP requests and CPU load makes it hard to justify the benefits gained from dynamically loading CSS. </p>

Body:
Within an xslt render I call the following

<xsl:value-of select="di:inject()"/>

The corresponding class retrieves the current page object and attempts to modify the page header

public class XslHelper : Sitecore.Xml.Xsl.XslHelper
{
    public void inject()
    {
        Page page = HttpContext.Current.Handler as Page;

        // page.GetType().FullName tells me that I have successfully got the reference

        page.Header.Controls.Add(new HtmlLink { Href = "/style.css" });
    }
}

However the header does not get updated? Why is this and is there another way to achieve the same result?

EDIT: We ended up extending the XslRender template and storing dependencies there instead, which can then be picked up and added to the session by overriding the InsertRenderings class in the renderLayout pipeline. The session object can then be accessed on Page_Load in the layout, which can access the header of the page.


问:
Running mongodb forever using forever in windows
I am trying to run MongoDB server forever locally on Windows 10. And for that I'm using forever server.js which throws an error i.e, Forever is not installed.

I did npm install. But then too showing the same error.
I have followed this guide, but it's for Ubuntu. I am using Windows 10.

I need something like if I close the server cmd also, it should keep running.

答:
You need to install mongo as a service.
To do so,

Open cmd in administrator mode.

Create two directories to store data and logs

mkdir c:\data\db

mkdir c:\data\log

Create a configuration file. The file must set systemLog.path. Include additional configuration options as appropriate.For example, create a file at C:\Program Files\MongoDB\Server\3.6\mongod.cfg that specifies both systemLog.path and storage.dbPath like this:

systemLog:

destination: file

path: c:\data\log\mongod.log

storage:

dbPath: c:\data\db

install mongo service, run the following command:

mongod.exe --config "C:\Program Files\MongoDB\Server\3.4\mongod.cfg" --install

Start service using: >net start mongodb

To stop service use : >net stop mongodb

You can refer official documents here


问:
Skybox is completely black
I'm following ThinMatrix's guide on Youtube and trying to create a skybox for my engine. However, my skybox comes out black. I've tried all the different suggestions and common mistakes that people suggested in the comments, I can not for the life of me figure out what is wrong with it.

I'm not getting any error either :/

Bellow are the relevant methods in the relevant classes. I can provide more code if needed.

Loader.java

```<code> public int loadCubeMap(String[] cubeMapTextures) {
        int textureID = GL11.glGenTextures();

        GL13.glActiveTexture(GL13.GL_TEXTURE0);
        GL11.glBindTexture(GL13.GL_TEXTURE_CUBE_MAP, textureID);

        for (int i = 0; i < cubeMapTextures.length; i++) {
          TextureData data = decodeTexture("res/skybox/" + cubeMapTextures[i] + ".png");

          GL11.glTexImage2D(GL13.GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL11.GL_RGBA, data.getWidth(), data.getHeight(),
              0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, data.getBuffer());
        }

        GL11.glTexParameteri(GL13.GL_PROXY_TEXTURE_CUBE_MAP, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR);
        GL11.glTexParameteri(GL13.GL_PROXY_TEXTURE_CUBE_MAP, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR);
        GL11.glTexParameteri(GL13.GL_TEXTURE_CUBE_MAP, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE);
        GL11.glTexParameteri(GL13.GL_TEXTURE_CUBE_MAP, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE);

        textures.add(textureID);
        return textureID;
      }

      private TextureData decodeTexture(String fileName) {
        int width = 0;
        int height = 0;
        ByteBuffer buffer = null;

        try {
          FileInputStream in = new FileInputStream(fileName);
          PNGDecoder decoder = new PNGDecoder(in);

          width = decoder.getWidth();
          height = decoder.getHeight();
          buffer = ByteBuffer.allocateDirect(4 * width * height);
          decoder.decode(buffer, width * 4, Format.RGBA);

          buffer.flip();
          in.close();
        } catch (Exception e) {
          e.printStackTrace();
          System.err.println("Failed loading:  " + fileName);
          System.exit(-1);
        }

        return new TextureData(height, width, buffer);
      }
</code>```

SkyboxRenderer.java

```<code>private static final float SIZE = 500f;
private static final float[] VERTICES = {
    -SIZE,  SIZE, -SIZE,
    -SIZE, -SIZE, -SIZE,
    SIZE, -SIZE, -SIZE,
     SIZE, -SIZE, -SIZE,
     SIZE,  SIZE, -SIZE,
    -SIZE,  SIZE, -SIZE,

    -SIZE, -SIZE,  SIZE,
    -SIZE, -SIZE, -SIZE,
    -SIZE,  SIZE, -SIZE,
    -SIZE,  SIZE, -SIZE,
    -SIZE,  SIZE,  SIZE,
    -SIZE, -SIZE,  SIZE,

     SIZE, -SIZE, -SIZE,
     SIZE, -SIZE,  SIZE,
     SIZE,  SIZE,  SIZE,
     SIZE,  SIZE,  SIZE,
     SIZE,  SIZE, -SIZE,
     SIZE, -SIZE, -SIZE,

    -SIZE, -SIZE,  SIZE,
    -SIZE,  SIZE,  SIZE,
     SIZE,  SIZE,  SIZE,
     SIZE,  SIZE,  SIZE,
     SIZE, -SIZE,  SIZE,
    -SIZE, -SIZE,  SIZE,

    -SIZE,  SIZE, -SIZE,
     SIZE,  SIZE, -SIZE,
     SIZE,  SIZE,  SIZE,
     SIZE,  SIZE,  SIZE,
    -SIZE,  SIZE,  SIZE,
    -SIZE,  SIZE, -SIZE,

    -SIZE, -SIZE, -SIZE,
    -SIZE, -SIZE,  SIZE,
     SIZE, -SIZE, -SIZE,
     SIZE, -SIZE, -SIZE,
    -SIZE, -SIZE,  SIZE,
     SIZE, -SIZE,  SIZE
};

private static String[] textureFiles = {"stormydays_rt", "stormydays_lf", "stormydays_up", "stormydays_dn", "stormydays_bk", "stormydays_ft"};

private RawModel cube;
private int textureID;
private SkyboxShader shader;

public SkyBoxRenderer(Loader loader, Matrix4f projectionMatrix) {
    cube = loader.loadToVAO(VERTICES, 3);
    textureID = loader.loadCubeMap(textureFiles);
    shader = new SkyboxShader();
    shader.start();
    shader.loadProjectionMatrix(projectionMatrix);
    shader.stop();
}

public void render(Camera camera) {
    shader.start();
    shader.loadViewMatrix(camera);

    GL30.glBindVertexArray(cube.getVaoID());
    GL20.glEnableVertexAttribArray(0);
    GL13.glActiveTexture(GL13.GL_TEXTURE0);
    GL11.glBindTexture(GL13.GL_TEXTURE_CUBE_MAP, textureID);
    GL11.glDrawArrays(GL11.GL_TRIANGLES, 0, cube.getVertexCount());
    GL20.glDisableVertexAttribArray(0);
    GL30.glBindVertexArray(0);

    shader.stop();
}
</code>```

SkyboxShader.java

```<code> private static final String VERTEX_FILE = "src/shaders/skyboxVertexShader.txt";
  private static final String FRAGMENT_FILE = "src/shaders/skyboxFragmentShader.txt";

  private int location_projectionMatrix;
  private int location_viewMatrix;

  public SkyboxShader() {
      super(VERTEX_FILE, FRAGMENT_FILE);
  }

  public void loadProjectionMatrix(Matrix4f matrix){
      super.loadMatrix(location_projectionMatrix, matrix);
  }

  public void loadViewMatrix(Camera camera){
      Matrix4f matrix = Maths.createViewMatrix(camera);
      super.loadMatrix(location_viewMatrix, matrix);
  }

  @Override
  protected void getAllUniformLocations() {
      location_projectionMatrix = super.getUniformLocation("projectionMatrix");
      location_viewMatrix = super.getUniformLocation("viewMatrix");
  }

  @Override
  protected void bindAttributes() {
      super.bindAttribute(0, "position");
  }
</code>```

And here is my GLSL code
skyboxVertexShader

```<code>#version 400

in vec3 position;
out vec3 textureCoords;

uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;

void main(void){

    gl_Position = projectionMatrix * viewMatrix * vec4(position, 1.0);
    textureCoords = position;

}
</code>```

skyboxFragmentShader

```<code>#version 400

in vec3 textureCoords;
out vec4 out_Color;

uniform samplerCube cubeMap;

void main(void){
    out_Color = texture(cubeMap, textureCoords);
}
</code>```

答:
This probably happens because the texture isn't complete.
To complete your cube map texture you have to set GL_TEXTURE_WRAP_R with glTexParameteri because a cube is 3D.
Furthermore you are using GL_PROXY_TEXTURE_CUBE_MAP instead of GL_TEXTURE_CUBE_MAP, this does't work because proxy textures aren't a valid parameter.

So just replace:

```<code>GL11.glTexParameteri(GL13.GL_PROXY_TEXTURE_CUBE_MAP, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR);
GL11.glTexParameteri(GL13.GL_PROXY_TEXTURE_CUBE_MAP, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR);
GL11.glTexParameteri(GL13.GL_TEXTURE_CUBE_MAP, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE);
GL11.glTexParameteri(GL13.GL_TEXTURE_CUBE_MAP, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE);
</code>```

With:

```<code>glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
</code>```

If this doesn't help, confirm that all textures have the same size.

PS: Use import static GL##.*;, then you can write methodName() instead of GL##.methodName() (replace ## with numbers)

Title: Skybox is completely black

Body:
I'm following ThinMatrix's guide on Youtube and trying to create a skybox for my engine. However, my skybox comes out black. I've tried all the different suggestions and common mistakes that people suggested in the comments, I can not for the life of me figure out what is wrong with it.

I'm not getting any error either :/

Bellow are the relevant methods in the relevant classes. I can provide more code if needed.

Loader.java

 public int loadCubeMap(String[] cubeMapTextures) {
        int textureID = GL11.glGenTextures();

        GL13.glActiveTexture(GL13.GL_TEXTURE0);
        GL11.glBindTexture(GL13.GL_TEXTURE_CUBE_MAP, textureID);

        for (int i = 0; i < cubeMapTextures.length; i++) {
          TextureData data = decodeTexture("res/skybox/" + cubeMapTextures[i] + ".png");

          GL11.glTexImage2D(GL13.GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL11.GL_RGBA, data.getWidth(), data.getHeight(),
              0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, data.getBuffer());
        }

        GL11.glTexParameteri(GL13.GL_PROXY_TEXTURE_CUBE_MAP, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR);
        GL11.glTexParameteri(GL13.GL_PROXY_TEXTURE_CUBE_MAP, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR);
        GL11.glTexParameteri(GL13.GL_TEXTURE_CUBE_MAP, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE);
        GL11.glTexParameteri(GL13.GL_TEXTURE_CUBE_MAP, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE);

        textures.add(textureID);
        return textureID;
      }

      private TextureData decodeTexture(String fileName) {
        int width = 0;
        int height = 0;
        ByteBuffer buffer = null;

        try {
          FileInputStream in = new FileInputStream(fileName);
          PNGDecoder decoder = new PNGDecoder(in);

          width = decoder.getWidth();
          height = decoder.getHeight();
          buffer = ByteBuffer.allocateDirect(4 * width * height);
          decoder.decode(buffer, width * 4, Format.RGBA);

          buffer.flip();
          in.close();
        } catch (Exception e) {
          e.printStackTrace();
          System.err.println("Failed loading:  " + fileName);
          System.exit(-1);
        }

        return new TextureData(height, width, buffer);
      }

SkyboxRenderer.java

private static final float SIZE = 500f;
private static final float[] VERTICES = {
    -SIZE,  SIZE, -SIZE,
    -SIZE, -SIZE, -SIZE,
    SIZE, -SIZE, -SIZE,
     SIZE, -SIZE, -SIZE,
     SIZE,  SIZE, -SIZE,
    -SIZE,  SIZE, -SIZE,

    -SIZE, -SIZE,  SIZE,
    -SIZE, -SIZE, -SIZE,
    -SIZE,  SIZE, -SIZE,
    -SIZE,  SIZE, -SIZE,
    -SIZE,  SIZE,  SIZE,
    -SIZE, -SIZE,  SIZE,

     SIZE, -SIZE, -SIZE,
     SIZE, -SIZE,  SIZE,
     SIZE,  SIZE,  SIZE,
     SIZE,  SIZE,  SIZE,
     SIZE,  SIZE, -SIZE,
     SIZE, -SIZE, -SIZE,

    -SIZE, -SIZE,  SIZE,
    -SIZE,  SIZE,  SIZE,
     SIZE,  SIZE,  SIZE,
     SIZE,  SIZE,  SIZE,
     SIZE, -SIZE,  SIZE,
    -SIZE, -SIZE,  SIZE,

    -SIZE,  SIZE, -SIZE,
     SIZE,  SIZE, -SIZE,
     SIZE,  SIZE,  SIZE,
     SIZE,  SIZE,  SIZE,
    -SIZE,  SIZE,  SIZE,
    -SIZE,  SIZE, -SIZE,

    -SIZE, -SIZE, -SIZE,
    -SIZE, -SIZE,  SIZE,
     SIZE, -SIZE, -SIZE,
     SIZE, -SIZE, -SIZE,
    -SIZE, -SIZE,  SIZE,
     SIZE, -SIZE,  SIZE
};

private static String[] textureFiles = {"stormydays_rt", "stormydays_lf", "stormydays_up", "stormydays_dn", "stormydays_bk", "stormydays_ft"};

private RawModel cube;
private int textureID;
private SkyboxShader shader;

public SkyBoxRenderer(Loader loader, Matrix4f projectionMatrix) {
    cube = loader.loadToVAO(VERTICES, 3);
    textureID = loader.loadCubeMap(textureFiles);
    shader = new SkyboxShader();
    shader.start();
    shader.loadProjectionMatrix(projectionMatrix);
    shader.stop();
}

public void render(Camera camera) {
    shader.start();
    shader.loadViewMatrix(camera);

    GL30.glBindVertexArray(cube.getVaoID());
    GL20.glEnableVertexAttribArray(0);
    GL13.glActiveTexture(GL13.GL_TEXTURE0);
    GL11.glBindTexture(GL13.GL_TEXTURE_CUBE_MAP, textureID);
    GL11.glDrawArrays(GL11.GL_TRIANGLES, 0, cube.getVertexCount());
    GL20.glDisableVertexAttribArray(0);
    GL30.glBindVertexArray(0);

    shader.stop();
}

SkyboxShader.java

 private static final String VERTEX_FILE = "src/shaders/skyboxVertexShader.txt";
  private static final String FRAGMENT_FILE = "src/shaders/skyboxFragmentShader.txt";

  private int location_projectionMatrix;
  private int location_viewMatrix;

  public SkyboxShader() {
      super(VERTEX_FILE, FRAGMENT_FILE);
  }

  public void loadProjectionMatrix(Matrix4f matrix){
      super.loadMatrix(location_projectionMatrix, matrix);
  }

  public void loadViewMatrix(Camera camera){
      Matrix4f matrix = Maths.createViewMatrix(camera);
      super.loadMatrix(location_viewMatrix, matrix);
  }

  @Override
  protected void getAllUniformLocations() {
      location_projectionMatrix = super.getUniformLocation("projectionMatrix");
      location_viewMatrix = super.getUniformLocation("viewMatrix");
  }

  @Override
  protected void bindAttributes() {
      super.bindAttribute(0, "position");
  }

And here is my GLSL code
skyboxVertexShader

#version 400

in vec3 position;
out vec3 textureCoords;

uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;

void main(void){

    gl_Position = projectionMatrix * viewMatrix * vec4(position, 1.0);
    textureCoords = position;

}

skyboxFragmentShader

#version 400

in vec3 textureCoords;
out vec4 out_Color;

uniform samplerCube cubeMap;

void main(void){
    out_Color = texture(cubeMap, textureCoords);
}

Body:
This probably happens because the texture isn't complete.
To complete your cube map texture you have to set GL_TEXTURE_WRAP_R with glTexParameteri because a cube is 3D.
Furthermore you are using GL_PROXY_TEXTURE_CUBE_MAP instead of GL_TEXTURE_CUBE_MAP, this does't work because proxy textures aren't a valid parameter.

So just replace:

GL11.glTexParameteri(GL13.GL_PROXY_TEXTURE_CUBE_MAP, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR);
GL11.glTexParameteri(GL13.GL_PROXY_TEXTURE_CUBE_MAP, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR);
GL11.glTexParameteri(GL13.GL_TEXTURE_CUBE_MAP, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE);
GL11.glTexParameteri(GL13.GL_TEXTURE_CUBE_MAP, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE);

With:

glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

If this doesn't help, confirm that all textures have the same size.

PS: Use import static GL##.*;, then you can write methodName() instead of GL##.methodName() (replace ## with numbers)