问:
How to add more than item to the session in Flask
I've created a add-to-cart in my website and it works just great.

Am using Jquery.getJSON to make the request to get the value of the chosen product, here is the code:

```<code>    $(function() {
      $('a#process_menu').bind('click', function() {
        /*var amount = document.getElementById('kale').value;*/
        $.getJSON('{{url_for("get_the_order")}}', {
          menu_order: $(this).text(), price_order: $('input[name="kalkal"]').val(),
        }, function(data) {
          location.reload();
        });
        return false;
      });
    });
</code>```

and here is the function that receiving the request:

```<code>@app.route('/get_the_order')
def get_the_order():

    global the_order_list

    try:

        the_order_list = []
        sum_list = []

        get_order = request.args.get('menu_order', 0, type=str)
        get_price = request.args.get('price_order', 0, type=str)

        the_order_list.append(get_order)
        sum_list.append(get_price)

        session['theOrder'] = ' '.join(the_order_list)
        session['price'] = ' '.join(sum_list)

        return jsonify(result=the_order_list + sum_list)

    except Exception as e:
        return redirect("menu")
</code>```

and here i have the template that shows all the products:

```<code>{% if entries_menu %}
    {% for menu_ent in entries_menu %}
        <div class="col-sm-6 col-md-3 col-lg-3 {{menu_ent.categorie}}">
            <div class="portfolio-item">
                <div class="hover-bg">
                    <a id="process_menu">
                        <div class="hover-text">
                            <h4 id="title">{{menu_ent.title}}</h4>
                            <small id="price">{{menu_ent.price}}</small>
                            <div class="clearfix"></div>
                            <i class="fa fa-plus add_basket"></i>
                            <div class="counter-order">
                                <div class="row">
                                    <div class="col-md-3">
                                        <form>
                                            <fieldset>
                                                <div class="form-group">
                                                    <input id="kale" name="kalkal" class="form-control" type="number" value="1" min="1" max="999" />
                                                </div>
                                            </fieldset>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <img src="../../static/{{menu_ent.path}}" class="img-responsive" alt="..." id="image-menu">
                    </a>
                </div>
                <h4 class="brand bold">{{menu_ent.title}}</h4>
                <span class="price pull-right">{{menu_ent.price}} </span><span class="amount pull-right"> {{menu_ent.amount}}</span>
                <p id="descr">{{menu_ent.descr}}</p>
            </div>
        </div>
    {% endfor %}
{% endif %}
</code>```

here i made this function to put all the products within array and showing them above where the cart exist beside the header, this is the file where all the logic happens also where it should show what i want:

```<code>        {% if session.logged_in %}

            {% if session.theOrder %}
                <div class="confirm-cancel">
                    <a href="{{url_for('flush')}}"><i class="fa fa-close fa-3x btn-danger"></i></a>
                    <a href="{{url_for('order_dish')}}"><i class="fa fa-check fa-3x btn-success"></i></a>
                </div>
            {% endif %}

            <li class='main'><a href='/#main'><span>Main</span></a></li>
            <li class="comfort"><a href='/#ckidki' ><span>Chief</span></a></li>
            <li class="menu"><a href='/menu/' ><span>Menu</span></a></li>
            <li class="order"><a href="/order/" ><span>Make an order</span></a></li>
            <li class="contact"><a href='/#contact' ><span>Contact us</span></a></li>
            <li class="last orders"><a href='/admin/' ><span>Admin</span></a></li>

            {% if session.theOrder %}

                <li class="basket"><i class="fa fa-shopping-basket fa-3x" style="color: #fff;"><p class="pull-left" id="bask" style="font-size: 19px; font-weight: 600; font-family: "Russo One",sans-serif;">{{session.get('theOrder')}} &nbspx{{session.get('price')}}</p></i></li>

            {% else %}

                <li class="basket"><i class="fa fa-shopping-basket fa-3x" style="color: #fff;"><p class="pull-left" id="bask" style="font-size: 19px; font-weight: 600; font-family: "Russo One",sans-serif;">0$ &nbsp&nbsp</p></i></li>

            {% endif %}
        {% endif %}
</code>```

The problem is i can't get all the products that i've been chosen inside the session, so if i checked the products list i see only one, in fact , am getting only the clicked item every time.

Please, any suggestion how to make that work, anyway please, any help would be tons appreciated .

答:
I modified your code like this:</p>

```<code>    the_order_list = session['theOrder']
    sum_list = session['price']

    the_order_list.append(get_order)
    sum_list.append(get_price)

    session['theOrder'] = the_order_list
    session['price'] = sum_list
</code>```

Body:
I've created a add-to-cart in my website and it works just great.

Am using Jquery.getJSON to make the request to get the value of the chosen product, here is the code:

    $(function() {
      $('a#process_menu').bind('click', function() {
        /*var amount = document.getElementById('kale').value;*/
        $.getJSON('{{url_for("get_the_order")}}', {
          menu_order: $(this).text(), price_order: $('input[name="kalkal"]').val(),
        }, function(data) {
          location.reload();
        });
        return false;
      });
    });

and here is the function that receiving the request:

@app.route('/get_the_order')
def get_the_order():

    global the_order_list

    try:

        the_order_list = []
        sum_list = []

        get_order = request.args.get('menu_order', 0, type=str)
        get_price = request.args.get('price_order', 0, type=str)

        the_order_list.append(get_order)
        sum_list.append(get_price)

        session['theOrder'] = ' '.join(the_order_list)
        session['price'] = ' '.join(sum_list)

        return jsonify(result=the_order_list + sum_list)

    except Exception as e:
        return redirect("menu")

and here i have the template that shows all the products:

{% if entries_menu %}
    {% for menu_ent in entries_menu %}

{{menu_ent.title}}

                            {{menu_ent.price}}

                                        <form>
                                            <fieldset>

                                                    <input id="kale" name="kalkal" class="form-control" type="number" value="1" min="1" max="999" />

                                            </fieldset>
                                        </form>

{{menu_ent.title}}

                {{menu_ent.price}}  {{menu_ent.amount}}

{{menu_ent.descr}}

    {% endfor %}
{% endif %}

here i made this function to put all the products within array and showing them above where the cart exist beside the header, this is the file where all the logic happens also where it should show what i want:

        {% if session.logged_in %}

            {% if session.theOrder %}

            {% endif %}

Main

Chief

Menu

Make an order

Contact us

Admin

            {% if session.theOrder %}

{{session.get('theOrder')}} &nbspx{{session.get('price')}}

            {% else %}

0$ &nbsp&nbsp

            {% endif %}
        {% endif %}

The problem is i can't get all the products that i've been chosen inside the session, so if i checked the products list i see only one, in fact , am getting only the clicked item every time.

Please, any suggestion how to make that work, anyway please, any help would be tons appreciated .

Body:
I modified your code like this:

    the_order_list = session['theOrder']
    sum_list = session['price']

    the_order_list.append(get_order)
    sum_list.append(get_price)

    session['theOrder'] = the_order_list
    session['price'] = sum_list


来源: stackexchange

问:
How to make http call when using Authentication Guards in Angular2
I am using authentication guards in my project. while i call http service i am getting invalid response / Anonymous object, Instead of the actual data.

below is my module.ts file

```<code>    // providers used to create fake backend
   import { NgModule }      from '@angular/core';
   import { BrowserModule } from '@angular/platform-browser';
   import { FormsModule }   from '@angular/forms';
   import { HttpModule,JsonpModule }    from '@angular/http';
   import { Jsonp } from '@angular/http';
   // used to create fake backend
   import { fakeBackendProvider } from './_helpers/index';
   import { MockBackend, MockConnection } from '@angular/http/testing';
   import { BaseRequestOptions } from '@angular/http';

   import { AppComponent }  from './app.component';
   import { routing }        from './app.routing';

   import { AlertComponent } from './_directives/index';
   import { AuthGuard } from './_guards/index';
   import { AlertService, AuthenticationService, UserService, AdminService }
   from './_services/index';
   import { HomeComponent } from './home/index';
   import { AdminDashComponent } from './home/admindashboard.component';
   import { LoginComponent } from './login/index';
   import { RegisterComponent } from './register/index';
   import { ChartsModule } from 'ng2-charts';

   @NgModule({
       imports: [
           BrowserModule,
           FormsModule,
           HttpModule,
           routing  ,
           ChartsModule,
           JsonpModule
       ],
       declarations: [
           AppComponent,
           AlertComponent,
           HomeComponent,
           LoginComponent,
           RegisterComponent,
           AdminDashComponent
       ],
       providers: [
           AuthGuard,
           AlertService,
           AuthenticationService,
           UserService,

           fakeBackendProvider,
           MockBackend,
           BaseRequestOptions,
           AdminService
       ],
       bootstrap: [AppComponent]
   })

   export class AppModule { }
</code>```

this is my Angular service

```<code>   import { Injectable } from '@angular/core';
   import { Http, Headers, Response } from '@angular/http';
   import 'rxjs/add/operator/map';
   import 'rxjs/add/operator/catch';
   import 'rxjs/add/operator/do';

   @Injectable()
   export class AdminService {

     // Define the routes we are going to interact with
     private dataUrl = 'app/_services/admin.json';

     constructor(private http: Http) { }

       adminData:any;

     // Implement a method to get the public deals
      getData(){

         var jwt = localStorage.getItem('currentUser');
         var authHeader = new Headers();

         if(jwt) {
           authHeader.append('Authorization', 'Bearer ' + jwt);
         }

         this.http.get('app/_services/admin.json', {headers: authHeader})
                   .map(res => res.text())
                   .subscribe(
                    data => {console.log('before assign ', data);
                    this.adminData = data;
                        console.log('after assign ', this.adminData)
                    },
                    err => console.log(err),
                   () => console.log('Complete')
     );
         console.log('at the end' , this.adminData);
         return this.adminData;
       }

   }
</code>```

Thanks in advance!

答:
you don't wait for http.get() and return adminData before it's set up. You should use ReplaySubject like this

```<code>import { ReplaySubject } from 'rxjs/ReplaySubject';
@Injectable()
export class AdminService {
    adminData: ReplaySubject<any> = new ReplaySubject(1);

    // Implement a method to get the public deals
    getData(){
        var jwt = localStorage.getItem('currentUser');
        var authHeader = new Headers();

        if(jwt) {
            authHeader.append('Authorization', 'Bearer ' + jwt);
        }

        // if first request get data from backend otherwise from cache
        if (!this.user.observers.length) {
            this.http.get('app/_services/admin.json', {headers: authHeader})
            .map(res => res.text())
            .subscribe(
            data => {
                console.log('before assign ', data);
                this.adminData.next(data);
                console.log('after assign ', this.adminData)
            },
            err => console.log(err),
            () => console.log('Complete'));
        }

        console.log('at the end' , this.adminData);
        return this.adminData;
    }
}
</code>```

