问:
Can't read custom environment variables in node using config.get()
I use config library to manage my configuration files in node application.

I have export my custom env variable in terminal by
  export app_password=12345

and map it into the custom-environment-variable.json file by

```<code>{
  "mail": {
  "password": "app_password"
   }
}
</code>```

when I use config.get('mail.password') in my index.js file (root module) .

I got error: Configuration property "mail.password" is not defined, detail in below:

```<code>/Users/tzhong/Documents/vidly-
backend/node_modules/config/lib/config.js:203
throw new Error('Configuration property "' + property + '" is not
defined');
^

Error: Configuration property "mail.password" is not defined
    at Config.get (/Users/tzhong/Documents/vidly-
 backend/node_modules/config/lib/config.js:203:11)
</code>```

I have use console.log(process.env.app_password) to check if my custom env variable is there, and the app_password show in the terminal.

```<code> Vidly evn is : Vidly backend -- development
 Vidly mail server is : dev-mail-server
 Mail-password is : 12345
 NODE_ENV is : undefined
 app: development
 Mongan enabled...
 Listenning 3000 port ...
</code>```

I want to use console.log(config.get('mail.password')); to show my custom variable in terminal instead of console.log(process.env.app_password)
Any suggestions?

Finally solve the problem :
It's tiny mistake, in config library, the file's name for creating custom environment variable is strict, the file's name should be 'custom-environment-variables.json', I have a wrong spell on 'environment' , after all , thanks for people offer other available package

答:
Right way to do this in nodejs is to make use of .env file. Create a .env file at the root. Keep your env variables and their value there in the key=value format for e.g password=app_password

In your main entry point file, Require the dotenv package and load the env variables with dotenv.configure() at the top just after requiring all the modules. See here for more details.

Body:
I use config library to manage my configuration files in node application.

I have export my custom env variable in terminal by
  export app_password=12345

and map it into the custom-environment-variable.json file by

{
  "mail": {
  "password": "app_password"
   }
}

when I use config.get('mail.password') in my index.js file (root module) .

I got error: Configuration property "mail.password" is not defined, detail in below:

/Users/tzhong/Documents/vidly-
backend/node_modules/config/lib/config.js:203
throw new Error('Configuration property "' + property + '" is not
defined');
^

Error: Configuration property "mail.password" is not defined
    at Config.get (/Users/tzhong/Documents/vidly-
 backend/node_modules/config/lib/config.js:203:11)

I have use console.log(process.env.app_password) to check if my custom env variable is there, and the app_password show in the terminal.

 Vidly evn is : Vidly backend -- development
 Vidly mail server is : dev-mail-server
 Mail-password is : 12345
 NODE_ENV is : undefined
 app: development
 Mongan enabled...
 Listenning 3000 port ...

I want to use console.log(config.get('mail.password')); to show my custom variable in terminal instead of console.log(process.env.app_password)
Any suggestions?

Finally solve the problem :
It's tiny mistake, in config library, the file's name for creating custom environment variable is strict, the file's name should be 'custom-environment-variables.json', I have a wrong spell on 'environment' , after all , thanks for people offer other available package


来源: stackexchange

问:
Output random number between 30-35 using Random.seed(), 'for' and multiplication in Python
I am new to programming. I had an assignment to write a code that will output a random number between 30 and 35. This code needs to use random.seed(), a for statement and a multiplication. I understand that the random.seed([x]) generates an initial value that could be used in the proceeding section of the code. However, I can't figure out how to proceed after obtaining the value of the random:

```<code>import random
random.seed(70)
print(random.random()) # This returns a value of 0.909769237923872
</code>```

How do I use this value to generate a random value between 30 and 35?

Note: Without the specific directions above, I have been able to write two codes that function as desired, so please I am not looking for alternative ways of writing the code.

答:
random is package which is imported at the top

since we ( i and you ) can't implement logic for a random number generation ( or any other use case which is beyond our skill set at the moment ) we use packages like these

seed makes the same random number appear so the answer don't differ from the testcase

Try this way:

```<code>import random
def problem2_4():
    A = []
    random.seed(70)
    for i in range(0,10):
        A.append(5*random.random()+30)
        # it gives in a range of 0-1 so multiplied by 5
        # we need in range of 30-35 so we add it to 30
        # if 0.000000001 ~30.000000005 it is still in 30-35 range
        # if 0.999999901 ~34.999999505 it is still in 30-35 range
    # print the list of numbers generated at random
    print(A)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am new to programming. I had an assignment to write a code that will output a random number between 30 and 35. This code needs to use random.seed(), a for statement and a multiplication. I understand that the random.seed([x]) generates an initial value that could be used in the proceeding section of the code. However, I can't figure out how to proceed after obtaining the value of the random:

import random
random.seed(70)
print(random.random()) # This returns a value of 0.909769237923872

How do I use this value to generate a random value between 30 and 35?

Note: Without the specific directions above, I have been able to write two codes that function as desired, so please I am not looking for alternative ways of writing the code.

Body:
random is package which is imported at the top

since we ( i and you ) can't implement logic for a random number generation ( or any other use case which is beyond our skill set at the moment ) we use packages like these

seed makes the same random number appear so the answer don't differ from the testcase

Try this way:

import random
def problem2_4():
    A = []
    random.seed(70)
    for i in range(0,10):
        A.append(5*random.random()+30)
        # it gives in a range of 0-1 so multiplied by 5
        # we need in range of 30-35 so we add it to 30
        # if 0.000000001 ~30.000000005 it is still in 30-35 range
        # if 0.999999901 ~34.999999505 it is still in 30-35 range
    # print the list of numbers generated at random
    print(A)


问:
flask-jwt-extended: Fake Authorization Header during testing (pytest)
This is the function I wish to test

```<code>@jwt_required
    def get_all_projects(self):
        # implementation not included here
</code>```

I call the function from a pytest class

```<code>def test_get_all_projects(db_session):
    all_projects = ProjectController.get_all_projects()
</code>```

with the db_session fixture

```<code>@pytest.fixture(scope='function')
def db_session(db, request):
    """Creates a new database session for a test."""
    engine = create_engine(
                            DefaultConfig.SQLALCHEMY_DATABASE_URI,
                            connect_args={"options": "-c timezone=utc"})
    DbSession = sessionmaker(bind=engine)
    session = DbSession()
    connection = engine.connect()
    transaction = connection.begin()
    options = dict(bind=connection, binds={})
    session = db.create_scoped_session(options=options)
    db.session = session

    yield session

    transaction.rollback()
    connection.close()
    session.remove()
</code>```

This result in the error

```<code>>           raise NoAuthorizationError("Missing {} Header".format(header_name))
E           flask_jwt_extended.exceptions.NoAuthorizationError: Missing Authorization Header

../../.virtualenvs/my-app/lib/python3.6/site-packages/flask_jwt_extended/view_decorators.py:132: NoAuthorizationError
</code>```

Manually Calling create_access_token

I still get the same result when I call create_access_token in the fixture above

```<code>db.session = session
session._test_access_token = create_access_token(identity='pytest')

yield session
</code>```

How can I fake JWT tokens during testing with pytest?

答:
In my case, I was using the @jwt.user_claims_loader wrapper for admin roles. I was also using cookies for the production side of things. In order to take advantage of the user_claims_loader, I created a test like so:

```<code># conftest.py
from my.app import create_app

@pytest.fixture
def app():
    app = create_app(testing=True)
    app.config['JWT_COOKIE_CSRF_PROTECT'] = False
    app.config['JWT_TOKEN_LOCATION'] = 'json'
    jwt = JWTManager(app)

    add_user_claims_loader(jwt)

    return app
</code>```

As you can see, I also reset my JWT_TOKEN_LOCATION to json so that it isn't looking for cookies. I created another fixture to create the access token so I could use it across tests

```<code># conftest.py
@pytest.fixture
def admin_json_access_token(app, client):
    access_token = create_access_token({'username': 'testadmin',
                                        'role': 'admin'})
    return {
        'access_token': access_token
    }
</code>```

And I used it in my tests:

```<code># test_user.py
def test_get_users(app, client, db, admin_json_access_token):
    rep = client.get('/api/v1/users', json=admin_json_access_token)
    assert rep.status_code == 200
</code>```

As an example of what my resource looked like:

```<code># my/resources/admin/api.py
class Users(Resource):
    @jwt_required
    @admin_required # custom wrapper that checks the claims
    def get(self):
        all_users = User.query.all()
        return all_users, 200
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This is the function I wish to test

@jwt_required
    def get_all_projects(self):
        # implementation not included here

I call the function from a pytest class

def test_get_all_projects(db_session):
    all_projects = ProjectController.get_all_projects()

with the db_session fixture

@pytest.fixture(scope='function')
def db_session(db, request):
    """Creates a new database session for a test."""
    engine = create_engine(
                            DefaultConfig.SQLALCHEMY_DATABASE_URI,
                            connect_args={"options": "-c timezone=utc"})
    DbSession = sessionmaker(bind=engine)
    session = DbSession()
    connection = engine.connect()
    transaction = connection.begin()
    options = dict(bind=connection, binds={})
    session = db.create_scoped_session(options=options)
    db.session = session

    yield session

    transaction.rollback()
    connection.close()
    session.remove()

This result in the error

>           raise NoAuthorizationError("Missing {} Header".format(header_name))
E           flask_jwt_extended.exceptions.NoAuthorizationError: Missing Authorization Header

../../.virtualenvs/my-app/lib/python3.6/site-packages/flask_jwt_extended/view_decorators.py:132: NoAuthorizationError

Manually Calling create_access_token

I still get the same result when I call create_access_token in the fixture above

db.session = session
session._test_access_token = create_access_token(identity='pytest')

yield session

How can I fake JWT tokens during testing with pytest?

Body:
In my case, I was using the @jwt.user_claims_loader wrapper for admin roles. I was also using cookies for the production side of things. In order to take advantage of the user_claims_loader, I created a test like so:

# conftest.py
from my.app import create_app

@pytest.fixture
def app():
    app = create_app(testing=True)
    app.config['JWT_COOKIE_CSRF_PROTECT'] = False
    app.config['JWT_TOKEN_LOCATION'] = 'json'
    jwt = JWTManager(app)

    add_user_claims_loader(jwt)

    return app

As you can see, I also reset my JWT_TOKEN_LOCATION to json so that it isn't looking for cookies. I created another fixture to create the access token so I could use it across tests

# conftest.py
@pytest.fixture
def admin_json_access_token(app, client):
    access_token = create_access_token({'username': 'testadmin',
                                        'role': 'admin'})
    return {
        'access_token': access_token
    }

And I used it in my tests:

# test_user.py
def test_get_users(app, client, db, admin_json_access_token):
    rep = client.get('/api/v1/users', json=admin_json_access_token)
    assert rep.status_code == 200

As an example of what my resource looked like:

# my/resources/admin/api.py
class Users(Resource):
    @jwt_required
    @admin_required # custom wrapper that checks the claims
    def get(self):
        all_users = User.query.all()
        return all_users, 200


问:
Changing tabBarController.selectedViewController only works once?
My iPhone app uses a UITabBarController.  On the first tab, there's a scenerio where the user can go two UIViewControllers deep without changing tabs.  So the screenflow is like this:

App loads with first tab opened by default.

User presses a UIButton which takes them to second UIViewController in the same tab.

From the second UIViewController, user can press another UIButton taking them to a third UIViewController, still in the same tab

This works when switching from the first UIViewController to the second with these 2 lines:

```<code>    2ndViewController = [[SecondViewController alloc] init];
    self.tabBarController.selectedViewController = 2ndViewController;
</code>```

However, when I try to do the same from the second UIViewController to the third, it doesn't work. The button doesn't do anything, and I stay on the second UIViewController.

Can anyone explain why that is?  Is there a workaround I can use?  I'm happy to provide more code if needed.

Thanks in advance.

答:
This isn't what that property was meant for. You are most likely experiencing the "undefined behavior" the documentation talks about.

The best way to do what you are doing is to place a UINavigationController in the tab and push each controller with that. If you don't want to show the navigation bar, you can hide that with navigationBarHidden.

Body:
My iPhone app uses a UITabBarController.  On the first tab, there's a scenerio where the user can go two UIViewControllers deep without changing tabs.  So the screenflow is like this:

App loads with first tab opened by default.

User presses a UIButton which takes them to second UIViewController in the same tab.

From the second UIViewController, user can press another UIButton taking them to a third UIViewController, still in the same tab

This works when switching from the first UIViewController to the second with these 2 lines:

    2ndViewController = [[SecondViewController alloc] init];
    self.tabBarController.selectedViewController = 2ndViewController;

However, when I try to do the same from the second UIViewController to the third, it doesn't work. The button doesn't do anything, and I stay on the second UIViewController.

Can anyone explain why that is?  Is there a workaround I can use?  I'm happy to provide more code if needed.

Thanks in advance.


问:
Chrome extension change border-radius and position
How can I add border-radius on chrome extension popup?
Also, can I add something like margin-top to the popup?

答:
I got the answer from chromium developer:

Alas, that's not something you can control. Your popup content is
  basically an iframe inside a window - you can't control the host
  window


问:
How to write query to get cumulative sum group by month and year?
i have below table

```<code>id      Dates           Amount
1   20170221    -192161
2   20170222    884
3   20170223    -74
4   20170227    961
5   20170321    -292161
6   20170322    994
7   20170323    -44
8   20170327    691
</code>```

i want output as below

```<code>id      Dates           Amount   Cumulative
1   20170221    -192161   -192161
2   20170222    884   -191277
3   20170223    -74   -191351
4   20170227    961   -190390
5   20170321    -292161   -482551
6   20170322    994   -481557
7   20170323    -44   -481601
8   20170327    691   -480910
</code>```

i have write this query but did not get desired output

```<code>select id
     , DATE_FORMAT(Dates,'%b-%Y')Dates
     , Amount
     , @total := @total + Amount as cumulative_sum
  from mytable
     , (Select @total := 0) as total;
</code>```

i want cumulative sum of all day of the month when i am apply group by month clause it return me only first row of the month

答:
One option which should work on all versions of MySQL would be to use a correlated subquery to find the cumulative sum:

```<code>SELECT
    id,
    Dates,
    Amount,
    (SELECT SUM(t2.Amount) FROM yourTable t2 WHERE t2.id <= t1.id) Cumulative
FROM yourTable t1
ORDER BY id;
</code>```

If you are using MySQL 8+, then we can try using SUM as an analytic function:

```<code>SELECT
    id,
    Dates,
    Amount,
    SUM(Amount) OVER (ORDER BY id) Cumulative
FROM yourTable
ORDER BY id;
</code>```

Demo

Body:
i have below table

id      Dates           Amount
1   20170221    -192161
2   20170222    884
3   20170223    -74
4   20170227    961
5   20170321    -292161
6   20170322    994
7   20170323    -44
8   20170327    691

i want output as below

id      Dates           Amount   Cumulative
1   20170221    -192161   -192161
2   20170222    884   -191277
3   20170223    -74   -191351
4   20170227    961   -190390
5   20170321    -292161   -482551
6   20170322    994   -481557
7   20170323    -44   -481601
8   20170327    691   -480910

i have write this query but did not get desired output

select id
     , DATE_FORMAT(Dates,'%b-%Y')Dates
     , Amount
     , @total := @total + Amount as cumulative_sum
  from mytable
     , (Select @total := 0) as total;

i want cumulative sum of all day of the month when i am apply group by month clause it return me only first row of the month

Body:
One option which should work on all versions of MySQL would be to use a correlated subquery to find the cumulative sum:

SELECT
    id,
    Dates,
    Amount,
    (SELECT SUM(t2.Amount) FROM yourTable t2 WHERE t2.id <= t1.id) Cumulative
FROM yourTable t1
ORDER BY id;

If you are using MySQL 8+, then we can try using SUM as an analytic function:

SELECT
    id,
    Dates,
    Amount,
    SUM(Amount) OVER (ORDER BY id) Cumulative
FROM yourTable
ORDER BY id;

Demo


问:
Html datalist option through JavaScript in node js
I want to pass data from MySQL database in datalist option. My application is written in express js using ejs view. I can't figure out how to pass database values to list in JavaScript and how to pass this list to ejs file.

add.js:

```<code>module.exports = {
  addProductPage: (req, res) => {
    let query = "SELECT shipper_names.Shipper_ID, shipper_names.Shipper_Name FROM shipper_names";
    conn.query(query, (err, results) => {
      if (err) {
        return res.status(500).send(err);
      }
      res.render('add-product.ejs', {
        title: "Add Product",
        shipper_names: results[0],
        message: ''
      });
    });
  }
}
</code>```

EJS file:

```<code><!doctype html>
<html lang="en">

<div>
  <a class="float-right" href="/" title="Home">Home</a>
</div>

<div class="contnainer">
  <% if (message) {%>
    <p class="text-container text-danger">
      <%= message %>
    </p>
    <%}%>
      <% if (shipper_names) {%>

        <form class="add-player-form" action="" method="POST" enctype="multipart/form-data">
          <div>
            <input type="text" id="shippers_names" list="languageList" />
            <!--your input textbox-->
            <datalist id="languageList">
                    <option value="">  </option>
                    </datalist>
          </div>
          <button type="submit" class="btn">Add Product</button>
        </form>
        <% } else { %>
          <p class="text center">Product Not Found. Go <a href="/add">Here</a>To Add Product.</p>
          <% } %>
</div>

</html>
</code>```

答:
module.exports = {
  addProductPage: (req, res) => {
    let query = "SELECT  * from shipper_names"
    conn.query(query, (err, results) => {
      if (err) {
        return res.status(500).send(err);
      }
      res.render('add-product.ejs', {
        shipper_names: results
      });
    });
  },```
<pre class="snippet-code-html lang-html prettyprint-override"><code>        <div>
            <input type="text" id="txtAutoComplete" list="names" />
            <!--your input textbox-->
            <datalist id="names">
                <% shipper_names.forEach((shipper_names, index)=>{%>
                <option id=<%= shipper_names.Shipper_ID%>>
                    <%= shipper_names.Shipper_Name%></option>
                <%})%>
            </datalist>
        </div></code>```

this is working

Body:
I want to pass data from MySQL database in datalist option. My application is written in express js using ejs view. I can't figure out how to pass database values to list in JavaScript and how to pass this list to ejs file.

add.js:

module.exports = {
  addProductPage: (req, res) => {
    let query = "SELECT shipper_names.Shipper_ID, shipper_names.Shipper_Name FROM shipper_names";
    conn.query(query, (err, results) => {
      if (err) {
        return res.status(500).send(err);
      }
      res.render('add-product.ejs', {
        title: "Add Product",
        shipper_names: results[0],
        message: ''
      });
    });
  }
}

EJS file:

<!doctype html>

  Home

  <% if (message) {%>

      <%= message %>

    <%}%>
      <% if (shipper_names) {%>

        <form class="add-player-form" action="" method="POST" enctype="multipart/form-data">

            <input type="text" id="shippers_names" list="languageList" />

            <datalist id="languageList">
                    <option value="">  </option>
                    </datalist>

          <button type="submit" class="btn">Add Product</button>
        </form>
        <% } else { %>

Product Not Found. Go HereTo Add Product.

          <% } %>

Body:
module.exports = {
  addProductPage: (req, res) => {
    let query = "SELECT  * from shipper_names"
    conn.query(query, (err, results) => {
      if (err) {
        return res.status(500).send(err);
      }
      res.render('add-product.ejs', {
        shipper_names: results
      });
    });
  },

        <div>
            <input type="text" id="txtAutoComplete" list="names" />
            <!--your input textbox-->
            <datalist id="names">
                <% shipper_names.forEach((shipper_names, index)=>{%>
                <option id=<%= shipper_names.Shipper_ID%>>
                    <%= shipper_names.Shipper_Name%></option>
                <%})%>
            </datalist>
        </div>

this is working


问:
Ajax GET returns 404 not found on CentOS
So I have a project in Laravel in which I use Ajax to move between views, so no data, only GET request.

This works fine on my local machine but I uploaded it to my VPS and when I click the button that should take me to another view, I get this error:

```<code>GET http://172.106.202.124/trabajos?_=1559303733962 404 (Not Found)
</code>```

So I've done some research and found some people with the same issue, but I haven't found any working answer.

Some said to modify .htaccess, I already did that and it's the same for me.

I've noticed that if I write /index.php/trabajos in the URL it gives me 'trabajos' view, but if I remove the /index.php/ it just gives me 'Not found'

This is my js code:

```<code> $(document).on('click', '#button1', function() {
        $.ajax({
                method: "GET",
                url:'/trabajos',
                success:function(result) {

                        $("#app").html(result).hide().fadeIn(1200);
                },
                error : function(e){
                        console.info("Error");
                }
                });
        });

</code>```

And these are my routes:

```<code>Route::get('/', function () {
    return view('master');
});
Route::get('/main', function () {
    return view('main');
});
Route::get('/trabajos', function(){
    return view('menu.trabajos');
});
Route::get('/contacto', function(){
    return view('menu.contacto');
});
Route::get('/empresa', function(){
    return view('menu.empresa');
});
</code>```

This is my httpd config:

```<code>#
# This is the main Apache HTTP server configuration file.  It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
# In particular, see
# <URL:http://httpd.apache.org/docs/2.4/mod/directives.html>
# for a discussion of each configuration directive.
#
# Do NOT simply read the instructions in here without understanding
# what they do.  They're here only as hints or reminders.  If you are unsure
# consult the online docs. You have been warned.
#
# Configuration and logfile names: If the filenames you specify for many
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# server will use that explicit path.  If the filenames do *not* begin
# with "/", the value of ServerRoot is prepended -- so 'log/access_log'
# with ServerRoot set to '/www' will be interpreted by the
# server as '/www/log/access_log', where as '/log/access_log' will be
# interpreted as '/log/access_log'.

#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# Do not add a slash at the end of the directory path.  If you point
# ServerRoot at a non-local disk, be sure to specify a local disk on the
# Mutex directive, if file-based mutexes are used.  If you wish to share the
# same ServerRoot for multiple httpd daemons, you will need to change at
# least PidFile.
#
ServerRoot "/etc/httpd"

#
# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
#
# Change this to Listen on specific IP addresses as shown below to
# prevent Apache from glomming onto all bound IP addresses.
#
#Listen 12.34.56.78:80
Listen 80

#
# Dynamic Shared Object (DSO) Support
#
# To be able to use the functionality of a module which was built as a DSO you
# have to place corresponding `LoadModule' lines at this location so the
# directives contained in it are actually available _before_ they are used.
# Statically compiled modules (those listed by `httpd -l') do not need
# to be loaded here.
#
# Example:
# LoadModule foo_module modules/mod_foo.so
#
Include conf.modules.d/*.conf

#
# If you wish httpd to run as a different user or group, you must run
# httpd as root initially and it will switch.
#
# User/Group: The name (or #number) of the user/group to run httpd as.
# It is usually good practice to create a dedicated user and group for
# running httpd, as with most system services.
#
User apache
Group apache

# 'Main' server configuration
#
# The directives in this section set up the values used by the 'main'
# server, which responds to any requests that aren't handled by a
# <VirtualHost> definition.  These values also provide defaults for
# any <VirtualHost> containers you may define later in the file.
#
# All of these directives may appear inside <VirtualHost> containers,
# in which case these default settings will be overridden for the
# virtual host being defined.
#

#
# ServerAdmin: Your address, where problems with the server should be
# e-mailed.  This address appears on some server-generated pages, such
# as error documents.  e.g. admin@your-domain.com
#
ServerAdmin root@localhost

#
# ServerName gives the name and port that the server uses to identify itself.
# This can often be determined automatically, but we recommend you specify
# it explicitly to prevent problems during startup.
#
# If your host doesn't have a registered DNS name, enter its IP address here.
#
#ServerName www.example.com:80

#
# Deny access to the entirety of your server's filesystem. You must
# explicitly permit access to web content directories in other
# <Directory> blocks below.
#
<Directory /var/www/laravel/>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

#
# Note that from this point forward you must specifically allow
# particular features to be enabled - so if something's not working as
# you might expect, make sure that you have specifically enabled it
# below.
#

#
# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
DocumentRoot "/var/www/html/imprenta/public/"

#
# Relax access to content within /var/www.
#
<Directory "/var/www">
    AllowOverride None
    # Allow open access:
    Require all granted
</Directory>

# Further relax access to the default document root:
<Directory "/var/www/html">
    #
    # Possible values for the Options directive are "None", "All",
    # or any combination of:
    #   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
    #
    # Note that "MultiViews" must be named *explicitly* --- "Options All"
    # doesn't give it to you.
    #
    # The Options directive is both complicated and important.  Please see
    # http://httpd.apache.org/docs/2.4/mod/core.html#options
    # for more information.
    #
    Options Indexes FollowSymLinks

    #
    # AllowOverride controls what directives may be placed in .htaccess files.
    # It can be "All", "None", or any combination of the keywords:
    #   Options FileInfo AuthConfig Limit
    #
    AllowOverride None

    #
    # Controls who can get stuff from this server.
    #
    Require all granted
</Directory>

#
# DirectoryIndex: sets the file that Apache will serve if a directory
# is requested.
#
<IfModule dir_module>
    DirectoryIndex index.html
</IfModule>

#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<Files ".ht*">
    Require all denied
</Files>

#
# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here.  If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog "logs/error_log"

#
# LogLevel: Control the number of messages logged to the error_log.
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
#
LogLevel warn

<IfModule log_config_module>
    #
    # The following directives define some format nicknames for use with
    # a CustomLog directive (see below).
    #
    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
    LogFormat "%h %l %u %t \"%r\" %>s %b" common

    <IfModule logio_module>
      # You need to enable mod_logio.c to use %I and %O
      LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
    </IfModule>

    #
    # The location and format of the access logfile (Common Logfile Format).
    # If you do not define any access logfiles within a <VirtualHost>
    # container, they will be logged here.  Contrariwise, if you *do*
    # define per-<VirtualHost> access logfiles, transactions will be
    # logged therein and *not* in this file.
    #
    #CustomLog "logs/access_log" common

    #
    # If you prefer a logfile with access, agent, and referer information
    # (Combined Logfile Format) you can use the following directive.
    #
    CustomLog "logs/access_log" combined
</IfModule>

<IfModule alias_module>
    #
    # Redirect: Allows you to tell clients about documents that used to
    # exist in your server's namespace, but do not anymore. The client
    # will make a new request for the document at its new location.
    # Example:
    # Redirect permanent /foo http://www.example.com/bar

    #
    # Alias: Maps web paths into filesystem paths and is used to
    # access content that does not live under the DocumentRoot.
    # Example:
    # Alias /webpath /full/filesystem/path
    #
    # If you include a trailing / on /webpath then the server will
    # require it to be present in the URL.  You will also likely
    # need to provide a <Directory> section to allow access to
    # the filesystem path.

    #
    # ScriptAlias: This controls which directories contain server scripts.
    # ScriptAliases are essentially the same as Aliases, except that
    # documents in the target directory are treated as applications and
    # run by the server when requested rather than as documents sent to the
    # client.  The same rules about trailing "/" apply to ScriptAlias
    # directives as to Alias.
    #
    ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"

</IfModule>

#
# "/var/www/cgi-bin" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "/var/www/cgi-bin">
    AllowOverride None
    Options None
    Require all granted
</Directory>

<IfModule mime_module>
    #
    # TypesConfig points to the file containing the list of mappings from
    # filename extension to MIME-type.
    #
    TypesConfig /etc/mime.types

    #
    # AddType allows you to add to or override the MIME configuration
    # file specified in TypesConfig for specific file types.
    #
    #AddType application/x-gzip .tgz
    #
    # AddEncoding allows you to have certain browsers uncompress
    # information on the fly. Note: Not all browsers support this.
    #
    #AddEncoding x-compress .Z
    #AddEncoding x-gzip .gz .tgz
    #
    # If the AddEncoding directives above are commented-out, then you
    # probably should define those extensions to indicate media types:
    #
    AddType application/x-compress .Z
    AddType application/x-gzip .gz .tgz

    #
    # AddHandler allows you to map certain file extensions to "handlers":
    # actions unrelated to filetype. These can be either built into the server
    # or added with the Action directive (see below)
    #
    # To use CGI scripts outside of ScriptAliased directories:
    # (You will also need to add "ExecCGI" to the "Options" directive.)
    #
    #AddHandler cgi-script .cgi

    # For type maps (negotiated resources):
    #AddHandler type-map var

    #
    # Filters allow you to process content before it is sent to the client.
    #
    # To parse .shtml files for server-side includes (SSI):
    # (You will also need to add "Includes" to the "Options" directive.)
    #
    AddType text/html .shtml
    AddOutputFilter INCLUDES .shtml
</IfModule>

#
# Specify a default charset for all content served; this enables
# interpretation of all content as UTF-8 by default.  To use the
# default browser choice (ISO-8859-1), or to allow the META tags
# in HTML content to override this choice, comment out this
# directive:
#
AddDefaultCharset UTF-8

<IfModule mime_magic_module>
    #
    # The mod_mime_magic module allows the server to use various hints from the
    # contents of the file itself to determine its type.  The MIMEMagicFile
    # directive tells the module where the hint definitions are located.
    #
    MIMEMagicFile conf/magic
</IfModule>

#
# Customizable error responses come in three flavors:
# 1) plain text 2) local redirects 3) external redirects
#
# Some examples:
#ErrorDocument 500 "The server made a boo boo."
#ErrorDocument 404 /missing.html
#ErrorDocument 404 "/cgi-bin/missing_handler.pl"
#ErrorDocument 402 http://www.example.com/subscription_info.html
#

#
# EnableMMAP and EnableSendfile: On systems that support it,
# memory-mapping or the sendfile syscall may be used to deliver
# files.  This usually improves server performance, but must
# be turned off when serving from networked-mounted
# filesystems or if support for these functions is otherwise
# broken on your system.
# Defaults if commented: EnableMMAP On, EnableSendfile Off
#
#EnableMMAP off
EnableSendfile on

# Supplemental configuration
#
# Load config files in the "/etc/httpd/conf.d" directory, if any.
IncludeOptional conf.d/*.conf
</code>```

I get this error with the config:

```<code>* httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
   Active: failed (Result: exit-code) since Fri 2019-05-31 08:44:37 EDT; 24s ago
     Docs: man:httpd(8)
           man:apachectl(8)
  Process: 28971 ExecStop=/bin/kill -WINCH ${MAINPID} (code=exited, status=1/FAILURE)
  Process: 28969 ExecStart=/usr/sbin/httpd $OPTIONS -DFOREGROUND (code=exited, status=1/FAILURE)
 Main PID: 28969 (code=exited, status=1/FAILURE)

May 31 08:44:37 server.imprentasanchez.tk systemd[1]: Starting The Apache HTTP Server...
May 31 08:44:37 server.imprentasanchez.tk httpd[28969]: AH00534: httpd: Configuration erro....
May 31 08:44:37 server.imprentasanchez.tk systemd[1]: httpd.service: main process exited, ...E
May 31 08:44:37 server.imprentasanchez.tk kill[28971]: kill: cannot find process ""
May 31 08:44:37 server.imprentasanchez.tk systemd[1]: httpd.service: control process exite...1
May 31 08:44:37 server.imprentasanchez.tk systemd[1]: Failed to start The Apache HTTP Server.
May 31 08:44:37 server.imprentasanchez.tk systemd[1]: Unit httpd.service entered failed state.
May 31 08:44:37 server.imprentasanchez.tk systemd[1]: httpd.service failed.
Hint: Some lines were ellipsized, use -l to show in full.
[root@server conf]#
</code>```

Config file with suggested configuration:

```<code><VirtualHost *:80>
    ServerName MyProject
    ServerAlias imprentasanchez.tk www.imprentasanchez.tk
    DocumentRoot /var/www/html/imprenta/public
    <Directory  "/var/www/html/imprenta/public">
        Options +Indexes +Includes +FollowSymLinks +MultiViews
        AllowOverride All
    </Directory>
</VirtualHost>
</code>```

答:
try install centosWebpanel for your server managment .
its really good </p>

Body:
So I have a project in Laravel in which I use Ajax to move between views, so no data, only GET request.

This works fine on my local machine but I uploaded it to my VPS and when I click the button that should take me to another view, I get this error:

GET http://172.106.202.124/trabajos?_=1559303733962 404 (Not Found)

So I've done some research and found some people with the same issue, but I haven't found any working answer.

Some said to modify .htaccess, I already did that and it's the same for me.

I've noticed that if I write /index.php/trabajos in the URL it gives me 'trabajos' view, but if I remove the /index.php/ it just gives me 'Not found'

This is my js code:

 $(document).on('click', '#button1', function() {
        $.ajax({
                method: "GET",
                url:'/trabajos',
                success:function(result) {

                        $("#app").html(result).hide().fadeIn(1200);
                },
                error : function(e){
                        console.info("Error");
                }
                });
        });

And these are my routes:

Route::get('/', function () {
    return view('master');
});
Route::get('/main', function () {
    return view('main');
});
Route::get('/trabajos', function(){
    return view('menu.trabajos');
});
Route::get('/contacto', function(){
    return view('menu.contacto');
});
Route::get('/empresa', function(){
    return view('menu.empresa');
});

This is my httpd config:

#
# This is the main Apache HTTP server configuration file.  It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
# In particular, see
# <URL:http://httpd.apache.org/docs/2.4/mod/directives.html>
# for a discussion of each configuration directive.
#
# Do NOT simply read the instructions in here without understanding
# what they do.  They're here only as hints or reminders.  If you are unsure
# consult the online docs. You have been warned.
#
# Configuration and logfile names: If the filenames you specify for many
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# server will use that explicit path.  If the filenames do *not* begin
# with "/", the value of ServerRoot is prepended -- so 'log/access_log'
# with ServerRoot set to '/www' will be interpreted by the
# server as '/www/log/access_log', where as '/log/access_log' will be
# interpreted as '/log/access_log'.

#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# Do not add a slash at the end of the directory path.  If you point
# ServerRoot at a non-local disk, be sure to specify a local disk on the
# Mutex directive, if file-based mutexes are used.  If you wish to share the
# same ServerRoot for multiple httpd daemons, you will need to change at
# least PidFile.
#
ServerRoot "/etc/httpd"

#
# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
#
# Change this to Listen on specific IP addresses as shown below to
# prevent Apache from glomming onto all bound IP addresses.
#
#Listen 12.34.56.78:80
Listen 80

#
# Dynamic Shared Object (DSO) Support
#
# To be able to use the functionality of a module which was built as a DSO you
# have to place corresponding `LoadModule' lines at this location so the
# directives contained in it are actually available _before_ they are used.
# Statically compiled modules (those listed by `httpd -l') do not need
# to be loaded here.
#
# Example:
# LoadModule foo_module modules/mod_foo.so
#
Include conf.modules.d/*.conf

#
# If you wish httpd to run as a different user or group, you must run
# httpd as root initially and it will switch.
#
# User/Group: The name (or #number) of the user/group to run httpd as.
# It is usually good practice to create a dedicated user and group for
# running httpd, as with most system services.
#
User apache
Group apache

# 'Main' server configuration
#
# The directives in this section set up the values used by the 'main'
# server, which responds to any requests that aren't handled by a
# <VirtualHost> definition.  These values also provide defaults for
# any <VirtualHost> containers you may define later in the file.
#
# All of these directives may appear inside <VirtualHost> containers,
# in which case these default settings will be overridden for the
# virtual host being defined.
#

#
# ServerAdmin: Your address, where problems with the server should be
# e-mailed.  This address appears on some server-generated pages, such
# as error documents.  e.g. admin@your-domain.com
#
ServerAdmin root@localhost

#
# ServerName gives the name and port that the server uses to identify itself.
# This can often be determined automatically, but we recommend you specify
# it explicitly to prevent problems during startup.
#
# If your host doesn't have a registered DNS name, enter its IP address here.
#
#ServerName www.example.com:80

#
# Deny access to the entirety of your server's filesystem. You must
# explicitly permit access to web content directories in other
# <Directory> blocks below.
#
<Directory /var/www/laravel/>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

#
# Note that from this point forward you must specifically allow
# particular features to be enabled - so if something's not working as
# you might expect, make sure that you have specifically enabled it
# below.
#

#
# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
DocumentRoot "/var/www/html/imprenta/public/"

#
# Relax access to content within /var/www.
#
<Directory "/var/www">
    AllowOverride None
    # Allow open access:
    Require all granted
</Directory>

# Further relax access to the default document root:
<Directory "/var/www/html">
    #
    # Possible values for the Options directive are "None", "All",
    # or any combination of:
    #   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
    #
    # Note that "MultiViews" must be named *explicitly* --- "Options All"
    # doesn't give it to you.
    #
    # The Options directive is both complicated and important.  Please see
    # http://httpd.apache.org/docs/2.4/mod/core.html#options
    # for more information.
    #
    Options Indexes FollowSymLinks

    #
    # AllowOverride controls what directives may be placed in .htaccess files.
    # It can be "All", "None", or any combination of the keywords:
    #   Options FileInfo AuthConfig Limit
    #
    AllowOverride None

    #
    # Controls who can get stuff from this server.
    #
    Require all granted
</Directory>

#
# DirectoryIndex: sets the file that Apache will serve if a directory
# is requested.
#
<IfModule dir_module>
    DirectoryIndex index.html
</IfModule>

#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<Files ".ht*">
    Require all denied
</Files>

#
# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here.  If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog "logs/error_log"

#
# LogLevel: Control the number of messages logged to the error_log.
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
#
LogLevel warn

<IfModule log_config_module>
    #
    # The following directives define some format nicknames for use with
    # a CustomLog directive (see below).
    #
    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
    LogFormat "%h %l %u %t \"%r\" %>s %b" common

    <IfModule logio_module>
      # You need to enable mod_logio.c to use %I and %O
      LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
    </IfModule>

    #
    # The location and format of the access logfile (Common Logfile Format).
    # If you do not define any access logfiles within a <VirtualHost>
    # container, they will be logged here.  Contrariwise, if you *do*
    # define per-<VirtualHost> access logfiles, transactions will be
    # logged therein and *not* in this file.
    #
    #CustomLog "logs/access_log" common

    #
    # If you prefer a logfile with access, agent, and referer information
    # (Combined Logfile Format) you can use the following directive.
    #
    CustomLog "logs/access_log" combined
</IfModule>

<IfModule alias_module>
    #
    # Redirect: Allows you to tell clients about documents that used to
    # exist in your server's namespace, but do not anymore. The client
    # will make a new request for the document at its new location.
    # Example:
    # Redirect permanent /foo http://www.example.com/bar

    #
    # Alias: Maps web paths into filesystem paths and is used to
    # access content that does not live under the DocumentRoot.
    # Example:
    # Alias /webpath /full/filesystem/path
    #
    # If you include a trailing / on /webpath then the server will
    # require it to be present in the URL.  You will also likely
    # need to provide a <Directory> section to allow access to
    # the filesystem path.

    #
    # ScriptAlias: This controls which directories contain server scripts.
    # ScriptAliases are essentially the same as Aliases, except that
    # documents in the target directory are treated as applications and
    # run by the server when requested rather than as documents sent to the
    # client.  The same rules about trailing "/" apply to ScriptAlias
    # directives as to Alias.
    #
    ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"

</IfModule>

#
# "/var/www/cgi-bin" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "/var/www/cgi-bin">
    AllowOverride None
    Options None
    Require all granted
</Directory>

<IfModule mime_module>
    #
    # TypesConfig points to the file containing the list of mappings from
    # filename extension to MIME-type.
    #
    TypesConfig /etc/mime.types

    #
    # AddType allows you to add to or override the MIME configuration
    # file specified in TypesConfig for specific file types.
    #
    #AddType application/x-gzip .tgz
    #
    # AddEncoding allows you to have certain browsers uncompress
    # information on the fly. Note: Not all browsers support this.
    #
    #AddEncoding x-compress .Z
    #AddEncoding x-gzip .gz .tgz
    #
    # If the AddEncoding directives above are commented-out, then you
    # probably should define those extensions to indicate media types:
    #
    AddType application/x-compress .Z
    AddType application/x-gzip .gz .tgz

    #
    # AddHandler allows you to map certain file extensions to "handlers":
    # actions unrelated to filetype. These can be either built into the server
    # or added with the Action directive (see below)
    #
    # To use CGI scripts outside of ScriptAliased directories:
    # (You will also need to add "ExecCGI" to the "Options" directive.)
    #
    #AddHandler cgi-script .cgi

    # For type maps (negotiated resources):
    #AddHandler type-map var

    #
    # Filters allow you to process content before it is sent to the client.
    #
    # To parse .shtml files for server-side includes (SSI):
    # (You will also need to add "Includes" to the "Options" directive.)
    #
    AddType text/html .shtml
    AddOutputFilter INCLUDES .shtml
</IfModule>

#
# Specify a default charset for all content served; this enables
# interpretation of all content as UTF-8 by default.  To use the
# default browser choice (ISO-8859-1), or to allow the META tags
# in HTML content to override this choice, comment out this
# directive:
#
AddDefaultCharset UTF-8

<IfModule mime_magic_module>
    #
    # The mod_mime_magic module allows the server to use various hints from the
    # contents of the file itself to determine its type.  The MIMEMagicFile
    # directive tells the module where the hint definitions are located.
    #
    MIMEMagicFile conf/magic
</IfModule>

#
# Customizable error responses come in three flavors:
# 1) plain text 2) local redirects 3) external redirects
#
# Some examples:
#ErrorDocument 500 "The server made a boo boo."
#ErrorDocument 404 /missing.html
#ErrorDocument 404 "/cgi-bin/missing_handler.pl"
#ErrorDocument 402 http://www.example.com/subscription_info.html
#

#
# EnableMMAP and EnableSendfile: On systems that support it,
# memory-mapping or the sendfile syscall may be used to deliver
# files.  This usually improves server performance, but must
# be turned off when serving from networked-mounted
# filesystems or if support for these functions is otherwise
# broken on your system.
# Defaults if commented: EnableMMAP On, EnableSendfile Off
#
#EnableMMAP off
EnableSendfile on

# Supplemental configuration
#
# Load config files in the "/etc/httpd/conf.d" directory, if any.
IncludeOptional conf.d/*.conf

I get this error with the config:

* httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
   Active: failed (Result: exit-code) since Fri 2019-05-31 08:44:37 EDT; 24s ago
     Docs: man:httpd(8)
           man:apachectl(8)
  Process: 28971 ExecStop=/bin/kill -WINCH ${MAINPID} (code=exited, status=1/FAILURE)
  Process: 28969 ExecStart=/usr/sbin/httpd $OPTIONS -DFOREGROUND (code=exited, status=1/FAILURE)
 Main PID: 28969 (code=exited, status=1/FAILURE)

May 31 08:44:37 server.imprentasanchez.tk systemd[1]: Starting The Apache HTTP Server...
May 31 08:44:37 server.imprentasanchez.tk httpd[28969]: AH00534: httpd: Configuration erro....
May 31 08:44:37 server.imprentasanchez.tk systemd[1]: httpd.service: main process exited, ...E
May 31 08:44:37 server.imprentasanchez.tk kill[28971]: kill: cannot find process ""
May 31 08:44:37 server.imprentasanchez.tk systemd[1]: httpd.service: control process exite...1
May 31 08:44:37 server.imprentasanchez.tk systemd[1]: Failed to start The Apache HTTP Server.
May 31 08:44:37 server.imprentasanchez.tk systemd[1]: Unit httpd.service entered failed state.
May 31 08:44:37 server.imprentasanchez.tk systemd[1]: httpd.service failed.
Hint: Some lines were ellipsized, use -l to show in full.
[root@server conf]#

Config file with suggested configuration:

<VirtualHost *:80>
    ServerName MyProject
    ServerAlias imprentasanchez.tk www.imprentasanchez.tk
    DocumentRoot /var/www/html/imprenta/public
    <Directory  "/var/www/html/imprenta/public">
        Options +Indexes +Includes +FollowSymLinks +MultiViews
        AllowOverride All
    </Directory>
</VirtualHost>


问:
Power BI change data source parameter
Is it possible and how change data source parameter value with slicer or check box click in power bi without manual edit and then refresh data.

答: No, it isn't possible. However, you can make a report which connects and reads all the data sources, and use a What-if parameter with slicer to calculate result based on one of the data sources only (depending on the what-if parameter's value).</p>

Title: Power BI change data source parameter


问:
Datamapper has n through and related queries
Here is my data model:

```<code>class A
  has n, :b
  has n, :c, through => :b

 def active_c
   c.active
 end
end

class C
  class << self
    def active
        all(self.end_on => nil) + all(:conditions => [ "cs.end_on > applied_to" ])
    end
  end
end
</code>```

The the SQLs look like:

```<code>SELECT `cs`.`id` FROM `cs` INNER JOIN `bs` ON `cs`.`id` = `bs`.`c_id` INNER JOIN `as` ON `bs`.`a_id` = `as`.`id` WHERE (`bs`.`a_id` = 1672 AND `cs`.`end_on` IS NULL)
SELECT `cs`.`id` FROM `cs` INNER JOIN `bs` ON `cs`.`id` = `bs`.`c_id` INNER JOIN `as` ON `bs`.`a_id` = `as`.`id` WHERE (`bs`.`a_id` = 1672 AND (cs > applied_to))
SELECT `id`, `created_at`, `updated_at`, `applied_to`, `end_on` FROM `cs` WHERE (1 = 0 OR 1 = 0) GROUP BY `id`, `created_at`, `updated_at`, `applied_to`, `end_on` ORDER BY `id`
</code>```

If I change the active_c to this impl:

```<code> def active_c
   C.all(:bs  => {:a_id => self.id}).active
 end
</code>```

The result SQLs for invoking a.active_c are:

```<code>SELECT `c_id` FROM `bs` WHERE `a_id` = 1670
SELECT `c_id` FROM `bs` WHERE `a_id` = 1670
SELECT `id`, `created_at`, `updated_at`, `applied_to`, `end_on` FROM `cs` WHERE ((1 = 0 AND `end_on` IS NULL) OR (1 = 0 AND (cs.end_on > applied_to))) ORDER BY `id`
</code>```

Now two problems:

I have to use cs.end_on in the second condition for the as table has also a column called end_on and DM will confuse

Why there are 3 queries and where the 1 = 0 coming from

Thanks

答:
I've tried setting up working models that should be in-line with what you're trying to achieve and here's the result:

```<code>class A
  include DataMapper::Resource

  property :id, Serial

  has n, :bs
  has n, :cs, :through => :bs, :via => :c

  def active_cs
    cs.active
  end
end

class B
  include DataMapper::Resource

  property :id, Serial

  belongs_to :a
  belongs_to :c
end

class C
  include DataMapper::Resource

  property :id, Serial
  property :end_on, Date
  property :applied_to, Date

  has n, :bs

  def active
    all(:end_on => nil) + all(:conditions => [ "cs.end_on > applied_to" ])
  end
end

a = A.create
b = B.create(:a => a)
c = C.create(:b => b)

puts a.active_cs.inspect
</code>```

Here's the SQL query:

```<code>SELECT "id", "end_on", "applied_to" FROM "cs" WHERE ("id" IN (SELECT "cs"."id" FROM "cs" INNER JOIN "bs" ON "cs"."id" = "bs"."c_id" INNER JOIN "as" ON "bs"."a_id" = "as"."id" WHERE ("bs"."a_id" = 1 AND "cs"."end_on" IS NULL)) OR "id" IN (SELECT "cs"."id" FROM "cs" INNER JOIN "bs" ON "cs"."id" = "bs"."c_id" INNER JOIN "as" ON "bs"."a_id" = "as"."id" WHERE ("bs"."a_id" = 1 AND (cs.end_on > applied_to)))) GROUP BY "id", "end_on", "applied_to" ORDER BY "id"
</code>```

I'm not sure if that's exactly what you need - but I hope it helps.

Here's a link to gist with a working script: https://gist.github.com/916164

Body:
Here is my data model:

class A
  has n, :b
  has n, :c, through => :b

 def active_c
   c.active
 end
end

class C
  class << self
    def active
        all(self.end_on => nil) + all(:conditions => [ "cs.end_on > applied_to" ])
    end
  end
end

The the SQLs look like:

SELECT `cs`.`id` FROM `cs` INNER JOIN `bs` ON `cs`.`id` = `bs`.`c_id` INNER JOIN `as` ON `bs`.`a_id` = `as`.`id` WHERE (`bs`.`a_id` = 1672 AND `cs`.`end_on` IS NULL)
SELECT `cs`.`id` FROM `cs` INNER JOIN `bs` ON `cs`.`id` = `bs`.`c_id` INNER JOIN `as` ON `bs`.`a_id` = `as`.`id` WHERE (`bs`.`a_id` = 1672 AND (cs > applied_to))
SELECT `id`, `created_at`, `updated_at`, `applied_to`, `end_on` FROM `cs` WHERE (1 = 0 OR 1 = 0) GROUP BY `id`, `created_at`, `updated_at`, `applied_to`, `end_on` ORDER BY `id`

If I change the active_c to this impl:

 def active_c
   C.all(:bs  => {:a_id => self.id}).active
 end

The result SQLs for invoking a.active_c are:

SELECT `c_id` FROM `bs` WHERE `a_id` = 1670
SELECT `c_id` FROM `bs` WHERE `a_id` = 1670
SELECT `id`, `created_at`, `updated_at`, `applied_to`, `end_on` FROM `cs` WHERE ((1 = 0 AND `end_on` IS NULL) OR (1 = 0 AND (cs.end_on > applied_to))) ORDER BY `id`

Now two problems:

I have to use cs.end_on in the second condition for the as table has also a column called end_on and DM will confuse

Why there are 3 queries and where the 1 = 0 coming from

Thanks

Body:
I've tried setting up working models that should be in-line with what you're trying to achieve and here's the result:

class A
  include DataMapper::Resource

  property :id, Serial

  has n, :bs
  has n, :cs, :through => :bs, :via => :c

  def active_cs
    cs.active
  end
end

class B
  include DataMapper::Resource

  property :id, Serial

  belongs_to :a
  belongs_to :c
end

class C
  include DataMapper::Resource

  property :id, Serial
  property :end_on, Date
  property :applied_to, Date

  has n, :bs

  def active
    all(:end_on => nil) + all(:conditions => [ "cs.end_on > applied_to" ])
  end
end

a = A.create
b = B.create(:a => a)
c = C.create(:b => b)

puts a.active_cs.inspect

Here's the SQL query:

SELECT "id", "end_on", "applied_to" FROM "cs" WHERE ("id" IN (SELECT "cs"."id" FROM "cs" INNER JOIN "bs" ON "cs"."id" = "bs"."c_id" INNER JOIN "as" ON "bs"."a_id" = "as"."id" WHERE ("bs"."a_id" = 1 AND "cs"."end_on" IS NULL)) OR "id" IN (SELECT "cs"."id" FROM "cs" INNER JOIN "bs" ON "cs"."id" = "bs"."c_id" INNER JOIN "as" ON "bs"."a_id" = "as"."id" WHERE ("bs"."a_id" = 1 AND (cs.end_on > applied_to)))) GROUP BY "id", "end_on", "applied_to" ORDER BY "id"

I'm not sure if that's exactly what you need - but I hope it helps.

Here's a link to gist with a working script: https://gist.github.com/916164


问:
Detecting reflexes with apple smartwatch
I want to ask whether it is possible to detect reflexes (fast movements) from the user with the apple smartwatch. Is it done by core motion?
Is there some reference code to get a grasp how to implement this functionality?

I hope that anyone can help out. Thank you very much.

答:
You shall use Core Motion to achieve that.

Apple provides watchOS 3 SwingWatch sample code demonstrating how to use CMMotionManager() and startDeviceMotionUpdates(to:) to count swings in a racquet sport.

Their code demonstrates how to detect the direction of a one-second interval of motion, although you may have to tweak the thresholds to account for the characteristics of the motion you want to track.
There's also an WWDC video Health and Fitness with Core Motion

You may also find this article helpful:

Introduction to Apple WatchKit with Core Motion — Tracking Jumping Jacks


问:
Calculate height of div based off width & maintain proportion
I am looking for a pure CSS solution to what I have here done using jQuery to help.

Basically I have 3 divs that spread evenly in width in a container. They maintain a 3/4 ration with the height being calculated off of the width. Furthermore, each div has a background image that stays proportional and some text that is centered horizontally and vertically.

$(document).ready(function() {
  function setw() {
    var footdivwidth = $('footer div').width();
    var footdivheight = footdivwidth * .75;
    $('footer div').css({
      'height': footdivheight + 'px'
    });
    $('footer div span').html('w: ' + footdivwidth + '
h: ' + footdivheight);
  }
  setw();
  $(window).resize(function() {
    setw();
  })
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>FOOTER {
  max-width: 1000px;
  margin: 0 auto;
  background-color: rgba(0, 0, 0, 0.171);
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

FOOTER DIV {
  background-image: url('https://learnwebdesign.online/img/bg.jpg');
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  flex: 1;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

FOOTER DIV SPAN {
  display: inline-block;
  text-align: center;
  background-color: rgba(165, 165, 165, 0.282);
  padding: 7px 15px;
  border-radius: 3px;
  color: #FFFFFF;
  text-transform: uppercase;
  font-weight: bold;
  letter-spacing: 2px;
  font-size: 21px;
}</code>```

left photo

center photo

right photo and more text

```
</div>
</div>
</p>

<p>Here is a pen showing what I have.
https://codepen.io/nom3d/pen/arGpBV</p>

<p>Here is a gif showing the effect when resized. Note the background image staying proportional and text staying centered.
<img src="https://i.stack.imgur.com/OyB78.gif" alt="3 box resize with proportions kept"></p>

<p>Also wondering if it's not possible with just CSS, how to do this with <strong>plain javascript</strong>, would I need to add id's to my divs?</p>

<p>Update: here is a plain javaScript function to handle this task</p>

```function setHeight(el,val){
    var box = document.querySelectorAll(el);
    var i;
    for(i = 0;i < box.length;i++){
        var width = box[i].offsetWidth;
        var height = width * val;
        box[i].style.height = height + 'px';
    }
}
// set your element to target and the ratio value
setHeight('footer div',.75);
window.onresize = function(event) {
    setHeight('footer div',.75);
};
```

答:
```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        FOOTER {
            max-width: 1000px;
            margin: 0 auto;
            background-color: rgba(0, 0, 0, 0.171);
            display: flex;
            flex-wrap: wrap;
            justify-content: space-between;
        }
        FOOTER DIV {
            position: relative;
            width: calc(100vw / 3);
            height: calc(100vw / 3 * 0.75 );
            max-height: calc(1000px / 3 * 0.75 );
            background-image: url('https://learnwebdesign.online/img/bg.jpg');
            background-position: center;
            background-size: cover;
            background-repeat: no-repeat;
            flex: 1;
            text-align: center;
            display: flex;
            align-items: center;
            justify-content: center;

        }
        FOOTER DIV SPAN {
            position: absolute;
            top:50%;
            left: 50%;
            transform: translate(-50%, -50%);
            display: inline-block;
            text-align: center;
            background-color: rgba(165, 165, 165, 0.282);
            padding: 7px 15px;
            border-radius: 3px;
            color: #FFFFFF;
            text-transform: uppercase;
            font-weight: bold;
            letter-spacing: 2px;
            font-size: 21px;
        }
    </style>
</head>
<body>
    <footer>
        <div><span>left photo</span></div>
        <div><span>center photo</span></div>
        <div><span>right photo and more text</span></div>
    </footer>
</body>
</html>
</code>```

You can Directly use given code, For making propostional width height, You have 2 different ways, one of them given below, you can use width in percentage and height with calc with the same,

another way give width in %, and instead of height you can give padding-bottom in percentage, the all are in same propostion.

Body:
I am looking for a pure CSS solution to what I have here done using jQuery to help.

Basically I have 3 divs that spread evenly in width in a container. They maintain a 3/4 ration with the height being calculated off of the width. Furthermore, each div has a background image that stays proportional and some text that is centered horizontally and vertically.

$(document).ready(function() {
  function setw() {
    var footdivwidth = $('footer div').width();
    var footdivheight = footdivwidth * .75;
    $('footer div').css({
      'height': footdivheight + 'px'
    });
    $('footer div span').html('w: ' + footdivwidth + '
h: ' + footdivheight);
  }
  setw();
  $(window).resize(function() {
    setw();
  })
});

FOOTER {
  max-width: 1000px;
  margin: 0 auto;
  background-color: rgba(0, 0, 0, 0.171);
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

FOOTER DIV {
  background-image: url('https://learnwebdesign.online/img/bg.jpg');
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  flex: 1;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

FOOTER DIV SPAN {
  display: inline-block;
  text-align: center;
  background-color: rgba(165, 165, 165, 0.282);
  padding: 7px 15px;
  border-radius: 3px;
  color: #FFFFFF;
  text-transform: uppercase;
  font-weight: bold;
  letter-spacing: 2px;
  font-size: 21px;
}

left photo

center photo

right photo and more text

Here is a pen showing what I have.
https://codepen.io/nom3d/pen/arGpBV

Here is a gif showing the effect when resized. Note the background image staying proportional and text staying centered.

Also wondering if it's not possible with just CSS, how to do this with plain javascript, would I need to add id's to my divs?

Update: here is a plain javaScript function to handle this task

function setHeight(el,val){
    var box = document.querySelectorAll(el);
    var i;
    for(i = 0;i < box.length;i++){
        var width = box[i].offsetWidth;
        var height = width * val;
        box[i].style.height = height + 'px';
    }
}
// set your element to target and the ratio value
setHeight('footer div',.75);
window.onresize = function(event) {
    setHeight('footer div',.75);
};

Body:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        FOOTER {
            max-width: 1000px;
            margin: 0 auto;
            background-color: rgba(0, 0, 0, 0.171);
            display: flex;
            flex-wrap: wrap;
            justify-content: space-between;
        }
        FOOTER DIV {
            position: relative;
            width: calc(100vw / 3);
            height: calc(100vw / 3 * 0.75 );
            max-height: calc(1000px / 3 * 0.75 );
            background-image: url('https://learnwebdesign.online/img/bg.jpg');
            background-position: center;
            background-size: cover;
            background-repeat: no-repeat;
            flex: 1;
            text-align: center;
            display: flex;
            align-items: center;
            justify-content: center;

        }
        FOOTER DIV SPAN {
            position: absolute;
            top:50%;
            left: 50%;
            transform: translate(-50%, -50%);
            display: inline-block;
            text-align: center;
            background-color: rgba(165, 165, 165, 0.282);
            padding: 7px 15px;
            border-radius: 3px;
            color: #FFFFFF;
            text-transform: uppercase;
            font-weight: bold;
            letter-spacing: 2px;
            font-size: 21px;
        }
    </style>
</head>
<body>
    <footer>
        <div><span>left photo</span></div>
        <div><span>center photo</span></div>
        <div><span>right photo and more text</span></div>
    </footer>
</body>
</html>

You can Directly use given code, For making propostional width height, You have 2 different ways, one of them given below, you can use width in percentage and height with calc with the same,

another way give width in %, and instead of height you can give padding-bottom in percentage, the all are in same propostion.


问:
Nodemon, in express.js, executes a file other than what is specified in package.json, I
Starting up a node.js express app with nodemon. If I run my app with

```<code>nodemon
</code>```

with no file specified, it starts index.js. Which fires up my express app, no problems. However, I am confused as to how it determined index.js was the correct file to start up. I looked in the package.json, for the 'main' and 'scripts' it specifies server.js, like below. Is index.js a fallback file to run for nodemon?

```<code>"description": "",
  "main": "server.js",
  "scripts": {
    "start": "node server.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
</code>```

答:
You have to add the nodemon in the scripts

"description": "",
  "main": "server.js",
  "scripts": {
    "start": "node server.js",
    "server": "nodemon server.js", //Add this
    "test": "echo \"Error: no test specified\" && exit 1"
  },
```

<p>And to run it just type</p>

<pre class="lang-js prettyprint-override"><code>npm server
</code>```

Body:
Starting up a node.js express app with nodemon. If I run my app with

nodemon

with no file specified, it starts index.js. Which fires up my express app, no problems. However, I am confused as to how it determined index.js was the correct file to start up. I looked in the package.json, for the 'main' and 'scripts' it specifies server.js, like below. Is index.js a fallback file to run for nodemon?

"description": "",
  "main": "server.js",
  "scripts": {
    "start": "node server.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },

Body:
You have to add the nodemon in the scripts

"description": "",
  "main": "server.js",
  "scripts": {
    "start": "node server.js",
    "server": "nodemon server.js", //Add this
    "test": "echo \"Error: no test specified\" && exit 1"
  },

And to run it just type

npm server


问:
How do I get the current published version in a .NET application?
I want to be able to display the current version of a .NET application that I have deployed using the publish wizard. There is a nice option to automatically update the version number every time I publish my application.

I found another question (Automatically update version number) that had this to get the current version:

```<code>Assembly.GetExecutingAssembly().GetName().Version
</code>```

This gets you the version you set in the project properties, but not the version that is automatically incremented each time you publish.

答:
You can use the following test

```<code>if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed) {
    return System.Deployment.Application.ApplicationDeployment.CurrentDeployment.CurrentVersion;
}
</code>```

to avoid the exception (as detailed in this post).

Also, I don't think you can get the current publish version via Visual Studio debugging because accessing CurrentDeployment will throw an InvalidDeploymentException.

Body:
I want to be able to display the current version of a .NET application that I have deployed using the publish wizard. There is a nice option to automatically update the version number every time I publish my application.

I found another question (Automatically update version number) that had this to get the current version:

Assembly.GetExecutingAssembly().GetName().Version

This gets you the version you set in the project properties, but not the version that is automatically incremented each time you publish.

Body:
You can use the following test

if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed) {
    return System.Deployment.Application.ApplicationDeployment.CurrentDeployment.CurrentVersion;
}

to avoid the exception (as detailed in this post).

Also, I don't think you can get the current publish version via Visual Studio debugging because accessing CurrentDeployment will throw an InvalidDeploymentException.


问:
Reduce spacing between buttons and image on mobile devices
I'm serving 2 images, one for big screens and other for mobile devices on this site:

stickersgallito.pe (In case you need another css class)

The image for mobile devices is way down than desired. I can make the image go up with: top: -40px; but this generates a gap between the green banner and the image.

CSS class:

```<code>.my_home_banner_image {
         bottom: 0;
         top: 0;
         position: relative;
         z-index: 0;
         width: 100%;
         display: block;
         margin-right: auto;
         margin-left: 0px;
 }
</code>```

Gap:

I'd like to:

1) get the image closer to the orange button by 40px.

2) make more space between blue and orange buttons (BONUS).

Complete MediaQuery:

```<code>@media (max-width: 480px) {
    /* smartphones, iPhone, portrait 480x320 phones */
    .my_home_banner {
        bottom: 0;
        margin-right: 8%;
        z-index: -600;
    }

    .productos_finales_home img {

        padding-bottom: 15px;
    }

    .my_home_banner_image {

        bottom: 0;
        top: 0;
        position: relative;
        z-index: 0;
        width: 100%;
        display: block;
        margin-right: auto;
        margin-left: 0px;
    }

    .my_home_banner_title {
        color: white;
        font-size: 36px;
        font-weight: bold;
    }

    .my_home_banner_subtitle {
        margin-top: 0%;
        padding-top: 0%;
    }

    .btn, h2, p {
        margin-bottom: 10px;
    }

    .btn-comentario {
        text-decoration: none;
        background-color: #969696;
        display: inline-block;
        text-align: center;
        vertical-align: middle;
        cursor: pointer;
        color: #fff;
        font-weight: 700;
        font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
        text-shadow: 0 -1px 0 rgba(0, 0, 0, .25);
        letter-spacing: 0;
        line-height: 1.2;
        -webkit-font-smoothing: antialiased;
        -webkit-box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        -ms-box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        -moz-box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        -o-box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        background-image: linear-gradient(to bottom, rgba(255, 255, 255, .09) 0%, rgba(0, 0, 0, .09) 100%);
        font-size: 1.4rem;
        padding: 22px 30px;
        border-radius: 6px;
        border: none;
    }

.my_home_banner_left {
    margin-left: 10px;
    z-index: 100;
}

.stickers_referenciales {
    margin-bottom: 5px;
}

}
</code>```

Codepen

https://codepen.io/anon/pen/mYaRKO

答:
I recommend not using
 elements for layout purposes.

For reference, see:

Why isn't the HTML break tag acceptable anymore for top and bottom margins?

Is it sometimes bad to use
?

: The Line Break element
.

Note: Do not use
 to create margins between paragraphs; wrap them in
 elements and use the CSS margin property to control their size.

I've removed them and adjusted the margins of the button elements.

Note that the changes must be viewed at width of 480px or less due to the media query.

@media (max-width: 480px) {

  .col-md-6 .btn {
    margin-bottom: 10%;
  }

  .col-md-6:last-child .btn {
    margin-bottom: 0;
  }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://fonts.googleapis.com/css?family=Bree+Serif" rel="stylesheet">
<link rel="stylesheet" href="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/css/custom.css">
<link rel="stylesheet" href="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/css/home.css">
<link rel="stylesheet" href="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/css/navbar.css">
<link rel="stylesheet" href="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/css/header.css">
<link rel="stylesheet" href="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/css/bootstrap.min.css">
<link rel="stylesheet" href="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/css/preloader.css">
<link rel="stylesheet" href="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/css/loader.css">
<link rel="stylesheet" href="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/css/footer.css">
<link rel="stylesheet" href="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/css/size-quantity-styles.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU" crossorigin="anonymous">

<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>

<div class="general-container"></div>

<nav class="navbar navbar-expand-md navbar-dark fixed-top navbar-bg">
    <img src="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/img/stickers_gallito_logo.png" width="20px" height="30px">
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>
  <div class="collapse navbar-collapse" id="navbarCollapse">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active">
        Stickers <span class="sr-only">(current)</span>
      </li>
    </ul>
    <ul class="navbar-nav ml-auto">
      <li class="nav-item active">
        <i class="fas fa-shopping-cart" style="color:white !important;"></i> ( 0)
      </li>
      <li class="nav-item active">
        <i class="fas fa-user-circle"></i> ogonzales
        <div class="dropdown-menu dropdown-menu-right">
          Historial de compras
        </div>
      </li>
      <li class="nav-item active">
        Salir <i class="fas fa-sign-out-alt"></i>
      </li>
    </ul>
  </div>
</nav>

<div class="container-fluid my_home_banner my_header_bg_color">
  <div class="row">
    <div class="col-md-6 my_home_banner-left">
      <div class="my_home_banner_left">
        <div class="my_home_banner_lef_text">
          <p class="my_home_banner_title">Stickers Personalizados</p>
          <p class="my_home_banner_subtitle my_title"><b>Fácil de ordenar por internet.</b><br><b>Envíos a todo el Perú.</b></p>
        </div>
        <div class="row ">
          <div class="col-md-6">
            Comprar
          </div>
          <div class="col-md-6">
            Muestras
          </div>
        </div>
      </div>
    </div>
    <div class="col-md-6">
      <picture>
        <source media="(max-width: 480px)" srcset="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/img/home/banner_home_mobiles.png">
        <source media="(max-width: 2056px)" srcset="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/img/home/banner_home_lion.png">
        <img class="my_home_banner_image" src="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/img/home/banner_home_lion.png">
      </picture>
    </div>
  </div>
</div></code>```

Body:
I'm serving 2 images, one for big screens and other for mobile devices on this site:

stickersgallito.pe (In case you need another css class)

The image for mobile devices is way down than desired. I can make the image go up with: top: -40px; but this generates a gap between the green banner and the image.

CSS class:

.my_home_banner_image {
         bottom: 0;
         top: 0;
         position: relative;
         z-index: 0;
         width: 100%;
         display: block;
         margin-right: auto;
         margin-left: 0px;
 }

Gap:

I'd like to:

1) get the image closer to the orange button by 40px.

2) make more space between blue and orange buttons (BONUS).

