问:
Error CS5001 Program does not contain a static Main Method
I realise that this error message is in all fairness pretty self-explanatory.  Given that why does the following console application fail to build citing that error.  Plainly a Main method exists.  Can someone suggest why this might be happening?

答:
You must enable C# 7.1 features by going to Project > Properties > Build > Advanced and changing it to the appropriate version:

You must have at least Visual Studio 2017 Update 3 (version 15.3) for this option to be available.


来源: stackexchange

问:
Grepping Ruby hash for regex not working as expected
I have a hash with this data:

```<code>{"ENABLED"=>
[#<Details:0x00007f910e946848
@context="ELP",
@instance="a1",
@side="blue",
@status="ENABLED",
@vm="ome-vm58",
@vmaddr="ajp://10.133.248.4:8009">,

... snip ...

#<Details:0x00007f910e944070
@context="learnItLive",
@instance="b2",
@side="green",
@status="ENABLED",
@vm="ome-vm61",
@vmaddr="ajp://10.133.248.7:8159">]}
</code>```

The hash is called status_hash. I want to determine if the key is ENABLED or not. The other potential key values are DISABLED, STOPPED, and WAITING.

These lines:

```<code>puts "Status key: " + status_hash.keys.to_s
puts "1 - Cluster has Disabled, Stopped, or Waiting contexts" if status_hash.keys.grep(/^[DSW]/)
</code>```

Produces output, even though the key is "ENABLED"

```<code>Status key: ["ENABLED"]
1 - Cluster has Disabled, Stopped, or Waiting contexts
</code>```

I don't understand why the regex is matching when the first character in the key is an E and not in DSW.

答:
Enumerable#grep always returns an array and even though your results produces [] that is truthy in ruby.

Example:

```<code>p 'hello world' if [].grep(/hi/).empty?
"hello world"
=> "hello world"
p 'hello world' if ![].grep(/hi/).empty?
=> nil
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a hash with this data:

{"ENABLED"=>
[#,

... snip ...

#]}

The hash is called status_hash. I want to determine if the key is ENABLED or not. The other potential key values are DISABLED, STOPPED, and WAITING.

These lines:

puts "Status key: " + status_hash.keys.to_s
puts "1 - Cluster has Disabled, Stopped, or Waiting contexts" if status_hash.keys.grep(/^[DSW]/)

Produces output, even though the key is "ENABLED"

Status key: ["ENABLED"]
1 - Cluster has Disabled, Stopped, or Waiting contexts

I don't understand why the regex is matching when the first character in the key is an E and not in DSW.

Body:
Enumerable#grep always returns an array and even though your results produces [] that is truthy in ruby.

Example:

p 'hello world' if [].grep(/hi/).empty?
"hello world"
=> "hello world"
p 'hello world' if ![].grep(/hi/).empty?
=> nil


问:
Detecting connection errors when using CFStreamCreatePairWithSocketToCFHost
I am finding the doc for CFStreamCreatePairWithSocketToCFHost confusing:

Specifically, its not clear to me how the function can set the readStream pointer to null on error.
as far as I understand, the pointer is passed by value - so the function can only change the objected pointed to by the pointer.
Right now I can't figure out how to detect connection errors.

Relevant doc snippet:

Creates readable and writable streams connected to a given CFHost object.

```<code>void CFStreamCreatePairWithSocketToCFHost (
   CFAllocatorRef alloc,
   CFHostRef host,
   SInt32 port,
   CFReadStreamRef *readStream,
   CFWriteStreamRef *writeStream
);
</code>```

readStream

Upon return, contains a CFReadStream object connected to the host host on port port, or NULL if there is a failure during creation. If you pass NULL, the function will not create a readable stream. Ownership follows the Create Rule.

This is my connecting code, it goes all the way to NSLog(@"Connected") even when the server is down.

```<code>NSLog(@"Attempting to (re)connect to %@:%d", m_host, m_port);
while(TRUE)
{
    CFHostRef host = CFHostCreateWithName(kCFAllocatorDefault, (CFStringRef)m_host);
    if (!host)
    {
        NSLog(@"Error resolving host %@", m_host);
        [NSThread sleepForTimeInterval:5.0];
        continue;
    }
    CFStreamCreatePairWithSocketToCFHost(kCFAllocatorDefault, host , m_port, &m_in, &m_out);
    CFRelease(host);

    if (!m_in)
    {
        NSLog(@"Error");
    }

    CFStreamClientContext context = {0, self,nil,nil,nil};

    if (CFReadStreamSetClient(m_in, kCFStreamEventHasBytesAvailable | kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered, networkReadEvent, &context))
    {
        CFReadStreamScheduleWithRunLoop(m_in, CFRunLoopGetCurrent(),kCFRunLoopCommonModes);
    }

    if (CFWriteStreamSetClient(m_out, kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered, networkWriteEvent, &context))
    {
        CFWriteStreamScheduleWithRunLoop(m_out, CFRunLoopGetCurrent(),kCFRunLoopCommonModes);
    }

    BOOL success = CFReadStreamOpen(m_in);
    CFErrorRef error = CFReadStreamCopyError(m_in);
    if (!success || (error && CFErrorGetCode(error) != 0))
    {
        NSLog(@"Connect error %s : %d", CFErrorGetDomain(error), CFErrorGetCode(error));
        [NSThread sleepForTimeInterval:5.0];
    }
    else
    {
        NSLog(@"Connected");
        break;
    }
}
</code>```

答:
In the documentation for CFReadStreamOpen we see:

Opening a stream causes it to reserve all the system resources it requires. If the stream can open in the background without blocking, this function always returns true.

I suspect that the stream is opening in the background, and thus you are saying "Connected" before it actually opens. You've already scheduled the stream with a runloop, so if you let the run loop run, you'll probably get a callback with the event type set to kCFStreamEventErrorOccurred, and from there you can process the error appropriately.

ContentLicense: CC BY-SA 2.5

Body:
I am finding the doc for CFStreamCreatePairWithSocketToCFHost confusing:

Specifically, its not clear to me how the function can set the readStream pointer to null on error.
as far as I understand, the pointer is passed by value - so the function can only change the objected pointed to by the pointer.
Right now I can't figure out how to detect connection errors.

Relevant doc snippet:

Creates readable and writable streams connected to a given CFHost object.

void CFStreamCreatePairWithSocketToCFHost (
   CFAllocatorRef alloc,
   CFHostRef host,
   SInt32 port,
   CFReadStreamRef *readStream,
   CFWriteStreamRef *writeStream
);

readStream

Upon return, contains a CFReadStream object connected to the host host on port port, or NULL if there is a failure during creation. If you pass NULL, the function will not create a readable stream. Ownership follows the Create Rule.

This is my connecting code, it goes all the way to NSLog(@"Connected") even when the server is down.

NSLog(@"Attempting to (re)connect to %@:%d", m_host, m_port);
while(TRUE)
{
    CFHostRef host = CFHostCreateWithName(kCFAllocatorDefault, (CFStringRef)m_host);
    if (!host)
    {
        NSLog(@"Error resolving host %@", m_host);
        [NSThread sleepForTimeInterval:5.0];
        continue;
    }
    CFStreamCreatePairWithSocketToCFHost(kCFAllocatorDefault, host , m_port, &m_in, &m_out);
    CFRelease(host);

    if (!m_in)
    {
        NSLog(@"Error");
    }

    CFStreamClientContext context = {0, self,nil,nil,nil};

    if (CFReadStreamSetClient(m_in, kCFStreamEventHasBytesAvailable | kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered, networkReadEvent, &context))
    {
        CFReadStreamScheduleWithRunLoop(m_in, CFRunLoopGetCurrent(),kCFRunLoopCommonModes);
    }

    if (CFWriteStreamSetClient(m_out, kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered, networkWriteEvent, &context))
    {
        CFWriteStreamScheduleWithRunLoop(m_out, CFRunLoopGetCurrent(),kCFRunLoopCommonModes);
    }

    BOOL success = CFReadStreamOpen(m_in);
    CFErrorRef error = CFReadStreamCopyError(m_in);
    if (!success || (error && CFErrorGetCode(error) != 0))
    {
        NSLog(@"Connect error %s : %d", CFErrorGetDomain(error), CFErrorGetCode(error));
        [NSThread sleepForTimeInterval:5.0];
    }
    else
    {
        NSLog(@"Connected");
        break;
    }
}


问:
Can I add more fields to the pre-filled template in actions-on-google console?
If I am going to use a template to create a trivia using prefilled Sheet Can I edit the structure to add more Follow-ups? The structure is

```<code>Question    Correct Answer  Incorrect Answer 1  Incorrect Answer 2  Follow Up
</code>```

Can I make it

```<code>Question    Correct Answer  Incorrect Answer 1  Incorrect Answer 2  Follow Up Follow Up Follow Up
</code>```

答: Only a single follow up is supported for action templates.</p>

Body:
If I am going to use a template to create a trivia using prefilled Sheet Can I edit the structure to add more Follow-ups? The structure is

Question    Correct Answer  Incorrect Answer 1  Incorrect Answer 2  Follow Up

Can I make it

Question    Correct Answer  Incorrect Answer 1  Incorrect Answer 2  Follow Up Follow Up Follow Up


答:
try using .any? on grep results

```<code>puts "1 - Cluster has Disabled, Stopped, or Waiting contexts" if status_hash.keys.grep(/^[DSW]/).any?
</code>```

The reason, why the issue was occurring, was grep returned empty array [] which is considered truthy. So we need to apply any?, which returns true if there is any element in an array.

Title: Grepping Ruby hash for regex not working as expected

Body:
try using .any? on grep results

puts "1 - Cluster has Disabled, Stopped, or Waiting contexts" if status_hash.keys.grep(/^[DSW]/).any?

The reason, why the issue was occurring, was grep returned empty array [] which is considered truthy. So we need to apply any?, which returns true if there is any element in an array.


问:
HTTP Request works with Postman but not in Rails
I'm trying to make a HTTP Request to get data from a website.
To do that, I have to use a custom header.
When I make a request with Postman, by adding well the custom header, everything works fine. When I remove the custom header, I get this error message : {"error": "content not found"}, which is normal.

I tried to make the same request in Rails.
This is my code :

```<code>uri = URI.parse("https://www.itqi.com/api/master-descriptor")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
req = Net::HTTP::Get.new(uri.path)
req["itqi-key"] = '************************'
response = http.request(req)
</code>```

In this case, I added the custom header. But in despite this, I got no data, only this error message : {"error": "content not found"}, like if my custom header was not taken into account. I tried many possibilities without success.

Is there somebody who can help me ? I'm running out of ideas.

Thanks in advance for your advices.

Best regards,

EDIT

Here is my https request with Faraday :

```<code>conn = Faraday.new(:url => 'https://www.itqi.com', :ssl => {:verify => false})
response = conn.get do |req|
    req.url '/api/master-descriptor'
    req.headers['Content-Type'] = 'application/json'
    req.headers['itqi-key'] = '********************'
end
</code>```

And here is the server response :

RESPONSE: #https://www.itqi.com/api/master-descriptor> @request=# @request_headers={"User-Agent"=>"Faraday v0.12.2", "Content-Type"=>"application/json", "itqi-key"=>"**********************"} @ssl=# @response=# @response_headers={"date"=>"Wed, 13 Dec 2017 08:25:53 GMT", "server"=>"Apache/2.4.10 (Debian)", "content-length"=>"29", "connection"=>"close", "content-type"=>"application/json; charset=UTF-8"} @status=404 @reason_phrase="Not Found">>

Always the same problem :(

************************ SOLUTION **************************

After some research, it seems to be that header keys are case sensitive in Rails. So, to resolve the problem, I had to force Rails to put them in lowercase. Without that, Rails systematically capitalized them.

There is my solution :

```<code>conn = Faraday.new(url: 'https://www.itqi.com', ssl: {verify: false}) do |conn|
  conn.request :json
  conn.response :json, :content_type => /\bjson$/
  conn.adapter Faraday.default_adapter
