问:
radio button doesn't fit inside a table?
i'm working on this calculator and when the user select one of the type a little table should appear to select a type from tha table but the radio button that should be clicked doesn't fit into table

this is lookup in ccs code of table and  the full code in jsfiddle link

```<code>    table {
border: 1px solid #ccc;
border-collapse: collapse;
margin: 0;
padding: 0;
width: 100%;
table-layout: fixed;
}
.rad
{width:1em;
height:1em;}
table thead,
table tbody {
  display: block;
}
table thead th ,table tbody td
{
  font-size : 12px;
}
table tbody {
  max-height: 100px;
  overflow-y: overlay;
  overflow-x: hidden;
}
tr:hover{
background-color:gray;
cursor:pointer;
}
table tbody td, table thead th {
  text-align: center;

}

table tbody td:last-child, table thead th:last-child {
  border-right: none;
}

table tbody td:first-child, table thead th:first-child {
  width: 10px;
}
table tbody td:nth-child(2), table thead th:nth-child(2) {
  width: 100px;
}
table tbody td:nth-child(3), table thead th:nth-child(3) {
  width: 100px;
}
table tbody td:nth-child(4), table thead th:nth-child(4) {
  width: 100px;
}
table tbody td:nth-child(5), table thead th:nth-child(5) {
  width: 100px;
}
</code>```

答: Just remove position: absolute from the css for input[type="radio"]. Working Fiddle.

Body:
i'm working on this calculator and when the user select one of the type a little table should appear to select a type from tha table but the radio button that should be clicked doesn't fit into table

this is lookup in ccs code of table and  the full code in jsfiddle link

    table {
border: 1px solid #ccc;
border-collapse: collapse;
margin: 0;
padding: 0;
width: 100%;
table-layout: fixed;
}
.rad
{width:1em;
height:1em;}
table thead,
table tbody {
  display: block;
}
table thead th ,table tbody td
{
  font-size : 12px;
}
table tbody {
  max-height: 100px;
  overflow-y: overlay;
  overflow-x: hidden;
}
tr:hover{
background-color:gray;
cursor:pointer;
}
table tbody td, table thead th {
  text-align: center;

}

table tbody td:last-child, table thead th:last-child {
  border-right: none;
}

table tbody td:first-child, table thead th:first-child {
  width: 10px;
}
table tbody td:nth-child(2), table thead th:nth-child(2) {
  width: 100px;
}
table tbody td:nth-child(3), table thead th:nth-child(3) {
  width: 100px;
}
table tbody td:nth-child(4), table thead th:nth-child(4) {
  width: 100px;
}
table tbody td:nth-child(5), table thead th:nth-child(5) {
  width: 100px;
}


来源: stackexchange

问:
preventing value compilation errors
Bixby raises "Value Compilation Errors" in the debugger whenever I run a script that brings back Empty Optional Values.  The variable model is correct in that these values really are optional, i.e not needed for the user task to succeed.  So you can simply ignore the debugger errors and everything will work, EXCEPT that the Story testing tool will report these runs as "failed."  This means that the Story tool is almost useless for these cases, and that's a big problem.

Can someone show me how to code to avoid them?

答:
Thanks to a tip from @mincheng I finally figured out how to do this. The key is to delete any object properties that are null, undefined, or empty strings. I loop over my array of objects with the delete function. </p>

```<code>  // remove undefined properties here

     const removeEmpty = (obj) => {
        Object.keys(obj).forEach(key => {
          if (obj[key] && typeof obj[key] === 'object') removeEmpty(obj[key]);
          else if (obj[key] === undefined || obj[key] === null || obj[key] === "") delete obj[key];
        });
        return obj;
      };

     for (var i = 0; i < altBrainsData.length; i++) {
           //console.log('i is', i);
           //console.log('function object', i, 'is', altBrainsData[i])
           //console.log(removeEmpty(altBrainsData[i]))
           altBrainsData[i] = removeEmpty(altBrainsData[i])
       }
</code>```

ContentLicense: CC BY-SA 4.0

Title: preventing value compilation errors

Body:
Thanks to a tip from @mincheng I finally figured out how to do this. The key is to delete any object properties that are null, undefined, or empty strings. I loop over my array of objects with the delete function.

  // remove undefined properties here

     const removeEmpty = (obj) => {
        Object.keys(obj).forEach(key => {
          if (obj[key] && typeof obj[key] === 'object') removeEmpty(obj[key]);
          else if (obj[key] === undefined || obj[key] === null || obj[key] === "") delete obj[key];
        });
        return obj;
      };

     for (var i = 0; i < altBrainsData.length; i++) {
           //console.log('i is', i);
           //console.log('function object', i, 'is', altBrainsData[i])
           //console.log(removeEmpty(altBrainsData[i]))
           altBrainsData[i] = removeEmpty(altBrainsData[i])
       }


问:
How to get a specific date type in java
I am using the below method to get this string to_date('2011/06/02','yyyy/mm/dd')

```<code>private static String getOperationDate() {
  Date today= new Date();
  String output;
  SimpleDateFormat formatter;
  String pattern="yyyy/MM/dd";

  formatter = new SimpleDateFormat(pattern, Locale.US);
  output = formatter.format(today);
  String temp="to_date('"+output+"','yyyy/mm/dd')";

  return temp;
}
</code>```

How can i generate something like this to_date('2011-05-27 12:45:56.1',....) i.e., apart from just date how can i also include time with milliseconds, which would then be updated to the database

Added a oracle insert statement, after referring to an answer by trutheality, but this gives me 01810. 00000 -  "format code appears twice" error

```<code>INSERT INTO CONFIG_INFO(CFG_ID,CFG_NAME,CFG_DESC,CFG_TYPE,FILE_NAME,ABSOLUTE_PATH,EMAIL_ADDRESS,PROJECT_ID,HOSTNAME,CREATE_DATE,UPDATE_DATE,STATE,PRODUCT_ID)
    VALUES (config_seq.NEXTVAL,'Abhishek','as','Production','asdclient1.xml','E:tomcat 5.5bin/../webapps/asd/files/asdclient.xml','a@a.com','ABC','abhinix',to_date('2011/06/02 11:18:38.211','yyyy/MM/dd HH:mm:ss.SSS'),to_date('2011/06/02 11:18:38.211','yyyy/MM/dd HH:mm:ss.SSS'),2,123456)
</code>```

答:
Look at the docs, and figure out what your format string should be.

Probably something like

```<code>String pattern = "yyyy-MM-dd HH:mm:ss.SSS";
</code>```

But the proper way is to use the JDBC driver as OMG Ponies has pointed out.

ContentLicense: CC BY-SA 3.0

Title: How to get a specific date type in java

Body:
I am using the below method to get this string to_date('2011/06/02','yyyy/mm/dd')

private static String getOperationDate() {
  Date today= new Date();
  String output;
  SimpleDateFormat formatter;
  String pattern="yyyy/MM/dd";

  formatter = new SimpleDateFormat(pattern, Locale.US);
  output = formatter.format(today);
  String temp="to_date('"+output+"','yyyy/mm/dd')";

  return temp;
}

How can i generate something like this to_date('2011-05-27 12:45:56.1',....) i.e., apart from just date how can i also include time with milliseconds, which would then be updated to the database

Added a oracle insert statement, after referring to an answer by trutheality, but this gives me 01810. 00000 -  "format code appears twice" error

INSERT INTO CONFIG_INFO(CFG_ID,CFG_NAME,CFG_DESC,CFG_TYPE,FILE_NAME,ABSOLUTE_PATH,EMAIL_ADDRESS,PROJECT_ID,HOSTNAME,CREATE_DATE,UPDATE_DATE,STATE,PRODUCT_ID)
    VALUES (config_seq.NEXTVAL,'Abhishek','as','Production','asdclient1.xml','E:tomcat 5.5bin/../webapps/asd/files/asdclient.xml','a@a.com','ABC','abhinix',to_date('2011/06/02 11:18:38.211','yyyy/MM/dd HH:mm:ss.SSS'),to_date('2011/06/02 11:18:38.211','yyyy/MM/dd HH:mm:ss.SSS'),2,123456)

Body:
Look at the docs, and figure out what your format string should be.

Probably something like

String pattern = "yyyy-MM-dd HH:mm:ss.SSS";

But the proper way is to use the JDBC driver as OMG Ponies has pointed out.


问:
npm postinstall runs only when not installing anything

I was wrong

The reason why npm install whatever deletes the node_modules/- folder is different: I thought it runs preinstall but no postinstall and I was wrong.

I runs neither of the two scripts.

The reason seems to be that npm install whatever also removes all packages not mentioned in my package.json. Funnilly, it does not install packages mentioned in my package.json but missing in node_modules. It's exactly like Michael Waddell wrote in a comment. This makes no sense to me, but....

Following this comment, I switched to absolute imports and rely on postinstall (in my own package.json) to create the link

```<code>{
  "scripts": {
    "preinstall": "rm node_modules/-",
    "postinstall": "ln -s `pwd`/src node_modules/-",
    ...
  },
}
</code>```

It works well, unless when I really install something. With

```<code>npm install
</code>```

the link gets deleted and then re-created. However, with

```<code>npm install whatever
</code>```

the link gets deleted, but not re-created. Is this a bug or is this intentional and I should use some other "postinstall"?

Please note that I'm not concerned about losing my src directory. That's a different problem. My problem is the "postinstall" running only sometimes.

Update

People commented that the hooks only get run when running npm install without any arguments. I could live with that, but it's not true:

```<code>> ls -l node_modules/-
lrwxrwxrwx 1 maaartinus maaartinus 40 May 29 11:53 node_modules/- -> /home/maaartinus/work/octopus/reocto/src

> npm i whatever
foo bar baz blah

> ls -l node_modules/-
ls: cannot access 'node_modules/-': No such file or directory
</code>```

This mean that preinstall runs, but postinstall did not. This sounds like a bug...

```<code>> node -v
v12.16.3
> npm -v
6.13.4
</code>```

Update 2

The pre- and postinstall scripts are in my own package.json (which can be understood from the context, but I should have stated clearly).

答:
sometime node currpted due to some reason therefore its delete node_module folder. you can install whatever by yarn

```<code>yarn add whatever
</code>```

preinstall & postinstall

preinstall: Run BEFORE the package is installed install

postinstall: Run AFTER the package is installed.

Absolute path:

install babel-plugin-module-resolver by

```<code>yarn add -D babel-plugin-module-resolver
yarn add -D customize-cra
</code>```

then add relative path in babel.config.js file like this

```<code>const { override, addBabelPlugins } = require('customize-cra');
module.exports = override(

    ...addBabelPlugins([
        'module-resolver',
        {
            alias : {
                '@components'     : './src/components',
            }
        }
    ])
);

</code>```

then you can use an absolute path like this

```<code>import TextLabel from '@components/textLabel/index.js'
</code>```

Body:
I was wrong

The reason why npm install whatever deletes the node_modules/- folder is different: I thought it runs preinstall but no postinstall and I was wrong.

I runs neither of the two scripts.

The reason seems to be that npm install whatever also removes all packages not mentioned in my package.json. Funnilly, it does not install packages mentioned in my package.json but missing in node_modules. It's exactly like Michael Waddell wrote in a comment. This makes no sense to me, but....

Following this comment, I switched to absolute imports and rely on postinstall (in my own package.json) to create the link

{
  "scripts": {
    "preinstall": "rm node_modules/-",
    "postinstall": "ln -s `pwd`/src node_modules/-",
    ...
  },
}

It works well, unless when I really install something. With

npm install

the link gets deleted and then re-created. However, with

npm install whatever

the link gets deleted, but not re-created. Is this a bug or is this intentional and I should use some other "postinstall"?

Please note that I'm not concerned about losing my src directory. That's a different problem. My problem is the "postinstall" running only sometimes.