In that case you return observable, subscribe in your component and when request to backend done you get your real data

ContentLicense: CC BY-SA 3.0

Body:
I am using authentication guards in my project. while i call http service i am getting invalid response / Anonymous object, Instead of the actual data.

below is my module.ts file

    // providers used to create fake backend
   import { NgModule }      from '@angular/core';
   import { BrowserModule } from '@angular/platform-browser';
   import { FormsModule }   from '@angular/forms';
   import { HttpModule,JsonpModule }    from '@angular/http';
   import { Jsonp } from '@angular/http';
   // used to create fake backend
   import { fakeBackendProvider } from './_helpers/index';
   import { MockBackend, MockConnection } from '@angular/http/testing';
   import { BaseRequestOptions } from '@angular/http';

   import { AppComponent }  from './app.component';
   import { routing }        from './app.routing';

   import { AlertComponent } from './_directives/index';
   import { AuthGuard } from './_guards/index';
   import { AlertService, AuthenticationService, UserService, AdminService }
   from './_services/index';
   import { HomeComponent } from './home/index';
   import { AdminDashComponent } from './home/admindashboard.component';
   import { LoginComponent } from './login/index';
   import { RegisterComponent } from './register/index';
   import { ChartsModule } from 'ng2-charts';

   @NgModule({
       imports: [
           BrowserModule,
           FormsModule,
           HttpModule,
           routing  ,
           ChartsModule,
           JsonpModule
       ],
       declarations: [
           AppComponent,
           AlertComponent,
           HomeComponent,
           LoginComponent,
           RegisterComponent,
           AdminDashComponent
       ],
       providers: [
           AuthGuard,
           AlertService,
           AuthenticationService,
           UserService,

           fakeBackendProvider,
           MockBackend,
           BaseRequestOptions,
           AdminService
       ],
       bootstrap: [AppComponent]
   })

   export class AppModule { }

this is my Angular service

   import { Injectable } from '@angular/core';
   import { Http, Headers, Response } from '@angular/http';
   import 'rxjs/add/operator/map';
   import 'rxjs/add/operator/catch';
   import 'rxjs/add/operator/do';

   @Injectable()
   export class AdminService {

     // Define the routes we are going to interact with
     private dataUrl = 'app/_services/admin.json';

     constructor(private http: Http) { }

       adminData:any;

     // Implement a method to get the public deals
      getData(){

         var jwt = localStorage.getItem('currentUser');
         var authHeader = new Headers();

         if(jwt) {
           authHeader.append('Authorization', 'Bearer ' + jwt);
         }

         this.http.get('app/_services/admin.json', {headers: authHeader})
                   .map(res => res.text())
                   .subscribe(
                    data => {console.log('before assign ', data);
                    this.adminData = data;
                        console.log('after assign ', this.adminData)
                    },
                    err => console.log(err),
                   () => console.log('Complete')
     );
         console.log('at the end' , this.adminData);
         return this.adminData;
       }

   }

Thanks in advance!

Body:
you don't wait for http.get() and return adminData before it's set up. You should use ReplaySubject like this

import { ReplaySubject } from 'rxjs/ReplaySubject';
@Injectable()
export class AdminService {
    adminData: ReplaySubject<any> = new ReplaySubject(1);

    // Implement a method to get the public deals
    getData(){
        var jwt = localStorage.getItem('currentUser');
        var authHeader = new Headers();

        if(jwt) {
            authHeader.append('Authorization', 'Bearer ' + jwt);
        }

        // if first request get data from backend otherwise from cache
        if (!this.user.observers.length) {
            this.http.get('app/_services/admin.json', {headers: authHeader})
            .map(res => res.text())
            .subscribe(
            data => {
                console.log('before assign ', data);
                this.adminData.next(data);
                console.log('after assign ', this.adminData)
            },
            err => console.log(err),
            () => console.log('Complete'));
        }

        console.log('at the end' , this.adminData);
        return this.adminData;
    }
}

In that case you return observable, subscribe in your component and when request to backend done you get your real data


问:
Show keyboard for edittext when fragment starts
When my fragment starts, I want my edittext to be in focus/let user to just start typing in it.  I am able to get it in focus with requestFocus(), but I cannot get the keyboard to show up.

I have tried both this:

```<code>edit = (EditText) view.findViewById(R.id.search);
edit.requestFocus();
InputMethodManager imgr = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imgr.showSoftInput(edit, 0);
</code>```

and

```<code>edit = (EditText) view.findViewById(R.id.search);
InputMethodManager imgr = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imgr.showSoftInput(edit, 0);
edit.requestFocus();
</code>```

How can I get the keyboard to show up for EditText?

答:
Simply, using adding 2 lines will work like a charm:

If using XML

```<code>android:focusable="true"
android:focusableInTouchMode="true"
</code>```

Else in Java:

```<code>view.setFocusableInTouchMode(true);
view.requestFocus();
</code>```

Body:
When my fragment starts, I want my edittext to be in focus/let user to just start typing in it.  I am able to get it in focus with requestFocus(), but I cannot get the keyboard to show up.

I have tried both this:

edit = (EditText) view.findViewById(R.id.search);
edit.requestFocus();
InputMethodManager imgr = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imgr.showSoftInput(edit, 0);

and

edit = (EditText) view.findViewById(R.id.search);
InputMethodManager imgr = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imgr.showSoftInput(edit, 0);
edit.requestFocus();

How can I get the keyboard to show up for EditText?

Body:
Simply, using adding 2 lines will work like a charm:

If using XML

android:focusable="true"
android:focusableInTouchMode="true"

Else in Java:

view.setFocusableInTouchMode(true);
view.requestFocus();


问:
Change the name of my zip file created with php
I have a script for create zip with images. It works really well !

```<code>create_zip($files_to_zip, 'zip/download-'.$id_account.'-'.$time.'.zip');

function create_zip($files = array(),$destination = '',$overwrite = true) {

        if(file_exists($destination) && !$overwrite) { return false; }
        $valid_files = array();
        if(is_array($files)) {
            foreach($files as $file) {
                if(file_exists($file)) {
                    $valid_files[] = $file;
                }
            }
        }
        if(count($valid_files)) {
            $zip = new ZipArchive();
            if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
                return false;
            }
            foreach($valid_files as $file) {
                $zip->addFile($file,$file);
            }
            $zip->close();

            return file_exists($destination);
        }
        else { return false; }
    }
</code>```

When I download the file, it's well named zip/download-'.$id_account.'-'.$time.'.zip
But when I want to extract this, the extract folder is always named files.
result

Please do you have any idea for rename my unzipped file to an another name ?

Thanks a lot !

答:
You can use this code to create you zip file.

do like this

```<code>$File = 'path' . time() . '.zip';
$zip = new \ZipArchive();
$res = $zip->open($File, \ZipArchive::CREATE);

if ($res === TRUE) {
    $zip->addFile($filename);
    $zip->close();
}
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=\"" . basename($File) . "\"");
header("Content-Length: " . filesize($File));
header("Pragma: no-cache");
header("Expires: 0");
readfile($File);
header("Connection: close");
</code>```

In your case you just missed header part.

Just add the header part in your code then it will work for you.

Body:
I have a script for create zip with images. It works really well !

create_zip($files_to_zip, 'zip/download-'.$id_account.'-'.$time.'.zip');

function create_zip($files = array(),$destination = '',$overwrite = true) {

        if(file_exists($destination) && !$overwrite) { return false; }
        $valid_files = array();
        if(is_array($files)) {
            foreach($files as $file) {
                if(file_exists($file)) {
                    $valid_files[] = $file;
                }
            }
        }
        if(count($valid_files)) {
            $zip = new ZipArchive();
            if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
                return false;
            }
            foreach($valid_files as $file) {
                $zip->addFile($file,$file);
            }
            $zip->close();

            return file_exists($destination);
        }
        else { return false; }
    }

When I download the file, it's well named zip/download-'.$id_account.'-'.$time.'.zip
But when I want to extract this, the extract folder is always named files.
result

Please do you have any idea for rename my unzipped file to an another name ?

Thanks a lot !

Body:
You can use this code to create you zip file.

do like this

$File = 'path' . time() . '.zip';
$zip = new \ZipArchive();
$res = $zip->open($File, \ZipArchive::CREATE);

if ($res === TRUE) {
    $zip->addFile($filename);
    $zip->close();
}
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=\"" . basename($File) . "\"");
header("Content-Length: " . filesize($File));
header("Pragma: no-cache");
header("Expires: 0");
readfile($File);
header("Connection: close");

In your case you just missed header part.

Just add the header part in your code then it will work for you.


问:
Storing reference of a class instance member function makes it loose scope
I am using Node v8.1.3

I have a class Utility in file utility.js

```<code>class Utility {
    constructor() {
        this.typeChecker = require('javascript-type-checker');
        this.internalErrors = require('../constants/internalErrors');
        this.axios = require('axios');
        this.config = require('../config');
    }

    getCurrentWeatherByLatLong(latitude, longitude) {
        if(!this.isValidLatitude(latitude)) throw this.internalErrors.ERR_LAT_INVALID;
        if(!this.isValidLongitude(longitude)) throw this.internalErrors.ERR_LONG_INVALID;
        const url = `${this.config.BASE_URL}?appid=${this.config.API_KEY}&lat=${latitude}&lon=${longitude}`;
        return this.axios.default.get(url);
    }

    isValidLatitude(latitude) {
        return (this.typeChecker.isNumber(latitude) && latitude >= -90 && latitude <=90);
    }

    isValidLongitude(longitude) {
        return (this.typeChecker.isNumber(longitude) && longitude >= -180 && longitude <= 180);
    }
}

module.exports = new Utility();
</code>```

Now, in my other file, when i do

```<code>const utility = require('./utility');
utility.getCurrentWeatherByLatLong(Number(latitude), Number(longitude))
        .then((result) => {
            console.log(result)
        })
</code>```

it works fine. However, when i do

```<code>const utility = require('./utility');
const functionToCall = utility.getCurrentWeatherByLatLong;
functionToCall(Number(latitude), Number(longitude))
        .then((result) => {
            console.log(result)
        })
</code>```

I get the error: Cannot read property 'isValidLatitude' of undefined.

Why does this error occur and how can i resolve it? thanks!

答:
Use the bind function to bind the context:

```<code>constructor() {
    this.typeChecker = require('javascript-type-checker');
    this.internalErrors = require('../constants/internalErrors');
    this.axios = require('axios');
    this.config = require('../config');
    this.getCurrentWeatherByLatLong = this.getCurrentWeatherByLatLong.bind(this)
}
</code>```

this points to the object on which the function was called. So, when you call utility.getCurrentWeatherByLatLong(...), this is utility. However, when you call functionToCall(...), this is undefined.

Alternatively, as you've suggested in the comments, you could bind functionToCall to utility:

```<code>const utility = require('./utility');
let functionToCall = utility.getCurrentWeatherByLatLong;
functionToCall = functionToCall.bind(utility);
functionToCall(Number(latitude), Number(longitude)).then((result) => {
    console.log(result);
})
</code>```

Body:
I am using Node v8.1.3

I have a class Utility in file utility.js

class Utility {
    constructor() {
        this.typeChecker = require('javascript-type-checker');
        this.internalErrors = require('../constants/internalErrors');
        this.axios = require('axios');
        this.config = require('../config');
    }

    getCurrentWeatherByLatLong(latitude, longitude) {
        if(!this.isValidLatitude(latitude)) throw this.internalErrors.ERR_LAT_INVALID;
        if(!this.isValidLongitude(longitude)) throw this.internalErrors.ERR_LONG_INVALID;
        const url = `${this.config.BASE_URL}?appid=${this.config.API_KEY}&lat=${latitude}&lon=${longitude}`;
        return this.axios.default.get(url);
    }

    isValidLatitude(latitude) {
        return (this.typeChecker.isNumber(latitude) && latitude >= -90 && latitude <=90);
    }

    isValidLongitude(longitude) {
        return (this.typeChecker.isNumber(longitude) && longitude >= -180 && longitude <= 180);
    }
}

module.exports = new Utility();

Now, in my other file, when i do

const utility = require('./utility');
utility.getCurrentWeatherByLatLong(Number(latitude), Number(longitude))
        .then((result) => {
            console.log(result)
        })

it works fine. However, when i do

const utility = require('./utility');
const functionToCall = utility.getCurrentWeatherByLatLong;
functionToCall(Number(latitude), Number(longitude))
        .then((result) => {
            console.log(result)
        })

I get the error: Cannot read property 'isValidLatitude' of undefined.

Why does this error occur and how can i resolve it? thanks!

Body:
Use the bind function to bind the context:

constructor() {
    this.typeChecker = require('javascript-type-checker');
    this.internalErrors = require('../constants/internalErrors');
    this.axios = require('axios');
    this.config = require('../config');
    this.getCurrentWeatherByLatLong = this.getCurrentWeatherByLatLong.bind(this)
}

this points to the object on which the function was called. So, when you call utility.getCurrentWeatherByLatLong(...), this is utility. However, when you call functionToCall(...), this is undefined.

Alternatively, as you've suggested in the comments, you could bind functionToCall to utility:

const utility = require('./utility');
let functionToCall = utility.getCurrentWeatherByLatLong;
functionToCall = functionToCall.bind(utility);
functionToCall(Number(latitude), Number(longitude)).then((result) => {
    console.log(result);
})


问:
Displaying a custom div inline with a h5
I know it sounds simple, but this is really annoying me. I have researched online and not found a perfect answer for me yet.

I have this html code:

```<code><h5 class="start-online"><div id="online_ajax">0</div> Clients online </h5>
</code>```

I want the online_ajax div to display inline before the Client online text.

My current css is:

```<code>h5.start-online {
    text-align: center;
    font-size: 11px;
}

.online_ajax {
    position: relative;
    display: inline-block;
}
</code>```

答:
You made a mistake.

online_ajax is an id, use # instead of dot(.)

Body:
I know it sounds simple, but this is really annoying me. I have researched online and not found a perfect answer for me yet.

I have this html code:

0
 Clients online

I want the online_ajax div to display inline before the Client online text.

My current css is:

h5.start-online {
    text-align: center;
    font-size: 11px;
}

.online_ajax {
    position: relative;
    display: inline-block;
}


问:
Meteor: Workaround for having websockets blocked in port 80?
I am having problems with a Meteor app. Some smartphones are not receiving data from subscriptions when they are connected via 3G/4G but they work properly when connecting via Wi-Fi. I think it is because Vodafone (a mobile network operator) is blocking websocket connections to port 80.

Is it possible to change the DDP port? Does anyone have a workaround to make it work?

I have tried changing the environment variable "DDP_DEFAULT_CONNECTION_URL": "ddp+sockjs://xxxxxx.com:443/sockjs" but it breaks the app for all devices and throws the following error:

```<code>GET http://0.0.1.187/sockjs/info?cb=23ctb533n5 net::ERR_ADDRESS_UNREACHABLE
</code>```

Thank you very much for your help and time!

答:
This should work out-of-the-box in Meteor, since the engine supposedly falls back to a backup technology (AJAX+JSON) if WebSockets fail. However, I had the same issue and still couldn't figure out why this wasn't automagic.

You can however force this behavior with

```<code>DISABLE_WEBSOCKETS=1
</code>```

From here: http://www.meteorpedia.com/read/Websockets

Body:
I am having problems with a Meteor app. Some smartphones are not receiving data from subscriptions when they are connected via 3G/4G but they work properly when connecting via Wi-Fi. I think it is because Vodafone (a mobile network operator) is blocking websocket connections to port 80.

Is it possible to change the DDP port? Does anyone have a workaround to make it work?

I have tried changing the environment variable "DDP_DEFAULT_CONNECTION_URL": "ddp+sockjs://xxxxxx.com:443/sockjs" but it breaks the app for all devices and throws the following error:

GET http://0.0.1.187/sockjs/info?cb=23ctb533n5 net::ERR_ADDRESS_UNREACHABLE

Thank you very much for your help and time!

Body:
This should work out-of-the-box in Meteor, since the engine supposedly falls back to a backup technology (AJAX+JSON) if WebSockets fail. However, I had the same issue and still couldn't figure out why this wasn't automagic.

You can however force this behavior with

DISABLE_WEBSOCKETS=1

From here: http://www.meteorpedia.com/read/Websockets


问:
How to omit module prefix?
I am very new to python, I have a simple question.

For example

If I do

```<code>import A
</code>```

then I can use A.b().
I am wondering, how to omit A in A.b()?

答:
This question has already been answered, but one thing to note when using imports is that

```<code>from module import foo
</code>```

and

```<code>import module
</code>```

Are absolutely the same, as far as memory and performance is concerned. In either case, the module is compiled and loaded into sys.modules. The only difference is what is brought into your namespace. In the first case, it is foo. In the second case, it is module.

Since the other answers do not explain why using from module import * is bad, this is the reason: * will import everything into your namespace for direct use. This is not a good idea unless you know what you are doing. Name clashes are definitely possible, especially when importing multiple large modules.

This may be a matter of opinion, but I believe import module followed by module.foo() is safer and gives the reader a better idea about that method/attribute, where it came from, and what it is doing. Readability matters!

Title: How to omit module prefix?

Body:
I am very new to python, I have a simple question.

For example

If I do

import A

then I can use A.b().
I am wondering, how to omit A in A.b()?

Body:
This question has already been answered, but one thing to note when using imports is that

from module import foo

and

import module

Are absolutely the same, as far as memory and performance is concerned. In either case, the module is compiled and loaded into sys.modules. The only difference is what is brought into your namespace. In the first case, it is foo. In the second case, it is module.

Since the other answers do not explain why using from module import * is bad, this is the reason: * will import everything into your namespace for direct use. This is not a good idea unless you know what you are doing. Name clashes are definitely possible, especially when importing multiple large modules.

This may be a matter of opinion, but I believe import module followed by module.foo() is safer and gives the reader a better idea about that method/attribute, where it came from, and what it is doing. Readability matters!


问:
RxJava2 Flowable do not call to onNext method in Subscriber
I'm new in rxjava and i have problem with Flowable.
When onComplete method has called in flatMap, onNext method in subscriber not called. What's wrong here?. Have any suggestion?

```<code>        ResourceSubscriber<List<Song>> subscriber = new ResourceSubscriber<List<Song>>() {
        @Override
        public void onStart() {
            Log.e(TAG, "onStart");
            mView.showProgress();
        }

        @Override
        public void onNext(List<Song> songs) {
            mView.onLocalMusicLoaded(songs);
            mView.emptyView(songs.isEmpty());
            Log.e(TAG, "onNext");
            //Not call here after onComplete called
        }

        @Override
        public void onError(Throwable t) {
            mView.hideProgress();
            Log.e(TAG, "onError: ", t);
        }

        @Override
        public void onComplete() {
            mView.hideProgress();
            Log.e(TAG, "onComplete");
        }
    };

    Disposable disposable = Flowable.just(cursor)
            .flatMap(new Function<Cursor, Publisher<List<Song>>>() {
                @Override
                public Publisher<List<Song>> apply(@NonNull Cursor cursor) throws Exception {
                    final List<Song> songs = new ArrayList<>();
                    if (cursor != null && cursor.getCount() > 0) {
                        cursor.moveToFirst();
                        do {
                            Song song = cursorToMusic(cursor);
                            songs.add(song);
                        } while (cursor.moveToNext());
                    }
                    return Flowable.create(new FlowableOnSubscribe<List<Song>>() {
                        @Override
                        public void subscribe(@NonNull FlowableEmitter<List<Song>> e) throws Exception {
                            e.onNext(songs);
                            e.onComplete();
                        }
                    }, BackpressureStrategy.LATEST);
                }
            })
            .doOnNext(new Consumer<List<Song>>() {
                @Override
                public void accept(@NonNull List<Song> songs) throws Exception {
                    Log.e(TAG, "onLoadFinished doOnNext: " + songs.size());
                    Collections.sort(songs, new Comparator<Song>() {
                        @Override
                        public int compare(Song left, Song right) {
                            return left.getDisplayName().compareTo(right.getDisplayName());
                        }
                    });
                }
            })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(subscriber);

    mCompositeDisposable.add(disposable);
</code>```

答:
From the Javadoc of ResourceSubscriber:

The default onStart() requests Long.MAX_VALUE by default. Override the method to request a custom positive amount. Use the protected request(long) to request more items and dispose() to cancel the sequence from within an onNext implementation.

```<code>    @Override
    public void onStart() {
        Log.e(TAG, "onStart");
        mView.showProgress();
        request(Long.MAX_VALUE);
    }
</code>```

Also you successfully found the Flowable.just operator, why did you replicate it via Flowable.create to emit the scalar sogs list?