end
response = conn.get do |req|
  req.url '/api/master-descriptor'
  itqi_key = CaseSensitiveString.new('itqi-key')
  req.headers[itqi_key] = '************************'
end

class CaseSensitiveString < String
  def downcase
     self
  end
  def capitalize
     self
  end

  def to_s
    self
  end
end
</code>```

答:
Your code does not look like the example on http://ruby-doc.org/stdlib-2.0.0/libdoc/net/http/rdoc/Net/HTTP.html#label-Setting+Headers.

But I suggest you'll be happier if you switch to Faraday (https://github.com/lostisland/faraday).

Body:
I'm trying to make a HTTP Request to get data from a website.
To do that, I have to use a custom header.
When I make a request with Postman, by adding well the custom header, everything works fine. When I remove the custom header, I get this error message : {"error": "content not found"}, which is normal.

I tried to make the same request in Rails.
This is my code :

uri = URI.parse("https://www.itqi.com/api/master-descriptor")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
req = Net::HTTP::Get.new(uri.path)
req["itqi-key"] = '************************'
response = http.request(req)

In this case, I added the custom header. But in despite this, I got no data, only this error message : {"error": "content not found"}, like if my custom header was not taken into account. I tried many possibilities without success.

Is there somebody who can help me ? I'm running out of ideas.

Thanks in advance for your advices.

Best regards,

EDIT

Here is my https request with Faraday :

conn = Faraday.new(:url => 'https://www.itqi.com', :ssl => {:verify => false})
response = conn.get do |req|
    req.url '/api/master-descriptor'
    req.headers['Content-Type'] = 'application/json'
    req.headers['itqi-key'] = '********************'
end

And here is the server response :

RESPONSE: #https://www.itqi.com/api/master-descriptor> @request=# @request_headers={"User-Agent"=>"Faraday v0.12.2", "Content-Type"=>"application/json", "itqi-key"=>"**********************"} @ssl=# @response=# @response_headers={"date"=>"Wed, 13 Dec 2017 08:25:53 GMT", "server"=>"Apache/2.4.10 (Debian)", "content-length"=>"29", "connection"=>"close", "content-type"=>"application/json; charset=UTF-8"} @status=404 @reason_phrase="Not Found">>

Always the same problem :(

************************ SOLUTION **************************

After some research, it seems to be that header keys are case sensitive in Rails. So, to resolve the problem, I had to force Rails to put them in lowercase. Without that, Rails systematically capitalized them.

There is my solution :

conn = Faraday.new(url: 'https://www.itqi.com', ssl: {verify: false}) do |conn|
  conn.request :json
  conn.response :json, :content_type => /\bjson$/
  conn.adapter Faraday.default_adapter
end
response = conn.get do |req|
  req.url '/api/master-descriptor'
  itqi_key = CaseSensitiveString.new('itqi-key')
  req.headers[itqi_key] = '************************'
end

class CaseSensitiveString < String
  def downcase
     self
  end
  def capitalize
     self
  end

  def to_s
    self
  end
end


问:
MySQL: database structure choice - big data - duplicate data or bridging
We have a 90GB MySQL database with some very big tables (more than 100M rows). We know this is not the best DB engine but this is not something we can change at this point.

Planning for a serious refactoring (performance and standardization), we are thinking on several approaches on how to restructure our tables.

The data flow / storage is currently done in this way:

We have one table called articles, one connection table called article_authors and one table authors

One single author can have 1..n firstnames, 1..n lastnames, 1..n emails

Every author has a unique parent (unique_author), except if that author is the parent

The possible data query scenarios are as follows:

Get the author firstname, lastname and email for a given article

Get the unique authors.id for an author called John Smith

Get all articles from the author called John Smith

The current DB schema looks like this:

EDIT: The main problem with this structure is that we always duplicate similar given_names and last_names.

We are now hesitating between two different structures:

Large number of tables, data are split and there are connections with IDs. No duplicates in the main tables: articles and authors. Not sure how this will impact the performance as we would need to use several joins in order to retrieve data, example:

Data is split among a reasonable number of tables with duplicate entries in the table article_authors (author firstname, lastname and email alternatives) in order to reduce the number of tables and the application code complexity. One author could have 10 alternatives, so we will have 10 entries for the same author in the article_authors table:

答: if you want to reduce size you could also think about splitting email addresses in two parts: 'jkrowling@' + 'gmail.com'. You could have a table where you store common email domains but seeing that over-normalization is a concern...</p>


问:
TypeError: app.address is not a function
I'm using Mocha to test my API, I've created a file to test my users routes which are contained in its custom file. I've also made an empty JSON file which will be filled and emptied respectively before and after each test.

File containing tests --> user-routes.spec.js :

```<code>const request = require("supertest")
require('chai').should()
const bodyParser = require("body-parser")

const app = require('./../../app')

const usersFixture = require("../fixtures/users-fixtures")

describe('Courses', () =>{

    beforeEach(() => { usersFixture.up() })
    afterEach(() => { usersFixture.down() })

    describe('Get users list', ()=>{
        it("Should get a list of all users", ()=>{
           return  request(app).get('/courses')
                        .then((res) => {
                            // res.body.should.have.lengthOf(1)
                            // res.body[0].title.should.eql("Ma course")
                        }).catch((err)  =>{
                            console.log(err)
                            throw new Error(err);
                         })
        })
    })
})
</code>```

app.js :

```<code>const mongoose = require("mongoose");
const bodyParser = require("body-parser");
mongoose.Promise = require("bluebird");

const course_router = require('./routes/courses_route');
const user_router = require('./routes/users_route');
const type_course_router = require('./routes/type_courses_route');
const avis_router = require("./routes/avis_router");

const HttpError = require('./errors/http_error')
const NotFoundError = require('./errors/not_found')

const helmet = require("helmet");
const express = require("express");
const cors = require("cors");
const app = express();
const manip = require("./routes/manip");

app.use(helmet());
app.use(cors());
app.use(bodyParser.urlencoded({
    extended: true
}));
app.disable('x-powered-by');

// app.use(file_upload());
app.use(bodyParser.json());
app.use(express.static('public'));
app.set('view engine', 'ejs');
app.set('views',(__dirname +'/views/'));

//Ajout du slug course
app.use('/courses', course_router);
app.use('/users', user_router);
app.use('/type-courses', type_course_router);
app.use('/manip', manip);
app.use('/avis', avis_router);

app.use(function(req, res, next) {
  next(new NotFoundError());
});

app.use(function(err, req, res, next) {
  if (!(err instanceof HttpError)) {
    console.error(err)
    err = new HttpError(err.message || 'Unknown error')
    }
    res.status(err.statusCode)
  res.send(err.toJSON());
});

//Connexion à la bdd
mongoose.connect('mongodb://WecodeAdmin:AG56_'+'%25'+'ez3j6@ds241055.mlab.com:41055/runmoov_test')
                .then(
                    console.log("Connection à mongolab réussie")
                );

app.listen(3000, function(){
    console.log("API en cours d'exécution sur le port 3000");
});
</code>```

When launching my test file I have an error :

```<code>TypeError: app.address is not a function
</code>```

I'm pretty sure the problem comes from app.js or user-routes.spec.js, I've tested adding module.exports = server; at the end of my app.js, I've also seen things talking about agant keyword but I don't know it is about
Any ideas where the deal is ?

答:
You need to make sure that app.js is exporting your Express server, so that it can be imported in user-routes.spec.js.

First assign the result of app.listen to a variable, and then set that variable as the export in your app.js:

```<code>const server = app.listen(3000, function(){
    console.log("API en cours d'exécution sur le port 3000");
});