Update

People commented that the hooks only get run when running npm install without any arguments. I could live with that, but it's not true:

> ls -l node_modules/-
lrwxrwxrwx 1 maaartinus maaartinus 40 May 29 11:53 node_modules/- -> /home/maaartinus/work/octopus/reocto/src

> npm i whatever
foo bar baz blah

> ls -l node_modules/-
ls: cannot access 'node_modules/-': No such file or directory

This mean that preinstall runs, but postinstall did not. This sounds like a bug...

> node -v
v12.16.3
> npm -v
6.13.4

Update 2

The pre- and postinstall scripts are in my own package.json (which can be understood from the context, but I should have stated clearly).

Body:
sometime node currpted due to some reason therefore its delete node_module folder. you can install whatever by yarn

yarn add whatever

preinstall & postinstall

preinstall: Run BEFORE the package is installed install

postinstall: Run AFTER the package is installed.

Absolute path:

install babel-plugin-module-resolver by

yarn add -D babel-plugin-module-resolver
yarn add -D customize-cra

then add relative path in babel.config.js file like this

const { override, addBabelPlugins } = require('customize-cra');
module.exports = override(

    ...addBabelPlugins([
        'module-resolver',
        {
            alias : {
                '@components'     : './src/components',
            }
        }
    ])
);

then you can use an absolute path like this

import TextLabel from '@components/textLabel/index.js'


问:
How to write a query that returns columns from join tables (associated using custom class) that returns an ActiveRecord Relation
```<code>class Event < ApplicationRecord
    belongs_to :event_type, :class_name => 'Keyword', :foreign_key => :event_type_id, optional: false
    belongs_to :promotion_type, :class_name => 'Keyword', :foreign_key => :promotion_type_id, optional: false
end

class Keyword < ApplicationRecord
    has_many :events
end
</code>```

I am attempting to write a query that returns columns form the joined table however I only seem to be able to create a working query if I use Pluck - which I do not wish to use as that ensures the query returns an array.  I need the query to return an ActiveRecord Relation.

Here is the query working using Pluck.  (Returns Array)

```<code>Event.joins(:event_type).pluck('event.id, event.name, keywords.name')
</code>```

When I attempt to use Select the joined table column does not appear in the results.  (Returns ActiveRecord Relation which is what I need)

```<code>Event.joins(:event_type).select('event.id, event.name, keywords.name')
</code>```

I'm obviously missing something simple but stuck.  Can anyone help?

答:
I ended up adjusting my models in order to remove custom class.  Once I did this the query worked as I always expected it to do.

Event.joins(:event_type).select('event.id, event.name, keywords.name')

Case closed.

Body:
class Event < ApplicationRecord
    belongs_to :event_type, :class_name => 'Keyword', :foreign_key => :event_type_id, optional: false
    belongs_to :promotion_type, :class_name => 'Keyword', :foreign_key => :promotion_type_id, optional: false
end

class Keyword < ApplicationRecord
    has_many :events
end

I am attempting to write a query that returns columns form the joined table however I only seem to be able to create a working query if I use Pluck - which I do not wish to use as that ensures the query returns an array.  I need the query to return an ActiveRecord Relation.

Here is the query working using Pluck.  (Returns Array)

Event.joins(:event_type).pluck('event.id, event.name, keywords.name')

When I attempt to use Select the joined table column does not appear in the results.  (Returns ActiveRecord Relation which is what I need)

Event.joins(:event_type).select('event.id, event.name, keywords.name')

I'm obviously missing something simple but stuck.  Can anyone help?


答:
Here you go:

def get_max_sum(triangle, row_index):
    if row_index == len(triangle):
        return max(triangle[row_index - 1])
    row = triangle[row_index]
    previous_row = triangle[row_index - 1]
    row[0] += previous_row[0]
    for i in range(1, len(previous_row)):
        row[i] += max(previous_row[i], previous_row[i - 1])
    row[-1] += previous_row[-1]
    triangle[row_index] = row
    return get_max_sum(triangle, row_index + 1)

max_sum = get_max_sum(numbers, 1)
print(f'Max sum = {max_sum}')

```

Title: Stuck on Euler 18. My for loops aren't going up the rows

Body:
My code should compare the values on the bottom row and then add the highest out of each pair to the corresponding number above/adjacent to it. It works for the first row but doesn't iterate to get to the top.
Find the maximum total from top to bottom of the triangle below:

numbers = [
    [75],
    [95, 64],
    [17, 47, 82],
    [18, 35, 87, 10],
    [20, 4, 82, 47, 65],
    [19, 1, 23, 75, 3, 34],
    [88, 2, 77, 73, 7, 63, 67],
    [99, 65, 4, 28, 6, 16, 70, 92],
    [41, 41, 26, 56, 83, 40, 80, 70, 33],
    [41, 48, 72, 33, 47, 32, 37, 16, 94, 29],
    [53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14],
    [70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57],
    [91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48],
    [63, 66, 4, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31],
    [4, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 4, 23]]

row = 14
col = 0
for j in range(14):
    for i in range(len(numbers[row-1])):
        if numbers[row][col] > numbers[row][col+1]:
            numbers[row-1][col] += numbers[row][col]
            col += 1

        elif numbers[row][col] == numbers[row][col+1]:
            numbers[row-1][col] += numbers[row][col]
            col += 1

        else:
            numbers[row - 1][col] += numbers[row][col+1]
            col += 1
    row -= 1
    col = 0


问:
How to rollback all recent transactions in Rails
I'm writing my first Ruby on Rails application, and I'm having trouble managing record associations overall. In this question, specifically, I'd like to ask the community for suggestions on how to rollback recent saves to the database, based on the code below.

```<code>def create
    @aula = Aula.create!(:name => aula_params[:name], :block_duration => aula_params[:block_duration], :rest_time => aula_params[:rest_time], :user_id => @current_user.id)

    if @aula.valid?
      JSON.parse(aula_params[:blocks]).each do |id, b|
        @block = @aula.blocks.create!(:name => b["name"], :sequence_number => id)

        if @block.valid?
          b["workouts"].each do |id, w|
            @block.block_workouts.create!(:workout_id => w["id"], :duration => w["duration"], :sequence_number => id, :repetitions_number => w["repetitions_number"])
          end
        else
          render :json => { message: "Não foi possível criar essa aula", status: 500 }
        end
      end

      render :json => { message: "Aula criada com sucesso", status: 200 }
    else
      render :json => { message: "Não foi possível criar essa aula", status: 500 }
    end
  end
</code>```

This piece of code basically creates an "aula", that consists of multiple "blocks", that in turn are composed by multiple "workouts".

But, the problem is: suppose that the creation of a specific workout fails. In this case, the "aula" that was just created (and so the blocks and its related workouts) should be deleted. But I can't find a way of doing this in a concise, elegant manner.

答:
It's called transactions, if one thing fail on creation, all records will rollback  https://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html

Transactions are protective blocks where SQL statements are only
  permanent if they can all succeed as one atomic action.

So in your case, you need to wrap your code into Rails transaction, something like this:

```<code>Aula.transaction do
  @aula = Aula.create!(...)

end
</code>```

remember to use create! with exclamation mark to raise an error in case of failure

Body:
I'm writing my first Ruby on Rails application, and I'm having trouble managing record associations overall. In this question, specifically, I'd like to ask the community for suggestions on how to rollback recent saves to the database, based on the code below.

def create
    @aula = Aula.create!(:name => aula_params[:name], :block_duration => aula_params[:block_duration], :rest_time => aula_params[:rest_time], :user_id => @current_user.id)

    if @aula.valid?
      JSON.parse(aula_params[:blocks]).each do |id, b|
        @block = @aula.blocks.create!(:name => b["name"], :sequence_number => id)

        if @block.valid?
          b["workouts"].each do |id, w|
            @block.block_workouts.create!(:workout_id => w["id"], :duration => w["duration"], :sequence_number => id, :repetitions_number => w["repetitions_number"])
          end
        else
          render :json => { message: "Não foi possível criar essa aula", status: 500 }
        end
      end

      render :json => { message: "Aula criada com sucesso", status: 200 }
    else
      render :json => { message: "Não foi possível criar essa aula", status: 500 }
    end
  end

This piece of code basically creates an "aula", that consists of multiple "blocks", that in turn are composed by multiple "workouts".

But, the problem is: suppose that the creation of a specific workout fails. In this case, the "aula" that was just created (and so the blocks and its related workouts) should be deleted. But I can't find a way of doing this in a concise, elegant manner.

Body:
It's called transactions, if one thing fail on creation, all records will rollback  https://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html

Transactions are protective blocks where SQL statements are only
  permanent if they can all succeed as one atomic action.

So in your case, you need to wrap your code into Rails transaction, something like this:

Aula.transaction do
  @aula = Aula.create!(...)

end

remember to use create! with exclamation mark to raise an error in case of failure


问:
'max_sp_recursion_depth' variable doesn't appear to set causing "Recursive limit 0 was exceeded" error
Quick note, I know this question has been asked here, but the 'answer' gives an alternative which doesn't involve recursion. I want to get recursion working. Here's some code I wrote to demonstrate the problem:

```<code>CREATE OR REPLACE PROCEDURE `test` (x INT)
BEGIN

  SHOW GLOBAL VARIABLES LIKE 'max_sp_recursion_depth';

  IF x = 0 THEN
    SELECT 1;
  ELSE
    CALL `test`(x-1);
  END IF;

END
</code>```

Returns:

```<code>+------------------------+-------+
| Variable_name          | Value |
+------------------------+-------+
| max_sp_recursion_depth | 64    |
+------------------------+-------+
1 row in set (0.001 sec)

ERROR 1456 (HY000) at line 43 in file: 'workspace.sql': Recursive limit 0 (as set by the max_sp_recursion_depth variable) was exceeded for routine test
</code>```

What I've tried

I will update this as I try more things:

setting the variable via the MariaDB CLI

setting the variable via PHPMyAdmin

restarting MariaDB

restarted the entire server

restarted my computer (currently running in a development environment on my mac) and the variable has reset to 0

答:
```<code>SET GLOBAL ...
</code>```

does not have any effect on the current connection; only future connections.  (Exception:  Some variables are "only global"; those probably do show up immediately.)

```<code>SET SESSION ...
</code>```

Is what to do to make it work for the current connection.

Body:
Quick note, I know this question has been asked here, but the 'answer' gives an alternative which doesn't involve recursion. I want to get recursion working. Here's some code I wrote to demonstrate the problem:

CREATE OR REPLACE PROCEDURE `test` (x INT)
BEGIN

  SHOW GLOBAL VARIABLES LIKE 'max_sp_recursion_depth';

  IF x = 0 THEN
    SELECT 1;
  ELSE
    CALL `test`(x-1);
  END IF;

END

Returns:

+------------------------+-------+
| Variable_name          | Value |
+------------------------+-------+
| max_sp_recursion_depth | 64    |
+------------------------+-------+
1 row in set (0.001 sec)

ERROR 1456 (HY000) at line 43 in file: 'workspace.sql': Recursive limit 0 (as set by the max_sp_recursion_depth variable) was exceeded for routine test

What I've tried

I will update this as I try more things:

setting the variable via the MariaDB CLI

setting the variable via PHPMyAdmin

restarting MariaDB

restarted the entire server

restarted my computer (currently running in a development environment on my mac) and the variable has reset to 0

Body:
SET GLOBAL ...

does not have any effect on the current connection; only future connections.  (Exception:  Some variables are "only global"; those probably do show up immediately.)

SET SESSION ...

Is what to do to make it work for the current connection.


问:
changing jhipster-registry port
I've looked over most of the documentation provided, couldn't find an absolute answer about changing jhipster-registry port, it's default is 8761, but when I try to chnage it's port through YAML config file it gets indeed working in that port but both the gateway and microservice cannot be found by the registry. am i doing anything wrong ? is jhipster-registry bound to remain intact when it comes to port manipulation ?

答:
You must change port in spring.cloud.config.uri in all application's bootstrap*.yml so they can retrieve their config from the registry and also change it in eureka.client.defaultZone in application.yml in jhipster-registry's central-config folder if you use file system backend or in git repo if you use git backend.

This is because the registry is both a Spring Cloud Config server and an Eureka server. In JHipster's setup, the applications first connect to the config server, retrieve their config which indicate the URL of the Eureka server. As this is a common config for all apps, it's set in application*.yml in config server.

Please read also the jhipster-registry doc: https://www.jhipster.tech/jhipster-registry/

Title: changing jhipster-registry port


问:
A practical example of GSDMM in python?
I want to use GSDMM to assign topics to some tweets in my data set. The only examples I found (1 and 2) are not detailed enough. I was wondering if you know of a source (or care enough to make a small example) that shows how GSDMM is implemented using python.</p>

答:
GSDMM (Gibbs Sampling Dirichlet Multinomial Mixture) is a short text
  clustering model. It is essentially a modified LDA (Latent Drichlet
  Allocation) which suppose that a document such as a tweet or any other
  text encompasses one topic.

GSDMM

LDA

Address: github.com/da03/GSDMM

```<code>import numpy as np
from scipy.sparse import lil_matrix
from scipy.sparse import find
import math

