问:
Is it more efficient to use the CASE in the original query or in a separate query?
I can't show the real query, but here is an example of the type of thing I'm doing:

```<code>select
  t1.contract,
  t1.state,
  t1.status,
  t2.product,
  case
    when t2.product_cost > 100 and t3.status = 'Closed' then 'Success'
    when t2.product_cost <= 100 and t3.status = 'Closed' then 'Semi-Success'
    else 'Failure'
  end as performance,
  t3.sales_date
from contract_table as t1
left join product_table as t2 on t1.prodkey = t2.prodkey
left join sales_table as t3 on (t1.client_number = t3.client_number and t1.contract=t3.contract)
where t1.client_number in (1, 2, 5, 8, 10)
</code>```

The tables involved have currently have 27 million records in them and are growing fast.

This query will be put in a view and then used to generate various summaries.

My question is this.  Would it be more efficient to join the 3 tables into 1 view that has the detail needed to do the case statements and then run a second query that creates the new variables using the case statements?  Or is it more efficient to do what I'm doing here?

Basically, I'm ignorant as to how SQL processes the select statement and accounts for the where statement filtering on the clients from the contract table but not the sales table even though the client_number field is in both.

答:
All other things being equal, the only thing I can see that would change the efficiency one way or another would be whether you have where clause conditions in your outer query.  If that outer query performed on the view is going to have where clauses that limit the number of records returned, then it would be more efficient to put the case statements on it.  That way the case operation will only be performed on the records that pass those conditions, rather than getting performed on every record that passes the view's conditions, only to have those values thrown away by the outer query.

With views, I tend to keep to pretty raw data, as much as possible.  Partly, for this reason, so that any query operating on the view, after deciding what rows to use, can do the necessary operations only on those rows.

As for how sql accounts for filtering on the clients from the contract table but not the sales table, think through both the where clause and the joins.  The where clause says grab only the records where the contract table's client is 1,2,5,8,10.  But the join conditions tell it to only grab the records from sales where that table's client number matches the contract table's client number.  If the only records it's grabbing from contract are 1,2,5,8,10, then the only records from sale that will match that join will be the ones where the client numbers are also 1,2,5,8,10.  Does that make sense?

Body:
I can't show the real query, but here is an example of the type of thing I'm doing:

select
  t1.contract,
  t1.state,
  t1.status,
  t2.product,
  case
    when t2.product_cost > 100 and t3.status = 'Closed' then 'Success'
    when t2.product_cost <= 100 and t3.status = 'Closed' then 'Semi-Success'
    else 'Failure'
  end as performance,
  t3.sales_date
from contract_table as t1
left join product_table as t2 on t1.prodkey = t2.prodkey
left join sales_table as t3 on (t1.client_number = t3.client_number and t1.contract=t3.contract)
where t1.client_number in (1, 2, 5, 8, 10)

The tables involved have currently have 27 million records in them and are growing fast.

This query will be put in a view and then used to generate various summaries.

My question is this.  Would it be more efficient to join the 3 tables into 1 view that has the detail needed to do the case statements and then run a second query that creates the new variables using the case statements?  Or is it more efficient to do what I'm doing here?

Basically, I'm ignorant as to how SQL processes the select statement and accounts for the where statement filtering on the clients from the contract table but not the sales table even though the client_number field is in both.


来源: stackexchange

问:
React/Express - required props 'undefined' in match/RouterContext
I'm working on implementing server-side rendering for my React/Express app - the app is actually working as desired, but I'm getting a warning on my server related to match() and RouterContext that I'd like to understand and resolve.

Basically, in the callback function for match, the arguments (err, redirect, props) are all evaluating as undefined.

index.js (Express app root):

```<code>'use strict'
require('babel-register')({
    presets: ['es2015', 'react']
});

const express = require('express')
const path = require('path')
const app = express()
const React = require('react')
const reactDomServer = require('react-dom/server')
const routes = require('./src/routes.jsx')
const reactRouter = require('react-router')
let { match, RouterContext, createRoutes } = reactRouter

app.get('*', (req, res) => {
    match({ routes: createRoutes(routes), location: req.url }, (err, redirect, props) => {
        const appHtml = renderToString(React.createElement(RouterContext, props))
        res.send(renderPage(appHtml))
    })
})
</code>```

So if I throw a console.log() in for err, redirect, and props, they all come back as undefined. This causes my server to return the warning

```<code>Warning: Failed prop type: The prop `router` is marked as required in `RouterContext`, but its value is `undefined`.
    in RouterContext
Warning: Failed prop type: The prop `location` is marked as required in `RouterContext`, but its value is `undefined`.
    in RouterContext
Warning: Failed prop type: The prop `routes` is marked as required in `RouterContext`, but its value is `undefined`.
    in RouterContext
Warning: Failed prop type: The prop `params` is marked as required in `RouterContext`, but its value is `undefined`.
    in RouterContext
Warning: Failed prop type: The prop `components` is marked as required in `RouterContext`, but its value is `undefined`.
    in RouterContext
Warning: Failed child context type: The child context `router` is marked as required in `RouterContext`, but its value is `undefined`.
    in RouterContext
</code>```

Again, to my surprise, my app seems to work just fine - I can refresh pages, access urls directly (i.e. 'localhost:3000/person/1234'), but these warnings persist. Maybe I don't understand the needs of RouterContext (likely).

Regardless, I would like to resolve this, because I want to use those arguments to set up some conditionals... any guidance on this would be much appreciated.

Update
I've realized that err and redirect are supposed to default to undefined (unless there's an error or redirect), but no matter what I do, props seems to be stuck on undefined as well.

From https://knowbody.github.io/react-router-docs/api/match.html: "If all three parameters are undefined, this means that there was no route found matching the given location."

But I don't understand - the app seems to work fine. What gives?

答:
Thanks to @taha for pointing me in the right direction on this. Turns out that the problem was both my use of createRoutes() and the fact that I was not correctly accessing the routes.

The call to match needs to be

```<code>match({ routes: routes.default, location: req.url }, (err, redirect, props) => { /* etc. */ }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm working on implementing server-side rendering for my React/Express app - the app is actually working as desired, but I'm getting a warning on my server related to match() and RouterContext that I'd like to understand and resolve.

Basically, in the callback function for match, the arguments (err, redirect, props) are all evaluating as undefined.

index.js (Express app root):

'use strict'
require('babel-register')({
    presets: ['es2015', 'react']
});

const express = require('express')
const path = require('path')
const app = express()
const React = require('react')
const reactDomServer = require('react-dom/server')
const routes = require('./src/routes.jsx')
const reactRouter = require('react-router')
let { match, RouterContext, createRoutes } = reactRouter

app.get('*', (req, res) => {
    match({ routes: createRoutes(routes), location: req.url }, (err, redirect, props) => {
        const appHtml = renderToString(React.createElement(RouterContext, props))
        res.send(renderPage(appHtml))
    })
})

So if I throw a console.log() in for err, redirect, and props, they all come back as undefined. This causes my server to return the warning

Warning: Failed prop type: The prop `router` is marked as required in `RouterContext`, but its value is `undefined`.
    in RouterContext
Warning: Failed prop type: The prop `location` is marked as required in `RouterContext`, but its value is `undefined`.
    in RouterContext
Warning: Failed prop type: The prop `routes` is marked as required in `RouterContext`, but its value is `undefined`.
    in RouterContext
Warning: Failed prop type: The prop `params` is marked as required in `RouterContext`, but its value is `undefined`.
    in RouterContext
Warning: Failed prop type: The prop `components` is marked as required in `RouterContext`, but its value is `undefined`.
    in RouterContext
Warning: Failed child context type: The child context `router` is marked as required in `RouterContext`, but its value is `undefined`.
    in RouterContext

Again, to my surprise, my app seems to work just fine - I can refresh pages, access urls directly (i.e. 'localhost:3000/person/1234'), but these warnings persist. Maybe I don't understand the needs of RouterContext (likely).

Regardless, I would like to resolve this, because I want to use those arguments to set up some conditionals... any guidance on this would be much appreciated.

Update
I've realized that err and redirect are supposed to default to undefined (unless there's an error or redirect), but no matter what I do, props seems to be stuck on undefined as well.

From https://knowbody.github.io/react-router-docs/api/match.html: "If all three parameters are undefined, this means that there was no route found matching the given location."

But I don't understand - the app seems to work fine. What gives?

Body:
Thanks to @taha for pointing me in the right direction on this. Turns out that the problem was both my use of createRoutes() and the fact that I was not correctly accessing the routes.

The call to match needs to be

match({ routes: routes.default, location: req.url }, (err, redirect, props) => { /* etc. */ }


问:
Submit form via headless browser - NodeJS
Due to an archaic stack, the response from a form submission is HTML. When rendered on my clients domain, the relevant information is injected in via a portlet. If you render the markup locally, the necessary content is missing. This makes it impossible for me to simply post data to the relevant form endpoint.

As a result of this, I need to submit a form and scrape the success/fail page for the necessary information in a headless browser.

I'm planning on wiring an API endpoint in my NodeJS application that I can post the form data to which in turn will submit the form in the headless browser and respond with the scraped content.

Are there any frameworks that would support this? I've looked at Nightwatch and Web Driver but they all seem to be aimed at automated testing rather than what I'm after.

答:
Try using casper.js

It is a scripting and testing utility for use with Slimer.js (headless browser)


问:
Stripe landing page setting not working
I'm currently taking an online course to make an airbnb like web application with ruby on rails. It utilizes Stripe for the payment and I want to make the landing page from my app to the Stripe a register page instead of a login page.

I'm completely following the tutorial that successfully makes the register page as the landing page with the below code.

stripe_landing: 'register'

But my landing page is still the login page. I googled the above code but all I could find was pages from 2-4 years ago. I wonder if Stripe changed it recently. (but hpar replied saying nothing has changed)

I put the whole code here... When I click the link to Stripe, it goes to stripe#oauth.

```<code>    class StripeController < ApplicationController
      # Connect yourself to a Stripe account.
      # Only works on the currently logged in user.
      # See app/services/stripe_oauth.rb for #oauth_url details.

      def oauth
        connector = StripeOauth.new( current_user )
        url, error = connector.oauth_url( redirect_uri: stripe_confirm_url )

        if url.nil?
          flash[:error] = error
          redirect_to manage_listing_payment_path( session[:listing_id] )
        else
          redirect_to url
        end
      end

    end
</code>```

then,

```<code>    class StripeOauth < Struct.new( :user )

      def oauth_url( params )
        url = client.authorize_url( {
          scope: 'read_write',
          stripe_landing: 'register',
          stripe_user: {
            email: user.email
          }
        }.merge( params ) )

        [ url, nil ]
      end

      # A simple OAuth2 client we can use to generate a URL
      # to redirect the user to as well as get an access token.
      # Used in #oauth_url and #verify!
      # see this docs https://github.com/intridea/oauth2
      def client
        @client ||= OAuth2::Client.new(
          ENV['STRIPE_CONNECT_CLIENT_ID'],
          Stripe.api_key,
          {
            site: 'https://connect.stripe.com',
            authorize_url: '/oauth/authorize',
            token_url: '/oauth/token'
          }
        ).auth_code
      end

    end