module.exports = server;
</code>```

Body:
I'm using Mocha to test my API, I've created a file to test my users routes which are contained in its custom file. I've also made an empty JSON file which will be filled and emptied respectively before and after each test.

File containing tests --> user-routes.spec.js :

const request = require("supertest")
require('chai').should()
const bodyParser = require("body-parser")

const app = require('./../../app')

const usersFixture = require("../fixtures/users-fixtures")

describe('Courses', () =>{

    beforeEach(() => { usersFixture.up() })
    afterEach(() => { usersFixture.down() })

    describe('Get users list', ()=>{
        it("Should get a list of all users", ()=>{
           return  request(app).get('/courses')
                        .then((res) => {
                            // res.body.should.have.lengthOf(1)
                            // res.body[0].title.should.eql("Ma course")
                        }).catch((err)  =>{
                            console.log(err)
                            throw new Error(err);
                         })
        })
    })
})

app.js :

const mongoose = require("mongoose");
const bodyParser = require("body-parser");
mongoose.Promise = require("bluebird");

const course_router = require('./routes/courses_route');
const user_router = require('./routes/users_route');
const type_course_router = require('./routes/type_courses_route');
const avis_router = require("./routes/avis_router");

const HttpError = require('./errors/http_error')
const NotFoundError = require('./errors/not_found')

const helmet = require("helmet");
const express = require("express");
const cors = require("cors");
const app = express();
const manip = require("./routes/manip");

app.use(helmet());
app.use(cors());
app.use(bodyParser.urlencoded({
    extended: true
}));
app.disable('x-powered-by');

// app.use(file_upload());
app.use(bodyParser.json());
app.use(express.static('public'));
app.set('view engine', 'ejs');
app.set('views',(__dirname +'/views/'));

//Ajout du slug course
app.use('/courses', course_router);
app.use('/users', user_router);
app.use('/type-courses', type_course_router);
app.use('/manip', manip);
app.use('/avis', avis_router);

app.use(function(req, res, next) {
  next(new NotFoundError());
});

app.use(function(err, req, res, next) {
  if (!(err instanceof HttpError)) {
    console.error(err)
    err = new HttpError(err.message || 'Unknown error')
    }
    res.status(err.statusCode)
  res.send(err.toJSON());
});

//Connexion à la bdd
mongoose.connect('mongodb://WecodeAdmin:AG56_'+'%25'+'ez3j6@ds241055.mlab.com:41055/runmoov_test')
                .then(
                    console.log("Connection à mongolab réussie")
                );

app.listen(3000, function(){
    console.log("API en cours d'exécution sur le port 3000");
});

When launching my test file I have an error :

TypeError: app.address is not a function

I'm pretty sure the problem comes from app.js or user-routes.spec.js, I've tested adding module.exports = server; at the end of my app.js, I've also seen things talking about agant keyword but I don't know it is about
Any ideas where the deal is ?

Body:
You need to make sure that app.js is exporting your Express server, so that it can be imported in user-routes.spec.js.

First assign the result of app.listen to a variable, and then set that variable as the export in your app.js:

const server = app.listen(3000, function(){
    console.log("API en cours d'exécution sur le port 3000");
});

module.exports = server;


问:
How to get the data from a Fragment which is inside a DialogFragment?
I have a DialogFragment that is using a FragmentPagerAdapter to display tabs. Each tab has a different Fragment that uses a RecyclerView. I can get what item is clicked passed to the Fragment, but how can I get the data from the Fragment to the DialogFragment in order to pass it to the calling Activity?

TabDialog extends DialogFragment:

```<code>public class TabDialog extends DialogFragment {

public interface OnCompleteListener{
    void onCompleteListener(String test);
}

private OnCompleteListener mListener;

TabLayout tabLayout;
ViewPager viewPager;
FragmentTabPositive tabPositive = new FragmentTabPositive();
FragmentTabNegative tabNegative = new FragmentTabNegative();
TabAdapter adapter;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    getDialog().setCanceledOnTouchOutside(true);
    View rootView = inflater.inflate(R.layout.dialog_layout, container, false);
    tabLayout = (TabLayout) rootView.findViewById(R.id.tabLayout1);
    viewPager = (ViewPager) rootView.findViewById(R.id.masterViewPager);
    adapter = new TabAdapter(getChildFragmentManager());
    adapter.addFragment("Positive", tabPositive);
    adapter.addFragment("Negative", tabNegative);
    viewPager.setAdapter(adapter);
    tabLayout.setupWithViewPager(viewPager);

    return rootView;
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    try{
        this.mListener = (OnCompleteListener)context;
    } catch(ClassCastException e){
        throw new ClassCastException(context.toString() +
                " must Implement OnCompleteListener");
    }

}
</code>```

TabAdapter extends FragmentPagerAdapter

```<code>public class TabAdapter extends FragmentPagerAdapter {

List<Fragment> mFragmentCollection = new ArrayList<>();
List<String> mTitleCollection = new ArrayList<>();

public TabAdapter(FragmentManager fm){
    super(fm);
}

public void addFragment(String title, Fragment fragment){

    mTitleCollection.add(title);
    mFragmentCollection.add(fragment);
}

@Override
public CharSequence getPageTitle(int position){
    return mTitleCollection.get(position);
}

@Override
public int getCount(){
    return mFragmentCollection.size();
}

@Override
public Fragment getItem(int position) {
    return mFragmentCollection.get(position);
}
</code>```

Inside the onCreateView within FragmentTabPos

```<code>popupAdapter = new PopupAdapter(view.getContext(), list);
    recyclerView.setAdapter(popupAdapter);

    popupAdapter.setmListener(new PopupAdapter.OnPointClickedListener() {
        @Override
        public void OnItemClicked(String test) {
            //This works
            Toast.makeText(FragmentTabPositive.this.getContext(), test + " Inside FragTabPos", Toast.LENGTH_LONG).show();
        }
    });
</code>```

答:
To avoid too tightly coupling your Fragments I would personally opt to transmit that data using the new architecture components.

You could use AndroidViewModel to pass your data around.

Here is an introduction on the Android Developer site: https://developer.android.com/topic/libraries/architecture/index.html

Alternatively, you could use an event bus to post data from one Fragment to its parent(s).

One such library: https://github.com/greenrobot/EventBus

The bonus of using the architecture components is that it follows the latest application design standards from Google.

Body:
I have a DialogFragment that is using a FragmentPagerAdapter to display tabs. Each tab has a different Fragment that uses a RecyclerView. I can get what item is clicked passed to the Fragment, but how can I get the data from the Fragment to the DialogFragment in order to pass it to the calling Activity?

TabDialog extends DialogFragment:

public class TabDialog extends DialogFragment {

public interface OnCompleteListener{
    void onCompleteListener(String test);
}

private OnCompleteListener mListener;

TabLayout tabLayout;
ViewPager viewPager;
FragmentTabPositive tabPositive = new FragmentTabPositive();
FragmentTabNegative tabNegative = new FragmentTabNegative();
TabAdapter adapter;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    getDialog().setCanceledOnTouchOutside(true);
    View rootView = inflater.inflate(R.layout.dialog_layout, container, false);
    tabLayout = (TabLayout) rootView.findViewById(R.id.tabLayout1);
    viewPager = (ViewPager) rootView.findViewById(R.id.masterViewPager);
    adapter = new TabAdapter(getChildFragmentManager());
    adapter.addFragment("Positive", tabPositive);
    adapter.addFragment("Negative", tabNegative);
    viewPager.setAdapter(adapter);
    tabLayout.setupWithViewPager(viewPager);

    return rootView;
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    try{
        this.mListener = (OnCompleteListener)context;
    } catch(ClassCastException e){
        throw new ClassCastException(context.toString() +
                " must Implement OnCompleteListener");
    }

}

TabAdapter extends FragmentPagerAdapter

public class TabAdapter extends FragmentPagerAdapter {

List<Fragment> mFragmentCollection = new ArrayList<>();
List<String> mTitleCollection = new ArrayList<>();

public TabAdapter(FragmentManager fm){
    super(fm);
}

public void addFragment(String title, Fragment fragment){

    mTitleCollection.add(title);
    mFragmentCollection.add(fragment);
}

@Override
public CharSequence getPageTitle(int position){
    return mTitleCollection.get(position);
}

@Override
public int getCount(){
    return mFragmentCollection.size();
}

@Override
public Fragment getItem(int position) {
    return mFragmentCollection.get(position);
}

Inside the onCreateView within FragmentTabPos

popupAdapter = new PopupAdapter(view.getContext(), list);
    recyclerView.setAdapter(popupAdapter);

    popupAdapter.setmListener(new PopupAdapter.OnPointClickedListener() {
        @Override
        public void OnItemClicked(String test) {
            //This works
            Toast.makeText(FragmentTabPositive.this.getContext(), test + " Inside FragTabPos", Toast.LENGTH_LONG).show();
        }
    });


问:
How to output contents of raw files
I'm just working through a chapter on Managing Application Resources and am having a bit of trouble with the following:

"Add a raw text file resource to the Droid1 project. Use the openRawResourse() method to create an InputStream object and read the file. Output the contents of the file by using Log.v() method. Rerun the application and view the result."

So firstly, I right clicked on the res folder, created a new raw folder and dragged a txt file from my desktop into this (think this was ok and couldn't find another way of importing the file).

Then I wrote these two lines:

```<code>InputStream iFile = getResources().openRawResource(R.raw.textfile);
Log.v(TAG, iFile);
</code>```

However I get the error:

"The method v(String, String) in the type Log is not applicable for the arguments (String, InputStream)"

Not sure what to do... any suggestions. Thanks.

答:
As the error indicates the second parameter for the v method needs to be of the String data type. So you need to convert the InputStream iFile to a string.

I referenced http://www.kodejava.org/examples/266.html

You'll need the following imports in your Activity:

```<code>import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.Writer;
import java.io.Reader;
import java.io.BufferedReader;
import java.io.InputStreamReader;
</code>```

And the method itself:

```<code>public String convertStreamToString(InputStream is) throws IOException {

    /* To convert the InputStream to String we use the
    * Reader.read(char[] buffer) method. We iterate until the
    * Reader return -1 which means there's no more data to
    * read. We use the StringWriter class to produce the string.*/
    if (is != null) {
        Writer writer = new StringWriter();
        char[] buffer = new char[1024];
    try {
        Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        int n;
        while ((n = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, n);
        }
    } finally {
        is.close();
    }
    return writer.toString();
    } else {
        return "";
    }

}
</code>```

Pass your InputStream into the method to get your String, and Log.v

```<code>InputStream iFile = getResources().openRawResource(R.raw.textfile);
String strInput = null;
try {
  strInput = convertStreamToString(iFile);
} catch (IOException e) {
  Log.v(TAG, "The string conversion failed.");
}
if(strInput != null){
  Log.v(TAG, strInput);
}
</code>```

Title: How to output contents of raw files

Body:
I'm just working through a chapter on Managing Application Resources and am having a bit of trouble with the following:

"Add a raw text file resource to the Droid1 project. Use the openRawResourse() method to create an InputStream object and read the file. Output the contents of the file by using Log.v() method. Rerun the application and view the result."

So firstly, I right clicked on the res folder, created a new raw folder and dragged a txt file from my desktop into this (think this was ok and couldn't find another way of importing the file).

Then I wrote these two lines:

InputStream iFile = getResources().openRawResource(R.raw.textfile);
Log.v(TAG, iFile);

However I get the error:

"The method v(String, String) in the type Log is not applicable for the arguments (String, InputStream)"

Not sure what to do... any suggestions. Thanks.

Body:
As the error indicates the second parameter for the v method needs to be of the String data type. So you need to convert the InputStream iFile to a string.

I referenced http://www.kodejava.org/examples/266.html

You'll need the following imports in your Activity:

import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.Writer;
import java.io.Reader;
import java.io.BufferedReader;
import java.io.InputStreamReader;

And the method itself:

public String convertStreamToString(InputStream is) throws IOException {

    /* To convert the InputStream to String we use the
    * Reader.read(char[] buffer) method. We iterate until the
    * Reader return -1 which means there's no more data to
    * read. We use the StringWriter class to produce the string.*/
    if (is != null) {
        Writer writer = new StringWriter();
        char[] buffer = new char[1024];
    try {
        Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        int n;
        while ((n = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, n);
        }
    } finally {
        is.close();
    }
    return writer.toString();
    } else {
        return "";
    }

}

Pass your InputStream into the method to get your String, and Log.v

InputStream iFile = getResources().openRawResource(R.raw.textfile);
String strInput = null;
try {
  strInput = convertStreamToString(iFile);
} catch (IOException e) {
  Log.v(TAG, "The string conversion failed.");
}
if(strInput != null){
  Log.v(TAG, strInput);
}


问:
c# regex remove text between tags
I have text that contains many tags , for example:

```<code><b class="bold"> some bold text </b> main text
<li>list text</li>
<script> script text </script>
</code>```

and I need that all texts between tags and the tags will be deleted
in this example I should get "main text" because its the only text that has no tags.

I tried

```<code>   Regex.Replace(input, "<.*?>", String.Empty);
</code>```

but it will remove all the tags and not the text between them

I tried this

```<code>var regEx = new Regex(@"<(.+).*>.*<\/\1>");
var result = regEx.Replace(input, string.Empty);
</code>```

with

```<code><b class="bold"> bold </b>
main text
<ul>
<li> list </li>
<li> list2 <li>
</ul>
</code>```

and i got

```<code>main text
<ul>

</ul>
</code>```

答:
I'm not sure why this questions getting negged without comments, it's not very well written but it's clear what he wants to do.

Here you go:

```<code>var regEx = new Regex(@"<(.+).*>.*<\/\1>");
var result = regEx.Replace(input, string.Empty);
</code>```

Bear in mind that in a valid HTML document, all content is going to be contained within a tag of some sort so your result should always be nothing.

Caveat: this is by no means a comprehensive or complete solution, but it's a good base point to start from depending on what your real input data looks like.

Title: c# regex remove text between tags

Body:
I have text that contains many tags , for example:

 some bold text  main text

list text

and I need that all texts between tags and the tags will be deleted
in this example I should get "main text" because its the only text that has no tags.

I tried

   Regex.Replace(input, "<.*?>", String.Empty);

but it will remove all the tags and not the text between them

I tried this

var regEx = new Regex(@"<(.+).*>.*<\/\1>");
var result = regEx.Replace(input, string.Empty);

with

 bold
main text

 list

 list2

and i got

main text

Body:
I'm not sure why this questions getting negged without comments, it's not very well written but it's clear what he wants to do.

Here you go:

var regEx = new Regex(@"<(.+).*>.*<\/\1>");
var result = regEx.Replace(input, string.Empty);

Bear in mind that in a valid HTML document, all content is going to be contained within a tag of some sort so your result should always be nothing.

Caveat: this is by no means a comprehensive or complete solution, but it's a good base point to start from depending on what your real input data looks like.


问:
HTML CSS responsively stacking images in two columns

John Doe

John Doe

```

What I'm trying to achieve, is making this type of effect to stack in two columns responsively. ( So that when I resize my window, images won't be streched )