class GSDMM:
    def __init__(self, n_topics, n_iter, random_state=910820, alpha=0.1, beta=0.1):
        self.n_topics = n_topics
        self.n_iter = n_iter
        self.random_state = random_state
        np.random.seed(random_state)
        self.alpha = alpha
        self.beta = beta
    def fit(self, X):
        alpha = self.alpha
        beta = self.beta

        D, V = X.shape
        K = self.n_topics

        N_d = X.sum(axis=1)
        words_d = {}
        for d in range(D):
            words_d[d] = find(X[d,:])[1]

        # initialization
        N_k = np.zeros(K)
        M_k = np.zeros(K)
        N_k_w = lil_matrix((K, V), dtype=np.int32)

        K_d = np.zeros(D)

        for d in range(D):
            k = np.random.choice(K, 1, p=[1.0/K]*K)[0]
            K_d[d] = k
            M_k[k] = M_k[k]+1
            N_k[k] = N_k[k] + N_d[d]
            for w in words_d[d]:
                N_k_w[k, w] = N_k_w[k,w]+X[d,w]

        for iter in range(self.n_iter):
            print 'iter ', iter
            for d in range(D):
                k_old = K_d[d]
                M_k[k_old] -= 1
                N_k[k_old] -= N_d[d]
                for w in words_d[d]:
                    N_k_w[k_old, w] -= X[d,w]
                # sample k_new
                log_probs = [0]*K
                for k in range(K):
                    log_probs[k] += math.log(alpha+M_k[k])
                    for w in words_d[d]:
                        N_d_w = X[d,w]
                        for j in range(N_d_w):
                            log_probs[k] += math.log(N_k_w[k,w]+beta+j)
                    for i in range(N_d[d]):
                        log_probs[k] -= math.log(N_k[k]+beta*V+i)
                log_probs = np.array(log_probs) - max(log_probs)
                probs = np.exp(log_probs)
                probs = probs/np.sum(probs)
                k_new = np.random.choice(K, 1, p=probs)[0]
                K_d[d] = k_new
                M_k[k_new] += 1
                N_k[k_new] += N_d[d]
                for w in words_d[d]:
                    N_k_w[k_new, w] += X[d,w]
        self.topic_word_ = N_k_w.toarray()
</code>```

Title: A practical example of GSDMM in python?

Body:
GSDMM (Gibbs Sampling Dirichlet Multinomial Mixture) is a short text
  clustering model. It is essentially a modified LDA (Latent Drichlet
  Allocation) which suppose that a document such as a tweet or any other
  text encompasses one topic.

GSDMM

LDA

Address: github.com/da03/GSDMM

import numpy as np
from scipy.sparse import lil_matrix
from scipy.sparse import find
import math

class GSDMM:
    def __init__(self, n_topics, n_iter, random_state=910820, alpha=0.1, beta=0.1):
        self.n_topics = n_topics
        self.n_iter = n_iter
        self.random_state = random_state
        np.random.seed(random_state)
        self.alpha = alpha
        self.beta = beta
    def fit(self, X):
        alpha = self.alpha
        beta = self.beta

        D, V = X.shape
        K = self.n_topics

        N_d = X.sum(axis=1)
        words_d = {}
        for d in range(D):
            words_d[d] = find(X[d,:])[1]

        # initialization
        N_k = np.zeros(K)
        M_k = np.zeros(K)
        N_k_w = lil_matrix((K, V), dtype=np.int32)

        K_d = np.zeros(D)

        for d in range(D):
            k = np.random.choice(K, 1, p=[1.0/K]*K)[0]
            K_d[d] = k
            M_k[k] = M_k[k]+1
            N_k[k] = N_k[k] + N_d[d]
            for w in words_d[d]:
                N_k_w[k, w] = N_k_w[k,w]+X[d,w]

        for iter in range(self.n_iter):
            print 'iter ', iter
            for d in range(D):
                k_old = K_d[d]
                M_k[k_old] -= 1
                N_k[k_old] -= N_d[d]
                for w in words_d[d]:
                    N_k_w[k_old, w] -= X[d,w]
                # sample k_new
                log_probs = [0]*K
                for k in range(K):
                    log_probs[k] += math.log(alpha+M_k[k])
                    for w in words_d[d]:
                        N_d_w = X[d,w]
                        for j in range(N_d_w):
                            log_probs[k] += math.log(N_k_w[k,w]+beta+j)
                    for i in range(N_d[d]):
                        log_probs[k] -= math.log(N_k[k]+beta*V+i)
                log_probs = np.array(log_probs) - max(log_probs)
                probs = np.exp(log_probs)
                probs = probs/np.sum(probs)
                k_new = np.random.choice(K, 1, p=probs)[0]
                K_d[d] = k_new
                M_k[k_new] += 1
                N_k[k_new] += N_d[d]
                for w in words_d[d]:
                    N_k_w[k_new, w] += X[d,w]
        self.topic_word_ = N_k_w.toarray()


问:
Column sorting check of subcategory of data
I Have this excel table with me, which contains article types and their size against it, I want to check whether for each article type the sizes are sorted in ascending order or not, by adding a column with indicators as SORTED, NOT SORTED, UNIQUE
I want to do it with Excel formula

```<code>     A      B    C
1**ARTICLE SIZE STATUS**
2   A       10   SORTED
3   B       11   SORTED
4   A       12   SORTED
5   A       14   NOT SORTED
6   C       11   SORTED
7   D       12   UNIQUE
8   C       13   SORTED
9   A       13   NOT SORTED
10  B       15   NOT SORTED
11  B       14   NOT SORTED
</code>```

I tried to apply =IF($A2=$A3:$A$11,IF($B2ATTACHED IMAGE OF DATASET

答:
Such a lookup is now relatively easy with the new XLookup function.

I tried to re-engineer the logic in your data sample, but there must be some typo or thinking error.

Scenario 1: If "sorted" means that the next number can only be 1 larger than the previous number, then A=12 should not be "sorted".  The formula is

```<code>=IF(XLOOKUP(A2,$A$1:A1,$B$1:B1,IF(COUNTIF(A:A,A2)>1,"sorted","unique"),0,-1)="unique","unique",
IF(XLOOKUP(A2,$A$1:A1,$B$1:B1,"sorted",0,-1)="sorted","sorted",
IF(XLOOKUP(A2,$A$1:A1,$B$1:B1,,0,-1)-B2>1,"sorted","not sorted"
)))
</code>```

Scenario 2:If, however, "sorted" means that the number in that row is bigger than the last number for this article, then B=15 should be "sorted". The formula is

```<code>=IF(XLOOKUP(A2,$A$1:A1,$B$1:B1,IF(COUNTIF(A:A,A2)>1,"sorted","unique"),0,-1)="unique","unique",
IF(XLOOKUP(A2,$A$1:A1,$B$1:B1,"sorted",0,-1)="sorted","sorted",
IF(XLOOKUP(A2,$A$1:A1,$B$1:B1,,0,-1)<B2,"sorted","not sorted"
)))
</code>```

With the new Let() function, the repeated Xlookups can be avoided.

```<code>=LET(
x,XLOOKUP(A2,$A$1:A1,$B$1:B1,IF(COUNTIF(A:A,A2)>1,"sorted","unique"),0,-1),
result,IF(ISTEXT(x),x,IF(x<B2,"sorted","not sorted")),
result)
</code>```

XLookup is available in Office 365 versions of Excel.
Let is currently in preview and only available in Insider/Beta builds of Office 365.

Body:
I Have this excel table with me, which contains article types and their size against it, I want to check whether for each article type the sizes are sorted in ascending order or not, by adding a column with indicators as SORTED, NOT SORTED, UNIQUE
I want to do it with Excel formula

     A      B    C
1**ARTICLE SIZE STATUS**
2   A       10   SORTED
3   B       11   SORTED
4   A       12   SORTED
5   A       14   NOT SORTED
6   C       11   SORTED
7   D       12   UNIQUE
8   C       13   SORTED
9   A       13   NOT SORTED
10  B       15   NOT SORTED
11  B       14   NOT SORTED

I tried to apply =IF($A2=$A3:$A$11,IF($B2ATTACHED IMAGE OF DATASET

Body:
Such a lookup is now relatively easy with the new XLookup function.

I tried to re-engineer the logic in your data sample, but there must be some typo or thinking error.

Scenario 1: If "sorted" means that the next number can only be 1 larger than the previous number, then A=12 should not be "sorted".  The formula is

=IF(XLOOKUP(A2,$A$1:A1,$B$1:B1,IF(COUNTIF(A:A,A2)>1,"sorted","unique"),0,-1)="unique","unique",
IF(XLOOKUP(A2,$A$1:A1,$B$1:B1,"sorted",0,-1)="sorted","sorted",
IF(XLOOKUP(A2,$A$1:A1,$B$1:B1,,0,-1)-B2>1,"sorted","not sorted"
)))

Scenario 2:If, however, "sorted" means that the number in that row is bigger than the last number for this article, then B=15 should be "sorted". The formula is

=IF(XLOOKUP(A2,$A$1:A1,$B$1:B1,IF(COUNTIF(A:A,A2)>1,"sorted","unique"),0,-1)="unique","unique",
IF(XLOOKUP(A2,$A$1:A1,$B$1:B1,"sorted",0,-1)="sorted","sorted",
IF(XLOOKUP(A2,$A$1:A1,$B$1:B1,,0,-1)<B2,"sorted","not sorted"
)))

With the new Let() function, the repeated Xlookups can be avoided.

=LET(
x,XLOOKUP(A2,$A$1:A1,$B$1:B1,IF(COUNTIF(A:A,A2)>1,"sorted","unique"),0,-1),
result,IF(ISTEXT(x),x,IF(x<B2,"sorted","not sorted")),
result)

XLookup is available in Office 365 versions of Excel.
Let is currently in preview and only available in Insider/Beta builds of Office 365.


问:
Finding permutation and combination in C++
I want to find a series of numbers of dynamic length in C++. Suppose I have 2 groups of numbers: arr1[3] = {1, 3, 8} and arr2[4] = {2, 9}, then the expected output is:

```<code>'1, 2',
'1, 9',
'3, 2',
'3, 9',
'8, 2',
'8, 9'.
</code>```

However, if there are 3 groups now : arr1[3] = {1, 3, 8}, arr2[2] = {2, 9} and arr3[5] = {1, 3, 9} then the output should be:

```<code>'1, 2, 1',
'1, 2, 3',
'1, 2, 9',
'1, 9, 1',
'1, 9, 3',
'1, 9, 9',
'3, 2, 1',
'3, 2, 3',
'3, 2, 9',
'3, 9, 1',
'3, 9, 3',
'3, 9, 9',
</code>```

and so on...

So there will 3 x 2 x 3 = 18 outcomes. I got the outcome for 2 groups and 3 groups using respective numbers of for loops.

See this code for 2 groups:

```<code>for(int i=1;i<=5;i++) {
   for (int j=1;j<=5;j++) {
       cout << i << "," << j << "," << endl;
   }
}
</code>```

But then I have to use different codes for different value of group number and have to use switch statement or if-else statement to choose that portion of code.

This will be a great help. Thanks in advance!

答:
I used vector instead of arrays, as they are way easier to deal with.

The trick is to enumerate, in lexicographic order, the positions in the arrays, then display the values at those positions:

```<code>#include <vector>
#include <iostream>