Body:
I'm new in rxjava and i have problem with Flowable.
When onComplete method has called in flatMap, onNext method in subscriber not called. What's wrong here?. Have any suggestion?

        ResourceSubscriber<List<Song>> subscriber = new ResourceSubscriber<List<Song>>() {
        @Override
        public void onStart() {
            Log.e(TAG, "onStart");
            mView.showProgress();
        }

        @Override
        public void onNext(List<Song> songs) {
            mView.onLocalMusicLoaded(songs);
            mView.emptyView(songs.isEmpty());
            Log.e(TAG, "onNext");
            //Not call here after onComplete called
        }

        @Override
        public void onError(Throwable t) {
            mView.hideProgress();
            Log.e(TAG, "onError: ", t);
        }

        @Override
        public void onComplete() {
            mView.hideProgress();
            Log.e(TAG, "onComplete");
        }
    };

    Disposable disposable = Flowable.just(cursor)
            .flatMap(new Function<Cursor, Publisher<List<Song>>>() {
                @Override
                public Publisher<List<Song>> apply(@NonNull Cursor cursor) throws Exception {
                    final List<Song> songs = new ArrayList<>();
                    if (cursor != null && cursor.getCount() > 0) {
                        cursor.moveToFirst();
                        do {
                            Song song = cursorToMusic(cursor);
                            songs.add(song);
                        } while (cursor.moveToNext());
                    }
                    return Flowable.create(new FlowableOnSubscribe<List<Song>>() {
                        @Override
                        public void subscribe(@NonNull FlowableEmitter<List<Song>> e) throws Exception {
                            e.onNext(songs);
                            e.onComplete();
                        }
                    }, BackpressureStrategy.LATEST);
                }
            })
            .doOnNext(new Consumer<List<Song>>() {
                @Override
                public void accept(@NonNull List<Song> songs) throws Exception {
                    Log.e(TAG, "onLoadFinished doOnNext: " + songs.size());
                    Collections.sort(songs, new Comparator<Song>() {
                        @Override
                        public int compare(Song left, Song right) {
                            return left.getDisplayName().compareTo(right.getDisplayName());
                        }
                    });
                }
            })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(subscriber);

    mCompositeDisposable.add(disposable);

Body:
From the Javadoc of ResourceSubscriber:

The default onStart() requests Long.MAX_VALUE by default. Override the method to request a custom positive amount. Use the protected request(long) to request more items and dispose() to cancel the sequence from within an onNext implementation.

    @Override
    public void onStart() {
        Log.e(TAG, "onStart");
        mView.showProgress();
        request(Long.MAX_VALUE);
    }

Also you successfully found the Flowable.just operator, why did you replicate it via Flowable.create to emit the scalar sogs list?


问:
Logging Framework for the ASP.NET application
My application needs to log informations about user actions (inserts, updates, deletes, etc) and exceptions and i want to store de log on Oracle10, so i'am searching some log framework to use.
I read a little bit about:

1 -Log4Net

2 - Logging Application Block

3 - Elmah

Whats your opinion about these log tools?
Whats a good framework (or way to implement) log on my application?

*After a discussion with the project manager, Logging Application Block
 will be our choice, but, lets comment about this =)

答:
Both log4net and Logging Application Block are valid choices. I think ELMAH is mostly focused on error logging, so that is probably not (the only thing) that you want.

At work, I use log4net on a couple of projects. It is stable, performant and extensible, and we have never had any problems with it.

I would probably do logging with log4net and log exceptions with ELMAH also. It can log unhandled exceptions manually, and any exception you catch and handle in your application can be logged with a single call to ELMAH. This might seem like double-logging (and it is :-)). But it is very valuable to have the ELMAH log when something unexpected has failed in your application.

I have heard good things about the NLog project, but haven't used it myself. It seems to be a bit more complex that log4net, but does have the added benefit of being able to add contextual information to log messages automatically (a bit like ELMAH).

ContentLicense: CC BY-SA 2.5


问:
Cannot set anything to stickynotification
I am starting stickynotification from my service using startForeground. Notification does show up however my settings, like title or intent to show up when clicked does not take effect.

```<code>@Override
public void onCreate()
{
    Intent notificationIntent = new Intent(this, MainActivity.class);

    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                                                            notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);

    Notification notification = new NotificationCompat.Builder(this)
        //.setSmallIcon(R.mipmap.app_icon)
        .setContentTitle("My Awesome App")
        .setContentText("Doing some work...")
        .setContentInfo("Server is running")
        .setContentIntent(pendingIntent).build();

    startForeground(1337, notification);
    super.onCreate();
}
</code>```

Notification shows app name and touch for more info or to stop....

When clicked it takes me to app info where i can forestop or uninstall it.

答:
If anybody out there in this universe having same problem i suggest do not overclock your brain else you will endup missing small things like requesting permissions.

Setting up icon fixed my issue.

Body:
I am starting stickynotification from my service using startForeground. Notification does show up however my settings, like title or intent to show up when clicked does not take effect.

@Override
public void onCreate()
{
    Intent notificationIntent = new Intent(this, MainActivity.class);

    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                                                            notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);

    Notification notification = new NotificationCompat.Builder(this)
        //.setSmallIcon(R.mipmap.app_icon)
        .setContentTitle("My Awesome App")
        .setContentText("Doing some work...")
        .setContentInfo("Server is running")
        .setContentIntent(pendingIntent).build();

    startForeground(1337, notification);
    super.onCreate();
}

Notification shows app name and touch for more info or to stop....

When clicked it takes me to app info where i can forestop or uninstall it.


问:
how do i send all item id at once through url success.php?id=
As i add some items in the cart i cant change the status in the database from "ADDED TO CART " to "CONFIRMED"

<!DOCTYPE html>

<?php
require 'includes/common.php';

if (!isset($_SESSION['email']))
{
    header('location: index.php');
}
?>

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

    <link href="style.css" rel="stylesheet" type="text/css"/>
        <title>Lifestyle Store | Products</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

          <?php
        include 'includes/header.php';
        ?>
        <?php
        $user_id=$_SESSION['id'];
        //changed from above user_id to $_getc ['user_id']
        $items_query="SELECT items.id,items.name,items.price from items INNER JOIN user_items INNER JOIN users ON items.id=user_items.item_id AND user_items.user_id=users.id WHERE user_items.user_id= $user_id AND user_items.status='Added To Cart'";

        // chaged from select * from user_items inner join items on user_items.item_id=items.id where items.id=$user_id";

        $items_query_result= mysqli_query($con, $items_query) or die(mysqli_error($con));

        ?>

       <?php  if (mysqli_num_rows($items_query_result)==0){ ?>
       <?php echo 'Add something in cart';  }  else  { ?>

                                Item Number
                                Item Name
                                Price
                                Total

                            <?php

                                $total=0;
                                    while ($row= mysqli_fetch_array($items_query_result)) {
                                        $total+=$row['price'];

                                                                                ?>

                                    <?php echo $row['id']  ?> 	   <?php echo $row['name'];   ?> " class='remove_item_link ' style="color:#e53939">Remove  	    Rs. <?php   echo $row['price']; } ?>  	 Rs. <?php echo $total;?>  Confirm Order

                             <?php }?>

             <?php
        include 'includes/footer.php';
        ?>

```

this is the code for a shopping cart

user add some this in the cart

**then when the user goes to the cart the cart displays all the items with their ids, name and the price **

and finally the total price

**i have defined a while loop to sum up the price and to display the id name etc **

now i want to send the item id to the success.php to change the status in the database from "Added To Cart " to "Confirmed"

答:
[UPDATED] You can stored the ids in one variable.

```<code> <?php
     $total=0;
     $ids = '';
     while ($row= mysqli_fetch_array($items_query_result)) {
         $total+=$row['price'];
         if(strlen($ids)== 0){
            $ids = $row['id'];
         }else{
           $ids = ','.$row['id'];
         }
 ?>
  <tr>

      <td><?php echo $row['id']  ?> </td>
      <td >  <?php echo $row['name'];   ?>
             <a href="cart-remove.php?id=<?php echo $row['id']; ?>" class='remove_item_link ' style="color:#e53939">
                 Remove
             </a>
      </td>
      <td> Rs. <?php   echo $row['price']; } ?>  </td>
      <td> Rs. <?php echo $total;?>
          <a href="success.php?id=<?php echo $ids;?>" class='btn btn-primary'>
            Confirm Order
          </a>
      </td>
</code>```

Then in your success.php you can explode the $ids like this:

```<code>$ids = explode(",",$_GET['id'])); //with explode you can get splits the ids