</code>```

The terminal says;

Started GET "/connect/oauth" for ::1 at 2017-07-09 00:37:55 +0800
Processing by StripeController#oauth as HTML
  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
Redirected to https://connect.stripe.com/oauth/authorize?client_id=ca_AuidWGx68TXWlWO3d3UbWcRcuPqfSeNH&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fconnect%2Fconfirm&response_type=code&scope=read_write&stripe_landing=register&stripe_user%5Bemail%5D=aaa%40gmail.com

so I think I get the right url here (same as the tutorial video gets). However, in Chrome, it actually goes to;

https://connect.stripe.com/login?redirect=%2Foauth%2Fauthorize%3Fclient_id%3Dca_AuidWGx68TXWlWO3d3UbWcRcuPqfSeNH%26redirect_uri%3Dhttp%253A%252F%252Flocalhost%253A3000%252Fconnect%252Fconfirm%26response_type%3Dcode%26scope%3Dread_write%26stripe_landing%3Dregister%26stripe_user%255Bemail%255D%3Daaa%2540gmail.com&force_login=true

Sorry for the poor explanation but it would be great if anyone can solve this mystery. Thanks a lot!

答:
Nothing has changed about this recently according to Stripe's docs:

https://stripe.com/docs/connect/oauth-reference#get-authorize-request

You can test this by opening this example link:

https://connect.stripe.com/oauth/authorize?response_type=code&client_id=ca_32D88BD1qLklliziD7gYQvctJIhWBSQ7&scope=read_write&stripe_landing=register

Title: Stripe landing page setting not working

Body:
I'm currently taking an online course to make an airbnb like web application with ruby on rails. It utilizes Stripe for the payment and I want to make the landing page from my app to the Stripe a register page instead of a login page.

I'm completely following the tutorial that successfully makes the register page as the landing page with the below code.

stripe_landing: 'register'

But my landing page is still the login page. I googled the above code but all I could find was pages from 2-4 years ago. I wonder if Stripe changed it recently. (but hpar replied saying nothing has changed)

I put the whole code here... When I click the link to Stripe, it goes to stripe#oauth.

    class StripeController < ApplicationController
      # Connect yourself to a Stripe account.
      # Only works on the currently logged in user.
      # See app/services/stripe_oauth.rb for #oauth_url details.

      def oauth
        connector = StripeOauth.new( current_user )
        url, error = connector.oauth_url( redirect_uri: stripe_confirm_url )

        if url.nil?
          flash[:error] = error
          redirect_to manage_listing_payment_path( session[:listing_id] )
        else
          redirect_to url
        end
      end

    end

then,

    class StripeOauth < Struct.new( :user )

      def oauth_url( params )
        url = client.authorize_url( {
          scope: 'read_write',
          stripe_landing: 'register',
          stripe_user: {
            email: user.email
          }
        }.merge( params ) )

        [ url, nil ]
      end

      # A simple OAuth2 client we can use to generate a URL
      # to redirect the user to as well as get an access token.
      # Used in #oauth_url and #verify!
      # see this docs https://github.com/intridea/oauth2
      def client
        @client ||= OAuth2::Client.new(
          ENV['STRIPE_CONNECT_CLIENT_ID'],
          Stripe.api_key,
          {
            site: 'https://connect.stripe.com',
            authorize_url: '/oauth/authorize',
            token_url: '/oauth/token'
          }
        ).auth_code
      end

    end

The terminal says;

Started GET "/connect/oauth" for ::1 at 2017-07-09 00:37:55 +0800
Processing by StripeController#oauth as HTML
  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
Redirected to https://connect.stripe.com/oauth/authorize?client_id=ca_AuidWGx68TXWlWO3d3UbWcRcuPqfSeNH&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fconnect%2Fconfirm&response_type=code&scope=read_write&stripe_landing=register&stripe_user%5Bemail%5D=aaa%40gmail.com

so I think I get the right url here (same as the tutorial video gets). However, in Chrome, it actually goes to;

https://connect.stripe.com/login?redirect=%2Foauth%2Fauthorize%3Fclient_id%3Dca_AuidWGx68TXWlWO3d3UbWcRcuPqfSeNH%26redirect_uri%3Dhttp%253A%252F%252Flocalhost%253A3000%252Fconnect%252Fconfirm%26response_type%3Dcode%26scope%3Dread_write%26stripe_landing%3Dregister%26stripe_user%255Bemail%255D%3Daaa%2540gmail.com&force_login=true

Sorry for the poor explanation but it would be great if anyone can solve this mystery. Thanks a lot!


问:
Junit test case for database insert method with DAO and web service
I am implementing a webservice based university management system. This system adds certain courses to database. here below is the code that I am using.

Course.java

```<code>public class Course {

    private String courseName;
    private String location;
    private String courseId;

       public String getCourseId()
               {
        return courseId;
            }

    public void setCourseId(String courseId) {
        this.courseId = courseId;
    }

    public String getCourseName() {
        return courseName;
    }

    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }

        public String getLocation() {
        return location;
    }
    public void setLocation(String location) {
        this.location = location;
    }
}
</code>```

then another file is as below

CourseDaoImpl.java

```<code>public class CourseDaoImpl implements IDao {
   Connection conn = null;
   Statement stmt = null;

public CourseDaoImpl(){

try {
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    conn = DriverManager.getConnection(
            "jdbc:mysql://localhost:3306/univesitydb", "root", "root");
    stmt = conn.createStatement();

    if (!conn.isClosed())
        System.out.println("Successfully connectiod");
} catch (SQLException e) {
    e.printStackTrace();
} catch (InstantiationException e) {
    e.printStackTrace();
} catch (IllegalAccessException e) {
    e.printStackTrace();
} catch (ClassNotFoundException e) {
    e.printStackTrace();
}
}

      @Override
  public String add(Object object) {

Course c = (Course) object ;

String courseId = c.getCourseId();
String courseName = c.getCourseName();
String location = c.getLocation();

String result = "";
int rowcount;

try {
    String query = "Insert into course (courseId,courseName,location) values"
            + " ('"
            + courseId
            + "', '"
            + courseName
            + "', '"
            + location
            + "')";
    rowcount = stmt.executeUpdate(query);
    if (rowcount > 0) {
        result = "true";
        System.out.println("Course inserted successful");
    } else {
        result = "false:The data could not be inserted in the databse";
    }
} catch (SQLException e) {
    e.printStackTrace();
}

return result;
}
</code>```

the third is the Web service file as follows which interacts with the previous two and adds data to database.

CourseService.java

```<code>package edu.service;

          import edu.dao.IDao;
          import edu.dao.impl.CourseDaoImpl;
          import edu.db.entity.Course;

       public class CourseService {

     public String addCourse(String courseId, String courseName, String location)
    {
       Course c = new Course();
       c.setCourseId(courseId);
       c.setCourseName(courseName);
       c.setLocation(location);
       IDao dao = new CourseDaoImpl();
       return dao.add(c);
     }
</code>```

Looking at my code listings can any body suggest me how do I write test case for my add method. I am totally beginner for JAVA, I took help from my friends to learn this java part and Now need to implement Junit test for my database methods like add course above.

Please suggest some thing that I can learn , read and use to implement Junit testing for my database methods.

答:
```<code>@Test
public void testSearchManagementStaff() throws SQLException
{
    boolean res=true;
    ManagementDaoImp mdi=new ManagementDaoImp();
    boolean b=mdi.searchManagementStaff("abc@gmail.com"," 123456");
    assertEquals(res,b);
}
</code>```

Body:
I am implementing a webservice based university management system. This system adds certain courses to database. here below is the code that I am using.

Course.java

public class Course {

    private String courseName;
    private String location;
    private String courseId;

       public String getCourseId()
               {
        return courseId;
            }

    public void setCourseId(String courseId) {
        this.courseId = courseId;
    }

    public String getCourseName() {
        return courseName;
    }

    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }

        public String getLocation() {
        return location;
    }
    public void setLocation(String location) {
        this.location = location;
    }
}

then another file is as below

CourseDaoImpl.java

public class CourseDaoImpl implements IDao {
   Connection conn = null;
   Statement stmt = null;

public CourseDaoImpl(){

try {
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    conn = DriverManager.getConnection(
            "jdbc:mysql://localhost:3306/univesitydb", "root", "root");
    stmt = conn.createStatement();

    if (!conn.isClosed())
        System.out.println("Successfully connectiod");
} catch (SQLException e) {
    e.printStackTrace();
} catch (InstantiationException e) {
    e.printStackTrace();
} catch (IllegalAccessException e) {
    e.printStackTrace();
} catch (ClassNotFoundException e) {
    e.printStackTrace();
}
}

      @Override
  public String add(Object object) {

Course c = (Course) object ;

String courseId = c.getCourseId();
String courseName = c.getCourseName();
String location = c.getLocation();

String result = "";
int rowcount;

try {
    String query = "Insert into course (courseId,courseName,location) values"
            + " ('"
            + courseId
            + "', '"
            + courseName
            + "', '"
            + location
            + "')";
    rowcount = stmt.executeUpdate(query);
    if (rowcount > 0) {
        result = "true";
        System.out.println("Course inserted successful");
    } else {
        result = "false:The data could not be inserted in the databse";
    }
} catch (SQLException e) {
    e.printStackTrace();
}

return result;
}

the third is the Web service file as follows which interacts with the previous two and adds data to database.

CourseService.java

package edu.service;

          import edu.dao.IDao;
          import edu.dao.impl.CourseDaoImpl;
          import edu.db.entity.Course;

       public class CourseService {

     public String addCourse(String courseId, String courseName, String location)
    {
       Course c = new Course();
       c.setCourseId(courseId);
       c.setCourseName(courseName);
       c.setLocation(location);
       IDao dao = new CourseDaoImpl();
       return dao.add(c);
     }

Looking at my code listings can any body suggest me how do I write test case for my add method. I am totally beginner for JAVA, I took help from my friends to learn this java part and Now need to implement Junit test for my database methods like add course above.

Please suggest some thing that I can learn , read and use to implement Junit testing for my database methods.

ContentLicense: CC BY-SA 4.0


问:
How to delete all events in MySQL
If I want to delete some event I need to query something like
"DROP EVENT IF EXISTS  eventname"
But I can't find the command of deleting all the events at one time,must delete event one by one.
Is there some SQL of deleting all events at one time?

```<code>"DROP EVENT IF EXISTS (SELECT EVENT_NAME FROM  information_schema.EVENTS)"
</code>```

is not working either.

答:
To construct a drop events query, you can do something like this:</p>

```<code>select concat('drop event if exists ', event_name, ';') from information_schema.events;
</code>```

Title: How to delete all events in MySQL

Body:
If I want to delete some event I need to query something like
"DROP EVENT IF EXISTS  eventname"
But I can't find the command of deleting all the events at one time,must delete event one by one.
Is there some SQL of deleting all events at one time?

"DROP EVENT IF EXISTS (SELECT EVENT_NAME FROM  information_schema.EVENTS)"

is not working either.

Body:
To construct a drop events query, you can do something like this:

select concat('drop event if exists ', event_name, ';') from information_schema.events;


问:
Downloading JSON file, but parsing displays unreadable characters
I'm trying to download a JSON file from a ParseHub API I created for a local website. If I type the URL into the browser, I get the JSON formatted and all.

But when downloading into my C# app, it just displays random, unreadable characters like in the following image:
Console app displaying the result of downloaded JSON

I tried downloading the page as a string:

Uri uri = new Uri(url); //url is the link to my API page
HttpClient wc = new HttpClient();

string json = await wc.GetStringAsync(uri);
```

During the debug sessions I see the unreadable characters that are downloaded and saved in the string json.

I tried the URL in "Postman", and it gives me: Postman Headers tab

Notice: it says Content-Encoding: gzip.

I think this may be the issue.

Any help is appreciated.

Thanks,
Andrew

答:
If it is gzip encoded then you can get the data as a stream instead and read it via a GZipStream

Also ideally you should use WebClient instead of HttpClient. I suspect making that change alone would be sufficient for it to automatically decompress.

Body:
I'm trying to download a JSON file from a ParseHub API I created for a local website. If I type the URL into the browser, I get the JSON formatted and all.

But when downloading into my C# app, it just displays random, unreadable characters like in the following image:
Console app displaying the result of downloaded JSON

I tried downloading the page as a string:

Uri uri = new Uri(url); //url is the link to my API page
HttpClient wc = new HttpClient();

string json = await wc.GetStringAsync(uri);

During the debug sessions I see the unreadable characters that are downloaded and saved in the string json.

I tried the URL in "Postman", and it gives me: Postman Headers tab

Notice: it says Content-Encoding: gzip.

I think this may be the issue.

Any help is appreciated.

Thanks,
Andrew


问:
How to find URLs in a string with PHP?
I know there is filter_var() but I don't want to validate a URL, I want to spot them in a whole text (e.g. a tweet). So you got any idea?

答:
Using a regex should take care of that.
This basically works for Twitter</p>

```<code>$text=$a_twitter_message;
preg_match_all("/http:\/\/(.*?)\/? /", $text, $link_match);
var_dump($link_match);
</code>```

ContentLicense: CC BY-SA 2.5

Title: How to find URLs in a string with PHP?

Body:
Using a regex should take care of that.
This basically works for Twitter

$text=$a_twitter_message;
preg_match_all("/http:\/\/(.*?)\/? /", $text, $link_match);
var_dump($link_match);


问:
IntelliJ not recognizing a particular file correctly, instead it's stuck as a text file
There is a freemarker file (ftl) in my IntelliJ project that is incorrectly recognized as a text file. There are many of the same type that are correct.

I am aware of the "Mark as text" option. This may be the original reason this file was marked as text but I am not provided with a "mark as ftl file" option to turn it back, if indeed this is the problem. If I mark other ftl files as txt, I am able to turn them back into ftl files as expected.

答:
I had the same problem to creat a new class java, the issue was on Header.java that can be access with the command crt+alt+s and go to Editor/FileAndCodeTemplates/Includes and this may be on this format:

/**
 * Created by Alex Leporoni on ${DATE}.
 */

This is solved my issue, now I can create classes again :)
I hope that this article can help others that have the same problems to creat classes on IntelliJIdea... hugs to all.


问:
How to get search button inside input field in mdbootstrap ?
Hi I trying to do the following for getting the search button inside the input field with class input-ol, but its not working. I am writing the following code.

```<code><form id="search_form" onsubmit="return false;">
                <div class="input-group">
                    <input type="text" class="input-ol" name="query" placeholder="Ex: cars, watches, exercise... "/>
                    <span class="input-group-btn" onclick="return searchcontent()">
                        <button class="btn btn-outline-primary" type="button" aria-label="Search">
                            <i class="fa fa-search fa-2x" aria-hidden="true"></i>
                        </button>
                    </span>
                </div>
</form>
</code>```

The output looks like this

答:
I think you need to add the class form-control to your input element to get it to work.

.input-group input.input-ol {
  border-radius: 50px;
}

button.rounded {
  border-radius: 10px 50px 50px 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<div class="row">
  <div class="col-lg-6">
    <form id="search_form" onsubmit="return false;">
      <div class="input-group">
        <input type="text" class="input-ol form-control" name="query" placeholder="Ex: cars, watches, exercise... " />
        <span class="input-group-btn" onclick="return searchcontent()">
          <button class="btn btn-outline-primary btn-primary rounded" type="button" aria-label="Search">
            <i class="fa fa-search" aria-hidden="true"></i>
           </button>
         </span>
      </div>
    </form>
  </div>
</div></code>```

I also removed the class fa-2x from the icon element just to make the snippet work, but if you have additional styles that make the larger button work with your input field you probably won't have to remove that class.

Body:
Hi I trying to do the following for getting the search button inside the input field with class input-ol, but its not working. I am writing the following code.

<form id="search_form" onsubmit="return false;">

                    <input type="text" class="input-ol" name="query" placeholder="Ex: cars, watches, exercise... "/>

                        <button class="btn btn-outline-primary" type="button" aria-label="Search">

                        </button>

</form>

The output looks like this

Body:
I think you need to add the class form-control to your input element to get it to work.

.input-group input.input-ol {
  border-radius: 50px;
}

button.rounded {
  border-radius: 10px 50px 50px 10px;
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<div class="row">
  <div class="col-lg-6">
    <form id="search_form" onsubmit="return false;">
      <div class="input-group">
        <input type="text" class="input-ol form-control" name="query" placeholder="Ex: cars, watches, exercise... " />
        <span class="input-group-btn" onclick="return searchcontent()">
          <button class="btn btn-outline-primary btn-primary rounded" type="button" aria-label="Search">
            <i class="fa fa-search" aria-hidden="true"></i>
           </button>
         </span>
      </div>
    </form>
  </div>
</div>

I also removed the class fa-2x from the icon element just to make the snippet work, but if you have additional styles that make the larger button work with your input field you probably won't have to remove that class.


问:
How to get job execution time from sidekiq?
I'd like to know execution time every time I run my jobs. Seems like there is a gem sidekiq-statistic that does what I want and even has GUI, but unfortunately it doesn't work with sidekiq 5. Can I get such info from inside perform method somehow? I'd prefer to avoid writing benchmarking code manually, wrapping up my method into Benchmark block

答: You can scrape it from the log output.</p>

Body: You can scrape it from the log output.


问:
Intellij Idea hint: Condition is always false - can that be true here? (Java)
I have the following code:

```<code>public String testExitPoints() {
    boolean myBoolean = false;
    try {
        if (getBoolean()) {
            return "exit 1";
        }
        if (getBoolean()) {
            throw new RuntimeException();
        }
    } finally {
        myBoolean = true;
    }
    if (getBoolean()) {
        return "exit 2";
    }
    return "exit 3";
}

public static boolean getBoolean() {
    Random rand = new Random();
    return rand.nextInt() > 100;
}
</code>```

Now IntelliJ idea gives me for the second and third invocation of getBoolean() the following hint:

```<code>Condition 'getBoolean()' is always 'false'
</code>```

Now to my understanding, that is not true, since getBoolean() can either be true or false, depending on the generated random value. Am I missing something here, or is that a bug in IntelliJ Idea?

答: In my case if I you use MY_ACTUAL_CLASS_NAME.getBoolean() it does not complain (since the method is static). May be it is because IntelliJ Idea does not take static into account (a possible bug here)</p>

Body:
I have the following code:

public String testExitPoints() {
    boolean myBoolean = false;
    try {
        if (getBoolean()) {
            return "exit 1";
        }
        if (getBoolean()) {
            throw new RuntimeException();
        }
    } finally {
        myBoolean = true;
    }
    if (getBoolean()) {
        return "exit 2";
    }
    return "exit 3";
}

public static boolean getBoolean() {
    Random rand = new Random();
    return rand.nextInt() > 100;
}

Now IntelliJ idea gives me for the second and third invocation of getBoolean() the following hint:

Condition 'getBoolean()' is always 'false'

Now to my understanding, that is not true, since getBoolean() can either be true or false, depending on the generated random value. Am I missing something here, or is that a bug in IntelliJ Idea?


问:
Invalid parameter number: parameter was not defined in {path}
Here is my query:

```<code>SELECT qa.id,
       qa.subject,
       qa.category cat,
       qa.keywords tags,
       qa.body_html,
       qa.amount,
       qa.author_id author,
       qa.visibility,
       qa.date_time,
       COALESCE(u.reputation, 'N') reputation,
       COALESCE(CONCAT(u.user_fname, ' ', u.user_lname), 'ناشناس') name,
       COALESCE(u.avatar, 'anonymous.png') avatar,

  (SELECT COALESCE(sum(vv.value),0)
   FROM votes vv
   WHERE qa.id = vv.post_id
     AND 15 = vv.table_code) AS total_votes,

  (SELECT COALESCE(sum(vt.total_viewed),0)
   FROM viewed_total vt
   WHERE qa.id = vt.post_id
     AND 15 = vt.table_code
   LIMIT 1) AS total_viewed
FROM qanda qa
INNER JOIN qanda_tags qt ON qt.qanda_id = qa.id
INNER JOIN tags ON tags.id = qt.tag_id
LEFT JOIN users u ON qa.author_id = u.id
AND qa.visibility = 1
WHERE qa.type = 0
  AND tags.name = :t
ORDER BY total_votes DESC,
         qa.id DESC
LIMIT :j,
      11;
</code>```

And this is print_r() the result of parameters' array: (which I pass it to the query as execute() argument)

```<code>Array ( [:t] => برچسب1 [:j] => 0 )
</code>```

And when I execute the query, it throws this error:

Fatal error: Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in C:\xampp\htdocs\myweb\others\questions.php:140 Stack trace: #0 C:\xampp\htdocs\myweb\others\questions.php(140): PDOStatement->execute(Array) #1 C:\xampp\htdocs\myweb\application\other.php(21): questions->index() #2 C:\xampp\htdocs\myweb\index.php(149): require_once('C:\xampp\htdocs...') #3 {main} thrown in C:\xampp\htdocs\myweb\others\questions.php on line 140

Can anybody find the problem? It's 1 hour I'm staring at it, and it seems fine to me.

答:
You should use  </p>

```<code> array( ':t' => برچسب1 ':j' => 0 )
</code>```

Body:
Here is my query:

SELECT qa.id,
       qa.subject,
       qa.category cat,
       qa.keywords tags,
       qa.body_html,
       qa.amount,
       qa.author_id author,
       qa.visibility,
       qa.date_time,
       COALESCE(u.reputation, 'N') reputation,
       COALESCE(CONCAT(u.user_fname, ' ', u.user_lname), 'ناشناس') name,
       COALESCE(u.avatar, 'anonymous.png') avatar,

  (SELECT COALESCE(sum(vv.value),0)
   FROM votes vv
   WHERE qa.id = vv.post_id
     AND 15 = vv.table_code) AS total_votes,

  (SELECT COALESCE(sum(vt.total_viewed),0)
   FROM viewed_total vt
   WHERE qa.id = vt.post_id
     AND 15 = vt.table_code
   LIMIT 1) AS total_viewed
FROM qanda qa
INNER JOIN qanda_tags qt ON qt.qanda_id = qa.id
INNER JOIN tags ON tags.id = qt.tag_id
LEFT JOIN users u ON qa.author_id = u.id
AND qa.visibility = 1
WHERE qa.type = 0
  AND tags.name = :t
ORDER BY total_votes DESC,
         qa.id DESC
LIMIT :j,
      11;

And this is print_r() the result of parameters' array: (which I pass it to the query as execute() argument)

Array ( [:t] => برچسب1 [:j] => 0 )

And when I execute the query, it throws this error:

Fatal error: Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in C:\xampp\htdocs\myweb\others\questions.php:140 Stack trace: #0 C:\xampp\htdocs\myweb\others\questions.php(140): PDOStatement->execute(Array) #1 C:\xampp\htdocs\myweb\application\other.php(21): questions->index() #2 C:\xampp\htdocs\myweb\index.php(149): require_once('C:\xampp\htdocs...') #3 {main} thrown in C:\xampp\htdocs\myweb\others\questions.php on line 140

Can anybody find the problem? It's 1 hour I'm staring at it, and it seems fine to me.

Body:
You should use

 array( ':t' => برچسب1 ':j' => 0 )


问:
Combinations and Permutations in F#
I've recently written the following combinations and permutations functions for an F# project, but I'm quite aware they're far from optimised.

```<code>/// Rotates a list by one place forward.
let rotate lst =
    List.tail lst @ [List.head lst]

/// Gets all rotations of a list.
let getRotations lst =
    let rec getAll lst i = if i = 0 then [] else lst :: (getAll (rotate lst) (i - 1))
    getAll lst (List.length lst)

/// Gets all permutations (without repetition) of specified length from a list.
let rec getPerms n lst =
    match n, lst with
    | 0, _ -> seq [[]]
    | _, [] -> seq []
    | k, _ -> lst |> getRotations |> Seq.collect (fun r -> Seq.map ((@) [List.head r]) (getPerms (k - 1) (List.tail r)))

/// Gets all permutations (with repetition) of specified length from a list.
let rec getPermsWithRep n lst =
    match n, lst with
    | 0, _ -> seq [[]]
    | _, [] -> seq []
    | k, _ -> lst |> Seq.collect (fun x -> Seq.map ((@) [x]) (getPermsWithRep (k - 1) lst))
    // equivalent: | k, _ -> lst |> getRotations |> Seq.collect (fun r -> List.map ((@) [List.head r]) (getPermsWithRep (k - 1) r))

/// Gets all combinations (without repetition) of specified length from a list.
let rec getCombs n lst =
    match n, lst with
    | 0, _ -> seq [[]]
    | _, [] -> seq []
    | k, (x :: xs) -> Seq.append (Seq.map ((@) [x]) (getCombs (k - 1) xs)) (getCombs k xs)

/// Gets all combinations (with repetition) of specified length from a list.
let rec getCombsWithRep n lst =
    match n, lst with
    | 0, _ -> seq [[]]
    | _, [] -> seq []
    | k, (x :: xs) -> Seq.append (Seq.map ((@) [x]) (getCombsWithRep (k - 1) lst)) (getCombsWithRep k xs)
</code>```

Does anyone have any suggestions for how these functions (algorithms) can be sped up? I'm particularly interested in how the permutation (with and without repetition) ones can be improved. The business involving rotations of lists doesn't look too efficient to me in retrospect.

Update

Here's my new implementation for the getPerms function, inspired by Tomas's answer.

Unfortunately, it's not really any fast than the existing one. Suggestions?

```<code>let getPerms n lst =
    let rec getPermsImpl acc n lst = seq {
        match n, lst with
        | k, x :: xs ->
            if k > 0 then
                for r in getRotations lst do
                    yield! getPermsImpl (List.head r :: acc) (k - 1) (List.tail r)
            if k >= 0 then yield! getPermsImpl acc k []
        | 0, [] -> yield acc
        | _, [] -> ()
        }
    getPermsImpl List.empty n lst
</code>```

答:
I noticed that your updated getPerms function contains duplicates. Here's my crack at a dupe-free version. Hopefully the comments speak for themselves. The hardest part was writing an efficient distrib function, because the concatenation operator has to be used somewhere. Luckily it's only used on small sublists, so the performance remains reasonable. My getAllPerms code below generates all permutations of [1..9] in around a quarter of a second, all 10-element permutations in around 2.5 seconds.

Edit: funny, I didn't look at Tomas' code, but his combinations function and my picks function are nearly identical.

```<code>// All ordered picks {x_i1, x_i2, .. , x_ik} of k out of n elements {x_1,..,x_n}
// where i1 < i2 < .. < ik
let picks n L =
    let rec aux nleft acc L = seq {
        match nleft,L with
        | 0,_ -> yield acc
        | _,[] -> ()
        | nleft,h::t -> yield! aux (nleft-1) (h::acc) t
                        yield! aux nleft acc t }
    aux n [] L

// Distribute an element y over a list:
// {x1,..,xn} --> {y,x1,..,xn}, {x1,y,x2,..,xn}, .. , {x1,..,xn,y}
let distrib y L =
    let rec aux pre post = seq {
        match post with
        | [] -> yield (L @ [y])
        | h::t -> yield (pre @ y::post)
                  yield! aux (pre @ [h]) t }
    aux [] L

// All permutations of a single list = the head of a list distributed
// over all permutations of its tail
let rec getAllPerms = function
    | [] -> Seq.singleton []
    | h::t -> getAllPerms t |> Seq.collect (distrib h)

// All k-element permutations out of n elements =
// all permutations of all ordered picks of length k combined
let getPerms2 n lst = picks n lst |> Seq.collect getAllPerms
</code>```

Edit: more code in response to comments

```<code>// Generates the cartesian outer product of a list of sequences LL
let rec outerProduct = function
    | [] -> Seq.singleton []
    | L::Ls -> L |> Seq.collect (fun x ->
                outerProduct Ls |> Seq.map (fun L -> x::L))

// Generates all n-element combination from a list L
let getPermsWithRep2 n L =
    List.replicate n L |> outerProduct
</code>```

Title: Combinations and Permutations in F#

Body:
I've recently written the following combinations and permutations functions for an F# project, but I'm quite aware they're far from optimised.

/// Rotates a list by one place forward.
let rotate lst =
    List.tail lst @ [List.head lst]

/// Gets all rotations of a list.
let getRotations lst =
    let rec getAll lst i = if i = 0 then [] else lst :: (getAll (rotate lst) (i - 1))
    getAll lst (List.length lst)

/// Gets all permutations (without repetition) of specified length from a list.
let rec getPerms n lst =
    match n, lst with
    | 0, _ -> seq [[]]
    | _, [] -> seq []
    | k, _ -> lst |> getRotations |> Seq.collect (fun r -> Seq.map ((@) [List.head r]) (getPerms (k - 1) (List.tail r)))

/// Gets all permutations (with repetition) of specified length from a list.
let rec getPermsWithRep n lst =
    match n, lst with
    | 0, _ -> seq [[]]
    | _, [] -> seq []
    | k, _ -> lst |> Seq.collect (fun x -> Seq.map ((@) [x]) (getPermsWithRep (k - 1) lst))
    // equivalent: | k, _ -> lst |> getRotations |> Seq.collect (fun r -> List.map ((@) [List.head r]) (getPermsWithRep (k - 1) r))

/// Gets all combinations (without repetition) of specified length from a list.
let rec getCombs n lst =
    match n, lst with
    | 0, _ -> seq [[]]
    | _, [] -> seq []
    | k, (x :: xs) -> Seq.append (Seq.map ((@) [x]) (getCombs (k - 1) xs)) (getCombs k xs)

/// Gets all combinations (with repetition) of specified length from a list.
let rec getCombsWithRep n lst =
    match n, lst with
    | 0, _ -> seq [[]]
    | _, [] -> seq []
    | k, (x :: xs) -> Seq.append (Seq.map ((@) [x]) (getCombsWithRep (k - 1) lst)) (getCombsWithRep k xs)

Does anyone have any suggestions for how these functions (algorithms) can be sped up? I'm particularly interested in how the permutation (with and without repetition) ones can be improved. The business involving rotations of lists doesn't look too efficient to me in retrospect.

Update

Here's my new implementation for the getPerms function, inspired by Tomas's answer.

Unfortunately, it's not really any fast than the existing one. Suggestions?

let getPerms n lst =
    let rec getPermsImpl acc n lst = seq {
        match n, lst with
        | k, x :: xs ->
            if k > 0 then
                for r in getRotations lst do
                    yield! getPermsImpl (List.head r :: acc) (k - 1) (List.tail r)
            if k >= 0 then yield! getPermsImpl acc k []
        | 0, [] -> yield acc
        | _, [] -> ()
        }
    getPermsImpl List.empty n lst

Body:
I noticed that your updated getPerms function contains duplicates. Here's my crack at a dupe-free version. Hopefully the comments speak for themselves. The hardest part was writing an efficient distrib function, because the concatenation operator has to be used somewhere. Luckily it's only used on small sublists, so the performance remains reasonable. My getAllPerms code below generates all permutations of [1..9] in around a quarter of a second, all 10-element permutations in around 2.5 seconds.

Edit: funny, I didn't look at Tomas' code, but his combinations function and my picks function are nearly identical.

// All ordered picks {x_i1, x_i2, .. , x_ik} of k out of n elements {x_1,..,x_n}
// where i1 < i2 < .. < ik
let picks n L =
    let rec aux nleft acc L = seq {
        match nleft,L with
        | 0,_ -> yield acc
        | _,[] -> ()
        | nleft,h::t -> yield! aux (nleft-1) (h::acc) t
                        yield! aux nleft acc t }
    aux n [] L

// Distribute an element y over a list:
// {x1,..,xn} --> {y,x1,..,xn}, {x1,y,x2,..,xn}, .. , {x1,..,xn,y}
let distrib y L =
    let rec aux pre post = seq {
        match post with
        | [] -> yield (L @ [y])
        | h::t -> yield (pre @ y::post)
                  yield! aux (pre @ [h]) t }
    aux [] L

// All permutations of a single list = the head of a list distributed
// over all permutations of its tail
let rec getAllPerms = function
    | [] -> Seq.singleton []
    | h::t -> getAllPerms t |> Seq.collect (distrib h)

// All k-element permutations out of n elements =
// all permutations of all ordered picks of length k combined
let getPerms2 n lst = picks n lst |> Seq.collect getAllPerms

Edit: more code in response to comments

// Generates the cartesian outer product of a list of sequences LL
let rec outerProduct = function
    | [] -> Seq.singleton []
    | L::Ls -> L |> Seq.collect (fun x ->
                outerProduct Ls |> Seq.map (fun L -> x::L))

// Generates all n-element combination from a list L
let getPermsWithRep2 n L =
    List.replicate n L |> outerProduct


问:
How to stream output from a continous view in pipelinedb?
I have setup pipelinedb and it works great! I would like to know if its possible to stream data out of a continuous view after the value in the view has been updated? That is, have some external process act on changes to a view.

I wish to stream metrics generated from the views into a dashboard, and I do not want to use polling the db to achieve this.

答:
As of 0.9.5, continuous triggers have been removed in favour of using output streams and continuous transforms. (First suggested by DidacticTactic). The output of a continuous view is essentially a stream, which means you can create continuous views or transforms based on it.

Simple Example:

First create a stream and continuous view.

CREATE STREAM s (
    x int
);

CREATE CONTINUOUS VIEW hourly_cv AS
    SELECT
        hour(arrival_timestamp) AS ts,
        SUM(x) AS sum
    FROM s GROUP BY ts;
```

<ol start="2">
<li>Every continuous view now has a output stream. You can create a transform based on the output of the view using <code>output_of</code>. In the transform you have access to the tuples <code>old</code> and <code>new</code> which represent the old values and new values respectively. (0.9.7 has a third called <code>delta</code>) So you can create a transform that uses the output of 'hourly_cv' like so:</li>
</ol>

<pre class="lang-sql prettyprint-override"><code>CREATE CONTINUOUS TRANSFORM hourly_ct AS
    SELECT
        (new).sum
    FROM output_of('hourly_cv')
    THEN EXECUTE PROCEDURE update();
</code>```

In this example I'm calling update which we still need to define. It needs to be a function that returns a trigger.

CREATE OR REPLACE FUNCTION update()
    RETURNS trigger AS
    $$
    BEGIN
        // Do anything you want here.
        RETURN NEW;
    END;
    $$
    LANGUAGE plpgsql;
```

I found the 0.9.5 release notes blog post helpful to understand output streams and why continuous triggers are no more.

Body:
As of 0.9.5, continuous triggers have been removed in favour of using output streams and continuous transforms. (First suggested by DidacticTactic). The output of a continuous view is essentially a stream, which means you can create continuous views or transforms based on it.

Simple Example:

First create a stream and continuous view.

CREATE STREAM s (
    x int
);

CREATE CONTINUOUS VIEW hourly_cv AS
    SELECT
        hour(arrival_timestamp) AS ts,
        SUM(x) AS sum
    FROM s GROUP BY ts;

Every continuous view now has a output stream. You can create a transform based on the output of the view using output_of. In the transform you have access to the tuples old and new which represent the old values and new values respectively. (0.9.7 has a third called delta) So you can create a transform that uses the output of 'hourly_cv' like so:

CREATE CONTINUOUS TRANSFORM hourly_ct AS
    SELECT
        (new).sum
    FROM output_of('hourly_cv')
    THEN EXECUTE PROCEDURE update();

In this example I'm calling update which we still need to define. It needs to be a function that returns a trigger.

CREATE OR REPLACE FUNCTION update()
    RETURNS trigger AS
    $$
    BEGIN
        // Do anything you want here.
        RETURN NEW;
    END;
    $$
    LANGUAGE plpgsql;

I found the 0.9.5 release notes blog post helpful to understand output streams and why continuous triggers are no more.


问:
How to separate an array of hashes into different arrays if a key is equal?
I've got an array of hashes in the following form:

```<code>{"user_id"=>2, "user_name"=>"Pepo", "beneficiary_document"=>"43991028", "calification_by_qualifier"=>5.0}
{"user_id"=>2, "user_name"=>"Pepo", "beneficiary_document"=>"71730550", "calification_by_qualifier"=>3.8499999999999996}
{"user_id"=>3, "user_name"=>"Carlos", "beneficiary_document"=>"43991028", "calification_by_qualifier"=>0.0}
{"user_id"=>3, "user_name"=>"Carlos", "beneficiary_document"=>"71730550", "calification_by_qualifier"=>3.4}
</code>```

basically i want to separate that array into arrays that contain the same value for the key beneficiary_document, so for this example i'd expect two arrays, one containing:

```<code>{"user_id"=>2, "user_name"=>"Pepo", "beneficiary_document"=>"43991028", "calification_by_qualifier"=>5.0}
{"user_id"=>3, "user_name"=>"Carlos", "beneficiary_document"=>"43991028", "calification_by_qualifier"=>0.0}
</code>```

and another one containing

```<code>{"user_id"=>3, "user_name"=>"Carlos", "beneficiary_document"=>"71730550", "calification_by_qualifier"=>3.4}
{"user_id"=>2, "user_name"=>"Pepo", "beneficiary_document"=>"71730550", "calification_by_qualifier"=>3.8499999999999996}
</code>```

How can i grant this?

Thanks a lot for reading.

答:
Given:

```<code>tst=[
{"user_id"=>2, "user_name"=>"Pepo", "beneficiary_document"=>"43991028", "calification_by_qualifier"=>5.0},
{"user_id"=>2, "user_name"=>"Pepo", "beneficiary_document"=>"71730550", "calification_by_qualifier"=>3.84},
{"user_id"=>3, "user_name"=>"Carlos", "beneficiary_document"=>"43991028", "calification_by_qualifier"=>0.0},
{"user_id"=>3, "user_name"=>"Carlos", "beneficiary_document"=>"71730550", "calification_by_qualifier"=>3.4}
]
</code>```

You can use .group_by to get a hash of elements by key. In this case, use the key ["beneficiary_document"] passed to the block and you will get a hash of arrays by that key -- two in this case.

You can do:

```<code>tst.group_by { |h| h["beneficiary_document"] }
# {"43991028"=>[{"user_id"=>2, "user_name"=>"Pepo", "beneficiary_document"=>"43991028", "calification_by_qualifier"=>5.0}, {"user_id"=>3, "user_name"=>"Carlos", "beneficiary_document"=>"43991028", "calification_by_qualifier"=>0.0}], "71730550"=>[{"user_id"=>2, "user_name"=>"Pepo", "beneficiary_document"=>"71730550", "calification_by_qualifier"=>3.84}, {"user_id"=>3, "user_name"=>"Carlos", "beneficiary_document"=>"71730550", "calification_by_qualifier"=>3.4}]}
</code>```

To see it pretty printed:

```<code>require "pp"
PP.pp(tst.group_by {|h| h["beneficiary_document"] },$>,120)
{"43991028"=>
  [{"user_id"=>2, "user_name"=>"Pepo", "beneficiary_document"=>"43991028", "calification_by_qualifier"=>5.0},
   {"user_id"=>3, "user_name"=>"Carlos", "beneficiary_document"=>"43991028", "calification_by_qualifier"=>0.0}],
 "71730550"=>
  [{"user_id"=>2, "user_name"=>"Pepo", "beneficiary_document"=>"71730550", "calification_by_qualifier"=>3.84},
   {"user_id"=>3, "user_name"=>"Carlos", "beneficiary_document"=>"71730550", "calification_by_qualifier"=>3.4}]}
</code>```

You can also achieve the same result with a hash that returns an array as a default procedure, then call .map over tst and push the hash into the array by that key:

```<code>h=Hash.new { |h,k| h[k]=[] }
tst.map { |eh| h[eh["beneficiary_document"]].push(eh) }
</code>```

Or, combine that into a single statement:

```<code>tst.each_with_object(Hash.new { |h,k| h[k]=[] }) { |g,h|
    h[g["beneficiary_document"]].push(g)}
</code>```

All three methods create identical hashes. The first, .group_by, is the easiest.

Body:
I've got an array of hashes in the following form:

{"user_id"=>2, "user_name"=>"Pepo", "beneficiary_document"=>"43991028", "calification_by_qualifier"=>5.0}
{"user_id"=>2, "user_name"=>"Pepo", "beneficiary_document"=>"71730550", "calification_by_qualifier"=>3.8499999999999996}
{"user_id"=>3, "user_name"=>"Carlos", "beneficiary_document"=>"43991028", "calification_by_qualifier"=>0.0}
{"user_id"=>3, "user_name"=>"Carlos", "beneficiary_document"=>"71730550", "calification_by_qualifier"=>3.4}

basically i want to separate that array into arrays that contain the same value for the key beneficiary_document, so for this example i'd expect two arrays, one containing:

{"user_id"=>2, "user_name"=>"Pepo", "beneficiary_document"=>"43991028", "calification_by_qualifier"=>5.0}
{"user_id"=>3, "user_name"=>"Carlos", "beneficiary_document"=>"43991028", "calification_by_qualifier"=>0.0}

and another one containing

{"user_id"=>3, "user_name"=>"Carlos", "beneficiary_document"=>"71730550", "calification_by_qualifier"=>3.4}
{"user_id"=>2, "user_name"=>"Pepo", "beneficiary_document"=>"71730550", "calification_by_qualifier"=>3.8499999999999996}

How can i grant this?

Thanks a lot for reading.

Body:
Given:

tst=[
{"user_id"=>2, "user_name"=>"Pepo", "beneficiary_document"=>"43991028", "calification_by_qualifier"=>5.0},
{"user_id"=>2, "user_name"=>"Pepo", "beneficiary_document"=>"71730550", "calification_by_qualifier"=>3.84},
{"user_id"=>3, "user_name"=>"Carlos", "beneficiary_document"=>"43991028", "calification_by_qualifier"=>0.0},
{"user_id"=>3, "user_name"=>"Carlos", "beneficiary_document"=>"71730550", "calification_by_qualifier"=>3.4}
]

You can use .group_by to get a hash of elements by key. In this case, use the key ["beneficiary_document"] passed to the block and you will get a hash of arrays by that key -- two in this case.

You can do:

tst.group_by { |h| h["beneficiary_document"] }
# {"43991028"=>[{"user_id"=>2, "user_name"=>"Pepo", "beneficiary_document"=>"43991028", "calification_by_qualifier"=>5.0}, {"user_id"=>3, "user_name"=>"Carlos", "beneficiary_document"=>"43991028", "calification_by_qualifier"=>0.0}], "71730550"=>[{"user_id"=>2, "user_name"=>"Pepo", "beneficiary_document"=>"71730550", "calification_by_qualifier"=>3.84}, {"user_id"=>3, "user_name"=>"Carlos", "beneficiary_document"=>"71730550", "calification_by_qualifier"=>3.4}]}

To see it pretty printed:

require "pp"
PP.pp(tst.group_by {|h| h["beneficiary_document"] },$>,120)
{"43991028"=>
  [{"user_id"=>2, "user_name"=>"Pepo", "beneficiary_document"=>"43991028", "calification_by_qualifier"=>5.0},
   {"user_id"=>3, "user_name"=>"Carlos", "beneficiary_document"=>"43991028", "calification_by_qualifier"=>0.0}],
 "71730550"=>
  [{"user_id"=>2, "user_name"=>"Pepo", "beneficiary_document"=>"71730550", "calification_by_qualifier"=>3.84},
   {"user_id"=>3, "user_name"=>"Carlos", "beneficiary_document"=>"71730550", "calification_by_qualifier"=>3.4}]}

You can also achieve the same result with a hash that returns an array as a default procedure, then call .map over tst and push the hash into the array by that key:

h=Hash.new { |h,k| h[k]=[] }
tst.map { |eh| h[eh["beneficiary_document"]].push(eh) }

Or, combine that into a single statement:

tst.each_with_object(Hash.new { |h,k| h[k]=[] }) { |g,h|
    h[g["beneficiary_document"]].push(g)}

All three methods create identical hashes. The first, .group_by, is the easiest.


问:
Is there a C++ equivalent to getcwd?
I see C's getcwd via:
man 3 cwd

I suspect C++ has a similar one, that could return me a std::string .

If so, what is it called, and where can I find it's documentation?

Thanks!

答:
You could create a new function, which I would prefer over linking to a library like boost(unless you already are).</p>

```<code> std::string getcwd()
 {
     char* buff;//automatically cleaned when it exits scope
     return std::string(getcwd(buff,255));
 }
</code>```

Title: Is there a C++ equivalent to getcwd?

Body:
You could create a new function, which I would prefer over linking to a library like boost(unless you already are).

 std::string getcwd()
 {
     char* buff;//automatically cleaned when it exits scope
     return std::string(getcwd(buff,255));
 }


问:
MS Access: Looping through subform records causes Error '3021'
I have a main form and a subform that displays several records. When a checkbox is checked on the main form, I want all "BoxLblTime" and "Material Arrived" fields on the subform to be updated. This is the vba code that is executed when the checkbox is clicked:

```<code>Private Sub MaterialArrived_chkbx_Click()
   Dim temp As Variant
   Dim tempString As String
   Dim ctl As Control

   'If checkbox is checked
   If Forms("JOBS Form").Controls("MaterialArrived_chkbx").Value < 0 Then

      Dim rs As Object
      'Get records of subform
      Set rs = Forms("JOBS Form").[Order Form].Form.Recordset
      'Loop until end
      Do While Not rs.EOF
        rs.Edit
        'Update the two fields
        rs![Material arrived] = True
        rs!BoxLblTime = Now()
        rs.Update
      rs.MoveNext
      Loop
      Set rs = Nothing
   End If
End Sub
</code>```

There is some unusual behavior when using this code:

1) When the checkbox on the main form is checked, the two fields are updated in the subform. But if I uncheck the checkbox on the subform and then recheck the main form checkbox, the subform checkbox stays unchecked.

2) When the checkbox on the main form is checked, the two fields are updated. But if I uncheck the checkbox on the subform, move to a new set of subform records (next or back) and then check the main form checkbox, I get the error: '3021' No current record.