Complete MediaQuery:

@media (max-width: 480px) {
    /* smartphones, iPhone, portrait 480x320 phones */
    .my_home_banner {
        bottom: 0;
        margin-right: 8%;
        z-index: -600;
    }

    .productos_finales_home img {

        padding-bottom: 15px;
    }

    .my_home_banner_image {

        bottom: 0;
        top: 0;
        position: relative;
        z-index: 0;
        width: 100%;
        display: block;
        margin-right: auto;
        margin-left: 0px;
    }

    .my_home_banner_title {
        color: white;
        font-size: 36px;
        font-weight: bold;
    }

    .my_home_banner_subtitle {
        margin-top: 0%;
        padding-top: 0%;
    }

    .btn, h2, p {
        margin-bottom: 10px;
    }

    .btn-comentario {
        text-decoration: none;
        background-color: #969696;
        display: inline-block;
        text-align: center;
        vertical-align: middle;
        cursor: pointer;
        color: #fff;
        font-weight: 700;
        font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
        text-shadow: 0 -1px 0 rgba(0, 0, 0, .25);
        letter-spacing: 0;
        line-height: 1.2;
        -webkit-font-smoothing: antialiased;
        -webkit-box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        -ms-box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        -moz-box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        -o-box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        background-image: linear-gradient(to bottom, rgba(255, 255, 255, .09) 0%, rgba(0, 0, 0, .09) 100%);
        font-size: 1.4rem;
        padding: 22px 30px;
        border-radius: 6px;
        border: none;
    }

.my_home_banner_left {
    margin-left: 10px;
    z-index: 100;
}

.stickers_referenciales {
    margin-bottom: 5px;
}

}