And I can't do it. Could you please guide my on how can I achieve this effect? I can't even make two images to stack side by side on that fiddle, they seem to always stack in one column like this.

I've tried using Boostrap with container and col-lg-6, had no success.

答:
The easiest way to do that is to use float:left but the you should add another elements wich resets the flow of the document, so that element should have the clear: both property.

John Doe

John Doe

John Doe

John Doe

John Doe

John Doe

```

Body:
John Doe

John Doe

What I'm trying to achieve, is making this type of effect to stack in two columns responsively. ( So that when I resize my window, images won't be streched )

And I can't do it. Could you please guide my on how can I achieve this effect? I can't even make two images to stack side by side on that fiddle, they seem to always stack in one column like this.

I've tried using Boostrap with container and col-lg-6, had no success.

Body:
The easiest way to do that is to use float:left but the you should add another elements wich resets the flow of the document, so that element should have the clear: both property.

<html>
<head>
<style>
.container {
    position: relative;
    width: 50%;
    float: left
}

.image {
  opacity: 1;
  display: block;
  width: 100%;
  height: auto;
  transition: .5s ease;
  backface-visibility: hidden;
}

.middle {
  transition: .5s ease;
  opacity: 0;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%)
}

.container:hover .image {
  opacity: 0.3;
}

.container:hover .middle {
  opacity: 1;
}

.text {
  background-color: #4CAF50;
  color: white;
  font-size: 16px;
  padding: 16px 32px;
}
</style>
</head>
<body>

<div class="container">
  <img src="http://img.draugas.lt/forumas/veidukai/973676.gif" alt="Avatar" class="image" style="width:100%">
  <div class="middle">
    <div class="text">John Doe</div>
  </div>
</div>
<div class="container">
  <img src="http://img.draugas.lt/forumas/veidukai/973676.gif" alt="Avatar" class="image" style="width:100%">
  <div class="middle">
    <div class="text">John Doe</div>
  </div>
</div>
<div class="container">
  <img src="http://img.draugas.lt/forumas/veidukai/973676.gif" alt="Avatar" class="image" style="width:100%">
  <div class="middle">
    <div class="text">John Doe</div>
  </div>
</div>
<div class="container">
  <img src="http://img.draugas.lt/forumas/veidukai/973676.gif" alt="Avatar" class="image" style="width:100%">
  <div class="middle">
    <div class="text">John Doe</div>
  </div>
</div>
<div class="container">
  <img src="http://img.draugas.lt/forumas/veidukai/973676.gif" alt="Avatar" class="image" style="width:100%">
  <div class="middle">
    <div class="text">John Doe</div>
  </div>
</div>
<div class="container">
  <img src="http://img.draugas.lt/forumas/veidukai/973676.gif" alt="Avatar" class="image" style="width:100%">
  <div class="middle">
    <div class="text">John Doe</div>
  </div>
</div>
<p style="clear: both;"></p>

</body>
</html>


问:
How to get the value of my button in JSP and show it on the tomcat log and eclipse consol
what im trying to do is get a message when the user click the button a message appear on the console and on the tomcat logs</p>

```<code>        <input type="button" value="Buscar" id="btnBuscar" name="btnBuscar" onclick="setTimeout(gotoPage(1),3000)" style="width: 100px"><br>
        <%
        System.out.println("page should refresh itself in 3 seconds" );
        %>
</code>```

答:
The button will generate a JavaScript event. You must make that event to send a request to the server, and get the server processed by a Servlet or JSP.

This may help you:

Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"

How to call servlet when button click

Body:
what im trying to do is get a message when the user click the button a message appear on the console and on the tomcat logs

        <input type="button" value="Buscar" id="btnBuscar" name="btnBuscar" onclick="setTimeout(gotoPage(1),3000)" style="width: 100px">

        <%
        System.out.println("page should refresh itself in 3 seconds" );
        %>


问:
get Data form mySql and echo it - PHP
I need get Data form mySql and echo it . but show to me error ! please help me . I am amator . please check my code. (get Data form mySql and echo it - PHP)

my error in $result1=mysqli_query($link,$query1);

my PHP file :

```<code><?php

$post_data=@$_POST['myjson'];
$post_data=json_decode($post_data,true);
$command=$post_data['command'];
$server="localhost";
$user="user";
$pass="pass";
$db="db";
$link=mysqli_connect($server,$user,$pass,$db);
mysqli_set_charset($link,"utf8");

if ($command=="get_contact") {
    $id=$post_data['id'];
    $query="select * from ad where id=$id";
    $result=mysqli_query($link,$query);
    $row=mysqli_fetch_assoc($result);
    $num=mysqli_num_rows($result);

    if ($num == 1) {
        $query1="select * from user where id=$row['user_id']";
        $result1=mysqli_query($link,$query1);
        $row1=mysqli_fetch_assoc($result1);
        $num1=mysqli_num_rows($result1);

        if ($num1 == 1) {
            $specifications=array("mobile"=>$row1["mobile"], "email"=>$row1["email"]);
            echo "<b>".json_encode($specifications)."</b>";
        } else {
            echo "<b>Not Found</b>";
        }

    } else {
        echo "<b>Not Found</b>";
    }

    exit();
}

?>
</code>```

答:
If you expect just one result of each query, you can get the same results with just one query instead of the two you have:

```<code>$query = "select user.* from user, ad where ad.id=$id and user.id = ad.user_id";
</code>```

Also, you should use prepared statements to avoid sql injection instead of writing vars inside the sql queries.

Besides that, give more info in the error messages because now you don't know which error is returning.

Title: get Data form mySql and echo it - PHP

Body:
I need get Data form mySql and echo it . but show to me error ! please help me . I am amator . please check my code. (get Data form mySql and echo it - PHP)

my error in $result1=mysqli_query($link,$query1);

my PHP file :

<?php

$post_data=@$_POST['myjson'];
$post_data=json_decode($post_data,true);
$command=$post_data['command'];
$server="localhost";
$user="user";
$pass="pass";
$db="db";
$link=mysqli_connect($server,$user,$pass,$db);
mysqli_set_charset($link,"utf8");

if ($command=="get_contact") {
    $id=$post_data['id'];
    $query="select * from ad where id=$id";
    $result=mysqli_query($link,$query);
    $row=mysqli_fetch_assoc($result);
    $num=mysqli_num_rows($result);

    if ($num == 1) {
        $query1="select * from user where id=$row['user_id']";
        $result1=mysqli_query($link,$query1);
        $row1=mysqli_fetch_assoc($result1);
        $num1=mysqli_num_rows($result1);

        if ($num1 == 1) {
            $specifications=array("mobile"=>$row1["mobile"], "email"=>$row1["email"]);
            echo "".json_encode($specifications)."";
        } else {
            echo "Not Found";
        }

    } else {
        echo "Not Found";
    }

    exit();
}

?>

Body:
If you expect just one result of each query, you can get the same results with just one query instead of the two you have:

$query = "select user.* from user, ad where ad.id=$id and user.id = ad.user_id";

Also, you should use prepared statements to avoid sql injection instead of writing vars inside the sql queries.

Besides that, give more info in the error messages because now you don't know which error is returning.


问:
Tradeoffs of using a join table vs type field
I'm looking insight into designing a database with a table which is related to multiple other tables.  A specific example is a site with comments on different kinds of the things - people could comment on articles, or they could comment on photos or they could comment on people.

It seems that there are two ways to represent this:

1) join tables for each other table
TABLES:

articles

articles_comments

comments

comments_people

comments_photos

people

photos

or
2)

articles

comments

people

photos

and the comment table will have a "type" field and a item_id to link back into the other table.

The first approach seems more "proper" and it seems we should have no problem using foreign key restraints whereas the second approach has fewer tables and might be "simpler" in some respect, but we can use FK restraints since the item_id can related to multiple FKs (AFAIK - using mysql innodb).  It might be good to not that in our application there might be 2-3 tables that have multiple relations (comments, photos, etc) and 5-10 tables that need relations.

I'm looking for advice on which is the better approach.

答:
The comment table with the type column (an enum btw), seems like the better approach because you may want to evolve what a ''comment'' is in the future.

Having the four tables like you described it also lends itself to your Model class fields and  their relationships easier.

Use a 'LEFT JOIN' to the comments table if its a 0-to-many relationship.  Otherwise its an 'INNER JOIN'.

Enjoy.


问:
How can I save new Date() in MongoDB?
When I save a date time in MongoDB using the following format, it shows:

```<code>Error "Unable to parse JSON"
</code>```

```<code>{
  "_id" : ObjectId("58cb759805aeeae37a56dd3d"),
  "name" : "Plutus",
  "admin" : "type 1",
  "created" : new Date()
}
</code>```

Please help me to save a date time in Robomongo using MongoDB in the above format.

Error description in picture:

Thanks

答:
Use shell to insert:

db.sites.insert({
  "_id" : ObjectId("58cb759805aeeae37a56dd3d"),
  "name" : "Plutus",
  "admin" : "type 1",
  "created" : new Date()
}

Title: How can I save new Date() in MongoDB?

Body:
When I save a date time in MongoDB using the following format, it shows:

Error "Unable to parse JSON"

{
  "_id" : ObjectId("58cb759805aeeae37a56dd3d"),
  "name" : "Plutus",
  "admin" : "type 1",
  "created" : new Date()
}

Please help me to save a date time in Robomongo using MongoDB in the above format.

Error description in picture:

Thanks


答:
Just inline the block and make sure the width is set such that two or more windows are able to fit. Simples.

<!DOCTYPE html>

Opacity with Box

Hover over the image to see the effect.

John Doe

John Doe

    ```

Title: HTML CSS responsively stacking images in two columns

Body:
Just inline the block and make sure the width is set such that two or more windows are able to fit. Simples.

<!DOCTYPE html>
    <html>
    <head>
    <style>
    .container {
        position: relative;
        width: 40%;
        display: inline-block;
    }

    .image {
      opacity: 1;
      display: block;
      width: 100%;
      height: auto;
      transition: .5s ease;
      backface-visibility: hidden;
    }

    .middle {
      transition: .5s ease;
      opacity: 0;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      -ms-transform: translate(-50%, -50%)
    }

    .container:hover .image {
      opacity: 0.3;
    }

    .container:hover .middle {
      opacity: 1;
    }

    .text {
      background-color: #4CAF50;
      color: white;
      font-size: 16px;
      padding: 16px 32px;
    }
    </style>
    </head>
    <body>

    <h2>Opacity with Box</h2>
    <p>Hover over the image to see the effect.</p>

    <div class="container">
      <img src="img_avatar.png" alt="Avatar" class="image" style="width:100%">
      <div class="middle">
        <div class="text">John Doe</div>
      </div>
    </div>

    <div class="container">
      <img src="img_avatar.png" alt="Avatar" class="image" style="width:100%">
      <div class="middle">
        <div class="text">John Doe</div>
      </div>
    </div>

    </body>
    </html>


问:
GLFW3 library in CLion with CMake causes undefined symbols on MacOS
I built GLFW from source in MacOS using cmake, and everything went well, the examples are working. But when I was trying to compile a program using cmake in clion, I got the following error:

```<code>Scanning dependencies of target triangle
[ 50%] Building CXX object CMakeFiles/triangle.dir/main.cpp.o
[100%] Linking CXX executable triangle
Undefined symbols for architecture x86_64:
  "_CFArrayAppendValue", referenced from:
    __glfwInitJoysticksNS in libglfw3.a(cocoa_joystick.m.o)
    _matchCallback in libglfw3.a(cocoa_joystick.m.o)
  "_CFArrayCreateMutable", referenced from:
    __glfwInitJoysticksNS in libglfw3.a(cocoa_joystick.m.o)
    _matchCallback in libglfw3.a(cocoa_joystick.m.o)
... (There are a huge bunch of errors like this, let me know if you want to read all of them)
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[3]: *** [triangle] Error 1
make[2]: *** [CMakeFiles/triangle.dir/all] Error 2
make[1]: *** [CMakeFiles/triangle.dir/rule] Error 2
make: *** [triangle] Error 2
</code>```

I browsed through the internet and the documentation and found that I should compile with framework arguments, like this:

```<code>cc -o myprog myprog.c -lglfw -framework Cocoa -framework OpenGL -framework IOKit -framework CoreVideo
</code>```

I tried it on the command line, it worked. But what if I want to have things done in CLion(or CMake?) Or how can I use framework in CMake?

My CMakeLists.txt in case you want to know:

```<code>cmake_minimum_required(VERSION 3.8)
project(triangle)

set(CMAKE_CXX_STANDARD 11)
find_package(glfw3 REQUIRED)

set(SOURCE_FILES main.cpp)
add_executable(triangle ${SOURCE_FILES})
target_link_libraries(triangle glfw3)
</code>```

答:
I added this to my CMakeLists.txt and it works now:

```<code>set(CMAKE_CXX_FLAGS "-framework Cocoa -framework OpenGL -framework IOKit -framework CoreVideo")
</code>```

so my CMakeLists.txt looks like this:

```<code>cmake_minimum_required(VERSION 3.8)
project(triangle)

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_FLAGS "-framework Cocoa -framework OpenGL -framework IOKit -framework CoreVideo")
find_package(glfw3 REQUIRED)

set(SOURCE_FILES main.cpp)
add_executable(triangle ${SOURCE_FILES})

target_link_libraries(triangle glfw3)
</code>```

I hope there is a more "graceful" way, but this solves my problem now.

Body:
I built GLFW from source in MacOS using cmake, and everything went well, the examples are working. But when I was trying to compile a program using cmake in clion, I got the following error:

Scanning dependencies of target triangle
[ 50%] Building CXX object CMakeFiles/triangle.dir/main.cpp.o
[100%] Linking CXX executable triangle
Undefined symbols for architecture x86_64:
  "_CFArrayAppendValue", referenced from:
    __glfwInitJoysticksNS in libglfw3.a(cocoa_joystick.m.o)
    _matchCallback in libglfw3.a(cocoa_joystick.m.o)
  "_CFArrayCreateMutable", referenced from:
    __glfwInitJoysticksNS in libglfw3.a(cocoa_joystick.m.o)
    _matchCallback in libglfw3.a(cocoa_joystick.m.o)
... (There are a huge bunch of errors like this, let me know if you want to read all of them)
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[3]: *** [triangle] Error 1
make[2]: *** [CMakeFiles/triangle.dir/all] Error 2
make[1]: *** [CMakeFiles/triangle.dir/rule] Error 2
make: *** [triangle] Error 2

I browsed through the internet and the documentation and found that I should compile with framework arguments, like this:

cc -o myprog myprog.c -lglfw -framework Cocoa -framework OpenGL -framework IOKit -framework CoreVideo

I tried it on the command line, it worked. But what if I want to have things done in CLion(or CMake?) Or how can I use framework in CMake?

My CMakeLists.txt in case you want to know:

cmake_minimum_required(VERSION 3.8)
project(triangle)

set(CMAKE_CXX_STANDARD 11)
find_package(glfw3 REQUIRED)

set(SOURCE_FILES main.cpp)
add_executable(triangle ${SOURCE_FILES})
target_link_libraries(triangle glfw3)

Body:
I added this to my CMakeLists.txt and it works now:

set(CMAKE_CXX_FLAGS "-framework Cocoa -framework OpenGL -framework IOKit -framework CoreVideo")

so my CMakeLists.txt looks like this:

cmake_minimum_required(VERSION 3.8)
project(triangle)

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_FLAGS "-framework Cocoa -framework OpenGL -framework IOKit -framework CoreVideo")
find_package(glfw3 REQUIRED)

set(SOURCE_FILES main.cpp)
add_executable(triangle ${SOURCE_FILES})

target_link_libraries(triangle glfw3)

I hope there is a more "graceful" way, but this solves my problem now.


问:
Dependent dropdownlist in ASP.NET MVC
At present I have two tables (Teams and Employees)
I am populating the dropdownList for Teams perfectly, next I am trying to populate the second dropdownlist depending on the selectedId of Teams for Employees.

Controller:

```<code> // GET: CalView
        public ActionResult Index(string ses, string DH)
        {     //Team Lead Members
                var eID = Convert.ToInt32(Session["currentEmployeeID"]);
                var EmpID = Session["currentEmpID"];
                Employee obj = (from o in db.Employees
                                where o.EnrollNumber == EmpID
                                select o).FirstOrDefault();

                Department dept = (from dep in db.Departments
                                   where dep.LeadBy == obj.EmployeeId
                                   select dep).FirstOrDefault();
                //this works fine
                ViewBag.showTeams = new SelectList(db.Teams.Where(tm => (tm.DeptID == dept.DepartmentId) && (dept.LeadBy == eID)), "TeamID","Name");
               //this obviously does not
                ViewBag.showMembers = new SelectList(db.Employees.Where(empt => (empT.TeamID == selectedIdFromPreviousDropDownList), "EmployeeID", "Employee"));

                return View();
        }
</code>```

View:

```<code>if ((Session["UT"] == "DD") && (@ViewBag.DeptLead != null))
  {
//this works
  @Html.DropDownList("showTeams", null, "-Select Team-", htmlAttributes: new { @class = "form-control" })
//this does not work
  @Html.DropDownList("showMembers", null, "-Select Team-", htmlAttributes: new { @class = "form-control" })
   }
</code>```

Do I need some AJAX call? or perhaps a POST method? Totally new to MVC.

答:
Do I need some AJAX call? or perhaps a POST method? Okay then, lets do it this way:

Give your DropdownLists some id's probably:

```<code> @Html.DropDownList("showTeams", null, "-Select Team-", htmlAttributes: new { id = "ddshowTeams", @class = "form-control" })
 @Html.DropDownList("showMembers", null, "-Select Team-", htmlAttributes: new {id = "ddshowMembers", @class = "form-control" })
</code>```

Create a jsonResult function, GetMembers and some Magic right there:

```<code><script type="text/javascript">

        $(document).ready(function () {
            //Dropdownlist Selectedchange event
            $("#ddshowTeams").change(function () {
                console.log("pehla andar");
                $("#ddshowMembers").empty();
                $.ajax({
                    type: 'POST',
                    url: '@Url.Action("GetMembers")',
                    dataType: 'json',
                    data: { id: $("#ddshowTeams").val() },
                    success: function (mems) {
                        console.log("wich ayaeee");
                        // states contains the JSON formatted list
                        // of states passed from the controller
                        $.each(mems, function (i, member) {
                            $("#ddshowMembers").append('<option value="'
    + member.Value + '">'
    + member.Text + '</option>');
                        });
                    },
                    error: function (ex) {
                        alert('Failed to retrieve states.' + ex);
                    }
                });
                return false;
            })
        });
</script>
</code>```

and in your controller:

```<code> public JsonResult GetMembers(int id)
        {
            return Json(new SelectList(db.Employees.Where(empt => (empt.TeamId == id)), "EmployeeID", "FirstName"));
        }
</code>```

Title: Dependent dropdownlist in ASP.NET MVC

Body:
At present I have two tables (Teams and Employees)
I am populating the dropdownList for Teams perfectly, next I am trying to populate the second dropdownlist depending on the selectedId of Teams for Employees.

Controller:

 // GET: CalView
        public ActionResult Index(string ses, string DH)
        {     //Team Lead Members
                var eID = Convert.ToInt32(Session["currentEmployeeID"]);
                var EmpID = Session["currentEmpID"];
                Employee obj = (from o in db.Employees
                                where o.EnrollNumber == EmpID
                                select o).FirstOrDefault();

                Department dept = (from dep in db.Departments
                                   where dep.LeadBy == obj.EmployeeId
                                   select dep).FirstOrDefault();
                //this works fine
                ViewBag.showTeams = new SelectList(db.Teams.Where(tm => (tm.DeptID == dept.DepartmentId) && (dept.LeadBy == eID)), "TeamID","Name");
               //this obviously does not
                ViewBag.showMembers = new SelectList(db.Employees.Where(empt => (empT.TeamID == selectedIdFromPreviousDropDownList), "EmployeeID", "Employee"));

                return View();
        }

View:

if ((Session["UT"] == "DD") && (@ViewBag.DeptLead != null))
  {
//this works
  @Html.DropDownList("showTeams", null, "-Select Team-", htmlAttributes: new { @class = "form-control" })
//this does not work
  @Html.DropDownList("showMembers", null, "-Select Team-", htmlAttributes: new { @class = "form-control" })
   }

Do I need some AJAX call? or perhaps a POST method? Totally new to MVC.

Body:
Do I need some AJAX call? or perhaps a POST method? Okay then, lets do it this way:

Give your DropdownLists some id's probably:

 @Html.DropDownList("showTeams", null, "-Select Team-", htmlAttributes: new { id = "ddshowTeams", @class = "form-control" })
 @Html.DropDownList("showMembers", null, "-Select Team-", htmlAttributes: new {id = "ddshowMembers", @class = "form-control" })

Create a jsonResult function, GetMembers and some Magic right there:

<script type="text/javascript">

        $(document).ready(function () {
            //Dropdownlist Selectedchange event
            $("#ddshowTeams").change(function () {
                console.log("pehla andar");
                $("#ddshowMembers").empty();
                $.ajax({
                    type: 'POST',
                    url: '@Url.Action("GetMembers")',
                    dataType: 'json',
                    data: { id: $("#ddshowTeams").val() },
                    success: function (mems) {
                        console.log("wich ayaeee");
                        // states contains the JSON formatted list
                        // of states passed from the controller
                        $.each(mems, function (i, member) {
                            $("#ddshowMembers").append('<option value="'
    + member.Value + '">'
    + member.Text + '</option>');
                        });
                    },
                    error: function (ex) {
                        alert('Failed to retrieve states.' + ex);
                    }
                });
                return false;
            })
        });
</script>

and in your controller:

 public JsonResult GetMembers(int id)
        {
            return Json(new SelectList(db.Employees.Where(empt => (empt.TeamId == id)), "EmployeeID", "FirstName"));
        }


问:
Add AngularFire to constructor
Hej I have problem with adding AngularFire to constructor at app.component.ts.

I have watching 4 courses realted with AngularFire and everybody add AngularFire to constructor at app.component.ts.