Why is this unusual behavior happening?

EDIT:
Here is my code using the update query approach:

```<code>Private Sub MaterialArrived_chkbx_Click()
   If Forms("JOBS Form").Controls("MaterialArrived_chkbx").Value < 0 Then

      With CurrentDb().QueryDefs("Update Orders")
         .Parameters("[Material Arrived]").Value = True
         .Parameters("[BoxLblTime]").Value = Now()
         .Execute dbFailOnError
      End With
      Forms("JOBS Form").Form.Requery
   End If
End Sub
</code>```

But I'm getting "Item not found in collection" error.

答:
I would suggest an alternative approach.

Create an update query and pass a Boolean parameter indicating the material arrived value.

```<code>'Call update query
Private Sub MaterialArrived_chkbx_Click()
    With CurrentDb().QueryDefs("Update Orders")
        .Parameters("[prmMaterialArrived]").Value = Me.MaterialArrived_chkbx.Value
        .Parameters("[prmID]").Value = Me!ID
        .Execute dbFailOnError
    End With
    Me.[Order Form].Form.Requery
End Sub

'SQL
PARAMETERS [prmMaterialArrived] Bit, [prmID] Long;
UPDATE T
SET T.[Material arrived] = [prmMaterialArrived], T.BoxLblTime = Now()
WHERE (((T.ID)=[prmID]));
</code>```