Codepen

https://codepen.io/anon/pen/mYaRKO

Body:
I recommend not using <br> elements for layout purposes.

For reference, see:

Why isn't the HTML break tag acceptable anymore for top and bottom margins?

Is it sometimes bad to use <BR />?

<br>: The Line Break element
.

Note: Do not use <br> to create margins between paragraphs; wrap them in <p> elements and use the CSS margin property to control their size.

I've removed them and adjusted the margins of the button elements.

Note that the changes must be viewed at width of 480px or less due to the media query.

@media (max-width: 480px) {

  .col-md-6 .btn {
    margin-bottom: 10%;
  }

  .col-md-6:last-child .btn {
    margin-bottom: 0;
  }

}

<link href="https://fonts.googleapis.com/css?family=Bree+Serif" rel="stylesheet">
<link rel="stylesheet" href="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/css/custom.css">
<link rel="stylesheet" href="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/css/home.css">
<link rel="stylesheet" href="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/css/navbar.css">
<link rel="stylesheet" href="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/css/header.css">
<link rel="stylesheet" href="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/css/bootstrap.min.css">
<link rel="stylesheet" href="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/css/preloader.css">
<link rel="stylesheet" href="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/css/loader.css">
<link rel="stylesheet" href="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/css/footer.css">
<link rel="stylesheet" href="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/css/size-quantity-styles.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU" crossorigin="anonymous">