for($i=0; $i<count($ids); $i++){
   $final_id = $ids[$i];
  //then here you can do the update sql query then the row id is the `final_id` in every loop you will update the database.
}
</code>```

hope it will help!

Body:
As i add some items in the cart i cant change the status in the database from "ADDED TO CART " to "CONFIRMED"

<!DOCTYPE html>

<?php
require 'includes/common.php';

if (!isset($_SESSION['email']))
{
    header('location: index.php');
}
?>

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

    <link href="style.css" rel="stylesheet" type="text/css"/>
        <title>Lifestyle Store | Products</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

          <?php
        include 'includes/header.php';
        ?>
        <?php
        $user_id=$_SESSION['id'];
        //changed from above user_id to $_getc ['user_id']
        $items_query="SELECT items.id,items.name,items.price from items INNER JOIN user_items INNER JOIN users ON items.id=user_items.item_id AND user_items.user_id=users.id WHERE user_items.user_id= $user_id AND user_items.status='Added To Cart'";

        // chaged from select * from user_items inner join items on user_items.item_id=items.id where items.id=$user_id";

        $items_query_result= mysqli_query($con, $items_query) or die(mysqli_error($con));

        ?>

       <?php  if (mysqli_num_rows($items_query_result)==0){ ?>
       <?php echo 'Add something in cart';  }  else  { ?>

                                Item Number
                                Item Name
                                Price
                                Total

                            <?php

                                $total=0;
                                    while ($row= mysqli_fetch_array($items_query_result)) {
                                        $total+=$row['price'];

                                                                                ?>

                                    <?php echo $row['id']  ?> 	   <?php echo $row['name'];   ?> <a href="cart-remove.php?id=<?php echo $row['id']; ?>" class='remove_item_link ' style="color:#e53939">Remove  	    Rs. <?php   echo $row['price']; } ?>  	 Rs. <?php echo $total;?>  Confirm Order

                             <?php }?>

             <?php
        include 'includes/footer.php';
        ?>

this is the code for a shopping cart

user add some this in the cart

**then when the user goes to the cart the cart displays all the items with their ids, name and the price **

and finally the total price

**i have defined a while loop to sum up the price and to display the id name etc **

now i want to send the item id to the success.php to change the status in the database from "Added To Cart " to "Confirmed"

Body:
[UPDATED] You can stored the ids in one variable.

 <?php
     $total=0;
     $ids = '';
     while ($row= mysqli_fetch_array($items_query_result)) {
         $total+=$row['price'];
         if(strlen($ids)== 0){
            $ids = $row['id'];
         }else{
           $ids = ','.$row['id'];
         }
 ?>
  <tr>

      <td><?php echo $row['id']  ?> </td>
      <td >  <?php echo $row['name'];   ?>
             <a href="cart-remove.php?id=<?php echo $row['id']; ?>" class='remove_item_link ' style="color:#e53939">
                 Remove
             </a>
      </td>
      <td> Rs. <?php   echo $row['price']; } ?>  </td>
      <td> Rs. <?php echo $total;?>
          <a href="success.php?id=<?php echo $ids;?>" class='btn btn-primary'>
            Confirm Order
          </a>
      </td>

Then in your success.php you can explode the $ids like this:

$ids = explode(",",$_GET['id'])); //with explode you can get splits the ids

for($i=0; $i<count($ids); $i++){
   $final_id = $ids[$i];
  //then here you can do the update sql query then the row id is the `final_id` in every loop you will update the database.
}

hope it will help!


问:
iOS - Shortcut for jumping to definition in Xcode 9?
In previous Xcode version , I could jump to definition with simple
Cmd + click on that method/variable .
But in Xcode 9, I feel uncomfortable to jump to definition .

Does anyone has a better solution for jumping to definition in Xcode 9 ?

I am tired of selecting options from dropdown list.

答:
Solution 1:

Go to Xcode menu

Click on Preferences

Select Navigation Tab from Top

Select Command-click on Code

Change to "Jumps to Definition"

Solution 2:
Use

Ctrl + ⌘ + Left click


问:
How do I `save()` a Profile model if it has a OneToOne relationship to my AbstractBaseUser model without running into UNIQUE constraint errors?
I have two separate models:

 1. A MyUser model which inherits from AbstractBaseUser, and has a field of profile_page = models.OneToOneField(Profile, null=True)

 2. A Profile model with a user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True) relationship to the User model.

I am attempting to allow users of the site to edit their own Profile information by providing them a ProfileForm ModelForm.

In my user_profile/views.py I have this profile_edit FBV:

```<code>def profile_edit(request):
if request.method == 'POST':
    form = ProfileForm(request.POST)

    if form.is_valid():
        form.instance.user = request.user
        form.instance.save()

        return redirect('/profile/edit')
else:
    form = ProfileForm(instance=request.user)
    print(request.user)
    print('hello get req here')

context = {
    'form': form,
}
return render(request, 'profile_edit.html', context)
</code>```

When I attempt to update profile information in profile_edit.html, the POST data will go through the first time, but not get saved to the DB. On a second attempt, I receive a UNIQUE constraint failed: user_profile_profile.user_id error.

form.instance.save() is pointed to as the direct cause of the exception.

In my estimation the error has something to do with the fact that upon creation of a new user, an initial unique ID is created for the user. So when I try to save() the Profile object, I think it is attempting to save() a new User, thereby causing the Unique Constraint failure.

How can I configure the two models in such a way that upon creation of a new User, the User has the ability to update their own Profile information? What should change in my views.py?

答:
You're doing two things wrong, both to do with the instance argument.

Firstly, in the GET block, you're passing request.user as the instance. But this is a Profile form; you need to pass the user profile, not the user itself:

```<code>form = ProfileForm(instance=request.user.profile)
</code>```

Secondly, in the POST block, you're not passing an instance at all. This means that Django won't know to update an existing item, but will try and create a new one. Again you need to pass the profile:

```<code>form = ProfileForm(request.POST, instance=request.user.profile)
</code>```

Note also though, you should consider whether you need a separate Profile model at all. Initially that was the recommended way to provide custom user information, but for several versions Django has given you a way to use a customised User model - which you are in fact doing. You probably want to put the profile data directly in MyUser, rather than in a separate model with a one-to-one relationship.

Edit after comment It sounds like you're not automatically creating a profile when you create the user. You could do something like this in the view:

```<code>def profile_edit(request):
    try:
        profile = request.user.profile
    except Profile.DoesNotExist:
        profile = Profile(user=request.user)

    if request.method == 'POST':
        form = ProfileForm(request.POST, instance=profile)
    ...
    else:
        form = ProfileForm(instance=profile)
</code>```

Body:
I have two separate models:

 1. A MyUser model which inherits from AbstractBaseUser, and has a field of profile_page = models.OneToOneField(Profile, null=True)

 2. A Profile model with a user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True) relationship to the User model.

I am attempting to allow users of the site to edit their own Profile information by providing them a ProfileForm ModelForm.

In my user_profile/views.py I have this profile_edit FBV:

def profile_edit(request):
if request.method == 'POST':
    form = ProfileForm(request.POST)

    if form.is_valid():
        form.instance.user = request.user
        form.instance.save()

        return redirect('/profile/edit')
else:
    form = ProfileForm(instance=request.user)
    print(request.user)
    print('hello get req here')

context = {
    'form': form,
}
return render(request, 'profile_edit.html', context)

When I attempt to update profile information in profile_edit.html, the POST data will go through the first time, but not get saved to the DB. On a second attempt, I receive a UNIQUE constraint failed: user_profile_profile.user_id error.

form.instance.save() is pointed to as the direct cause of the exception.

In my estimation the error has something to do with the fact that upon creation of a new user, an initial unique ID is created for the user. So when I try to save() the Profile object, I think it is attempting to save() a new User, thereby causing the Unique Constraint failure.

How can I configure the two models in such a way that upon creation of a new User, the User has the ability to update their own Profile information? What should change in my views.py?

Body:
You're doing two things wrong, both to do with the instance argument.

Firstly, in the GET block, you're passing request.user as the instance. But this is a Profile form; you need to pass the user profile, not the user itself:

form = ProfileForm(instance=request.user.profile)

Secondly, in the POST block, you're not passing an instance at all. This means that Django won't know to update an existing item, but will try and create a new one. Again you need to pass the profile:

form = ProfileForm(request.POST, instance=request.user.profile)

Note also though, you should consider whether you need a separate Profile model at all. Initially that was the recommended way to provide custom user information, but for several versions Django has given you a way to use a customised User model - which you are in fact doing. You probably want to put the profile data directly in MyUser, rather than in a separate model with a one-to-one relationship.

Edit after comment It sounds like you're not automatically creating a profile when you create the user. You could do something like this in the view:

def profile_edit(request):
    try:
        profile = request.user.profile
    except Profile.DoesNotExist:
        profile = Profile(user=request.user)

    if request.method == 'POST':
        form = ProfileForm(request.POST, instance=profile)
    ...
    else:
        form = ProfileForm(instance=profile)


问:
How I set maxLength attribute in <input type='number'> in HTML5?
I want maxLength Validation in  in HTML5.

I tried like this

```<code><input type="number" name="trainer_mobile_no[]" maxlength="10" class="form-control" required="required"/>
</code>```

答:
Use as</p>

```<code><input type="number" name="trainer_mobile_no[]" min="1" max="5" class="form-control" required="required">
</code>```

Body:
I want maxLength Validation in  in HTML5.

I tried like this

<input type="number" name="trainer_mobile_no[]" maxlength="10" class="form-control" required="required"/>

Body:
Use as

<input type="number" name="trainer_mobile_no[]" min="1" max="5" class="form-control" required="required">


问:
Google Drive PHP API - How to stream a large file
I know how to download files all at once, as shown in the example on this page: Google Drive API -Files: get.

However, if I have a very large file, loading it all into memory would be inefficient and resource-hogging. Therefore, I would like to know if it's possible to stream files with the Drive API, only loading bits of the file into memory at a time, and processing them (in some way like writing to a file or writing directly to output). I've read the docs and even looked a bit at the source for the PHP Google Drive SDK, and it seems that there is support for streaming, but I can't figure out how to use it. All help is appreciated.

答:
Good example in library git repo
https://github.com/google/google-api-php-client/blob/master/examples/large-file-download.php</p>

```<code><?php
      /*
       * Copyright 2011 Google Inc.
       *
       * Licensed under the Apache License, Version 2.0 (the "License");
       * you may not use this file except in compliance with the License.
       * You may obtain a copy of the License at
       *
       *     http://www.apache.org/licenses/LICENSE-2.0
       *
       * Unless required by applicable law or agreed to in writing, software
       * distributed under the License is distributed on an "AS IS" BASIS,
       * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       * See the License for the specific language governing permissions and
       * limitations under the License.
       */

  include_once __DIR__ . '/../vendor/autoload.php';
include_once "templates/base.php";

echo pageHeader("File Download - Downloading a large file");

/*************************************************
 * Ensure you've downloaded your oauth credentials
 ************************************************/
if (!$oauth_credentials = getOAuthCredentialsFile()) {
    echo missingOAuth2CredentialsWarning();
    return;
}

/************************************************
 * The redirect URI is to the current page, e.g:
 * http://localhost:8080/large-file-download.php
 ************************************************/
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];

$client = new Google_Client();
$client->setAuthConfig($oauth_credentials);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/drive");
$service = new Google_Service_Drive($client);

/************************************************
 * If we have a code back from the OAuth 2.0 flow,
 * we need to exchange that with the
 * Google_Client::fetchAccessTokenWithAuthCode()
 * function. We store the resultant access token
 * bundle in the session, and redirect to ourself.
 ************************************************/