using std::vector;

void permutate(vector<vector<int>> values)
{
    // the positions in each vector
    vector<size_t> pos(values.size());

    do
    {
        // display one of each array at current position
        for(size_t i = 0; i < values.size(); ++i)
        {
            std::cout << values[i][pos[i]] << ", ";
        }
        std::cout << std::endl;

        // increment the last array's display position
        size_t p = 0;
        pos[p]++;

        // while we get to the end of current array, return to 0 and carry to next position
        while(pos[p] == values[p].size())
        {
            pos[p] = 0;
            p++;
            pos[p]++;

            // return when the last array's position get to its size
            if (p == values.size())
            {
                return;
            }
        }
    }
    while(true);

}

int main()
{
    vector<int> arr1 = {1, 3, 8};
    vector<int> arr2 = {2, 9};
    vector<int> arr3 = {1, 3, 9};

    vector<vector<int>> allThree = {arr1, arr2, arr3};

    permutate(allThree);
}
</code>```

A good exercise, next, would be to template it so you accept std::vector<std::vector<T>>

Body:
I want to find a series of numbers of dynamic length in C++. Suppose I have 2 groups of numbers: arr1[3] = {1, 3, 8} and arr2[4] = {2, 9}, then the expected output is:

'1, 2',
'1, 9',
'3, 2',
'3, 9',
'8, 2',
'8, 9'.

However, if there are 3 groups now : arr1[3] = {1, 3, 8}, arr2[2] = {2, 9} and arr3[5] = {1, 3, 9} then the output should be:

'1, 2, 1',
'1, 2, 3',
'1, 2, 9',
'1, 9, 1',
'1, 9, 3',
'1, 9, 9',
'3, 2, 1',
'3, 2, 3',
'3, 2, 9',
'3, 9, 1',
'3, 9, 3',
'3, 9, 9',

and so on...

So there will 3 x 2 x 3 = 18 outcomes. I got the outcome for 2 groups and 3 groups using respective numbers of for loops.

See this code for 2 groups:

for(int i=1;i<=5;i++) {
   for (int j=1;j<=5;j++) {
       cout << i << "," << j << "," << endl;
   }
}

But then I have to use different codes for different value of group number and have to use switch statement or if-else statement to choose that portion of code.

This will be a great help. Thanks in advance!

Body:
I used vector instead of arrays, as they are way easier to deal with.

The trick is to enumerate, in lexicographic order, the positions in the arrays, then display the values at those positions:

#include <vector>
#include <iostream>

using std::vector;

void permutate(vector<vector<int>> values)
{
    // the positions in each vector
    vector<size_t> pos(values.size());

    do
    {
        // display one of each array at current position
        for(size_t i = 0; i < values.size(); ++i)
        {
            std::cout << values[i][pos[i]] << ", ";
        }
        std::cout << std::endl;

        // increment the last array's display position
        size_t p = 0;
        pos[p]++;

        // while we get to the end of current array, return to 0 and carry to next position
        while(pos[p] == values[p].size())
        {
            pos[p] = 0;
            p++;
            pos[p]++;

            // return when the last array's position get to its size
            if (p == values.size())
            {
                return;
            }
        }
    }
    while(true);

}

int main()
{
    vector<int> arr1 = {1, 3, 8};
    vector<int> arr2 = {2, 9};
    vector<int> arr3 = {1, 3, 9};

    vector<vector<int>> allThree = {arr1, arr2, arr3};

    permutate(allThree);
}

A good exercise, next, would be to template it so you accept std::vector<std::vector<T>>


问:
Object object is shown in select tag in react
Data inside options(JSON) is </p>

<p>const options =  {"option":"Male","value":"M"};
Raect code is </p>

```<code>{props.options.map((option) => {
      return (
         <option key={option.value} value={option.option}>
            <Translate>{option.option}</Translate>
         </option>
      );
})}
</code>```

答:
You don't need to map through an object just to use its keys.

Instead simply do:

```<code>const options = {option: 'male': value: 'm'} // this is your parsed JSON

function App() {
 return (
  <div>
    <option key={options.value} value={options.option}>
        <Translate>{options.option}</Translate>
     </option>
  </div>
 );
}
</code>```

Body:
Data inside options(JSON) is

const options =  {"option":"Male","value":"M"};
Raect code is

{props.options.map((option) => {
      return (
         <option key={option.value} value={option.option}>
            <Translate>{option.option}</Translate>
         </option>
      );
})}

Body:
You don't need to map through an object just to use its keys.

Instead simply do:

const options = {option: 'male': value: 'm'} // this is your parsed JSON

function App() {
 return (
  <div>
    <option key={options.value} value={options.option}>
        <Translate>{options.option}</Translate>
     </option>
  </div>
 );
}


问:
Kubernetes AutoScaler Not Scaling, HPA shows target <unknown>
I'm pretty new to kubernetes, not so much with docker.

I've been working through the example but I am stuck with the autoscaler, (which doesn't seem to scale).

I am working through the example here https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale-walkthrough/#step-one-run--expose-php-apache-server

You'll find the build at the bottom

kubectl create -f https://k8s.io/docs/tasks/run-application/hpa-php-apache.yaml

Which looks like this

```<code>apiVersion: autoscaling/v1
kind: HorizontalPodAutoscaler
metadata:
  name: php-apache
  namespace: default
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: php-apache
  minReplicas: 1
  maxReplicas: 10
  targetCPUUtilizationPercentage: 50
</code>```

kubectl get hba shows

```<code>NAME         REFERENCE               TARGETS         MINPODS   MAXPODS   REPLICAS   AGE
php-apache   Deployment/php-apache   <unknown>/50%   1         10        0          7s
</code>```

Clue in the <unknown> section.

Then kubectl describe hba shows

```<code>Name:                                                  php-apache
Namespace:                                             default
Labels:                                                <none>
Annotations:                                           <none>
CreationTimestamp:                                     Sat, 14 Apr 2018 23:05:05 +0100
Reference:                                             Deployment/php-apache
Metrics:                                               ( current / target )
  resource cpu on pods  (as a percentage of request):  <unknown> / 50%
Min replicas:                                          1
Max replicas:                                          10
Conditions:
  Type         Status  Reason          Message
  ----         ------  ------          -------
  AbleToScale  False   FailedGetScale  the HPA controller was unable to get the target's current scale: deployments/scale.extensions "php-apache" not found
Events:
  Type     Reason          Age                From                       Message
  ----     ------          ----               ----                       -------
  Warning  FailedGetScale  12s (x14 over 6m)  horizontal-pod-autoscaler  deployments/scale.extensions "php-apache" not found
</code>```

So then I manually add it in with...

kubectl run php-apache --image=k8s.gcr.io/hpa-example --requests=cpu=200m --expose --port=80

Then if i run kubectl describe hpa again I get this error..

```<code>Name:                                                  php-apache
Namespace:                                             default
Labels:                                                <none>
Annotations:                                           <none>
CreationTimestamp:                                     Sat, 14 Apr 2018 23:05:05 +0100
Reference:                                             Deployment/php-apache
Metrics:                                               ( current / target )
  resource cpu on pods  (as a percentage of request):  <unknown> / 50%
Min replicas:                                          1
Max replicas:                                          10
Conditions:
  Type           Status  Reason                   Message
  ----           ------  ------                   -------
  AbleToScale    True    SucceededGetScale        the HPA controller was able to get the target's current scale
  ScalingActive  False   FailedGetResourceMetric  the HPA was unable to compute the replica count: unable to get metrics for resource cpu: unable to fetch metrics from API: the server could not find the requested resource (get pods.metrics.k8s.io)
Events:
  Type     Reason                        Age                From                       Message
  ----     ------                        ----               ----                       -------
  Warning  FailedGetScale                1m (x21 over 11m)  horizontal-pod-autoscaler  deployments/scale.extensions "php-apache" not found
  Warning  FailedGetResourceMetric       8s (x2 over 38s)   horizontal-pod-autoscaler  unable to get metrics for resource cpu: unable to fetch metrics from API: the server could not find the requested resource (get pods.metrics.k8s.io)
  Warning  FailedComputeMetricsReplicas  8s (x2 over 38s)   horizontal-pod-autoscaler  failed to get cpu utilization: unable to get metrics for resource cpu: unable to fetch metrics from API: the server could not find the requested resource (get pods.metrics.k8s.io)
</code>```

答:
To answer the question directly, if you have set up an HPA resource and using the metrics server, and ran into this error.

This error means that in your pods, which may have more than one container, either one or both of the containers have not defined resource requests:

```<code>Resources:
     requests:
       cpu: <this is missing! Add it>