Body:
I have a main form and a subform that displays several records. When a checkbox is checked on the main form, I want all "BoxLblTime" and "Material Arrived" fields on the subform to be updated. This is the vba code that is executed when the checkbox is clicked:

Private Sub MaterialArrived_chkbx_Click()
   Dim temp As Variant
   Dim tempString As String
   Dim ctl As Control

   'If checkbox is checked
   If Forms("JOBS Form").Controls("MaterialArrived_chkbx").Value < 0 Then

      Dim rs As Object
      'Get records of subform
      Set rs = Forms("JOBS Form").[Order Form].Form.Recordset
      'Loop until end
      Do While Not rs.EOF
        rs.Edit
        'Update the two fields
        rs![Material arrived] = True
        rs!BoxLblTime = Now()
        rs.Update
      rs.MoveNext
      Loop
      Set rs = Nothing
   End If
End Sub

There is some unusual behavior when using this code:

1) When the checkbox on the main form is checked, the two fields are updated in the subform. But if I uncheck the checkbox on the subform and then recheck the main form checkbox, the subform checkbox stays unchecked.

2) When the checkbox on the main form is checked, the two fields are updated. But if I uncheck the checkbox on the subform, move to a new set of subform records (next or back) and then check the main form checkbox, I get the error: '3021' No current record.