if (isset($_GET['code'])) {
    $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
    $client->setAccessToken($token);

// store in the session also
$_SESSION['upload_token'] = $token;

// redirect back to the example
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

// set the access token as part of the client
   if (!empty($_SESSION['upload_token'])) {
    $client->setAccessToken($_SESSION['upload_token']);
if ($client->isAccessTokenExpired()) {
unset($_SESSION['upload_token']);
}
} else {
      $authUrl = $client->createAuthUrl();
  }

/************************************************
 * If we're signed in then lets try to download our
 * file.
 ************************************************/
if ($client->getAccessToken()) {
// Check for "Big File" and include the file ID and size
$files = $service->files->listFiles([
'q' => "name='Big File'",
'fields' => 'files(id,size)'
]);

if (count($files) == 0) {
    echo "
    <h3 class='warn'>
    Before you can use this sample, you need to
    <a href='/large-file-upload.php'>upload a large file to Drive</a>.
    </h3>";
    return;
}

// If this is a POST, download the file
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Determine the file's size and ID
$fileId = $files[0]->id;
    $fileSize = intval($files[0]->size);

// Get the authorized Guzzle HTTP client
$http = $client->authorize();

// Open a file for writing
$fp = fopen('Big File (downloaded)', 'w');

// Download in 1 MB chunks
$chunkSizeBytes = 1 * 1024 * 1024;
    $chunkStart = 0;

// Iterate over each chunk and write it to our file
   while ($chunkStart < $fileSize) {
    $chunkEnd = $chunkStart + $chunkSizeBytes;
    $response = $http->request(
    'GET',
    sprintf('/drive/v3/files/%s', $fileId),
    [
    'query' => ['alt' => 'media'],
    'headers' => [
    'Range' => sprintf('bytes=%s-%s', $chunkStart, $chunkEnd)
    ]
    ]
    );
    $chunkStart = $chunkEnd + 1;
fwrite($fp, $response->getBody()->getContents());
}
// close the file pointer
fclose($fp);

// redirect back to this example
header('Location: ' . filter_var($redirect_uri . '?downloaded', FILTER_SANITIZE_URL));
}
}
?>

<div class="box">
<?php if (isset($authUrl)): ?>
<div class="request">
<a class='login' href='<?= $authUrl ?>'>Connect Me!</a>
                                                     </div>
                                                       <?php elseif(isset($_GET['downloaded'])): ?>
<div class="shortened">
<p>Your call was successful! Check your filesystem for the file:</p>
                                                                  <p><code><?= __DIR__ . DIRECTORY_SEPARATOR ?>Big File (downloaded)</code></p>
                                                                                </div>
                                                                                <?php else: ?>
<form method="POST">
<input type="submit" value="Click here to download a large (20MB) test file" />
</form>
  <?php endif ?>
    </div>

      <?= pageFooter(__FILE__) ?>
</code>```

Body:
Good example in library git repo
https://github.com/google/google-api-php-client/blob/master/examples/large-file-download.php

<?php
      /*
       * Copyright 2011 Google Inc.
       *
       * Licensed under the Apache License, Version 2.0 (the "License");
       * you may not use this file except in compliance with the License.
       * You may obtain a copy of the License at
       *
       *     http://www.apache.org/licenses/LICENSE-2.0
       *
       * Unless required by applicable law or agreed to in writing, software
       * distributed under the License is distributed on an "AS IS" BASIS,
       * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       * See the License for the specific language governing permissions and
       * limitations under the License.
       */

  include_once __DIR__ . '/../vendor/autoload.php';
include_once "templates/base.php";

echo pageHeader("File Download - Downloading a large file");

/*************************************************
 * Ensure you've downloaded your oauth credentials
 ************************************************/
if (!$oauth_credentials = getOAuthCredentialsFile()) {
    echo missingOAuth2CredentialsWarning();
    return;
}

/************************************************
 * The redirect URI is to the current page, e.g:
 * http://localhost:8080/large-file-download.php
 ************************************************/
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];

$client = new Google_Client();
$client->setAuthConfig($oauth_credentials);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/drive");
$service = new Google_Service_Drive($client);

/************************************************
 * If we have a code back from the OAuth 2.0 flow,
 * we need to exchange that with the
 * Google_Client::fetchAccessTokenWithAuthCode()
 * function. We store the resultant access token
 * bundle in the session, and redirect to ourself.
 ************************************************/
if (isset($_GET['code'])) {
    $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
    $client->setAccessToken($token);

// store in the session also
$_SESSION['upload_token'] = $token;

// redirect back to the example
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

// set the access token as part of the client
   if (!empty($_SESSION['upload_token'])) {
    $client->setAccessToken($_SESSION['upload_token']);
if ($client->isAccessTokenExpired()) {
unset($_SESSION['upload_token']);
}
} else {
      $authUrl = $client->createAuthUrl();
  }

/************************************************
 * If we're signed in then lets try to download our
 * file.
 ************************************************/
if ($client->getAccessToken()) {
// Check for "Big File" and include the file ID and size
$files = $service->files->listFiles([
'q' => "name='Big File'",
'fields' => 'files(id,size)'
]);

if (count($files) == 0) {
    echo "
    <h3 class='warn'>
    Before you can use this sample, you need to
    <a href='/large-file-upload.php'>upload a large file to Drive</a>.
    </h3>";
    return;
}

// If this is a POST, download the file
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Determine the file's size and ID
$fileId = $files[0]->id;
    $fileSize = intval($files[0]->size);

// Get the authorized Guzzle HTTP client
$http = $client->authorize();

// Open a file for writing
$fp = fopen('Big File (downloaded)', 'w');

// Download in 1 MB chunks
$chunkSizeBytes = 1 * 1024 * 1024;
    $chunkStart = 0;

// Iterate over each chunk and write it to our file
   while ($chunkStart < $fileSize) {
    $chunkEnd = $chunkStart + $chunkSizeBytes;
    $response = $http->request(
    'GET',
    sprintf('/drive/v3/files/%s', $fileId),
    [
    'query' => ['alt' => 'media'],
    'headers' => [
    'Range' => sprintf('bytes=%s-%s', $chunkStart, $chunkEnd)
    ]
    ]
    );
    $chunkStart = $chunkEnd + 1;
fwrite($fp, $response->getBody()->getContents());
}
// close the file pointer
fclose($fp);

// redirect back to this example
header('Location: ' . filter_var($redirect_uri . '?downloaded', FILTER_SANITIZE_URL));
}
}
?>

<div class="box">
<?php if (isset($authUrl)): ?>
<div class="request">
<a class='login' href='<?= $authUrl ?>'>Connect Me!</a>
                                                     </div>
                                                       <?php elseif(isset($_GET['downloaded'])): ?>
<div class="shortened">
<p>Your call was successful! Check your filesystem for the file:</p>
                                                                  <p><code><?= __DIR__ . DIRECTORY_SEPARATOR ?>Big File (downloaded)</code></p>
                                                                                </div>
                                                                                <?php else: ?>
<form method="POST">
<input type="submit" value="Click here to download a large (20MB) test file" />
</form>
  <?php endif ?>
    </div>

      <?= pageFooter(__FILE__) ?>


问:
Parsing XML string using XSLT
I have an XML document that has a TextBlock that contains HTML code.

```<code><TextBlock>
  <h1>This is a header.</h1>
  <p>This is a paragraph.</p>
</TextBlock>
</code>```

In the actual XML, however, it is coded like this:

```<code><TextBlock>
  <h1>This is a header.</h1>
  <p>This is a paragraph.</p>
</TextBlock>
</code>```

So when I use <xsl:value-of select="TextBlock"/> it displays all of the coding on the page. Is there a way using XSLT to convert < to < within the TextBlock element?

答:
```<code><xsl:value-of select="TextBlock" disable-output-escaping="yes"/>
</code>```

and the result:

```<code><h1>This is a header.</h1>
<p>This is a paragraph.</p>
</code>```

Firefox has a corresponding bug: https://bugzilla.mozilla.org/show_bug.cgi?id=98168, which contains a lot of comments and is an interesting reading.

I am looking for a fix now.

EDIT

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:import href="disable-output-escaping.xsl"/>
    <!-- https://bug98168.bugzilla.mozilla.org/attachment.cgi?id=434081 -->
    <xsl:output method="xml" encoding="UTF-8" indent="yes"/>

    <xsl:template match="/TextBlock">
        <xsl:copy>
            <xsl:call-template name="disable-output-escaping"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>
</code>```

When inspecting via Firebug, the result looks correct:

```<code><textblock>
    <h1>This is a header.</h1>
    <p>This is a paragraph.</p>
</textblock>
</code>```

Title: Parsing XML string using XSLT

Body:
I have an XML document that has a TextBlock that contains HTML code.

<TextBlock>

This is a header.

This is a paragraph.

</TextBlock>

In the actual XML, however, it is coded like this:

<TextBlock>

This is a header.

This is a paragraph.

</TextBlock>

So when I use <xsl:value-of select="TextBlock"/> it displays all of the coding on the page. Is there a way using XSLT to convert < to < within the TextBlock element?

Body:
<xsl:value-of select="TextBlock" disable-output-escaping="yes"/>

and the result:

<h1>This is a header.</h1>
<p>This is a paragraph.</p>

Firefox has a corresponding bug: https://bugzilla.mozilla.org/show_bug.cgi?id=98168, which contains a lot of comments and is an interesting reading.

I am looking for a fix now.

EDIT

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:import href="disable-output-escaping.xsl"/>
    <!-- https://bug98168.bugzilla.mozilla.org/attachment.cgi?id=434081 -->
    <xsl:output method="xml" encoding="UTF-8" indent="yes"/>

    <xsl:template match="/TextBlock">
        <xsl:copy>
            <xsl:call-template name="disable-output-escaping"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

When inspecting via Firebug, the result looks correct:

<textblock>
    <h1>This is a header.</h1>
    <p>This is a paragraph.</p>
</textblock>


问:
Laravel to Basic PHP Login Integration, Working! But Fail to Set Session
So I'm trying to use laravel-based login table, which is the hash that I can't even compare it with basic php hash login. No, you can't make hash exactly look like laravel. But I use the remember_token that is come from users table.

Here is the code on my laravel view:

```<code><form action="http://localhost/log/index.php" method="post">
       <input type="hidden" value="{{ Auth::user()->remember_token }}" name="wex">
       <button type="submit" class="btn btn-default">Check</button>
</form>
</code>```

As you can see, I'm trying to POST remember_token value, that will received on my http://localhost/log/index.php as variable.

Index.php (Not use Laravel):

```<code><?php
    include "koneksi.php";

    if (isset($_POST['wex'])) {
        $token = $_POST['wex'];
        $query = "SELECT * FROM users WHERE remember_token = '". $token ."'" ;
        $result = mysqli_query($db_link,$query);

        if (mysqli_num_rows($result) != 1) {
            header("Location: http://localhost/laralearn/public/login");
        }

        session_start();
        $_SESSION['user'] = "member";
    }
    else{

        if(!isset($_SESSION['user'])){
            header("Location: http://localhost/laralearn/public/login");
        }
    }

?>

<html>
<head>
    <title>Customer</title>
</head>
<body>

    <table cellpadding="5" cellspacing="5" border="1" align="center">
    <tr>
        <td colspan="2">If you can see this table, you are logged in. </td>
    </tr>
    <tr>
        <td>Username:
        </td>
        <td><?php

        while($data = mysqli_fetch_array($result))
        {
            echo "$data[name]";
        }

        ?></td>
    </tr>
    <tr>
        <td>
            Token:
        </td>
        <td>
            <?php echo $token; ?>
        </td>
    </tr>

    </table>
</body>
</html>
</code>```