</code>```

Check that all containers have resource requests defined.

To add edit and add resources directly, use
kubectl edit <resource>

Kubernetes may not allow you to update if your using helm even with the force flag.

A note, this may cause downtime if you have not set PodDisruptionBudgets so set those before you ran your edit

Body:
I'm pretty new to kubernetes, not so much with docker.

I've been working through the example but I am stuck with the autoscaler, (which doesn't seem to scale).

I am working through the example here https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale-walkthrough/#step-one-run--expose-php-apache-server

You'll find the build at the bottom

kubectl create -f https://k8s.io/docs/tasks/run-application/hpa-php-apache.yaml

Which looks like this

apiVersion: autoscaling/v1
kind: HorizontalPodAutoscaler
metadata:
  name: php-apache
  namespace: default
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: php-apache
  minReplicas: 1
  maxReplicas: 10
  targetCPUUtilizationPercentage: 50

kubectl get hba shows

NAME         REFERENCE               TARGETS         MINPODS   MAXPODS   REPLICAS   AGE
php-apache   Deployment/php-apache   <unknown>/50%   1         10        0          7s

Clue in the <unknown> section.

Then kubectl describe hba shows

Name:                                                  php-apache
Namespace:                                             default
Labels:                                                <none>
Annotations:                                           <none>
CreationTimestamp:                                     Sat, 14 Apr 2018 23:05:05 +0100
Reference:                                             Deployment/php-apache
Metrics:                                               ( current / target )
  resource cpu on pods  (as a percentage of request):  <unknown> / 50%
Min replicas:                                          1
Max replicas:                                          10
Conditions:
  Type         Status  Reason          Message
  ----         ------  ------          -------
  AbleToScale  False   FailedGetScale  the HPA controller was unable to get the target's current scale: deployments/scale.extensions "php-apache" not found
Events:
  Type     Reason          Age                From                       Message
  ----     ------          ----               ----                       -------
  Warning  FailedGetScale  12s (x14 over 6m)  horizontal-pod-autoscaler  deployments/scale.extensions "php-apache" not found

So then I manually add it in with...

kubectl run php-apache --image=k8s.gcr.io/hpa-example --requests=cpu=200m --expose --port=80

Then if i run kubectl describe hpa again I get this error..

Name:                                                  php-apache
Namespace:                                             default
Labels:                                                <none>
Annotations:                                           <none>
CreationTimestamp:                                     Sat, 14 Apr 2018 23:05:05 +0100
Reference:                                             Deployment/php-apache
Metrics:                                               ( current / target )
  resource cpu on pods  (as a percentage of request):  <unknown> / 50%
Min replicas:                                          1
Max replicas:                                          10
Conditions:
  Type           Status  Reason                   Message
  ----           ------  ------                   -------
  AbleToScale    True    SucceededGetScale        the HPA controller was able to get the target's current scale
  ScalingActive  False   FailedGetResourceMetric  the HPA was unable to compute the replica count: unable to get metrics for resource cpu: unable to fetch metrics from API: the server could not find the requested resource (get pods.metrics.k8s.io)
Events:
  Type     Reason                        Age                From                       Message
  ----     ------                        ----               ----                       -------
  Warning  FailedGetScale                1m (x21 over 11m)  horizontal-pod-autoscaler  deployments/scale.extensions "php-apache" not found
  Warning  FailedGetResourceMetric       8s (x2 over 38s)   horizontal-pod-autoscaler  unable to get metrics for resource cpu: unable to fetch metrics from API: the server could not find the requested resource (get pods.metrics.k8s.io)
  Warning  FailedComputeMetricsReplicas  8s (x2 over 38s)   horizontal-pod-autoscaler  failed to get cpu utilization: unable to get metrics for resource cpu: unable to fetch metrics from API: the server could not find the requested resource (get pods.metrics.k8s.io)

Body:
To answer the question directly, if you have set up an HPA resource and using the metrics server, and ran into this error.

This error means that in your pods, which may have more than one container, either one or both of the containers have not defined resource requests:

Resources:
     requests:
       cpu: <this is missing! Add it>

Check that all containers have resource requests defined.

To add edit and add resources directly, use
kubectl edit <resource>

Kubernetes may not allow you to update if your using helm even with the force flag.

A note, this may cause downtime if you have not set PodDisruptionBudgets so set those before you ran your edit


问:
How do I disable a UIButton?
I am working on a project in which I have to show all photos of Photo Library in a plist and show them horizontally on UIButtons.

My app will also have an edit button: when the user clicks this button, a delete mark (such as usually appears in other iPhone/iPad apps) should show on each button.

But here's the crucial bit: as soon as this delete mark appears, the functionality of the button should be disabled. I've tried accomplishing this with the following:

```<code>{
  editbutton.enabled=NO;
}
</code>```

...but it neither produces an error nor works. What should I do?

答:
Use the enabled property of UIControl which the super class of UIButton and set it with NO.

myButton.enabled = NO;

You could also try as @Marvin suggested,
In that case your button will not respond to any touch event from user,

Title: How do I disable a UIButton?

Body:
I am working on a project in which I have to show all photos of Photo Library in a plist and show them horizontally on UIButtons.

My app will also have an edit button: when the user clicks this button, a delete mark (such as usually appears in other iPhone/iPad apps) should show on each button.

But here's the crucial bit: as soon as this delete mark appears, the functionality of the button should be disabled. I've tried accomplishing this with the following:

{
  editbutton.enabled=NO;
}

...but it neither produces an error nor works. What should I do?


问:
Round by next quarter minutes always
We have a requirement to Round by next quarter minutes in Java code, for example:

if current date time is  2020-05-28T10:01:00
then, round up to next quarter to make it  2020-05-28T10:15:00

if current date time is 2020-05-28T10:15:01
then, round up to next quarter to make it  2020-05-28T10:30:00

if current date time is 2020-05-28T10:46:15
then, round up to next quarter to make it  2020-05-28T11:00:00

if current date time is 2020-12-31T23:47:00
then, round up to next quarter to make it 2021-01-01T00:00:00

Can someone please provide Java code to achieve this. Any help is appreciated.

Tried below code but unable to get the output which I'm looking for:

```<code>import java.util.Calendar;
import java.util.Date;

    public class Main {
        public static void main(String[] args) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            int round = calendar.get(Calendar.MINUTE) % 15;
            calendar.add(Calendar.MINUTE, round < 8 ? -round : (15-round));
            calendar.set( Calendar.SECOND, 0 );
            System.out.println(calendar.getTime());
        }
    }
</code>```

答:
You can try below code.</p>

```<code>    Calendar calendar = Calendar.getInstance();
    calendar.setTime(new Date(1609438620000l));
    int fraction = calendar.get(Calendar.MINUTE) / 15;
    switch (fraction) {
    case 0: {
        calendar.set(Calendar.MINUTE, 0);
        break;
    }
    case 1: {
        calendar.set(Calendar.MINUTE, 15);
        break;
    }
    case 2: {
        calendar.set(Calendar.MINUTE, 30);
        break;
    }
    default: {
        calendar.set(Calendar.MINUTE, 45);
        break;
    }
    }
    calendar.add(Calendar.MINUTE, 15);
    calendar.set(Calendar.SECOND, 0);
    System.out.println(calendar.getTime());
</code>```

Title: Round by next quarter minutes always

Body:
We have a requirement to Round by next quarter minutes in Java code, for example:

if current date time is  2020-05-28T10:01:00
then, round up to next quarter to make it  2020-05-28T10:15:00

if current date time is 2020-05-28T10:15:01
then, round up to next quarter to make it  2020-05-28T10:30:00

if current date time is 2020-05-28T10:46:15
then, round up to next quarter to make it  2020-05-28T11:00:00

if current date time is 2020-12-31T23:47:00
then, round up to next quarter to make it 2021-01-01T00:00:00

Can someone please provide Java code to achieve this. Any help is appreciated.

Tried below code but unable to get the output which I'm looking for:

import java.util.Calendar;
import java.util.Date;

    public class Main {
        public static void main(String[] args) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            int round = calendar.get(Calendar.MINUTE) % 15;
            calendar.add(Calendar.MINUTE, round < 8 ? -round : (15-round));
            calendar.set( Calendar.SECOND, 0 );
            System.out.println(calendar.getTime());
        }
    }

Body:
You can try below code.

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(new Date(1609438620000l));
    int fraction = calendar.get(Calendar.MINUTE) / 15;
    switch (fraction) {
    case 0: {
        calendar.set(Calendar.MINUTE, 0);
        break;
    }
    case 1: {
        calendar.set(Calendar.MINUTE, 15);
        break;
    }
    case 2: {
        calendar.set(Calendar.MINUTE, 30);
        break;
    }
    default: {
        calendar.set(Calendar.MINUTE, 45);
        break;
    }
    }
    calendar.add(Calendar.MINUTE, 15);
    calendar.set(Calendar.SECOND, 0);
    System.out.println(calendar.getTime());


问:
Using C++ objects from C
I would like to use C/C++ mixed code. I also need access to C++ object member variables from C code.

It works (at least in gcc), that I pass pointer to the object and handle it as a struct.

From C++:

```<code>class MyData {
  ...
};
</code>```

From C:

```<code>struct MyData {
  ...
};
</code>```

(Of course, I do not duplicate code in the final header file)

1, I am not sure that this would work using any of the compilers. Is there any reasons why I should not rely on this?

2, If MyData class has virtual member functions, this would not work, but a pointer to the first member variable could solve the problem. Is this safe, or may I get into trouble with this?

答:
The way to do this is to write a C interface API for your C++ code.

I would make this by using a separate header and a separate .cpp file. In the header define an API that does not include the C++ header. That's a rookie mistake. This header has to stand alone as a C version of your code.

I would not expose any kind of struct. If you have to, have functions that return pointers to members. Then the C code can directly read and write to the pointer. Better yet are functions to explicitly get and set member values.

You can use a void* or use a struct forward declaration for your object type.

Then build C functions to construct, destruct, copy, and all member functions which take a pointer to this as a parameter. You can't call it this because that conflicts with C++, so use self or something. Constructors and copy constructors obviously don't take this, they return a pointer to a new object.

Put all of these functions in the header inside an extern "C" { } block with ifdef guards.

So here's an example I played with:

```<code>// c-cpp-string-api.cpp

#include "c-cpp-string-api.h"
#include <string>

namespace {
static inline struct cppstring *to_c(std::string *p) {
  return reinterpret_cast<cppstring *>(p);
}

static inline std::string *from_c(struct cppstring *p) {
  return reinterpret_cast<std::string *>(p);
}
} // namespace

struct cppstring *cppstring_construct(const char *str) {
  return to_c(new std::string(str));
}

cppstring *cppstring_copy(cppstring *str) {
  return to_c(new std::string(*from_c(str)));
}

void cppstring_destruct(cppstring *str) { delete from_c(str); }

const char *cppstring_cstr(cppstring *str) { return from_c(str)->c_str(); }
</code>```

```<code>// c-cpp-string-api.h

#pragma once

#ifdef __cplusplus
extern "C" {
#endif

struct cppstring;

struct cppstring *cppstring_construct(const char *str);
struct cppstring *cppstring_copy(struct cppstring *str);
void cppstring_destruct(struct cppstring *str);

const char *cppstring_cstr(struct cppstring *str);

#ifdef __cplusplus
}
#endif
</code>```

```<code>// c-cpp-string-api-test.c

#include "c-cpp-string-api.h"
#include <stdio.h>

int main(int argc, char *argv[]) {
  if (argc < 2)
    return 1;

  struct cppstring *p1 = cppstring_construct(argv[1]);
  struct cppstring *p2 = cppstring_copy(p1);

  printf("value of string is %s and %s\n", cppstring_cstr(p1),
         cppstring_cstr(p2));

  cppstring_destruct(p2);
  cppstring_destruct(p1);
  return 0;
}
</code>```

```<code># Makefile

LTOFLAGS += -flto -fno-fat-lto-objects
OPTFLAGS += -O3 -march=native $(LTOFLAGS)
FLAGS += -Wall -W -pedantic -g $(OPTFLAGS) -MMD $(EXTRA)
FLAGS += -fPIC -fPIE -fstack-protector-strong
CFLAGS = $(FLAGS) -std=c11
CXXFLAGS = $(FLAGS) -std=c++17
LDFLAGS += $(LTOFLAGS)

c-cpp-string-api-test: c-cpp-string-api.o c-cpp-string-api-test.o
    $(CXX) $(CXXFLAGS) $(LDFLAGS) $^ -o $@

-include *.d

clean:
    rm -f *.o *.d c-cpp-string-api-test