Why is this unusual behavior happening?

EDIT:
Here is my code using the update query approach:

Private Sub MaterialArrived_chkbx_Click()
   If Forms("JOBS Form").Controls("MaterialArrived_chkbx").Value < 0 Then

      With CurrentDb().QueryDefs("Update Orders")
         .Parameters("[Material Arrived]").Value = True
         .Parameters("[BoxLblTime]").Value = Now()
         .Execute dbFailOnError
      End With
      Forms("JOBS Form").Form.Requery
   End If
End Sub

But I'm getting "Item not found in collection" error.

Body:
I would suggest an alternative approach.

Create an update query and pass a Boolean parameter indicating the material arrived value.

'Call update query
Private Sub MaterialArrived_chkbx_Click()
    With CurrentDb().QueryDefs("Update Orders")
        .Parameters("[prmMaterialArrived]").Value = Me.MaterialArrived_chkbx.Value
        .Parameters("[prmID]").Value = Me!ID
        .Execute dbFailOnError
    End With
    Me.[Order Form].Form.Requery
End Sub

'SQL
PARAMETERS [prmMaterialArrived] Bit, [prmID] Long;
UPDATE T
SET T.[Material arrived] = [prmMaterialArrived], T.BoxLblTime = Now()
WHERE (((T.ID)=[prmID]));