The variable and page redirect if the remember_token isn't valid (working), but I can't set the session. The page keep redirecting to Laravel site.

Can you tell me where am I doing something wrong? It would be nice if you explain it and tell me what the code should look like.

Thank you.

答:
Use in Laravel session like below:

```<code>Session::set('user', "member");
</code>```

Get session variable:

```<code>Session::get('user');
</code>```

Body:
So I'm trying to use laravel-based login table, which is the hash that I can't even compare it with basic php hash login. No, you can't make hash exactly look like laravel. But I use the remember_token that is come from users table.

Here is the code on my laravel view:

<form action="http://localhost/log/index.php" method="post">
       <input type="hidden" value="{{ Auth::user()->remember_token }}" name="wex">
       <button type="submit" class="btn btn-default">Check</button>
</form>

As you can see, I'm trying to POST remember_token value, that will received on my http://localhost/log/index.php as variable.

Index.php (Not use Laravel):

<?php
    include "koneksi.php";

    if (isset($_POST['wex'])) {
        $token = $_POST['wex'];
        $query = "SELECT * FROM users WHERE remember_token = '". $token ."'" ;
        $result = mysqli_query($db_link,$query);

        if (mysqli_num_rows($result) != 1) {
            header("Location: http://localhost/laralearn/public/login");
        }

        session_start();
        $_SESSION['user'] = "member";
    }
    else{

        if(!isset($_SESSION['user'])){
            header("Location: http://localhost/laralearn/public/login");
        }
    }

?>

    <title>Customer</title>

        If you can see this table, you are logged in.

        Username:

        <?php

        while($data = mysqli_fetch_array($result))
        {
            echo "$data[name]";
        }

        ?>

            Token:

            <?php echo $token; ?>

The variable and page redirect if the remember_token isn't valid (working), but I can't set the session. The page keep redirecting to Laravel site.

Can you tell me where am I doing something wrong? It would be nice if you explain it and tell me what the code should look like.

Thank you.

Body:
Use in Laravel session like below:

Session::set('user', "member");

Get session variable:

Session::get('user');


问:
PHP & MySQL - not inserting into database
I've got an problem in my code. The insert is not working. The code is below.

HTML:

```<code><form action="staff.php" method="post" class="center" enctype="multipart/form-data" autocomplete="off">
    <input type="hidden" name="size" value="1000000">
    <input type="text" placeholder="headline of the news" name="title">
    <input type="file" accept="image/*" name="image">
    <select name="side" value="side">
        <option>Left</option>
        <option>Header</option>
        <option>Main</option>
        <option>Ending</option>
    </select>
    <textarea name="desc" id="description" cols="30" rows="10" placeholder="full news" name="desc"></textarea>
    <input type="submit" name="go" value="Post">
</form>
</code>```

PHP:

```<code><?php
$db = mysqli_connect("DB SERVER", "DB USER", "DB PASS", "DataBase");
$charset = mysqli_set_charset($db,"utf8");
$msg = "";
if (isset($_POST['go'])) {
    $target = "images/".basename($_FILES['image']['name']);
    $title = $_POST['title'];
    $image = $_FILES['image']['name'];
    $side = $_POST['side'];
    $desc = $_POST['desc'];
    $sql = "INSERT INTO contents (title, image, side, description)
    VALUES ('$title', '$image', '$side', '$desc')";
    $result = mysqli_query($db, $sql);
    if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
        $msg = "<p class='success'>Image uploaded successfully</p>";
    } else {
        $msg = "<p class='error'>There was a problem uploading the image</p>";
    }
}
?>
</code>```

Everything is fine except the inserting into database.

答:
add concatenation in the query like this</p>

```<code>$sql = "INSERT INTO contents (title, image, side, description)
        VALUES ('".$title."', '".$image."', '".$side."', '".$desc."')";
</code>```

Body:
I've got an problem in my code. The insert is not working. The code is below.

HTML:

<form action="staff.php" method="post" class="center" enctype="multipart/form-data" autocomplete="off">
    <input type="hidden" name="size" value="1000000">
    <input type="text" placeholder="headline of the news" name="title">
    <input type="file" accept="image/*" name="image">
    <select name="side" value="side">
        <option>Left</option>
        <option>Header</option>
        <option>Main</option>
        <option>Ending</option>
    </select>
    <textarea name="desc" id="description" cols="30" rows="10" placeholder="full news" name="desc"></textarea>
    <input type="submit" name="go" value="Post">
</form>

PHP:

<?php
$db = mysqli_connect("DB SERVER", "DB USER", "DB PASS", "DataBase");
$charset = mysqli_set_charset($db,"utf8");
$msg = "";
if (isset($_POST['go'])) {
    $target = "images/".basename($_FILES['image']['name']);
    $title = $_POST['title'];
    $image = $_FILES['image']['name'];
    $side = $_POST['side'];
    $desc = $_POST['desc'];
    $sql = "INSERT INTO contents (title, image, side, description)
    VALUES ('$title', '$image', '$side', '$desc')";
    $result = mysqli_query($db, $sql);
    if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
        $msg = "
Image uploaded successfully
";
    } else {
        $msg = "
There was a problem uploading the image
";
    }
}
?>

Everything is fine except the inserting into database.

Body:
add concatenation in the query like this

$sql = "INSERT INTO contents (title, image, side, description)
        VALUES ('".$title."', '".$image."', '".$side."', '".$desc."')";


问:
Is it safe to grant "auth | User | Can change user" permissions without the "is staff" flag?
I need certain users to edit django.contrib.auth.models.User objects.

My first thought was to grant them the auth | User | Can change user permission and flag them as is staff, so they can log into the Django Admin site. The problem is though, that they can use that to make themselves super admins.

Since I want them to only be able to edit certain fields, I created a very limited view for that. What's left for me to do, is to actually grant permission on that view to that subset of users. The only solution I found was to still grant them the auth | User | Can change user permission (without making them staff).

My question is this:

If I use the @permission_required decorator on that view in cooperation with the auth | User | Can change user permission, is there any other way for the users to hack their way into granting themselves the super admin role (even assuming the user is a advanced Django programmer)? I am talking about things like e. g. API calls I am unaware of, or similar.

I want to take possible mistakes in my code out of the scope here.

答:
IMHO, Yes it is very safe to use your own type/create any type of custom fields on User.

In one of our project, we had added 2-3 types of admin users and it was pretty secure. We had added Maintainer, Administrator, SuperUser and two types of end user (that was requirement). We had done many customization in Django Admin as well to list all types of groups and user in the Django Admin.

JFYI we had not provided access to Django Admin to the customers, we had provided SuperUser login to create any type of User to access our tool.


问:
Compare matrices in Python and store results
I would like to compare a 70x1 matrix with a 1000x3 matrix. What i want to do is compare the first column of the second matrix with the first matrix, find all the common values and then store the results in a new third matrix which is going to have all 3 columns.

I used np.intersect1d to find the common values between the two matrices but that is about it.

I can't find a way to import the other two columns of the second matrix to the new one.

Matrix1

```<code>[1.0

4.7

4.8

4.9

5.0

5.1]
</code>```

Matrix2

```<code>[[3.0, 1.8, -3.0]

[3.1, 2.2, -3.0]

[4.7, 2.4, -3.0]

[3.3, 2.8, -3.0]

[3.40, 3.0, -3.0]]
</code>```

Matrix3

```<code>[4.7, 2.4, -3.0]
</code>```

Body:
I would like to compare a 70x1 matrix with a 1000x3 matrix. What i want to do is compare the first column of the second matrix with the first matrix, find all the common values and then store the results in a new third matrix which is going to have all 3 columns.

I used np.intersect1d to find the common values between the two matrices but that is about it.

I can't find a way to import the other two columns of the second matrix to the new one.

Matrix1

[1.0

4.7

4.8

4.9

5.0

5.1]

Matrix2

[[3.0, 1.8, -3.0]

[3.1, 2.2, -3.0]

[4.7, 2.4, -3.0]

[3.3, 2.8, -3.0]

[3.40, 3.0, -3.0]]

Matrix3

[4.7, 2.4, -3.0]

Body:
I don't see the need for numpy:

m1 = [1.0, 4.7, 4.8, 4.9, 5.0, 5.1]
m2 = [[3.0, 1.8, -3.0],
[3.1, 2.2, -3.0],
[4.7, 2.4, -3.0],
[3.3, 2.8, -3.0],
[3.40, 3.0, -3.0]]

output = []
for value in m2:
    if value[0] in m1:
        output.append(value)

print(output)

Gives:

[[4.7, 2.4, -3.0]]


问:
Forcing the Soft Keyboard open
I am trying to force the Soft Keyboard open in an Activity and grab everything that is entered as I want to handle the input myself, I don't have an EditText.  Currently I have tried this but it does not work.  I would like the Soft Keyboardto open below mAnswerTextView (Note: it is a TextView not EditText).

```<code>    InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    // only will trigger it if no physical keyboard is open
    mgr.showSoftInput(mAnswerTextView, InputMethodManager.SHOW_IMPLICIT);
</code>```

how do I force the Soft Keyboard open

How do I gab everything that is entered so that I can handle each character.  I would like to flush each character from the Soft Keyboard after I have handled it. ie, the user should not be able to enter whole words in the Soft Keyboard.

答:
Simply, using adding 2 lines will work like a charm:

If using XML

```<code>android:focusable="true"
android:focusableInTouchMode="true"
</code>```

Else in Java:

```<code>view.setFocusableInTouchMode(true);
view.requestFocus();
</code>```

Title: Forcing the Soft Keyboard open

Body:
I am trying to force the Soft Keyboard open in an Activity and grab everything that is entered as I want to handle the input myself, I don't have an EditText.  Currently I have tried this but it does not work.  I would like the Soft Keyboardto open below mAnswerTextView (Note: it is a TextView not EditText).

    InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    // only will trigger it if no physical keyboard is open
    mgr.showSoftInput(mAnswerTextView, InputMethodManager.SHOW_IMPLICIT);

how do I force the Soft Keyboard open

How do I gab everything that is entered so that I can handle each character.  I would like to flush each character from the Soft Keyboard after I have handled it. ie, the user should not be able to enter whole words in the Soft Keyboard.

Body:
Simply, using adding 2 lines will work like a charm:

If using XML