.PHONY: clean
</code>```

Title: Using C++ objects from C

Body:
I would like to use C/C++ mixed code. I also need access to C++ object member variables from C code.

It works (at least in gcc), that I pass pointer to the object and handle it as a struct.

From C++:

class MyData {
  ...
};

From C:

struct MyData {
  ...
};

(Of course, I do not duplicate code in the final header file)

1, I am not sure that this would work using any of the compilers. Is there any reasons why I should not rely on this?

2, If MyData class has virtual member functions, this would not work, but a pointer to the first member variable could solve the problem. Is this safe, or may I get into trouble with this?

Body:
The way to do this is to write a C interface API for your C++ code.

I would make this by using a separate header and a separate .cpp file. In the header define an API that does not include the C++ header. That's a rookie mistake. This header has to stand alone as a C version of your code.

I would not expose any kind of struct. If you have to, have functions that return pointers to members. Then the C code can directly read and write to the pointer. Better yet are functions to explicitly get and set member values.

You can use a void* or use a struct forward declaration for your object type.

Then build C functions to construct, destruct, copy, and all member functions which take a pointer to this as a parameter. You can't call it this because that conflicts with C++, so use self or something. Constructors and copy constructors obviously don't take this, they return a pointer to a new object.

Put all of these functions in the header inside an extern "C" { } block with ifdef guards.

So here's an example I played with:

// c-cpp-string-api.cpp

#include "c-cpp-string-api.h"
#include <string>

namespace {
static inline struct cppstring *to_c(std::string *p) {
  return reinterpret_cast<cppstring *>(p);
}

static inline std::string *from_c(struct cppstring *p) {
  return reinterpret_cast<std::string *>(p);
}
} // namespace

struct cppstring *cppstring_construct(const char *str) {
  return to_c(new std::string(str));
}

cppstring *cppstring_copy(cppstring *str) {
  return to_c(new std::string(*from_c(str)));
}

void cppstring_destruct(cppstring *str) { delete from_c(str); }

const char *cppstring_cstr(cppstring *str) { return from_c(str)->c_str(); }

// c-cpp-string-api.h

#pragma once

#ifdef __cplusplus
extern "C" {
#endif

struct cppstring;

struct cppstring *cppstring_construct(const char *str);
struct cppstring *cppstring_copy(struct cppstring *str);
void cppstring_destruct(struct cppstring *str);

const char *cppstring_cstr(struct cppstring *str);

#ifdef __cplusplus
}
#endif

// c-cpp-string-api-test.c

#include "c-cpp-string-api.h"
#include <stdio.h>

int main(int argc, char *argv[]) {
  if (argc < 2)
    return 1;

  struct cppstring *p1 = cppstring_construct(argv[1]);
  struct cppstring *p2 = cppstring_copy(p1);

  printf("value of string is %s and %s\n", cppstring_cstr(p1),
         cppstring_cstr(p2));

  cppstring_destruct(p2);
  cppstring_destruct(p1);
  return 0;
}

# Makefile

LTOFLAGS += -flto -fno-fat-lto-objects
OPTFLAGS += -O3 -march=native $(LTOFLAGS)
FLAGS += -Wall -W -pedantic -g $(OPTFLAGS) -MMD $(EXTRA)
FLAGS += -fPIC -fPIE -fstack-protector-strong
CFLAGS = $(FLAGS) -std=c11
CXXFLAGS = $(FLAGS) -std=c++17
LDFLAGS += $(LTOFLAGS)

c-cpp-string-api-test: c-cpp-string-api.o c-cpp-string-api-test.o
    $(CXX) $(CXXFLAGS) $(LDFLAGS) $^ -o $@

-include *.d

clean:
    rm -f *.o *.d c-cpp-string-api-test

.PHONY: clean


问:
How to solve an error with curl (security)
When using curl for opening a website, everything worked fine.
Until today, when I got this error:
"Security Violation (403)" and "Access denied".

Could you imagine, what the reason for this spontaneous problem could be?
I tried using the "-k" parameter and the "cacert"-parameter, but both options just won't work.

Kind regards,
X3nion

```<code><!DOCTYPE html><html><head><title>Error Page</title><style type="text/css">html{font-family:'Helvetica Neue',Helvetica,Arial,sans-serif;font-size:1em}.center-box{margin: 20% auto auto auto;width: 50%;border: 1px solid #dcdcdc;padding: 1em;} </style>
<title>Security Violation (403)</title></head></head><body>
<div class="center-box">
<h3>www.ebay-kleinanzeigen.de | Access denied (403)</h3>
<h4>Current session has been terminated.</h2>
<p>For further information, do not hesitate to contact us.</p>
<p>Ref: <span id="addr">2003:6:63e3:2d98:8d19:56d:b877:8b2f</span> <span id="time">1590873486</span></p>
</div></body><script>document.getElementById("time").innerHTML = (new Date()).toISOString()</script>                 </html>
</code>```

答:
One way to try to workaround this problem, is setting the same request headers from a default request made with a browser.

you can access this address in a browser and copy as curl in the developer tools (F12 or ⌘ Command + ⇧ Shift + C), network tab, and try to do the request again. If it pass, you can use now this new command with all attributes (headers and cookies) from current request.

Here is a way to reproduce this instructions:

In my example I'm using the browser to access www.google.com.br.

Here is the output from this copy (30/05/2020):

```<code>curl 'https://www.google.com.br/' \
  -H 'authority: www.google.com.br' \
  -H 'pragma: no-cache' \
  -H 'cache-control: no-cache' \
  -H 'upgrade-insecure-requests: 1' \
  -H 'user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36' \
  -H 'accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9' \
  -H 'x-client-data: CIm2yQEIprbJAQjBtskBCKmdygEIlcfKARibvsoB' \
  -H 'sec-fetch-site: same-origin' \
  -H 'sec-fetch-mode: navigate' \
  -H 'sec-fetch-user: ?1' \
  -H 'sec-fetch-dest: document' \
  -H 'accept-language: en-US,en;q=0.9' \
  -H 'cookie: SID=xQcxtDTQXD5qliOgo8FsNlkDrKtYI_jrPiJR2ZfyZh_S6rACWTHDFRPceJ1Tlr5vll4Oyg.; __Secure-3PSID=xQcxtDTQXD5qliOgo8FsNlkDrKtYI_jrPiJR2ZfyZh_S6rAC6tkjLmhvnJemQDVkqRXJzA.; HSID=Arao901D7S0l5puo5; SSID=ADCpbatyj1vAsJkQ4; APISID=VFdN0avW09MCGbDg/AfSwcaKj2K-5VAdEp; SAPISID=H6_f7UhMDkCvL5NK/AU2VJW0BtPIm65yd_; __Secure-HSID=Arao901D7S0l5puo5; __Secure-SSID=ADCpbatyj1vAsJkQ4; __Secure-APISID=VFdN0avW09MCGbDg/AfSwcaKj2K-5VAdEp; __Secure-3PAPISID=H6_f7UhMDkCvL5NK/AU2VJW0BtPIm65yd_; NID=204=vxNaEkPbH3XB5fl2OuV-8vZcxKvBqg9d9FRiPCTjZkUMw-row1uJJYuEp7OOJtX7XyAMPjbeo_wWhcl08zcEGI6v1HfRrAx8e8y6pXNQndD8B-FzUwHkFUZ5D-znDzlyGEeZIDOUma9tRg7tQNImG355pJlmUXplzwh2A4HqFugemrGZBmsOlDZoyfnkuXdi-TP75sXHND7eHONxuVBxcioAftLteD6p6_B8YmutQ9DW4fmGO-vDW670jO-Z3xrJrlP9AZGpLgqevJHccRvFhKcHrQtFLGjpnWUL6DUX_Wh03O7QA-Fd5P8gblr1fV8HTEkHXNm8Ts4g3KNV6XeGZXgApfgthCXTZbS29fdcsxgtM5O6nQ; ANID=AHWqTUkfogufuIUy88wEaeh3NUYr_VlBp2vI5oaQxuA-EzjvZKFBNZW-Fu09sowM; 1P_JAR=2020-05-30-21' \
  --compressed
</code>```

Body:
When using curl for opening a website, everything worked fine.
Until today, when I got this error:
"Security Violation (403)" and "Access denied".

Could you imagine, what the reason for this spontaneous problem could be?
I tried using the "-k" parameter and the "cacert"-parameter, but both options just won't work.

Kind regards,
X3nion

<!DOCTYPE html><title>Error Page</title>
<title>Security Violation (403)</title>

www.ebay-kleinanzeigen.de | Access denied (403)

Current session has been terminated.

For further information, do not hesitate to contact us.

Ref: 2003:6:63e3:2d98:8d19:56d:b877:8b2f 1590873486

Body:
One way to try to workaround this problem, is setting the same request headers from a default request made with a browser.

you can access this address in a browser and copy as curl in the developer tools (F12 or ⌘ Command + ⇧ Shift + C), network tab, and try to do the request again. If it pass, you can use now this new command with all attributes (headers and cookies) from current request.

Here is a way to reproduce this instructions:

In my example I'm using the browser to access www.google.com.br.

Here is the output from this copy (30/05/2020):

curl 'https://www.google.com.br/' \
  -H 'authority: www.google.com.br' \
  -H 'pragma: no-cache' \
  -H 'cache-control: no-cache' \
  -H 'upgrade-insecure-requests: 1' \
  -H 'user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36' \
  -H 'accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9' \
  -H 'x-client-data: CIm2yQEIprbJAQjBtskBCKmdygEIlcfKARibvsoB' \
  -H 'sec-fetch-site: same-origin' \
  -H 'sec-fetch-mode: navigate' \
  -H 'sec-fetch-user: ?1' \
  -H 'sec-fetch-dest: document' \
  -H 'accept-language: en-US,en;q=0.9' \
  -H 'cookie: SID=xQcxtDTQXD5qliOgo8FsNlkDrKtYI_jrPiJR2ZfyZh_S6rACWTHDFRPceJ1Tlr5vll4Oyg.; __Secure-3PSID=xQcxtDTQXD5qliOgo8FsNlkDrKtYI_jrPiJR2ZfyZh_S6rAC6tkjLmhvnJemQDVkqRXJzA.; HSID=Arao901D7S0l5puo5; SSID=ADCpbatyj1vAsJkQ4; APISID=VFdN0avW09MCGbDg/AfSwcaKj2K-5VAdEp; SAPISID=H6_f7UhMDkCvL5NK/AU2VJW0BtPIm65yd_; __Secure-HSID=Arao901D7S0l5puo5; __Secure-SSID=ADCpbatyj1vAsJkQ4; __Secure-APISID=VFdN0avW09MCGbDg/AfSwcaKj2K-5VAdEp; __Secure-3PAPISID=H6_f7UhMDkCvL5NK/AU2VJW0BtPIm65yd_; NID=204=vxNaEkPbH3XB5fl2OuV-8vZcxKvBqg9d9FRiPCTjZkUMw-row1uJJYuEp7OOJtX7XyAMPjbeo_wWhcl08zcEGI6v1HfRrAx8e8y6pXNQndD8B-FzUwHkFUZ5D-znDzlyGEeZIDOUma9tRg7tQNImG355pJlmUXplzwh2A4HqFugemrGZBmsOlDZoyfnkuXdi-TP75sXHND7eHONxuVBxcioAftLteD6p6_B8YmutQ9DW4fmGO-vDW670jO-Z3xrJrlP9AZGpLgqevJHccRvFhKcHrQtFLGjpnWUL6DUX_Wh03O7QA-Fd5P8gblr1fV8HTEkHXNm8Ts4g3KNV6XeGZXgApfgthCXTZbS29fdcsxgtM5O6nQ; ANID=AHWqTUkfogufuIUy88wEaeh3NUYr_VlBp2vI5oaQxuA-EzjvZKFBNZW-Fu09sowM; 1P_JAR=2020-05-30-21' \
  --compressed


问:
What are some disadvantages of the GoF Flyweight design pattern
I understand the benefits of the flyweight design pattern, but I am unsure of its exact drawback.
For example, I understand that it may be break encapsulation, but that is all I can currently think of, what are some possible drawbacks of the flyweight design pattern, there is very little documentation, on this matter.</p>

答:
On page 199, the GoF mentions,

Flyweights may introduce run-time costs associated with transferring, finding, and/or computing extrinsic state, especially if it was formerly stored as intrinsic state.

Flyweights can be a trade-off of space for time, if extrinsic state is computed or queried rather than stored. And of course there is some added complexity inherent to the pattern itself: data that was previously owned by each object and accessed directly must now be retrieved through some type of Factory, which adds an additional layer of indirection.

The narrow applicability of the Flyweight pattern could be considered a disadvantage as well. Five separate conditions must be met to take advantage of the pattern's benefits according to the GoF. This is the reason I believe Java's String.intern() is not a Flyweight.


问:
How to prevent useQuery for running when state changes?
I am using React Apollo to get data from my server. When my page loads I am using useQuery to retrieve the data. This works fine. The problem is when I make a change to the search form, this updates the state which causes an unwanted re-render which calls the server again.

I want to call the server only when the page loads and when I click the search button.

useQuery:

```<code>const { loading: loadingLessons, error: lessonsError, data: lessons } = useQuery(
 LESSON_BY_PARAMS,
    {
      variables: { findLessonsInput: searchParams },
    },
);
</code>```

When I change a form field it calls updateFormField which updates the redux state causing a re-render

```<code><Autocomplete
  options={categories}
  getOptionLabel={(option: any) => option.label}
  inputValue={form.category}
  defaultValue={() => {
    const value = categories.find(option => option.label === form.category);
    return value;
  }}
  onChange={(event, value) => updateFormField('category', value?.label)}
  renderInput={params => (
    <TextField {...params} label="Category" variant="outlined" fullWidth />
  )}
/>
</code>```

I am using react hooks.

答:
If you use pure apollo client you will loose some features from apollo. There is no need to move graphql call into redux action, you can use selectors in Redux to prevent components from reloading or making unnecessary calls to a server.

Selectors in Redux

Body:
I am using React Apollo to get data from my server. When my page loads I am using useQuery to retrieve the data. This works fine. The problem is when I make a change to the search form, this updates the state which causes an unwanted re-render which calls the server again.

I want to call the server only when the page loads and when I click the search button.

useQuery:

const { loading: loadingLessons, error: lessonsError, data: lessons } = useQuery(
 LESSON_BY_PARAMS,
    {
      variables: { findLessonsInput: searchParams },
    },
);

When I change a form field it calls updateFormField which updates the redux state causing a re-render

<Autocomplete
  options={categories}
  getOptionLabel={(option: any) => option.label}
  inputValue={form.category}
  defaultValue={() => {
    const value = categories.find(option => option.label === form.category);
    return value;
  }}
  onChange={(event, value) => updateFormField('category', value?.label)}
  renderInput={params => (
    <TextField {...params} label="Category" variant="outlined" fullWidth />
  )}
/>

I am using react hooks.


问:
How to collapse an array by joining all strings, but leaving objects
While I'm sure I'm waay over-complicating things, I'm curious to know how I would "collapse" an array by combining all adjacent strings, but leaving objects as objects so that:

```<code>array = ["I","want","to",[Obj],"come","together"]
</code>```

outputs

```<code>["I want to", [Obj], "come together"];
</code>```

I feel like array.reduce() might be the ticket here, but I'm still wrapping my head around that function.

答:
In case you wanna go with the plain old for-loop :)

var result = [], array = ["I","want","to",{a: 1, b:2},"come","together"];
var i=0;var str = "";
for(; i< array.length; i++){
  if(typeof array[i] === 'object' ){
     result.push(str);
     result.push(array[i]);
     str="";

   }else{
    str = str+" "+ array[i];
  }
}
if(i==array.length){
  result.push(str);
}
console.log(result);```

Body:
While I'm sure I'm waay over-complicating things, I'm curious to know how I would "collapse" an array by combining all adjacent strings, but leaving objects as objects so that:

array = ["I","want","to",[Obj],"come","together"]

outputs

["I want to", [Obj], "come together"];

I feel like array.reduce() might be the ticket here, but I'm still wrapping my head around that function.


问:
Unable to acquire the state change lock for the module: osgi.identity on Windows server 2012
I am not able to open eclipse downloaded on a remote desktop running on Windows server 2012 R2 standard edition. How do I solve this issue?
Here is what I have tried:

Deleted configuration/.log file

Deleted .fileTable.1, .fileTable.2, .fileTableLock in configuration/org.eclipse.osgi/.manager

Deleted framework.info.1 in configuration/org.eclipse.osgi

I am not at liberty to restart the shared server.
This is in my .eclipseproduct:

```<code>name=Eclipse Platform
id=org.eclipse.platform
version=4.6.3
</code>```

And here is the beginning of the log file:

!ENTRY org.eclipse.equinox.ds 2 0 2018-02-16 10:28:57.812
!MESSAGE [SCR] Enabling components of bundle org.eclipse.ui.trace did not complete in 30000 ms

```<code>!ENTRY org.eclipse.core.runtime 4 0 2018-02-16 10:29:02.855
!MESSAGE FrameworkEvent ERROR
!STACK 0
org.osgi.framework.BundleException: Unable to acquire the state change lock for the module: osgi.identity; osgi.identity="org.eclipse.core.runtime"; type="osgi.bundle"; version:Version="3.12.0.v20160606-1342"; singleton:="true" [id=98] STARTED [STARTED]
    at org.eclipse.osgi.container.Module.lockStateChange(Module.java:337)
    at org.eclipse.osgi.container.Module.start(Module.java:401)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1620)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1600)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.doContainerStartLevel(ModuleContainer.java:1571)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1514)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1)
    at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230)
    at org.eclipse.osgi.framework.eventmgr.EventManager$EventThread.run(EventManager.java:340)
Caused by: java.util.concurrent.TimeoutException: Timeout after waiting 5 seconds to acquire the lock.
    at org.eclipse.osgi.container.Module.lockStateChange(Module.java:334)
    ... 8 more
Root exception:
java.util.concurrent.TimeoutException: Timeout after waiting 5 seconds to acquire the lock.
    at org.eclipse.osgi.container.Module.lockStateChange(Module.java:334)
    at org.eclipse.osgi.container.Module.start(Module.java:401)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1620)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1600)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.doContainerStartLevel(ModuleContainer.java:1571)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1514)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1)
    at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230)
    at org.eclipse.osgi.framework.eventmgr.EventManager$EventThread.run(EventManager.java:340)
</code>```

答:
I tried this solution with myeclipse and word¿ks, specifically I tried this:

backup on a zip all your files from this folder

delete the files
the folder is
\MyEclipse 2017 CI\configuration\org.eclipse.osgi.manager

restart myeclipse

Body:
I am not able to open eclipse downloaded on a remote desktop running on Windows server 2012 R2 standard edition. How do I solve this issue?
Here is what I have tried:

Deleted configuration/.log file

Deleted .fileTable.1, .fileTable.2, .fileTableLock in configuration/org.eclipse.osgi/.manager

Deleted framework.info.1 in configuration/org.eclipse.osgi

I am not at liberty to restart the shared server.
This is in my .eclipseproduct:

name=Eclipse Platform
id=org.eclipse.platform
version=4.6.3

And here is the beginning of the log file:

!ENTRY org.eclipse.equinox.ds 2 0 2018-02-16 10:28:57.812
!MESSAGE [SCR] Enabling components of bundle org.eclipse.ui.trace did not complete in 30000 ms

!ENTRY org.eclipse.core.runtime 4 0 2018-02-16 10:29:02.855
!MESSAGE FrameworkEvent ERROR
!STACK 0
org.osgi.framework.BundleException: Unable to acquire the state change lock for the module: osgi.identity; osgi.identity="org.eclipse.core.runtime"; type="osgi.bundle"; version:Version="3.12.0.v20160606-1342"; singleton:="true" [id=98] STARTED [STARTED]
    at org.eclipse.osgi.container.Module.lockStateChange(Module.java:337)
    at org.eclipse.osgi.container.Module.start(Module.java:401)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1620)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1600)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.doContainerStartLevel(ModuleContainer.java:1571)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1514)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1)
    at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230)
    at org.eclipse.osgi.framework.eventmgr.EventManager$EventThread.run(EventManager.java:340)