My code look like that:

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'Test App';

  constructor(private af: AngularFire){

  }
}
</code>```

VisualCode is telling me that he don't know what is AngularFire.
But even if I try add import from angularfire2 I have access only to  AngularFireModule

I forget install something or what can be an issue?
Yes, I used npm install angularfire --save

答:
You are doing wrong. You are installing angularjs version I think. Use this

```<code>npm install firebase angularfire2 --save
</code>```

Then import it doing this inside your component

```<code>import { AngularFirestore } from 'angularfire2/firestore';
</code>```

Your constructor should look like this

```<code>constructor(db: AngularFirestore) {

}
</code>```

Here https://github.com/angular/angularfire2

Title: Add AngularFire to constructor

Body:
Hej I have problem with adding AngularFire to constructor at app.component.ts.

I have watching 4 courses realted with AngularFire and everybody add AngularFire to constructor at app.component.ts.

My code look like that:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'Test App';

  constructor(private af: AngularFire){

  }
}

VisualCode is telling me that he don't know what is AngularFire.
But even if I try add import from angularfire2 I have access only to  AngularFireModule

I forget install something or what can be an issue?
Yes, I used npm install angularfire --save

Body:
You are doing wrong. You are installing angularjs version I think. Use this

npm install firebase angularfire2 --save

Then import it doing this inside your component

import { AngularFirestore } from 'angularfire2/firestore';

Your constructor should look like this

constructor(db: AngularFirestore) {

}

Here https://github.com/angular/angularfire2


问:
Extract type of object to use as generic <T>
I have a class VResult<T> that can be instantiated with

```<code>bool value = true;
VResult<bool> vr =  new VResult<bool>(value);
</code>```

If I don't know the type of value, I'd like to do something like

```<code>VResult<typeof value> = new VResult<typeof value>(value);
</code>```

Is that possible?

The ultimate goal is to serialize/deserialize VResult<T>:

```<code>string json = JsonConvert.SerializeObject(new VResult<bool>(true));
</code>```

where  could be an object or basic datatype such as int or bool.

I'm using a data transfer object that adds

```<code>ValueTypeName = Value.GetType().Name;
</code>```

and

```<code>ValueTypeNamespace = Value.GetType().Namespace;
</code>```

properties so that on the receiving side I can use

```<code>JObject obj = JObject.Parse(json);
string vt = (string)obj["ValueTypeName"];
string vtn = (string)obj["ValueTypeNamespace"];
Type type = Type.GetType($"{vtn}.{vt}");
var value = Activator.CreateInstance(type);
value = obj["Value"];
VResult<typeof value> vr = new VResult<typeof value> (value); //not correct
</code>```

to get all the Type information about value, but I just don't figure out how to get the generic <T> from value to pass it in the VResult<T> constructor;

答:
You can create the generic instance like this:

```<code>object value = 1; //I don't know the runtime type of this
var genericType = typeof(VResult<>).MakeGenericType(value.GetType());
var genericInstance = Activator.CreateInstance(genericType,
                                               new object[] { value });
</code>```

And now you have a instance of VResult<int> with a value of 1. Is this what you were looking for?

Body:
I have a class VResult<T> that can be instantiated with

bool value = true;
VResult<bool> vr =  new VResult<bool>(value);

If I don't know the type of value, I'd like to do something like

VResult<typeof value> = new VResult<typeof value>(value);

Is that possible?

The ultimate goal is to serialize/deserialize VResult<T>:

string json = JsonConvert.SerializeObject(new VResult<bool>(true));

where  could be an object or basic datatype such as int or bool.

I'm using a data transfer object that adds

ValueTypeName = Value.GetType().Name;

and

ValueTypeNamespace = Value.GetType().Namespace;

properties so that on the receiving side I can use

JObject obj = JObject.Parse(json);
string vt = (string)obj["ValueTypeName"];
string vtn = (string)obj["ValueTypeNamespace"];
Type type = Type.GetType($"{vtn}.{vt}");
var value = Activator.CreateInstance(type);
value = obj["Value"];
VResult<typeof value> vr = new VResult<typeof value> (value); //not correct

to get all the Type information about value, but I just don't figure out how to get the generic <T> from value to pass it in the VResult<T> constructor;

Body:
You can create the generic instance like this:

object value = 1; //I don't know the runtime type of this
var genericType = typeof(VResult<>).MakeGenericType(value.GetType());
var genericInstance = Activator.CreateInstance(genericType,
                                               new object[] { value });

And now you have a instance of VResult<int> with a value of 1. Is this what you were looking for?


问:
Java: Accessing variables from other classes
I am fairly new to java and was wondering, if I had a two classes as follows:

```<code>public class Class {
    char[][] charArray = new charArray[100[10];
}
class OtherClass extends Class {

}
</code>```

Would the OtherClass class be able to access charArray? If so, how do you do it?

答:
Please look at answer here: sharing-variable-only-between-two-classes-java

Question is slightly different, but in answer there is basic about visibility in Java.

In short:

for your example charArray from Class will be visible from OtherClass only if both classes are in the same package.

To make it visible by child classes from any package it must be either public char[][] charArray or protected char[][] charArray

Body:
I am fairly new to java and was wondering, if I had a two classes as follows:

public class Class {
    char[][] charArray = new charArray[100[10];
}
class OtherClass extends Class {

}

Would the OtherClass class be able to access charArray? If so, how do you do it?


问:
Service worker caching with workbox and server-side rendered SPA
I have a server-side rendered react app and I want to add service worker caching to it.

In the app users can login and see their saved settings. On initial load the server serves the app with these settings pre-rendered based on auth cookie. If user is not logged in then server pre-renders login form instead.

If I use default cache-first strategy on the homepage index.html , then when user logs out and refreshes page, they will see the cached version where they were still logged in.

Using network-first strategy on index.html solves this problem partially, but it fails in this scenario: user logs out or changes any of their settings , goes offline and then refreshes the page - they would see cached version as if none of their actions ever happened, although they just saw the actual up to date version before refresh.

One solution I can think of is to update index.html cache each time a non-GET request happens - logout would have to be a DELETE request, for example. This would solve everything actually and might be universal enough to be included in the framework.

Anyway, I guess I can figure out how to listen to non-GET requests with workbox , but how can I update index.html cache in the listener?

I'll continue inspecting workbox source code, but I would love to get a hint, thanks in advance!

答:
You can use the Cache Storage API directly to remove cached data when a user logs out. I'd recommend an approach where you use named caches in your Workbox strategies, and have a specific name (like 'user-data') for all of the data that's tied to a logged-in user. Then you can delete it via

```<code>// This code can run in the context of your web page:
if ('caches' in window) {
  window.caches.delete('user-data');
}
</code>```

The nice thing about this approach is that if you use a different cache name for data that's not specific to a given user (like, a cache of images or CSS files) you don't have to remove those cached entries when the user logs out.

Body:
You can use the Cache Storage API directly to remove cached data when a user logs out. I'd recommend an approach where you use named caches in your Workbox strategies, and have a specific name (like 'user-data') for all of the data that's tied to a logged-in user. Then you can delete it via

// This code can run in the context of your web page:
if ('caches' in window) {
  window.caches.delete('user-data');
}

The nice thing about this approach is that if you use a different cache name for data that's not specific to a given user (like, a cache of images or CSS files) you don't have to remove those cached entries when the user logs out.


问:
this.setState making infinite loop outside of array.map function
I have this array map function for rendering some stuff...
I have 5 variables that start from 0 and depending on a switch statement each variable value is increased by 1.

```<code>renderUser = (index)=>{
    let C1Count = 0, C2Count = 0, C3Count = 0, C4Count = 0, C5Count = 0;
    let users = this.state.users.map((user,index)=>{

   // swiching some value , that is from 0 to 4

   switch(this.state.users[index].result){
      case 0: { C1Count += 1;   break; }
      case 1: { C2Count += 1;  break; }
      case 2: { C3Count += 1;  break; }
      case 3: { C4Count += 1;   break; }
      case 4: { C5Count += 1;   break; }
      default: { console.log("non");  break; };
    }
    return(
      ....stuff to render
                   )

   }).reverse();

  return users;
</code>```

}

I want to update 5 states

```<code>this.setState({
C1Count:C1Count, // state : variable value
C2Count:C2Count, // state : variable value
C3Count:C3Count, // state : variable value
C4Count:C4Count, // state : variable value
C5Count:C5Count  // state : variable value
});
</code>```

If i place the setState code after ...}).reverse(); and before  ..return users;

I get a

Maximum update depth exceeded. This can happen when a component
  repeatedly calls setState inside componentWillUpdate or
  componentDidUpdate. React limits the number of nested updates to
  prevent infinite loops.

error .... so my question is ... how to update the state AFTER all the loops are finished and the C1Count, C2Count, C3Count, C4Count, C5Count variables are updated.

答: When you setState(), you will cause another render hence your infinite loop. You shouldn't call setState from render. One of the lifecycle methods (componentDidMount etc) would be a better place depending on your needs or the constructor if this is the initial state of the component.

ContentLicense: CC BY-SA 4.0

Body:
I have this array map function for rendering some stuff...
I have 5 variables that start from 0 and depending on a switch statement each variable value is increased by 1.

renderUser = (index)=>{
    let C1Count = 0, C2Count = 0, C3Count = 0, C4Count = 0, C5Count = 0;
    let users = this.state.users.map((user,index)=>{

   // swiching some value , that is from 0 to 4

   switch(this.state.users[index].result){
      case 0: { C1Count += 1;   break; }
      case 1: { C2Count += 1;  break; }
      case 2: { C3Count += 1;  break; }
      case 3: { C4Count += 1;   break; }
      case 4: { C5Count += 1;   break; }
      default: { console.log("non");  break; };
    }
    return(
      ....stuff to render
                   )

   }).reverse();

  return users;

}

I want to update 5 states

this.setState({
C1Count:C1Count, // state : variable value
C2Count:C2Count, // state : variable value
C3Count:C3Count, // state : variable value
C4Count:C4Count, // state : variable value
C5Count:C5Count  // state : variable value
});

If i place the setState code after ...}).reverse(); and before  ..return users;

I get a

Maximum update depth exceeded. This can happen when a component
  repeatedly calls setState inside componentWillUpdate or
  componentDidUpdate. React limits the number of nested updates to
  prevent infinite loops.

error .... so my question is ... how to update the state AFTER all the loops are finished and the C1Count, C2Count, C3Count, C4Count, C5Count variables are updated.


问:
Accessing c++ object data members from R
Apologies if this is a silly question as I am not a c++ or Rcpp expert but is it possible to access c++ data members from R? My attempt below fails:

test.cpp

```<code>#include <Rcpp.h>
using namespace Rcpp;

class myclass {
private:
  int k;
public:
  myclass(int &n) : k(n){}
  int getk() const {return k;}
};

typedef myclass* pmyclass;

// [[Rcpp::export]]
XPtr<pmyclass> new_myclass(NumericVector n_) {
  int n = as<int>(n_);
  myclass x(n);
  return(XPtr<pmyclass>(new pmyclass(&x)));
}

// [[Rcpp::export]]
NumericVector getk(SEXP xpsexp){
  XPtr<pmyclass> xp(xpsexp);
  pmyclass x = *xp;
  return wrap(x -> getk());
}
</code>```

test.R

```<code>library(Rcpp)

sourceCpp('./cpp_attempt/live_in_cpp/minimal_fail/test.cpp')

ptr <- new_myclass(10)

getk(ptr)
#19274768
</code>```

答:
I would use</p>

```<code>#include <Rcpp.h>
using namespace Rcpp;

class myclass {
private:
  int k;
public:
  myclass(int n) : k(n){}
  int getk() const {return k;}
};

// [[Rcpp::export]]
SEXP new_myclass(int n) {
  XPtr<myclass> ptr(new myclass(n), true);
  return ptr;
}

// [[Rcpp::export]]
int getk(SEXP xpsexp){
  XPtr<myclass> xp(xpsexp);
  return xp->getk();
}
</code>```

Body:
Apologies if this is a silly question as I am not a c++ or Rcpp expert but is it possible to access c++ data members from R? My attempt below fails:

test.cpp

#include <Rcpp.h>
using namespace Rcpp;

class myclass {
private:
  int k;
public:
  myclass(int &n) : k(n){}
  int getk() const {return k;}
};

typedef myclass* pmyclass;

// [[Rcpp::export]]
XPtr<pmyclass> new_myclass(NumericVector n_) {
  int n = as<int>(n_);
  myclass x(n);
  return(XPtr<pmyclass>(new pmyclass(&x)));
}

// [[Rcpp::export]]
NumericVector getk(SEXP xpsexp){
  XPtr<pmyclass> xp(xpsexp);
  pmyclass x = *xp;
  return wrap(x -> getk());
}

test.R

library(Rcpp)

sourceCpp('./cpp_attempt/live_in_cpp/minimal_fail/test.cpp')

ptr <- new_myclass(10)

getk(ptr)
#19274768

Body:
I would use

#include <Rcpp.h>
using namespace Rcpp;

class myclass {
private:
  int k;
public:
  myclass(int n) : k(n){}
  int getk() const {return k;}
};

// [[Rcpp::export]]
SEXP new_myclass(int n) {
  XPtr<myclass> ptr(new myclass(n), true);
  return ptr;
}

// [[Rcpp::export]]
int getk(SEXP xpsexp){
  XPtr<myclass> xp(xpsexp);
  return xp->getk();
}


答:
You could wrap your image containers in a div with display: flex

updated as per comment

.wrapper {
  display: flex;
  flex-wrap: wrap;
}

.container {
  position: relative;
  min-width: 50%;
}

.image {
  opacity: 1;
  width: 100%;
  height: auto;
  transition: .5s ease;
  backface-visibility: hidden;
  display: block;
}

.middle {
  transition: .5s ease;
  opacity: 0;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%)
}

.container:hover .image {
  opacity: 0.3;
}

.container:hover .middle {
  opacity: 1;
}

.text {
  background-color: #4CAF50;
  color: white;
  font-size: 16px;
  padding: 16px 32px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">

  <div class="container">
    <img src="http://img.draugas.lt/forumas/veidukai/973676.gif" alt="Avatar" class="image" style="width:100%">
    <div class="middle">
      <div class="text">John Doe</div>
    </div>
  </div>
  <div class="container">
    <img src="http://img.draugas.lt/forumas/veidukai/973676.gif" alt="Avatar" class="image" style="width:100%">
    <div class="middle">
      <div class="text">John Doe</div>
    </div>
  </div>
   <div class="container">
    <img src="http://img.draugas.lt/forumas/veidukai/973676.gif" alt="Avatar" class="image" style="width:100%">
    <div class="middle">
      <div class="text">John Doe</div>
    </div>
  </div>
   <div class="container">
    <img src="http://img.draugas.lt/forumas/veidukai/973676.gif" alt="Avatar" class="image" style="width:100%">
    <div class="middle">
      <div class="text">John Doe</div>
    </div>
  </div>
   <div class="container">
    <img src="http://img.draugas.lt/forumas/veidukai/973676.gif" alt="Avatar" class="image" style="width:100%">
    <div class="middle">
      <div class="text">John Doe</div>
    </div>
  </div>
   <div class="container">
    <img src="http://img.draugas.lt/forumas/veidukai/973676.gif" alt="Avatar" class="image" style="width:100%">
    <div class="middle">
      <div class="text">John Doe</div>
    </div>
  </div>
</div></code>```

Body:
John Doe

John Doe

What I'm trying to achieve, is making this type of effect to stack in two columns responsively. ( So that when I resize my window, images won't be streched )

And I can't do it. Could you please guide my on how can I achieve this effect? I can't even make two images to stack side by side on that fiddle, they seem to always stack in one column like this.

I've tried using Boostrap with container and col-lg-6, had no success.

Body:
You could wrap your image containers in a div with display: flex

updated as per comment

.wrapper {
  display: flex;
  flex-wrap: wrap;
}

.container {
  position: relative;
  min-width: 50%;
}

.image {
  opacity: 1;
  width: 100%;
  height: auto;
  transition: .5s ease;
  backface-visibility: hidden;
  display: block;
}

.middle {
  transition: .5s ease;
  opacity: 0;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%)
}