android:focusable="true"
android:focusableInTouchMode="true"

Else in Java:

view.setFocusableInTouchMode(true);
view.requestFocus();


问:
Creating an overlay in CSS?
I have div that I display dynamically when certain conditions arise.

When I display the div, how can I create the effect of the background dimming and my div appearing to be prominent? much like a number of AJAX lightboxes or popups. (Thickbox, ColorBox, PrettyPhoto, etc)

I don;t quite get how they do it. I have everything else working in my own custom code except that piece.

Can anyone help me learn how?

答: If you create a layer that is the full width & height of your page and give it a higher z index than your whole page, you can create this effect. Then put your appearing div over it.</p>

Title: Creating an overlay in CSS?


问:
Android Alarm Manager Start time
I have this code, but the Alarm won't start from the beginning of time. I want myReceiver to start from the start of minutes and also repeat it from start of times . How can I achieve that?

```<code>PendingIntent pendingIntent3;
AlarmManager manager =(AlarmManager) getSystemService(Context.ALARM_SERVICE);

Intent alarmIntent3 = new Intent(getBaseContext(), myReceiver.class);
pendingIntent3 = PendingIntent.getBroadcast(getBaseContext(), 0, alarmIntent3, 0);

manager.setRepeating(AlarmManager.ELAPSED_REALTIME  _WAKEUP,
                SystemClock.currentThreadTimeMillis(),
                1*60*1000, pendingIntent3);
</code>```

答:
Use below code to set repeating alarm:

```<code>Intent alarmIntent3 = new Intent(getBaseContext(), myReceiver.class);
PendingIntent pendingIntent3 = PendingIntent.getBroadcast(getBaseContext(), 0, alarmIntent3, PendingIntent.FLAG_UPDATE_CURRENT);

// Current time
Calendar calendarNotifiedTime = Calendar.getInstance();
calendarNotifiedTime.setTimeInMillis(System.currentTimeMillis());
calendarNotifiedTime.set(Calendar.SECOND, 0);

// Set alarm
AlarmManager manager =(AlarmManager) getSystemService(Context.ALARM_SERVICE);
manager.setRepeating(AlarmManager.RTC_WAKEUP, calendarNotifiedTime.getTimeInMillis(), 1*60*1000, pendingIntent3);
</code>```

Make sure you have declared myReceiver BroadcastReceiver in your AndroidManifest.xml.

Title: Android Alarm Manager Start time

Body:
I have this code, but the Alarm won't start from the beginning of time. I want myReceiver to start from the start of minutes and also repeat it from start of times . How can I achieve that?

PendingIntent pendingIntent3;
AlarmManager manager =(AlarmManager) getSystemService(Context.ALARM_SERVICE);

Intent alarmIntent3 = new Intent(getBaseContext(), myReceiver.class);
pendingIntent3 = PendingIntent.getBroadcast(getBaseContext(), 0, alarmIntent3, 0);

manager.setRepeating(AlarmManager.ELAPSED_REALTIME  _WAKEUP,
                SystemClock.currentThreadTimeMillis(),
                1*60*1000, pendingIntent3);

Body:
Use below code to set repeating alarm:

Intent alarmIntent3 = new Intent(getBaseContext(), myReceiver.class);
PendingIntent pendingIntent3 = PendingIntent.getBroadcast(getBaseContext(), 0, alarmIntent3, PendingIntent.FLAG_UPDATE_CURRENT);

// Current time
Calendar calendarNotifiedTime = Calendar.getInstance();
calendarNotifiedTime.setTimeInMillis(System.currentTimeMillis());
calendarNotifiedTime.set(Calendar.SECOND, 0);

// Set alarm
AlarmManager manager =(AlarmManager) getSystemService(Context.ALARM_SERVICE);
manager.setRepeating(AlarmManager.RTC_WAKEUP, calendarNotifiedTime.getTimeInMillis(), 1*60*1000, pendingIntent3);

Make sure you have declared myReceiver BroadcastReceiver in your AndroidManifest.xml.


问:
Calling an excel file via a macro
I want to create a macro that pulls a file by allowing the user to browse and locate the file from his/her local and then perform some functions on the pulled file.

I am not sure how to incorporate the browsing file feature in the macro.

答:
The below will open and set wkbFileToOpen, you will then be able to use this as your workbook to manipulate.</p>

```<code>Dim vFileToOpen As Variant
Dim wkbFileToOpen As Workbook

'Ask the user to select the file, you can change your desired file extensions and file types
vFileToOpen = Application.GetOpenFilename("Excel Files (*.xls),*.xls,", 1, "Select the workbook", , False)

'if the user cancels, then vFileToOpen will be false, so we need to check there's a value
If Not vFileToOpen Then

    Workbooks.Open vFileToOpen
    Set wkbFileToOpen = ActiveWorkbook

End If
</code>```

Title: Calling an excel file via a macro

Body:
The below will open and set wkbFileToOpen, you will then be able to use this as your workbook to manipulate.

Dim vFileToOpen As Variant
Dim wkbFileToOpen As Workbook

'Ask the user to select the file, you can change your desired file extensions and file types
vFileToOpen = Application.GetOpenFilename("Excel Files (*.xls),*.xls,", 1, "Select the workbook", , False)

'if the user cancels, then vFileToOpen will be false, so we need to check there's a value
If Not vFileToOpen Then

    Workbooks.Open vFileToOpen
    Set wkbFileToOpen = ActiveWorkbook

End If


问:
Add base to permalink
Added 'custom structure' for premalink and placed '/mybase/%postname%/'

It is making all posts look like 'www.mysite.com/mybase/postname'

But it is not working for pages.

page name still remains 'www.mysite.com/pagename'.

How to change it ?

答:
Put this code in your functions.php file.

```<code>add_action( 'init', 'custom_page_rules' );

function custom_page_rules() {
    global $wp_rewrite;
    $wp_rewrite->page_structure = $wp_rewrite->root . '/mybase/%pagename%';
}
</code>```

After put this code you want to save permalink once time in wordpress back end.

Title: Add base to permalink

Body:
Put this code in your functions.php file.

add_action( 'init', 'custom_page_rules' );

function custom_page_rules() {
    global $wp_rewrite;
    $wp_rewrite->page_structure = $wp_rewrite->root . '/mybase/%pagename%';
}

After put this code you want to save permalink once time in wordpress back end.


答:
```<code>$sql = "INSERT INTO contents (title, image, side, description) VALUES ('".$title."', '".$image."', '".$side."', '".$desc."')";
</code>```

The problem is here use this.

Title: PHP & MySQL - not inserting into database

Body:
$sql = "INSERT INTO contents (title, image, side, description) VALUES ('".$title."', '".$image."', '".$side."', '".$desc."')";

The problem is here use this.


问:
VBA obtaining values from a workbook and put them in another workbook
I'm having trouble putting values from one workbook to another.

Right now it works, but as you can probably see in the code below, it constantly opens one workbook after the second one until the loop ends. So my question: how can I do this without opening the workbooks all the time?

Code:

```<code>For i = 2 To LastRow
Set wb2 = Workbooks.Open("...")
With Worksheets("...")
    x = .Cells(i, 2).Value
    y = .Cells(i, 3).Value
End With

If variable1 = variable2 Then
Set wb = Workbooks.Open("...")
With Worksheets("...")
    .Cells(i, 2).Value = x
    .Cells(i, 3).Value = y
End With
End If

Next i
</code>```

The following code gives me an error: Subscript out of range at x = wb2.WorkSheets("...").Cells(i, 2).Value

```<code>Set wb2 = Workbooks.Open("...")
Set wb = Workbooks.Open("...")
For i = 2 To LastRow
    x = wb2.WorkSheets("...").Cells(i, 2).Value
    y = wb2.WorkSheets("...").Cells(i, 3).Value
If variable1 = variable2 Then
    wb.WorkSheets("...").Cells(i, 2).Value = x
    wb.WorkSheets("...").Cells(i, 3).Value = y
End If

Next i
</code>```

答:
How about like this, first set the wb and wb2 objects outside the loop, and after just set the values directly between workbook.

```<code>Set wb2 = Workbooks.Open("...")
Set wb = Workbooks.Open("...")

For i = 2 To LastRow
    wb.Worksheets("...").Cells(i, 2).Value = wb2.Worksheets("...").Cells(i, 2).Value
    wb.Worksheets("...").Cells(i, 3).Value = wb2.Worksheets("...").Cells(i, 3).Value
Next i
</code>```

Body:
I'm having trouble putting values from one workbook to another.

Right now it works, but as you can probably see in the code below, it constantly opens one workbook after the second one until the loop ends. So my question: how can I do this without opening the workbooks all the time?

Code:

For i = 2 To LastRow
Set wb2 = Workbooks.Open("...")
With Worksheets("...")
    x = .Cells(i, 2).Value
    y = .Cells(i, 3).Value
End With

If variable1 = variable2 Then
Set wb = Workbooks.Open("...")
With Worksheets("...")
    .Cells(i, 2).Value = x
    .Cells(i, 3).Value = y
End With
End If

Next i

The following code gives me an error: Subscript out of range at x = wb2.WorkSheets("...").Cells(i, 2).Value

Set wb2 = Workbooks.Open("...")
Set wb = Workbooks.Open("...")
For i = 2 To LastRow
    x = wb2.WorkSheets("...").Cells(i, 2).Value
    y = wb2.WorkSheets("...").Cells(i, 3).Value
If variable1 = variable2 Then
    wb.WorkSheets("...").Cells(i, 2).Value = x
    wb.WorkSheets("...").Cells(i, 3).Value = y
End If

Next i

Body:
How about like this, first set the wb and wb2 objects outside the loop, and after just set the values directly between workbook.

Set wb2 = Workbooks.Open("...")
Set wb = Workbooks.Open("...")

For i = 2 To LastRow
    wb.Worksheets("...").Cells(i, 2).Value = wb2.Worksheets("...").Cells(i, 2).Value
    wb.Worksheets("...").Cells(i, 3).Value = wb2.Worksheets("...").Cells(i, 3).Value
Next i


问:
Rails 3: Social Stream Gem. Where is the code?
I've installed social_stream according to the README ( https://github.com/ging/social_stream ) and it works fine, however, I'd like to have the code in my app/ directory and the code isn't there.

The same question arises for Devise and other gems. When I install it, I'd like to have access to the controllers, models, views, etc but it seems nothing is in the app/.

What do I have to do in order to put the code there and being able to change it as I'd like? Or, access it in other folder.

Thank you

答: "gem which social_stream" tells me the place where the gem is installed so I can change the code.</p>