Caused by: java.util.concurrent.TimeoutException: Timeout after waiting 5 seconds to acquire the lock.
    at org.eclipse.osgi.container.Module.lockStateChange(Module.java:334)
    ... 8 more
Root exception:
java.util.concurrent.TimeoutException: Timeout after waiting 5 seconds to acquire the lock.
    at org.eclipse.osgi.container.Module.lockStateChange(Module.java:334)
    at org.eclipse.osgi.container.Module.start(Module.java:401)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1620)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1600)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.doContainerStartLevel(ModuleContainer.java:1571)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1514)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1)
    at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230)
    at org.eclipse.osgi.framework.eventmgr.EventManager$EventThread.run(EventManager.java:340)


问:
Loop through list operating on result and next value
I have a sorted list of objects

```<code>l = sorted(['/path/to/1.obj', '/path/to/2.obj', '/path/to/3.obj', '/path/to/4.obj'])
</code>```

I want to loop through the object performing an operation on them and using the result to preform the next operation.

For example

```<code>result1 = my_operation(l[0], l[1])
result2 = my_operation(result1, l[2])
resultFinal = my_operation(result2, l[3])
</code>```

How can I do this in a list of an arbitrary length?

答:
The concept you are looking for is a loop:

```<code>def op(a,b):
    return a*b

l = [1, 2, 4, 7, 12, 92]

k = op(*l[:2])
print(k)

for item in l[2:]:
    k = op(k, item)
    print(k)
</code>```

Output:

```<code>2           # 1 * 2
8           #       * 4
56          #            * 7
672         #                * 12
61824       #                     * 92
</code>```

Make sure your list has at least 2 elements and you should be fine.

Body:
I have a sorted list of objects

l = sorted(['/path/to/1.obj', '/path/to/2.obj', '/path/to/3.obj', '/path/to/4.obj'])

I want to loop through the object performing an operation on them and using the result to preform the next operation.

For example

result1 = my_operation(l[0], l[1])
result2 = my_operation(result1, l[2])
resultFinal = my_operation(result2, l[3])

How can I do this in a list of an arbitrary length?

Body:
The concept you are looking for is a loop:

def op(a,b):
    return a*b

l = [1, 2, 4, 7, 12, 92]

k = op(*l[:2])
print(k)

for item in l[2:]:
    k = op(k, item)
    print(k)

Output:

2           # 1 * 2
8           #       * 4
56          #            * 7
672         #                * 12
61824       #                     * 92

Make sure your list has at least 2 elements and you should be fine.


问:
what does this code mean in xv6 entrypgdir?
I'm currently delving into the xv6 operating system. I have a question for the below code snippet. I know entrypgdir is an array of pde_t type with size of NPDENTRIES. But what does "[0] = (0) | PTE_P | PTE_W | PTE_PS" mean?
Thanks in advance