<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>

<div class="general-container"></div>

<nav class="navbar navbar-expand-md navbar-dark fixed-top navbar-bg">
  <a class="navbar-brand" href="/">&emsp;&emsp;<img src="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/img/stickers_gallito_logo.png" width="20px" height="30px"></a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>
  <div class="collapse navbar-collapse" id="navbarCollapse">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active">
        <a class="nav-link" href="/stickers">Stickers <span class="sr-only">(current)</span></a>
      </li>
    </ul>
    <ul class="navbar-nav ml-auto">
      <li class="nav-item active">
        <a class="nav-link" href="/carrito_de_compras/"><i class="fas fa-shopping-cart" style="color:white !important;"></i> ( 0)</a>
      </li>
      <li class="nav-item active">
        <a class="nav-link dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><i class="fas fa-user-circle"></i> ogonzales</a>
        <div class="dropdown-menu dropdown-menu-right">
          <a href="/ordenes/historial_de_compras/" class="dropdown-item">Historial de compras</a>
        </div>
      </li>
      <li class="nav-item active">
        <a class="nav-link" href="/salir/">Salir <i class="fas fa-sign-out-alt"></i></a>
      </li>
    </ul>
  </div>
</nav>

<div class="container-fluid my_home_banner my_header_bg_color">
  <div class="row">
    <div class="col-md-6 my_home_banner-left">
      <div class="my_home_banner_left">
        <div class="my_home_banner_lef_text">
          <p class="my_home_banner_title">Stickers Personalizados</p>
          <p class="my_home_banner_subtitle my_title"><b>Fácil de ordenar por internet.</b><br><b>Envíos a todo el Perú.</b></p>
        </div>
        <div class="row ">
          <div class="col-md-6">
            <a href="stickers" class="my_home_buttons btn btn-azul text-white btn-block">Comprar</a>
          </div>
          <div class="col-md-6">
            <a href="/muestras/" class="my_home_buttons btn btn-naranja text-white btn-block">Muestras</a>
          </div>
        </div>
      </div>
    </div>
    <div class="col-md-6">
      <picture>
        <source media="(max-width: 480px)" srcset="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/img/home/banner_home_mobiles.png">
        <source media="(max-width: 2056px)" srcset="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/img/home/banner_home_lion.png">
        <img class="my_home_banner_image" src="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/img/home/banner_home_lion.png">
      </picture>
    </div>
  </div>