.container:hover .image {
  opacity: 0.3;
}

.container:hover .middle {
  opacity: 1;
}

.text {
  background-color: #4CAF50;
  color: white;
  font-size: 16px;
  padding: 16px 32px;
}

<div class="wrapper">

  <div class="container">
    <img src="http://img.draugas.lt/forumas/veidukai/973676.gif" alt="Avatar" class="image" style="width:100%">
    <div class="middle">
      <div class="text">John Doe</div>
    </div>
  </div>
  <div class="container">
    <img src="http://img.draugas.lt/forumas/veidukai/973676.gif" alt="Avatar" class="image" style="width:100%">
    <div class="middle">
      <div class="text">John Doe</div>
    </div>
  </div>
   <div class="container">
    <img src="http://img.draugas.lt/forumas/veidukai/973676.gif" alt="Avatar" class="image" style="width:100%">
    <div class="middle">
      <div class="text">John Doe</div>
    </div>
  </div>
   <div class="container">
    <img src="http://img.draugas.lt/forumas/veidukai/973676.gif" alt="Avatar" class="image" style="width:100%">
    <div class="middle">
      <div class="text">John Doe</div>
    </div>
  </div>
   <div class="container">
    <img src="http://img.draugas.lt/forumas/veidukai/973676.gif" alt="Avatar" class="image" style="width:100%">
    <div class="middle">
      <div class="text">John Doe</div>
    </div>
  </div>
   <div class="container">
    <img src="http://img.draugas.lt/forumas/veidukai/973676.gif" alt="Avatar" class="image" style="width:100%">
    <div class="middle">
      <div class="text">John Doe</div>
    </div>
  </div>
</div>


问:
Ramda - R.Both with functions taking different number of params
Just learning Ramda and find I keep running into this same scenario.   I have 2 conditional functions that I want to evaluate with R.both.   The twist is that 1 function will require an extra parameter.   Something like:

const condition1 = (y) => y===1;

const condition2 = (x, y) => x===y;

const validator = R.both(condition1, condition2)

Notice that the parms for condition2 are switched.   If I know that x will be applied first this works fine.  But what if it isn't?

Do I:

1)  alter condition1 like const conditionAltered = () => condition1

2)  use some Ramda function to do the same (not sure what that would be)

3)  ????

Looking for a "best practice" type answer.

OK, so as it turns out I completely misunderstood how the R.both operated.   First I thought it would auto-curry the passed in conditions and second I didn't realize it short-circuited.

Given that my (1) should read const conditionAltered = (x, y) => condition1(y)

答:
Not sure, if the conditions in questions are correct but I will try my best to give a solution.

Let above conditions are like following.

```<code>const condition1 = (x) => x === 2;
const condition2 = (x, y) => x > y;
</code>```

To check both the conditions, you can do

```<code>const validator = R.both(condition1, condition2);
validator(2, 1) // return `true`
</code>```

Now if you want to invert the arguments of condition2, then you can do like following

```<code>const condition1 = (x) => x === 2;
const condition2 = (y, x) => x > y;
const validator = R.both(condition1, R.flip(condition2));
validator(2, 1) // return `true`
</code>```

Note, I have added R.flip() to flip the arguments.

Body:
Not sure, if the conditions in questions are correct but I will try my best to give a solution.

Let above conditions are like following.

const condition1 = (x) => x === 2;
const condition2 = (x, y) => x > y;

To check both the conditions, you can do

const validator = R.both(condition1, condition2);
validator(2, 1) // return `true`

Now if you want to invert the arguments of condition2, then you can do like following

const condition1 = (x) => x === 2;
const condition2 = (y, x) => x > y;
const validator = R.both(condition1, R.flip(condition2));
validator(2, 1) // return `true`

Note, I have added R.flip() to flip the arguments.


问:
ILMerge problem: start with command prompt only
I build 5 DLLS and my exe in C#.Net 2.0 with ILMerge to one exe file.
The problem is that now every time I start the output exe, an empty command prompt opened with the exe. Anyone knows the problem and know how to solve it?</p>

答: I found answer. The output parameter is "winexe", don't "exe". Me is it solve the problem.</p>


问:
all possible combinations of a set in Matlab
I'm trying to find all possible combinations of a set but the order of the elements are also important for my problem.

For example for the set set={A, B, C}, the possible subsets are subsets={A},{B},{C},{A,B},{A,C},{B,A},{B,C},{C,A},{C,B},{A,B,C},{A,C,B},{B,A,C},{B,C,A},{C,A,B},{C,B,A}.

Are there any Matlab function to find that?

Thanks in advance.

答:
I couldn't bear to see all those for loops in Tommaso's answer, so here's one with no loops:

```<code>a = {'A' 'B' 'C'};

% Build an array of binary vectors which we will use to select subsets of
% the array to be permuted
nGroups = 2^numel(a) - 1;
selector = dec2bin(1:nGroups) == '1'; % hack to convert numbers to binary vectors
selectVectors = arrayfun(@(x) selector(x,:), 1:size(selector, 1), 'UniformOutput', false);

% Get the permutations of each subset of the array
permsCell = cellfun(@(s) perms(a(s)), selectVectors, 'UniformOutput', false);

% Rearrange the permutations into a one-dimensional cell array with one
% permutation in each element
rowsAsCells = @(ca) arrayfun(@(x) ca(x,:), 1:size(ca,1), 'UniformOutput', false);
permsAsRows = cellfun(rowsAsCells, permsCell, 'UniformOutput', false);
result = cat(2, permsAsRows{:});
</code>```

This returns a cell array with one permutation in each element, like Tommaso's second solution.

Whether this version is preferable is a matter of taste ;-)

Body:
I couldn't bear to see all those for loops in Tommaso's answer, so here's one with no loops:

a = {'A' 'B' 'C'};

% Build an array of binary vectors which we will use to select subsets of
% the array to be permuted
nGroups = 2^numel(a) - 1;
selector = dec2bin(1:nGroups) == '1'; % hack to convert numbers to binary vectors
selectVectors = arrayfun(@(x) selector(x,:), 1:size(selector, 1), 'UniformOutput', false);

% Get the permutations of each subset of the array
permsCell = cellfun(@(s) perms(a(s)), selectVectors, 'UniformOutput', false);

% Rearrange the permutations into a one-dimensional cell array with one
% permutation in each element
rowsAsCells = @(ca) arrayfun(@(x) ca(x,:), 1:size(ca,1), 'UniformOutput', false);
permsAsRows = cellfun(rowsAsCells, permsCell, 'UniformOutput', false);
result = cat(2, permsAsRows{:});

This returns a cell array with one permutation in each element, like Tommaso's second solution.

Whether this version is preferable is a matter of taste ;-)


问:
Weird Value When Calculating Date Difference
I have been using the following code to calculate the difference between two dates and I have been getting an unusual error:

if I pass the following dates:

d1 = 08/12/2017
d2 = 31/07/2022

it returns: 24055..

isn't the result supposed to be return as the number of months?

```<code> public static int CalcDateDiff( java.util.Date  date1,  java.util.Date  date2) {
    if(date1 == null || date2 ==null )
    {
        if(date2 == null)
        {
              Calendar d1 = Calendar.getInstance();
                d1.setTime(date1);
                final Calendar d2 = Calendar.getInstance();
                int diff = (d2.get(Calendar.YEAR) - d1.get(Calendar.YEAR)) * 12 + d2.get(Calendar.MONTH) - d1.get(Calendar.MONTH);

                return diff;
        }
        else
            return -1;
    }
    else
    {

            Calendar d1 = Calendar.getInstance();
            d1.setTime(date1);
            final Calendar d2 = Calendar.getInstance();
            d2.setTime(date2);
            int diff = (d2.get(Calendar.YEAR) - d1.get(Calendar.YEAR)) * 12 + d2.get(Calendar.MONTH) - d1.get(Calendar.MONTH);

            return diff;
        }
}
</code>```