__attribute__((__aligned__(PGSIZE)))
pde_t entrypgdir[NPDENTRIES] = {
  // Map VA's [0, 4MB) to PA's [0, 4MB)
  [0] = (0) | PTE_P | PTE_W | PTE_PS,
  // Map VA's [KERNBASE, KERNBASE+4MB) to PA's [0, 4MB)
  [KERNBASE>>PDXSHIFT] = (0) | PTE_P | PTE_W | PTE_PS,
};```

答:
The code is initializing the contents of the page directory. (See designated array initialization in C).

Consider this image of the contents of a page directory entry from OSDev Wiki:

Then consider this line of code:

```<code>[0] = (0) | PTE_P | PTE_W | PTE_PS
</code>```

The code sets the value of the first page directory entry (index 0) to 0 | PTE_P | PTE_W | PTE_PS. This is a bitwise OR to set the various fields:

0      - clear all bits

PTE_P  - set the present bit

PTE_W  - set the read\write bit

PTE_PS - set the 4MiB page size bit

The next line does a similar thing. Except it sets the contents of the 513th entry (index 512 (0x80000000 >> 22)):

```<code>[KERNBASE >> PDXSHIFT] = (0) | PTE_P | PTE_W | PTE_PS
</code>```

.

Aside:

The bit position of the flags of interest to xv6 is the same for page directory entries (PDE) and page table entries (PTE). Instead of creating separate constants for the PDE flags, the authors opted to share the constants... In my opinion, this shortcut makes the code slightly less clear in intent.

```<code>// Page table/directory entry flags.
#define PTE_P  0x001   // Present
#define PTE_W  0x002   // Writeable
#define PTE_U  0x004   // User
#define PTE_PS 0x080   // Page Size
</code>```

Body:
The code is initializing the contents of the page directory. (See designated array initialization in C).

Consider this image of the contents of a page directory entry from OSDev Wiki:

Then consider this line of code:

[0] = (0) | PTE_P | PTE_W | PTE_PS

The code sets the value of the first page directory entry (index 0) to 0 | PTE_P | PTE_W | PTE_PS. This is a bitwise OR to set the various fields:

0      - clear all bits

PTE_P  - set the present bit

PTE_W  - set the read\write bit

PTE_PS - set the 4MiB page size bit

The next line does a similar thing. Except it sets the contents of the 513th entry (index 512 (0x80000000 >> 22)):

[KERNBASE >> PDXSHIFT] = (0) | PTE_P | PTE_W | PTE_PS

.

Aside:

The bit position of the flags of interest to xv6 is the same for page directory entries (PDE) and page table entries (PTE). Instead of creating separate constants for the PDE flags, the authors opted to share the constants... In my opinion, this shortcut makes the code slightly less clear in intent.

// Page table/directory entry flags.
#define PTE_P  0x001   // Present
#define PTE_W  0x002   // Writeable
#define PTE_U  0x004   // User
#define PTE_PS 0x080   // Page Size


问:
How to use regex in Pandas?
I have extracted the  column names from a .csv file and now I want to use a regex expression in order to capitalise the first letter of the word and the first letter after the _ character.
Example: loan_status -> Loan_Status

```<code>Loan_ID
loan_status
Principal
terms
effective_date
due_date
paid_off_time
past_due_days
age
education
Gender
</code>```

This is what I have  come up with so far (^[a-z])+\w+

UPDATE
Thanks to Wiktor Stribiżew, this is what I came up with.
I am wondering if there is a more compact way to do the below.

```<code>import csv
import pandas  as pd
import re

dataFrame = pd.read_csv('Loan_payments_data_2020_unclean.csv')

columnsDict = {"columnName": list(dataFrame.columns)}
columnsDataFrame = pd.DataFrame(columnsDict)

replacedColumns = columnsDataFrame['columnName'].str.replace(r'(?<![^_]).', lambda x: x.group().upper())
dataFrame.columns = list(replacedColumns)
print(dataFrame)
</code>```

答:
You may use

```<code>>>> df = pd.DataFrame({'Loan_ID': ['loan_status','Principal','terms','effective_date','due_date','paid_off_time','past_due_days','age','education','Gender']})
>>> df['Loan_ID'].str.replace(r'(?<![^_]).', lambda x: x.group().upper())
0       Loan_Status
1         Principal
2             Terms
3    Effective_Date
4          Due_Date
5     Paid_Off_Time
6     Past_Due_Days
7               Age
8         Education
9            Gender
Name: Loan_ID, dtype: object
</code>```

The (?<![^_]). regex matches any char other than line break char that is either at the start of string or appears immediately after a _ char. It is equal to (?:(?<=^)|(?<=_)). regex, see its demo online.

Since you cannot manipulate the matched value from within a string replacement pattern, a callable is required as the replacement argument. lambda x: x.group().upper() just grabs the match value and turns it to upper case.

Title: How to use regex in Pandas?

Body:
I have extracted the  column names from a .csv file and now I want to use a regex expression in order to capitalise the first letter of the word and the first letter after the _ character.
Example: loan_status -> Loan_Status

Loan_ID
loan_status
Principal
terms
effective_date
due_date
paid_off_time
past_due_days
age
education
Gender

This is what I have  come up with so far (^[a-z])+\w+

UPDATE
Thanks to Wiktor Stribiżew, this is what I came up with.
I am wondering if there is a more compact way to do the below.

import csv
import pandas  as pd
import re

dataFrame = pd.read_csv('Loan_payments_data_2020_unclean.csv')

columnsDict = {"columnName": list(dataFrame.columns)}
columnsDataFrame = pd.DataFrame(columnsDict)

replacedColumns = columnsDataFrame['columnName'].str.replace(r'(?<![^_]).', lambda x: x.group().upper())
dataFrame.columns = list(replacedColumns)
print(dataFrame)

Body:
You may use

>>> df = pd.DataFrame({'Loan_ID': ['loan_status','Principal','terms','effective_date','due_date','paid_off_time','past_due_days','age','education','Gender']})
>>> df['Loan_ID'].str.replace(r'(?<![^_]).', lambda x: x.group().upper())
0       Loan_Status
1         Principal
2             Terms
3    Effective_Date
4          Due_Date
5     Paid_Off_Time
6     Past_Due_Days
7               Age
8         Education
9            Gender
Name: Loan_ID, dtype: object

The (?<![^_]). regex matches any char other than line break char that is either at the start of string or appears immediately after a _ char. It is equal to (?:(?<=^)|(?<=_)). regex, see its demo online.

Since you cannot manipulate the matched value from within a string replacement pattern, a callable is required as the replacement argument. lambda x: x.group().upper() just grabs the match value and turns it to upper case.


问:
Jquery Inputmask saving wrong monetary value
I'm trying to save a monetary value  with InputMask like this 1000.5 -> 1.000,50

This is my code for the InputMask

```<code>var mmoney = new Inputmask('decimal', {
            autoUnmask: true,
            unmaskAsNumber: true,
            groupSeparator: '.',
            radixPoint: ",",
            digits: 2,
            digitsOptional: false,
            rightAlign: false });
if($('.msk-money').length) {
    mmoney.mask($(".msk-money"));
}
</code>```

but insted saving 1000.5 are saving 1.0005. How I remove the mask to save in database?

答:
This depends on how you are getting the value. The autoMask should take care of it if you use .val().  It may not work if you are using default submit behavior.

you can do this:

```<code>$(selector).inputmask('unmaskedvalue');
</code>```

But, it's likely that you are setting the initial value of to "1.000,50".  If you set the initial value to the formatted version, it won't recognize it. Be sure to set the initial value as a decimal so that you can later retrieve it.

Body:
I'm trying to save a monetary value  with InputMask like this 1000.5 -> 1.000,50

This is my code for the InputMask

var mmoney = new Inputmask('decimal', {
            autoUnmask: true,
            unmaskAsNumber: true,
            groupSeparator: '.',
            radixPoint: ",",
            digits: 2,
            digitsOptional: false,
            rightAlign: false });
if($('.msk-money').length) {
    mmoney.mask($(".msk-money"));
}

but insted saving 1000.5 are saving 1.0005. How I remove the mask to save in database?

Body:
This depends on how you are getting the value. The autoMask should take care of it if you use .val().  It may not work if you are using default submit behavior.

you can do this:

$(selector).inputmask('unmaskedvalue');

But, it's likely that you are setting the initial value of to "1.000,50".  If you set the initial value to the formatted version, it won't recognize it. Be sure to set the initial value as a decimal so that you can later retrieve it.


问:
Update data in CoreData and its value in a view
I am new to developing in Swift and CoreData. I've been struggling with the following code which displays a view with some information on a student which is stored with CoreData. The button "Ask question" which is displayed in the view updates student.questionAskedClass but the view does not updates its value.

The value is clearly updated internally because if I relaunch the application, I can see that the value has been updated. But I would like to see it updated live.

Thanks for your help,
Francois

```<code>import SwiftUI

struct StudentView: View {
  @Environment(\.managedObjectContext) var managedObjectContext

  var student: Student

  var body: some View {
    VStack(alignment: .leading) {
      Text("\(student.firstName)").font(.headline).foregroundColor(Color.black)
      Text("\(student.lastName)").font(.headline).foregroundColor(Color.gray)
      Spacer().frame(height: 10)
      Text("\(student.email)").font(.headline).foregroundColor(Color.gray)
      Spacer().frame(height: 10)
      Text("Number of questions asked: \(student.questionAskedClass)").font(.headline).foregroundColor(Color.gray)
      Button(action: {
        self.askQuestion()
      }) {
        Text("Ask question")
      }
    }
  }

  func askQuestion() {
    self.managedObjectContext.performAndWait {
      self.student.questionAskedClass += 1
      try? self.managedObjectContext.save()
    }
  }
}
</code>```

答:
You are changing a property of one of your CoreData object. However, that won't refresh the view as you only use on person instance to display the data. You will need to refresh the view, to display the update.

Just use a dummy @State, which you will toggle after changes.

```<code>@State var updateView : Bool = false
</code>```

You will need to use it inside your view, so just add it somewhere:

```<code>  Text("\(student.firstName)" + (self.updateView ? "" : "").font(.headline).foregroundColor(Color.black)
</code>```

And then toggle it:

```<code>Button(action: {
    self.askQuestion()
    self.updateView.toggle()
}) {
    Text("Ask question")
}
</code>```

Body:
I am new to developing in Swift and CoreData. I've been struggling with the following code which displays a view with some information on a student which is stored with CoreData. The button "Ask question" which is displayed in the view updates student.questionAskedClass but the view does not updates its value.

The value is clearly updated internally because if I relaunch the application, I can see that the value has been updated. But I would like to see it updated live.

Thanks for your help,
Francois

import SwiftUI

struct StudentView: View {
  @Environment(\.managedObjectContext) var managedObjectContext

  var student: Student

  var body: some View {
    VStack(alignment: .leading) {
      Text("\(student.firstName)").font(.headline).foregroundColor(Color.black)
      Text("\(student.lastName)").font(.headline).foregroundColor(Color.gray)
      Spacer().frame(height: 10)
      Text("\(student.email)").font(.headline).foregroundColor(Color.gray)
      Spacer().frame(height: 10)
      Text("Number of questions asked: \(student.questionAskedClass)").font(.headline).foregroundColor(Color.gray)
      Button(action: {
        self.askQuestion()
      }) {
        Text("Ask question")
      }
    }
  }

  func askQuestion() {
    self.managedObjectContext.performAndWait {
      self.student.questionAskedClass += 1
      try? self.managedObjectContext.save()
    }
  }
}

Body:
You are changing a property of one of your CoreData object. However, that won't refresh the view as you only use on person instance to display the data. You will need to refresh the view, to display the update.

Just use a dummy @State, which you will toggle after changes.

@State var updateView : Bool = false

You will need to use it inside your view, so just add it somewhere:

  Text("\(student.firstName)" + (self.updateView ? "" : "").font(.headline).foregroundColor(Color.black)

And then toggle it:

Button(action: {
    self.askQuestion()
    self.updateView.toggle()
}) {
    Text("Ask question")
}


问:
igraph python import error
I want to use the python wrapper from igraph. Compiling igraph and installing python-igraph works fine, but when I try to import igraph I get the following error (see image link below):

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.4/dist-packages/igraph/__init__.py", line 34, in <module>
    from igraph._igraph import *
ImportError: /usr/local/lib/python3.4/dist-packages/igraph/_igraph.cpython-34m.so: undefined symbol: igraph_gomory_hu_tree
</code>```

Error message screenshot

答: FYI: Tried for more than a day with all kinds of resources online for installing python-igraph on mac. And I also wasn't able to import graph in .py file or .ipynb. Though it did allow me to import igraph in terminal when launching python. My solution is to make a virtual environment, conda install -c conda-forge python-igraph, then switch python from version 3.8 (which never passes the igraph.test.run_tests, Failed = 2) to 3.5 (passed the test). Hope it helps.

Title: igraph python import error

Body:
I want to use the python wrapper from igraph. Compiling igraph and installing python-igraph works fine, but when I try to import igraph I get the following error (see image link below):

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.4/dist-packages/igraph/__init__.py", line 34, in <module>
    from igraph._igraph import *
ImportError: /usr/local/lib/python3.4/dist-packages/igraph/_igraph.cpython-34m.so: undefined symbol: igraph_gomory_hu_tree

Error message screenshot