</div>


问:
How to concat two columns value like - product_name(product_quantity), ..... from table in while loop and store in a variable
I have a table with two columns : product_name and product_qty with multiple rows

I want output as:

product_name(product_qty).........

like this one

product_one(2), product_two(4), product_three(1)

I'm trying by this method :

```<code>require 'config.php';
$grand_total = 0;
$items = array();
$qty = array();
$allItems ='';
$stmt = $conn->prepare("SELECT * FROM cart");
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()){
    $grand_total +=$row['total_price'];
    $items[] = $row['product_name'];
    $qty[] = $row['qty'];
}
$array = array_combine($items, $qty);
foreach ($array as $key => $value) {
    $allItems .= $key."(".$value."), ";
}
</code>```

And getting output as :
product_one(2), product_two(4), product_three(1),

but I don't want comma in last......

答:
You can do this using CONCAT function

SELECT CONCAT(product_name, ' ', product_qty) FROM table

No Need to use foreach and array_combine all. From query itself you can fetch data as you need. Check below your update code

```<code>$grand_total = 0;
$sqlStmt = "SELECT CONCAT(product_name, '(', product_qty,')') AS ItemQty,total_price FROM cart";
$stmt = $conn->prepare($sqlStmt);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()){
    $grand_total +=$row['total_price'];
    $items[] = $row['ItemQty'];
}
echo "```";
print_r($items);
print_r($grand_total);
```

<p>Sample output</p>

<blockquote>
```Array (
[0] => product_one(2)
[1] => product_two(4)
[2] => product_one(2)
[3] => product_two(4)
[4] => product_three(1) ) 1700
```

Body:
I have a table with two columns : product_name and product_qty with multiple rows

I want output as:

product_name(product_qty).........

like this one

product_one(2), product_two(4), product_three(1)

I'm trying by this method :

require 'config.php';
$grand_total = 0;
$items = array();
$qty = array();
$allItems ='';
$stmt = $conn->prepare("SELECT * FROM cart");
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()){
    $grand_total +=$row['total_price'];
    $items[] = $row['product_name'];
    $qty[] = $row['qty'];
}
$array = array_combine($items, $qty);
foreach ($array as $key => $value) {
    $allItems .= $key."(".$value."), ";
}

And getting output as :
product_one(2), product_two(4), product_three(1),

but I don't want comma in last......

Body:
You can do this using CONCAT function

SELECT CONCAT(product_name, ' ', product_qty) FROM table

No Need to use foreach and array_combine all. From query itself you can fetch data as you need. Check below your update code

$grand_total = 0;
$sqlStmt = "SELECT CONCAT(product_name, '(', product_qty,')') AS ItemQty,total_price FROM cart";
$stmt = $conn->prepare($sqlStmt);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()){
    $grand_total +=$row['total_price'];
    $items[] = $row['ItemQty'];
}
echo "<pre>";
print_r($items);
print_r($grand_total);

Sample output

Array (
[0] => product_one(2)
[1] => product_two(4)
[2] => product_one(2)
[3] => product_two(4)
[4] => product_three(1) ) 1700


问:
How to konw the Primary InterCardinal direction (N,E,S,W) of a place using the current location latitude and longitude?
I'm kind of lost here, I'm working on my app and this really confused me. Let me explain it like this, for example;

A- is my current location with Lat&Long.
B- is another location Lat&Long.

Now, I want the lat&Long of B pointing toward A Lat&Long. However,
I want to get the data as Compass Degree and Primary InterCardinal directions

Something like this: <== Just an Example not real :)

A- Current Location: Washington, D.C. ,USA
B- Another Location: Ottawa, Canada

The output something like:-  B to A: 185 Degree, South West (SW)

Thanks in Advance

P.S. I Already Created a Compass Activity, and I know how to get my current location as will getting the other location lat&long.

答: Use Location.bearingTo to get the angle between the two locations.  The return is degrees, with 0 being north and going clockwise from there.  You can do the math yourself to figure out a bearing.  Just divide those 360 degrees into equally sized ranges with the exact bearing you want to print in the center of each range, and see which range its in.</p>


问:
Why my cql query with double quotes doesn't work but with single quotes works?
Are double quotes not allowed in cql?

running this query works

```<code>val statement4 =
        s"""
           | INSERT INTO users (bucket,email,firstname,lastname,authprovider,password,confirmed,id,hasher,salt) VALUES
           | (1,'${testEnv.email}','fn','ln','${testEnv.loginInfo.providerID}','somePassword',false,${testEnv.mockHelperMethods.getUniqueID()},'someHasher','someSalt')
        """.stripMargin