Thanks in advance!

答:
tl;dr

```<code>ChronoUnit.MONTHS.between(                                           // Use enum method to calculate elapsed time.
    date1.toInstant().atZone( ZoneId.of( "Africa/Casablanca " ) ) ,  // Convert from legacy `Date` class to modern `java.time.Instant` class. Adjust from UTC to a specific time zone.
    date2.toInstant().atZone( ZoneId.of( "Africa/Casablanca " ) )
)                                                                    // Return a number of months elapsed.
</code>```

Details

The Answer by Roberson is good. Here's an alternative.

Your use of the troublesomeDate class is now outmoded. That legacy class is replaced by Instant in the java.time package. Both represent a moment, a point on the timeline in UTC. The modern class has a resolution of nanoseconds rather than milliseconds.

Convert using new methods added to the old classes.

```<code>Instant instant = myUtilDate.toInstant() ;
</code>```

To determine a number of months, we need dates. Determining a date requires a time zone. For any given moment the date varies around the globe by zone.

```<code>ZoneId z = ZoneId.of( "Pacific/Auckland " ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
</code>```

The ChronoUnit enum offers the between method for calculating elapsed time.

```<code>long months = ChronoUnit.MONTHS.between( zdt1 , zdt2 ) ;
</code>```

Body:
I have been using the following code to calculate the difference between two dates and I have been getting an unusual error:

if I pass the following dates:

d1 = 08/12/2017
d2 = 31/07/2022

it returns: 24055..

isn't the result supposed to be return as the number of months?

 public static int CalcDateDiff( java.util.Date  date1,  java.util.Date  date2) {
    if(date1 == null || date2 ==null )
    {
        if(date2 == null)
        {
              Calendar d1 = Calendar.getInstance();
                d1.setTime(date1);
                final Calendar d2 = Calendar.getInstance();
                int diff = (d2.get(Calendar.YEAR) - d1.get(Calendar.YEAR)) * 12 + d2.get(Calendar.MONTH) - d1.get(Calendar.MONTH);

                return diff;
        }
        else
            return -1;
    }
    else
    {

            Calendar d1 = Calendar.getInstance();
            d1.setTime(date1);
            final Calendar d2 = Calendar.getInstance();
            d2.setTime(date2);
            int diff = (d2.get(Calendar.YEAR) - d1.get(Calendar.YEAR)) * 12 + d2.get(Calendar.MONTH) - d1.get(Calendar.MONTH);

            return diff;
        }
}

Thanks in advance!

Body:
tl;dr

ChronoUnit.MONTHS.between(                                           // Use enum method to calculate elapsed time.
    date1.toInstant().atZone( ZoneId.of( "Africa/Casablanca " ) ) ,  // Convert from legacy `Date` class to modern `java.time.Instant` class. Adjust from UTC to a specific time zone.
    date2.toInstant().atZone( ZoneId.of( "Africa/Casablanca " ) )
)                                                                    // Return a number of months elapsed.

Details

The Answer by Roberson is good. Here's an alternative.

Your use of the troublesomeDate class is now outmoded. That legacy class is replaced by Instant in the java.time package. Both represent a moment, a point on the timeline in UTC. The modern class has a resolution of nanoseconds rather than milliseconds.

Convert using new methods added to the old classes.

Instant instant = myUtilDate.toInstant() ;

To determine a number of months, we need dates. Determining a date requires a time zone. For any given moment the date varies around the globe by zone.

ZoneId z = ZoneId.of( "Pacific/Auckland " ) ;
ZonedDateTime zdt = instant.atZone( z ) ;

The ChronoUnit enum offers the between method for calculating elapsed time.

long months = ChronoUnit.MONTHS.between( zdt1 , zdt2 ) ;


问:
nginx location does not interpret php
I'am going crazy to understand this nginx vhost config. My issue is with the /v2 location, it does not send php stuff to php-fpm while it works properly outside /v2. Can anyone point me the mistake ?

```<code>server {
  listen 443 ssl;
  include ssl.conf;
   include hardening.conf;
   server_name myapp.domain.com myapp;
   ssl_certificate /etc/pki/tls/certs/myapp.domain.com.crt;
   ssl_certificate_key /etc/pki/tls/private/myapp.domain.com.key;
   access_log /var/log/nginx/myapp.domain.com-access.log main;
   error_log /var/log/nginx/myapp.domain.com-error.log notice;
   root /var/www/html/myapp.domain.com;

   location ~ /\.ht {
     deny  all;
   }

   location ~ /v2 {
     alias /var/www/html/myapp.domain.com/version-2/web;
     try_files $uri index.php$is_args$args;
   }

   location ~ [^/]\.php(/|$) {
     fastcgi_split_path_info ^(.+?\.php)(/.*)$;
     if (!-f $document_root$fastcgi_script_name) {
       return 404;
     }

     # Mitigate https://httpoxy.org/ vulnerabilities
     fastcgi_param HTTP_PROXY "";

     fastcgi_pass localhost:9000;
     fastcgi_index index.php;
     include fastcgi_params.conf;
   }
 }
</code>```

According to comments, I'm trying the nested location solution but I receive now 404 when I try https://myapp.domain.com/v2/index.php while /var/www/html/myapp.domain.com/version-2/web/index.php is present on the filesystem. Also as explained on the link given, I modified my location from ^ to ^~. Any idea what's wrong?

```<code>server {
  listen 443 ssl;
  include ssl.conf;
   include hardening.conf;
   server_name myapp.domain.com myapp;
   ssl_certificate /etc/pki/tls/certs/myapp.domain.com.crt;
   ssl_certificate_key /etc/pki/tls/private/myapp.domain.com.key;
   access_log /var/log/nginx/myapp.domain.com-access.log main;
   error_log /var/log/nginx/myapp.domain.com-error.log notice;
   root /var/www/html/myapp.domain.com;

   location ~ /\.ht {
     deny  all;
   }

   location ^~ /v2 {
     alias /var/www/html/myapp.domain.com/version-2/web;
     try_files $uri index.php$is_args$args;

     location ~ [^/]\.php(/|$) {
       fastcgi_split_path_info ^(.+?\.php)(/.*)$;
       if (!-f $document_root$fastcgi_script_name) {
         return 404;
       }

       # Mitigate https://httpoxy.org/ vulnerabilities
       fastcgi_param HTTP_PROXY "";

       fastcgi_pass localhost:9000;
       fastcgi_index index.php;
       include fastcgi_params.conf;
     }

   }

   location ~ [^/]\.php(/|$) {
     fastcgi_split_path_info ^(.+?\.php)(/.*)$;
     if (!-f $document_root$fastcgi_script_name) {
       return 404;
     }

     # Mitigate https://httpoxy.org/ vulnerabilities
     fastcgi_param HTTP_PROXY "";

     fastcgi_pass localhost:9000;
     fastcgi_index index.php;
     include fastcgi_params.conf;
   }
 }
</code>```

答:
you have to point to the php5-fpm location. like this:

```<code>location ~ \.php$ {
      include snippets/fastcgi-php.conf;
      fastcgi_pass unix:/var/run/php5-fpm.sock;
}
</code>```

Take a look in a whole example:

```<code>server {
    listen 8082;
    listen [::]:8082;
    server_name 192.168.2.60;

    root /usr/share/nginx/html/phpmyadmin/;
    index index.php index.html index.htm;

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

    location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/var/run/php5-fpm.sock;
     }

     location ~ /\.ht {
            deny all;
     }
}
</code>```

Title: nginx location does not interpret php

Body:
I'am going crazy to understand this nginx vhost config. My issue is with the /v2 location, it does not send php stuff to php-fpm while it works properly outside /v2. Can anyone point me the mistake ?

server {
  listen 443 ssl;
  include ssl.conf;
   include hardening.conf;
   server_name myapp.domain.com myapp;
   ssl_certificate /etc/pki/tls/certs/myapp.domain.com.crt;
   ssl_certificate_key /etc/pki/tls/private/myapp.domain.com.key;
   access_log /var/log/nginx/myapp.domain.com-access.log main;
   error_log /var/log/nginx/myapp.domain.com-error.log notice;
   root /var/www/html/myapp.domain.com;

   location ~ /\.ht {
     deny  all;
   }

   location ~ /v2 {
     alias /var/www/html/myapp.domain.com/version-2/web;
     try_files $uri index.php$is_args$args;
   }

   location ~ [^/]\.php(/|$) {
     fastcgi_split_path_info ^(.+?\.php)(/.*)$;
     if (!-f $document_root$fastcgi_script_name) {
       return 404;
     }

     # Mitigate https://httpoxy.org/ vulnerabilities
     fastcgi_param HTTP_PROXY "";

     fastcgi_pass localhost:9000;
     fastcgi_index index.php;
     include fastcgi_params.conf;
   }
 }

According to comments, I'm trying the nested location solution but I receive now 404 when I try https://myapp.domain.com/v2/index.php while /var/www/html/myapp.domain.com/version-2/web/index.php is present on the filesystem. Also as explained on the link given, I modified my location from ^ to ^~. Any idea what's wrong?

server {
  listen 443 ssl;
  include ssl.conf;
   include hardening.conf;
   server_name myapp.domain.com myapp;
   ssl_certificate /etc/pki/tls/certs/myapp.domain.com.crt;
   ssl_certificate_key /etc/pki/tls/private/myapp.domain.com.key;
   access_log /var/log/nginx/myapp.domain.com-access.log main;
   error_log /var/log/nginx/myapp.domain.com-error.log notice;
   root /var/www/html/myapp.domain.com;

   location ~ /\.ht {
     deny  all;
   }

   location ^~ /v2 {
     alias /var/www/html/myapp.domain.com/version-2/web;
     try_files $uri index.php$is_args$args;

     location ~ [^/]\.php(/|$) {
       fastcgi_split_path_info ^(.+?\.php)(/.*)$;
       if (!-f $document_root$fastcgi_script_name) {
         return 404;
       }

       # Mitigate https://httpoxy.org/ vulnerabilities
       fastcgi_param HTTP_PROXY "";

       fastcgi_pass localhost:9000;
       fastcgi_index index.php;
       include fastcgi_params.conf;
     }

   }

   location ~ [^/]\.php(/|$) {
     fastcgi_split_path_info ^(.+?\.php)(/.*)$;
     if (!-f $document_root$fastcgi_script_name) {
       return 404;
     }

     # Mitigate https://httpoxy.org/ vulnerabilities
     fastcgi_param HTTP_PROXY "";

     fastcgi_pass localhost:9000;
     fastcgi_index index.php;
     include fastcgi_params.conf;
   }
 }

Body:
you have to point to the php5-fpm location. like this:

location ~ \.php$ {
      include snippets/fastcgi-php.conf;
      fastcgi_pass unix:/var/run/php5-fpm.sock;
}

Take a look in a whole example:

server {
    listen 8082;
    listen [::]:8082;
    server_name 192.168.2.60;

    root /usr/share/nginx/html/phpmyadmin/;
    index index.php index.html index.htm;

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

    location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/var/run/php5-fpm.sock;
     }

     location ~ /\.ht {
            deny all;
     }
}