问:
How to get JSON Object using Retrofit for Android
I'm using Android and DRF, Retrofit now.

I'm trying to get Django models using Retrofit, It returns JSON Response.

But in my model, there is multiple JSON Objects.

For example,

request url is [object1's url]

and

response =
{
object2:[object2's url],
some other data(s)
}

How can I change object2 to json object using Retrofit?

Edit

I solved this issue using multiple AsyncTask.
get Object1 and object2's url, and in onPostExecute, make some new AsyncTask, get Object2 by Retrofit, check Object2's url and Object2's list parameter 'url' and match.
for example,

```<code>AsyncTask() {
  doInBackground() {
    get object1List
  }
  onPostExecute(object1List) {
    AsyncTask2() {
      doInBackground() {
        get object2List
        for (object1 : object1List)
          object2ListItem & object1.url match
      }
      onPostExecute() {
        something to do
      }
    }
  }
}
</code>```

答:
i recommend you to receive the raw JSON and then parsing with GSON

```<code>private static Retrofit retrofit = null;
private static Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setLenient().create();

public static Retrofit getClient(String baseUrl) {
        if (retrofit==null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .client(httpClient.build())
                    .build();
        }
        return retrofit;
    }
</code>```

and create a class where got the expected information example

```<code>public class People{
    @Expose
    private String Name;
    @Expose
    private Int Age;
    @Expose
    private String Surname;

// setters and getters...
</code>```

the api interface

```<code>public interface APIService {
 @POST("people.php")
    Call<whatyoureceive> response();

}
</code>```

Also

```<code>private static final String BASE_URL = "YOUR URL";

public static APIService getAPIService() {

    return RetrofitClient.getClient(BASE_URL).create(APIService.class);
}
</code>```

In your activity

```<code>private APIService mAPIService;

mAPIService = ApiUtils.getAPIService();

public void sendRequest() {
        mAPIService.responseo().enqueue(new Callback<PlanDetails>() {
@Override
            public void onResponse(......) {
// what you want to do
}
@Override
            public void onFailure(.....) {
// what you want to do
}
</code>```

More information https://futurestud.io/tutorials/retrofit-getting-started-and-android-client

Hope help!

Body:
I'm using Android and DRF, Retrofit now.

I'm trying to get Django models using Retrofit, It returns JSON Response.

But in my model, there is multiple JSON Objects.

For example,

request url is [object1's url]

and

response =
{
object2:[object2's url],
some other data(s)
}

How can I change object2 to json object using Retrofit?

Edit

I solved this issue using multiple AsyncTask.
get Object1 and object2's url, and in onPostExecute, make some new AsyncTask, get Object2 by Retrofit, check Object2's url and Object2's list parameter 'url' and match.
for example,

AsyncTask() {
  doInBackground() {
    get object1List
  }
  onPostExecute(object1List) {
    AsyncTask2() {
      doInBackground() {
        get object2List
        for (object1 : object1List)
          object2ListItem & object1.url match
      }
      onPostExecute() {
        something to do
      }
    }
  }
}

Body:
i recommend you to receive the raw JSON and then parsing with GSON

private static Retrofit retrofit = null;
private static Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setLenient().create();

public static Retrofit getClient(String baseUrl) {
        if (retrofit==null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .client(httpClient.build())
                    .build();
        }
        return retrofit;
    }

and create a class where got the expected information example

public class People{
    @Expose
    private String Name;
    @Expose
    private Int Age;
    @Expose
    private String Surname;

// setters and getters...

the api interface

public interface APIService {
 @POST("people.php")
    Call<whatyoureceive> response();

}

Also

private static final String BASE_URL = "YOUR URL";

public static APIService getAPIService() {

    return RetrofitClient.getClient(BASE_URL).create(APIService.class);
}

In your activity

private APIService mAPIService;

mAPIService = ApiUtils.getAPIService();

public void sendRequest() {
        mAPIService.responseo().enqueue(new Callback<PlanDetails>() {
@Override
            public void onResponse(......) {
// what you want to do
}
@Override
            public void onFailure(.....) {
// what you want to do
}

More information https://futurestud.io/tutorials/retrofit-getting-started-and-android-client

Hope help!


问:
Set session variable with NodeJS
After an authentification I want to set a session variable. The goal is to acess to the id of user on every views.

I use express and express-session.
My problem is that when I want to access to the session variable.
I don't find if they are initialisations to do before using it. Because when I use :

if(req.session.username)```
</div>
</div>
</p>

<p>for example, I have an error : username is not defined.</p>

<p>app.js : </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cors=require('cors');

//var index = require('./routes/index');
//var users = require('./routes/users');
var UsersDB=require('./routes/UsersDB');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(cors());
app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));

//app.use('/', index);
//app.use('/users', users);
app.use('/Users',UsersDB);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

app.use(function(req, res, next) {
 res.set({'Content-Type': 'text/plain; charset=utf-8;',
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Methods': 'GET, POST, DELETE, OPTIONS',
  'Access-Control-Allow-Headers': 'X-PINGOTHER',
  'Access-Control-Max-Age': '1728000'});
 next();
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

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

UsersDB.js :

var express = require('express');
var router = express.Router();
var Users=require('../models/Users');
var multer = require('multer');
var crypto = require('crypto');

var cookieParser = require('cookie-parser');
var session = require('express-session');

var app = express();

app.use(cookieParser());
app.use(session({
    secret: "fd34s@!@dfa453f3DF#$D&W",
    resave: false,
    saveUninitialized: true,
    cookie: { secure: false }
}));

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './uploads')
},
filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now() + ".png")
}
});

var upload = multer({ storage: storage }).single('avatar');

router.post('/login',function(req,res,next)
{
    upload(req, res, function (err) {
        if (err) {
      // An error occurred when uploading
            return
        }
    // Everything went fine
        console.log(req.body);
        var login = req.body.username;
        var pass = req.body.password;

        if(req.session.username) {
            console.log(req.session.username);
        }
        else{
            req.session.username = "toto";
        }

        const hash = crypto.createHmac('sha256','YouOu').update(pass).digest('hex');
        Users.getUsersByEmail(login,function(err,rows)
        {
            if(rows == null){
                res.end("No such user");
                return;
            }
            if(rows[0].password != hash){
                res.end("Wrong pass")
                return;
            }
            else{
                res.end("Ok")
                return;
            }
        })

    })
});

module.exports=router;```
</div>
</div>
</p>

<p>Login.html : </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="text/javascript">
        $("form[name=loginform]").submit(function(event){

            //disable the default form submission
            event.preventDefault();

            //grab all form data
            var formData = new FormData($(this)[0]);

            $.ajax({
              url:'http://localhost:3000/Users/login',
              type: 'POST',
              data: formData,
              async: false,
              cache: false,
              contentType: false,
              processData: false,
              success: function (returndata) {
                if(returndata == "Wrong pass") {
                  alert("wrong password");
                } else if(returndata == "No such user")
                {
                  alert("no such user");
                } else {
                   alert("Welcome");
                    window.location.href="index.html"
                }

              }
            });

            return false;
        });

      </script></code>```

答: As far as I can see the issue is that you are initializing the session in UsersDB.js on an app module that is not going to be used. Try to initialize it in app.js instead.</p>

Title: Set session variable with NodeJS

Body:
After an authentification I want to set a session variable. The goal is to acess to the id of user on every views.

I use express and express-session.
My problem is that when I want to access to the session variable.
I don't find if they are initialisations to do before using it. Because when I use :

if(req.session.username)

for example, I have an error : username is not defined.

app.js :

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cors=require('cors');

//var index = require('./routes/index');
//var users = require('./routes/users');
var UsersDB=require('./routes/UsersDB');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(cors());
app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));

//app.use('/', index);
//app.use('/users', users);
app.use('/Users',UsersDB);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

app.use(function(req, res, next) {
 res.set({'Content-Type': 'text/plain; charset=utf-8;',
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Methods': 'GET, POST, DELETE, OPTIONS',
  'Access-Control-Allow-Headers': 'X-PINGOTHER',
  'Access-Control-Max-Age': '1728000'});
 next();
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

UsersDB.js :

var express = require('express');
var router = express.Router();
var Users=require('../models/Users');
var multer = require('multer');
var crypto = require('crypto');

var cookieParser = require('cookie-parser');
var session = require('express-session');

var app = express();

app.use(cookieParser());
app.use(session({
    secret: "fd34s@!@dfa453f3DF#$D&W",
    resave: false,
    saveUninitialized: true,
    cookie: { secure: false }
}));

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './uploads')
},
filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now() + ".png")
}
});

var upload = multer({ storage: storage }).single('avatar');

router.post('/login',function(req,res,next)
{
    upload(req, res, function (err) {
        if (err) {
      // An error occurred when uploading
            return
        }
    // Everything went fine
        console.log(req.body);
        var login = req.body.username;
        var pass = req.body.password;

        if(req.session.username) {
            console.log(req.session.username);
        }
        else{
            req.session.username = "toto";
        }

        const hash = crypto.createHmac('sha256','YouOu').update(pass).digest('hex');
        Users.getUsersByEmail(login,function(err,rows)
        {
            if(rows == null){
                res.end("No such user");
                return;
            }
            if(rows[0].password != hash){
                res.end("Wrong pass")
                return;
            }
            else{
                res.end("Ok")
                return;
            }
        })

    })
});

module.exports=router;

Login.html :


答:
See it here:

http://saturnboy.com/2010/02/parsing-twitter-with-regexp/

Title: How to find URLs in a string with PHP?

Body: I know there is filter_var() but I don't want to validate a URL, I want to spot them in a whole text (e.g. a tweet). So you got any idea?


问:
Word-wrap not working in Internet Explorer
When I'm using word-wrap:break-word with Browser Mode: IE9 Compatibility View and Document Mode: IE7 standards its working perfectly fine. However when I change the Document Mode: IE9 standards, its not working.
I've also tried using -ms-word-wrap:break-word however its giving me the same result.

Document Type Definition: DTD/xhtml1-transitional.dtd

Can anyone tell me why is it so and if there is any workaround to cope up with it ?

答:
```<code>-ms-word-break: break-all;
</code>```

works in > IE9

Body:
-ms-word-break: break-all;

works in > IE9


问:
populate text file to database
I'm trying to read from a text file that contains a bunch of words line by line.
I tried to use this question's solution but I couldn't do it.
This is how I setup my models.py file:

```<code>from django.db import models
class words(models.Model):
    wordslist = models.CharField(null='True', max_length=128)
</code>```

I tried to run this code in the python manage.py shell:

```<code>from app.models import words
WORDLIST_FILENAME = "app/words.txt"
inFile = open(WORDLIST_FILENAME, 'r')
wordlist = []
for line in inFile:
    wordlist.append(line.strip().lower()) # wordlist: list of strings
    words.objects.create()
</code>```

This doesn't end up completing and I have to keyboard interrupt. I'm using Django 1.11

答:
Here is a working example of pulling lines out of a file as storing them in the database using your words model which should be capitalized.

I would add this to the model since you might do this sometime in the future with more files. Potentially you could get a list of file paths and run a for loop, passing the file paths into this function to do the work.

```<code>def lines_in_file_to_db(file_path):
    """ Handles reading lines from a file and saving to the Database.

    :param file_path: Path to where file is located.
    :type file_path: str
    """
    data = []

    with open(file_path) as file:
        for line in file:
            # do line manipulation in here...
            line = line.replace('\n', '')
            data.append(line)

    for line in data:
        words.objects.create(wordslist=line)
</code>```

Title: populate text file to database

Body:
I'm trying to read from a text file that contains a bunch of words line by line.
I tried to use this question's solution but I couldn't do it.
This is how I setup my models.py file:

from django.db import models
class words(models.Model):
    wordslist = models.CharField(null='True', max_length=128)

I tried to run this code in the python manage.py shell:

from app.models import words
WORDLIST_FILENAME = "app/words.txt"
inFile = open(WORDLIST_FILENAME, 'r')
wordlist = []
for line in inFile:
    wordlist.append(line.strip().lower()) # wordlist: list of strings
    words.objects.create()

This doesn't end up completing and I have to keyboard interrupt. I'm using Django 1.11

Body:
Here is a working example of pulling lines out of a file as storing them in the database using your words model which should be capitalized.

I would add this to the model since you might do this sometime in the future with more files. Potentially you could get a list of file paths and run a for loop, passing the file paths into this function to do the work.

def lines_in_file_to_db(file_path):
    """ Handles reading lines from a file and saving to the Database.

    :param file_path: Path to where file is located.
    :type file_path: str
    """
    data = []

    with open(file_path) as file:
        for line in file:
            # do line manipulation in here...
            line = line.replace('\n', '')
            data.append(line)

    for line in data:
        words.objects.create(wordslist=line)


问:
Routing & Modules
I have the following routing configuration in my app:

```<code>app.module.ts

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpModule,
    AppRouting,

    // Feature Modules
    CoreModule,
    AuthModule,
    AdminModule,
    SharedModule
  ],
  bootstrap: [AppComponent]
})

app.routing.ts

const routes: Routes = [
  { path: '', redirectTo: 'admin', pathMatch: 'full' },
  { path: 'admin', loadChildren: () => AdminModule }
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes, {preloadingStrategy: PreloadAllModules})
  ],
  exports: [RouterModule]
})
</code>```

admin.module.ts

```<code>@NgModule({
  declarations: [
    AdminComponent
  ],

  imports: [
    CommonModule,
    FormsModule,
    UserModule,

    AdminRouting,
    SharedModule
  ],

  providers: [
    UserService
  ]
})

admin.routing.ts

const routes: Routes = [
  { path: '', component: AdminComponent, canActivate: [AuthGuard], children: [
    { path: 'users', loadChildren: () => UserModule }
  ]}
];

@NgModule({
  imports: [
    RouterModule.forChild(routes)
  ],
  exports: [RouterModule]
})

user.module.ts

@NgModule({
  declarations: [
    UserComponent,
    UserManageComponent,
    UserListComponent
  ],

  imports: [
    CommonModule,
    FormsModule,

    UserRouting,
    SharedModule
  ]
})

user.routing.ts

const routes: Routes = [
  { path: '', component: UserComponent, children: [
    { path: '', component: UserListComponent },
    { path: 'new', component: UserManageComponent },
    { path: ':id/edit', component: UserManageComponent }
  ]},
];

@NgModule({
  imports: [
    RouterModule.forChild(routes)
  ],
  exports: [RouterModule]
})
</code>```

And there's the problem:

What I expected my application routing does:

```<code>/users => not a valid route
/users/new => not a valid route

/admin/users => valid route
/admin/users/new => valid route
/admin => valid route (should render AdminComponent)
</code>```

I don't know why, but if I enter /users, the applications render UserComponent, what is not the behavior I would like to.

I would like UserComponent to be accessed only from /admin/users.

Does anybody could explain me why?

答:
Try this to see:</p>

```<code>admin.routing.ts

const routes: Routes = [
  { path: 'admin', component: AdminComponent, canActivate: [AuthGuard],
        children: [{ path: 'users', loadChildren: () => UserModule }]}
];
</code>```

Title: Routing & Modules

Body:
I have the following routing configuration in my app:

app.module.ts

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpModule,
    AppRouting,

    // Feature Modules
    CoreModule,
    AuthModule,
    AdminModule,
    SharedModule
  ],
  bootstrap: [AppComponent]
})

app.routing.ts

const routes: Routes = [
  { path: '', redirectTo: 'admin', pathMatch: 'full' },
  { path: 'admin', loadChildren: () => AdminModule }
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes, {preloadingStrategy: PreloadAllModules})
  ],
  exports: [RouterModule]
})

admin.module.ts

@NgModule({
  declarations: [
    AdminComponent
  ],

  imports: [
    CommonModule,
    FormsModule,
    UserModule,

    AdminRouting,
    SharedModule
  ],

  providers: [
    UserService
  ]
})

admin.routing.ts

const routes: Routes = [
  { path: '', component: AdminComponent, canActivate: [AuthGuard], children: [
    { path: 'users', loadChildren: () => UserModule }
  ]}
];

@NgModule({
  imports: [
    RouterModule.forChild(routes)
  ],
  exports: [RouterModule]
})

user.module.ts

@NgModule({
  declarations: [
    UserComponent,
    UserManageComponent,
    UserListComponent
  ],

  imports: [
    CommonModule,
    FormsModule,

    UserRouting,
    SharedModule
  ]
})

user.routing.ts

const routes: Routes = [
  { path: '', component: UserComponent, children: [
    { path: '', component: UserListComponent },
    { path: 'new', component: UserManageComponent },
    { path: ':id/edit', component: UserManageComponent }
  ]},
];

@NgModule({
  imports: [
    RouterModule.forChild(routes)
  ],
  exports: [RouterModule]
})

And there's the problem:

What I expected my application routing does:

/users => not a valid route
/users/new => not a valid route

/admin/users => valid route
/admin/users/new => valid route
/admin => valid route (should render AdminComponent)

I don't know why, but if I enter /users, the applications render UserComponent, what is not the behavior I would like to.

I would like UserComponent to be accessed only from /admin/users.

Does anybody could explain me why?

Body:
Try this to see:

admin.routing.ts

const routes: Routes = [
  { path: 'admin', component: AdminComponent, canActivate: [AuthGuard],
        children: [{ path: 'users', loadChildren: () => UserModule }]}
];


问:
Button animation only works for specific margin
I've got some strange problem. In my code the button css animation only works if the margin-top is set to be 125px (for sim-button class). I want to reduce the margin-top to 25px but then the animation doesn't works.

Codepen Here

HTML:

```<code><div class="media" style = "background-color:#000;">
                          <img class="media__image" src="https://www.offensive-security.com/wp-content/uploads/2012/01/security-risk-assessment-report.png">
                          <div class="media__body">
                            <h2>Penetration Report</h2>
                            <p>Get your hands on our Sample Presentation Report</p>
                            <div class="sim-button button1" data-toggle="modal" data-target="#getQuoteModal">Download Report</div>
                          </div>
                        </div>
</code>```

CSS:

```<code>    .media {
  display: inline-block;
  position: relative;
  vertical-align: top;
}

.media__image { display: block; }

.media__body {
  background: rgba(41, 128, 185, 0.7);
  bottom: 0;
  color: white;
  font-size: 1em;
  left: 0;
  opacity: 0;
  overflow: hidden;
  padding: 3.75em 3em;
  position: absolute;
  text-align: center;
  top: 0;
  right: 0;
  -webkit-transition: 0.6s;
  transition: 0.6s;
}

.media__body:hover { opacity: 1; }

.media__body:after,
.media__body:before {
  border: 1px solid rgba(255, 255, 255, 0.7);
  bottom: 1em;
  content: '';
  left: 1em;
  opacity: 0;
  position: absolute;
  right: 1em;
  top: 1em;
  -webkit-transform: scale(1.5);
  -ms-transform: scale(1.5);
  transform: scale(1.5);
  -webkit-transition: 0.6s 0.2s;
  transition: 0.6s 0.2s;
}

.media__body:before {
  border-bottom: none;
  border-top: none;
  left: 2em;
  right: 2em;
}

.media__body:after {
  border-left: none;
  border-right: none;
  bottom: 2em;
  top: 2em;
}

.media__body:hover:after,
.media__body:hover:before {
  -webkit-transform: scale(1);
  -ms-transform: scale(1);
  transform: scale(1);
  opacity: 1;
}

.media__body h2 { margin-top: 0; }

.media__body p { margin-bottom: 0em; }

.sim-button{
    line-height: 50px;
    height: 50px;
    text-align: center;
    margin-right: auto;
    margin-left: auto;
    margin-top: 125px;
    width: 60%;
    cursor: pointer;
}
.button1 {
    color: rgba(255,255,255,1);
    -webkit-transition: all 0.5s;
    -moz-transition: all 0.5s;
    -o-transition: all 0.5s;
    transition: all 0.5s;
    position: relative;
    border: 1px solid rgba(255,255,255,0.5);
}
.button1 a{
    color: rgba(51,51,51,1);
    text-decoration: none;
    display: block;
}
.button1:hover {
    background-color: rgba(255,255,255,0.2);
    -webkit-border-radius: 25px;
    -moz-border-radius: 25px;
    border-radius: 25px;
}
</code>```

Thanks for help in advance.

答:
Another way to do it, if you want the text to be selectable and the button effect to work and be clickable is to set z-index: 1 on .media__body, then z-index: -1 on the ::before/::after pseudo elements. That will put the pseudo elements behind all of the content in .media__body but keep them from going behind .media__body

.media {
  display: inline-block;
  position: relative;
  vertical-align: top;
}

.media__image {
  display: block;
}

.media__body {
  background: rgba(41, 128, 185, 0.7);
  bottom: 0;
  color: white;
  font-size: 1em;
  left: 0;
  opacity: 0;
  overflow: hidden;
  padding: 3.75em 3em;
  position: absolute;
  text-align: center;
  top: 0;
  right: 0;
  -webkit-transition: 0.6s;
  transition: 0.6s;
  z-index: 1;
}

.media__body:hover {
  opacity: 1;
}

.media__body:after, .media__body:before {
  border: 1px solid rgba(255, 255, 255, 0.7);
  bottom: 1em;
  content: '';
  left: 1em;
  opacity: 0;
  position: absolute;
  right: 1em;
  top: 1em;
  -webkit-transform: scale(1.5);
  -ms-transform: scale(1.5);
  transform: scale(1.5);
  -webkit-transition: 0.6s 0.2s;
  transition: 0.6s 0.2s;
  z-index: -1;
}

.media__body:before {
  border-bottom: none;
  border-top: none;
  left: 2em;
  right: 2em;
}

.media__body:after {
  border-left: none;
  border-right: none;
  bottom: 2em;
  top: 2em;
}

.media__body:hover:after, .media__body:hover:before {
  -webkit-transform: scale(1);
  -ms-transform: scale(1);
  transform: scale(1);
  opacity: 1;
}

.media__body h2 {
  margin-top: 0;
}

.media__body p {
  margin-bottom: 0em;
}

.sim-button {
  line-height: 50px;
  height: 50px;
  text-align: center;
  margin-right: auto;
  margin-left: auto;
  margin-top: 25px;
  width: 60%;
  cursor: pointer;
}
.button1 {
  color: rgba(255, 255, 255, 1);
  -webkit-transition: all 0.5s;
  -moz-transition: all 0.5s;
  -o-transition: all 0.5s;
  transition: all 0.5s;
  position: relative;
  border: 1px solid rgba(255, 255, 255, 0.5);
}
.button1 a {
  color: rgba(51, 51, 51, 1);
  text-decoration: none;
  display: block;
}
.button1:hover {
  background-color: rgba(255, 255, 255, 0.2);
  -webkit-border-radius: 25px;
  -moz-border-radius: 25px;
  border-radius: 25px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="media" style="background-color:#000;">
  <img class="media__image" src="https://www.offensive-security.com/wp-content/uploads/2012/01/security-risk-assessment-report.png">
  <div class="media__body">
    <h2>Penetration Report</h2>
    <p>Get your hands on our Sample Presentation Report</p>
    <div class="sim-button button1" data-toggle="modal" data-target="#getQuoteModal">Download Report</div>
  </div>
</div></code>```

Body:
I've got some strange problem. In my code the button css animation only works if the margin-top is set to be 125px (for sim-button class). I want to reduce the margin-top to 25px but then the animation doesn't works.

Codepen Here

HTML:

Penetration Report

Get your hands on our Sample Presentation Report

Download Report

CSS:

    .media {
  display: inline-block;
  position: relative;
  vertical-align: top;
}

.media__image { display: block; }

.media__body {
  background: rgba(41, 128, 185, 0.7);
  bottom: 0;
  color: white;
  font-size: 1em;
  left: 0;
  opacity: 0;
  overflow: hidden;
  padding: 3.75em 3em;
  position: absolute;
  text-align: center;
  top: 0;
  right: 0;
  -webkit-transition: 0.6s;
  transition: 0.6s;
}

.media__body:hover { opacity: 1; }

.media__body:after,
.media__body:before {
  border: 1px solid rgba(255, 255, 255, 0.7);
  bottom: 1em;
  content: '';
  left: 1em;
  opacity: 0;
  position: absolute;
  right: 1em;
  top: 1em;
  -webkit-transform: scale(1.5);
  -ms-transform: scale(1.5);
  transform: scale(1.5);
  -webkit-transition: 0.6s 0.2s;
  transition: 0.6s 0.2s;
}

.media__body:before {
  border-bottom: none;
  border-top: none;
  left: 2em;
  right: 2em;
}

.media__body:after {
  border-left: none;
  border-right: none;
  bottom: 2em;
  top: 2em;
}

.media__body:hover:after,
.media__body:hover:before {
  -webkit-transform: scale(1);
  -ms-transform: scale(1);
  transform: scale(1);
  opacity: 1;
}

.media__body h2 { margin-top: 0; }

.media__body p { margin-bottom: 0em; }

.sim-button{
    line-height: 50px;
    height: 50px;
    text-align: center;
    margin-right: auto;
    margin-left: auto;
    margin-top: 125px;
    width: 60%;
    cursor: pointer;
}
.button1 {
    color: rgba(255,255,255,1);
    -webkit-transition: all 0.5s;
    -moz-transition: all 0.5s;
    -o-transition: all 0.5s;
    transition: all 0.5s;
    position: relative;
    border: 1px solid rgba(255,255,255,0.5);
}
.button1 a{
    color: rgba(51,51,51,1);
    text-decoration: none;
    display: block;
}
.button1:hover {
    background-color: rgba(255,255,255,0.2);
    -webkit-border-radius: 25px;
    -moz-border-radius: 25px;
    border-radius: 25px;
}

Thanks for help in advance.

Body:
Another way to do it, if you want the text to be selectable and the button effect to work and be clickable is to set z-index: 1 on .media__body, then z-index: -1 on the ::before/::after pseudo elements. That will put the pseudo elements behind all of the content in .media__body but keep them from going behind .media__body

.media {
  display: inline-block;
  position: relative;
  vertical-align: top;
}

.media__image {
  display: block;
}

.media__body {
  background: rgba(41, 128, 185, 0.7);
  bottom: 0;
  color: white;
  font-size: 1em;
  left: 0;
  opacity: 0;
  overflow: hidden;
  padding: 3.75em 3em;
  position: absolute;
  text-align: center;
  top: 0;
  right: 0;
  -webkit-transition: 0.6s;
  transition: 0.6s;
  z-index: 1;
}

.media__body:hover {
  opacity: 1;
}

.media__body:after, .media__body:before {
  border: 1px solid rgba(255, 255, 255, 0.7);
  bottom: 1em;
  content: '';
  left: 1em;
  opacity: 0;
  position: absolute;
  right: 1em;
  top: 1em;
  -webkit-transform: scale(1.5);
  -ms-transform: scale(1.5);
  transform: scale(1.5);
  -webkit-transition: 0.6s 0.2s;
  transition: 0.6s 0.2s;
  z-index: -1;
}

.media__body:before {
  border-bottom: none;
  border-top: none;
  left: 2em;
  right: 2em;
}

.media__body:after {
  border-left: none;
  border-right: none;
  bottom: 2em;
  top: 2em;
}

.media__body:hover:after, .media__body:hover:before {
  -webkit-transform: scale(1);
  -ms-transform: scale(1);
  transform: scale(1);
  opacity: 1;
}

.media__body h2 {
  margin-top: 0;
}

.media__body p {
  margin-bottom: 0em;
}

.sim-button {
  line-height: 50px;
  height: 50px;
  text-align: center;
  margin-right: auto;
  margin-left: auto;
  margin-top: 25px;
  width: 60%;
  cursor: pointer;
}
.button1 {
  color: rgba(255, 255, 255, 1);
  -webkit-transition: all 0.5s;
  -moz-transition: all 0.5s;
  -o-transition: all 0.5s;
  transition: all 0.5s;
  position: relative;
  border: 1px solid rgba(255, 255, 255, 0.5);
}
.button1 a {
  color: rgba(51, 51, 51, 1);
  text-decoration: none;
  display: block;
}
.button1:hover {
  background-color: rgba(255, 255, 255, 0.2);
  -webkit-border-radius: 25px;
  -moz-border-radius: 25px;
  border-radius: 25px;
}

<div class="media" style="background-color:#000;">
  <img class="media__image" src="https://www.offensive-security.com/wp-content/uploads/2012/01/security-risk-assessment-report.png">
  <div class="media__body">
    <h2>Penetration Report</h2>
    <p>Get your hands on our Sample Presentation Report</p>
    <div class="sim-button button1" data-toggle="modal" data-target="#getQuoteModal">Download Report</div>
  </div>
</div>