</code>```

but this doesn't (because I am using double quotes)

```<code>val statement4 =
        s"""
           | INSERT INTO users (bucket,email,firstname,lastname,authprovider,password,confirmed,id,hasher,salt) VALUES
           | (1,"${testEnv.email}","fn","ln","${testEnv.loginInfo.providerID}","somePassword",false,${testEnv.mockHelperMethods.getUniqueID()},"someHasher","someSalt")
        """.stripMargin
</code>```

答:
This behaviour may come from cql, where double quotes are used to ensure that the case of the names of objects (like keyspaces, tables or user-defined functions), while single quotes are usually use to delimit values.

Note that if single quotes are not an option, you can use a double-dollar sign to delimit those values.

Body:
Are double quotes not allowed in cql?

running this query works

val statement4 =
        s"""
           | INSERT INTO users (bucket,email,firstname,lastname,authprovider,password,confirmed,id,hasher,salt) VALUES
           | (1,'${testEnv.email}','fn','ln','${testEnv.loginInfo.providerID}','somePassword',false,${testEnv.mockHelperMethods.getUniqueID()},'someHasher','someSalt')
        """.stripMargin

but this doesn't (because I am using double quotes)

val statement4 =
        s"""
           | INSERT INTO users (bucket,email,firstname,lastname,authprovider,password,confirmed,id,hasher,salt) VALUES
           | (1,"${testEnv.email}","fn","ln","${testEnv.loginInfo.providerID}","somePassword",false,${testEnv.mockHelperMethods.getUniqueID()},"someHasher","someSalt")
        """.stripMargin


问:
last day/time of month
How do I get the last day of the month to be 11:59:59 pm? Right now it is showing 05/31/2019 12:00 AM. If I just do sysdate it just shows the time I ran it. Thanks. </p>

```<code>LAST_DAY(TRUNC(SYSDATE,'MM'))
</code>```

答:
The oldfashioned way would be to subtract a second (that's what 1 / (24*60*60) represents as there are 24 hours in a day, 60 minutes in an hour and 60 seconds in a minute) from the first day of the next month (and that's what trunc(add_months(sysdate, 1)) does):

```<code>SQL> select sysdate today,
  2         trunc(add_months(sysdate, 1)) - 1/(24*60*60) result
  3  from dual;

TODAY                  RESULT
---------------------- ----------------------
06/01/2019 07:52:40 AM 06/30/2019 11:59:59 PM

SQL>
</code>```

Title: last day/time of month

Body:
How do I get the last day of the month to be 11:59:59 pm? Right now it is showing 05/31/2019 12:00 AM. If I just do sysdate it just shows the time I ran it. Thanks.

LAST_DAY(TRUNC(SYSDATE,'MM'))

Body:
The oldfashioned way would be to subtract a second (that's what 1 / (24*60*60) represents as there are 24 hours in a day, 60 minutes in an hour and 60 seconds in a minute) from the first day of the next month (and that's what trunc(add_months(sysdate, 1)) does):

SQL> select sysdate today,
  2         trunc(add_months(sysdate, 1)) - 1/(24*60*60) result
  3  from dual;

TODAY                  RESULT
---------------------- ----------------------
06/01/2019 07:52:40 AM 06/30/2019 11:59:59 PM

SQL>


问:
How to display logged in user id on page header in Oracle apex?
I am trying to display the logged in user id on the header of the page. How to achieve this?

I can see app name on top left corner. I need to display logged in user id using a query on top middle part.

答:
You will find all the documentation for substitution strings at

https://docs.oracle.com/database/121/HTMDB/concept_sub.htm#HTMDB03024

Consider the following examples:

From within an HTML region:

```<code>Hello you are logged in as &APP_USER.
</code>```

Using PL/SQL:

```<code>htp.p('Hello you are logged in as'||V('APP_USER'));
</code>```

As a bind variable:

```<code>SELECT * FROM some_table WHERE user_id = :APP_USER
</code>```

Body:
You will find all the documentation for substitution strings at

https://docs.oracle.com/database/121/HTMDB/concept_sub.htm#HTMDB03024

Consider the following examples:

From within an HTML region:

Hello you are logged in as &APP_USER.

Using PL/SQL:

htp.p('Hello you are logged in as'||V('APP_USER'));

As a bind variable:

SELECT * FROM some_table WHERE user_id = :APP_USER


问:
how to transfer or transform html
 to html <datalist>
I have some object in li in my html file I want to transfer same items to html datalist in same html file I am working in node js express framework application where data in li comes from sql databse

I have tried coating li inside datalist but it did not work

```<code><input type="text" id="txtAutoComplete" list="names"/><!--your input textbox-->
        <datalist id="names">
            <option>
            <% shipper_names.forEach((shipper_names, index)=>{%>
                <ul id="names">
                    <li>
                           <%= shipper_names.Shipper_Name%>
                    </li>
                </ul>
            <%})%>
            </option>
        </datalist>
</code>```

expected result is an autocomplete text box but when I tried to put variable between option tag of datalist it did not work than i tried to put li inside  tag of datalist  its also not working but when I removed datalist  list tag from html file list is displaying perfectly

答:
            <input type="text" id="txtAutoComplete" list="names" />

            <datalist id="names">
                <% shipper_names.forEach((shipper_names, index)=>{%>
                <option id=<%= shipper_names.Shipper_ID%>>
                    <%= shipper_names.Shipper_Name%></option>
                <%})%>
            </datalist>

```

this is working correctly

Title: how to transfer or transform html <li> to html <datalist>

Body:
I have some object in li in my html file I want to transfer same items to html datalist in same html file I am working in node js express framework application where data in li comes from sql databse

I have tried coating li inside datalist but it did not work

<input type="text" id="txtAutoComplete" list="names"/>
        <datalist id="names">
            <option>
            <% shipper_names.forEach((shipper_names, index)=>{%>

                           <%= shipper_names.Shipper_Name%>

            <%})%>
            </option>
        </datalist>

expected result is an autocomplete text box but when I tried to put variable between option tag of datalist it did not work than i tried to put li inside  tag of datalist  its also not working but when I removed datalist  list tag from html file list is displaying perfectly

Body:
<div>
            <input type="text" id="txtAutoComplete" list="names" />
            <!--your input textbox-->
            <datalist id="names">
                <% shipper_names.forEach((shipper_names, index)=>{%>
                <option id=<%= shipper_names.Shipper_ID%>>
                    <%= shipper_names.Shipper_Name%></option>
                <%})%>
            </datalist>
</div>

this is working correctly