问:
cannot add a background image retrieved from data provided by an api to a div node.js
I am trying to add a background image to a div by giving the background image property in my css the link provided by the api I am using. However, it does not work. If I try to access the image directly from chrome, I get nothing either. Here is my code:

```<code>function getData(responseData) {
    var poster = responseData.results[0].poster_path;
    appendToDom(poster);
}

function appendToDom(poster) {
    var aPoster = $('<div>');
    var movie_poster = 'url("' + poster + '")';
    console.log(movie_poster);
    aPoster.css({
        'float': 'left',
        'margin': 10,
        'margin-left': 37,
        'margin-top': 20,
        'width': 200,
        'height': 300,
        'font-size': 36,
        'color': 'black',
        'background-size': '200px 300px',
        'background-image': movie_poster //'url("./../images/question.jpg")'
    })
    $(main).append(aPoster);
}
</code>```

My console.log returns url("/rwn876MeqienhOVSSjtUPnwxn0Z.jpg") which is the url I expect. I am working with The Movie DataBase API if that helps.

Thanks for all the help in advance!

Hey guys! I finally figured it out. Here's my final js file with a list of posters that are attached to a certain name displayed.

```<code>$('#search').keypress(function(e) {
        if (e.which == 13) {
            var movie = $('#search-input').val();
            $('form#login').submit();
            console.log('onclick fun', movie)
            makeCall(movie);
            return false;
        }
    });

    function makeCall(aMovie) {
        console.log('makecall', aMovie);

        link = url + aMovie;
        console.log(link);
        $.ajax({
            method: "GET",
            url: link,
            success: function(data) {
                console.log("the data -->", data);
                getData(data);
            },
        })
    }

    function getData(responseData) {
        for (let i = 0; i < responseData.results.length; i++) {
            var poster = responseData.results[i].poster_path;
            appendToDom(poster);
        }
    }

    function appendToDom(poster) {
        var aPoster = $('<div>');
        var movie_poster = 'url("https://image.tmdb.org/t/p/w1280' + poster + '")';
        console.log(movie_poster);
        aPoster.css({
            'float': 'left',
            'margin': 10,
            'margin-left': 37,
            'margin-top': 20,
            'width': 200,
            'height': 300,
            'font-size': 36,
            'color': 'black',
            'background-size': '200px 300px',
        })

        if (poster === null) {
            aPoster.css({
                'background-image': 'url("./../images/question.jpg")'
            })
        } else {
            aPoster.css({
                'background-image': movie_poster //'url("https://image.tmdb.org/t/p/w1280/rwn876MeqienhOVSSjtUPnwxn0Z.jpg")' //'url("./../images/question.jpg")'
            })
        }
        $(main).append(aPoster);
    }
</code>```

答:
```<code>   html file .

 <!Doctype html>
    <html>

    <head>
      <Title>Image Background</Title>

    </head>

    <Body>
      <main></main>
      <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
      <script>
        $.getJSON("http://127.0.0.1/json", function(result) {
          console.log(result);
          getData(result);
        });

        function getData(responseData) {
          var poster = responseData.poster_path;
          appendToDom(poster);
        }

        function appendToDom(poster) {
          console.log(poster);
          var aPoster = $('<div>');
          var movie_poster = 'url("' + poster + '")';
          console.log(movie_poster);
          aPoster.css({
            'float': 'left',
            'margin': 10,
            'margin-left': 37,
            'margin-top': 20,
            'width': 200,
            'height': 300,
            'font-size': 36,
            'color': 'black',
            'background-size': '200px 300px',
            'background-image': movie_poster //'url("./../images/question.jpg")'
          })
          $("main").append(aPoster);
        }
      </script>
    </Body>

    </html>
</code>```

simple backend.

```<code>var http = require('http');
var fs = require('fs');

var server = http.createServer(function (req, res) {
  console.log(req.url);

  if (req.url == "/json") {
    var j = {
      poster_path: "./public/images/foxxi.webp"
    }
    console.log('sending json');
    res.end(JSON.stringify(j));
  } else if (req.url == "/public/images/foxxi.webp") {
    fs.readFile("./public/images/foxxi.webp", function (err, image) {
      res.write(image);
      console.log('sending image');
      res.end();
    });

  } else {
    fs.readFile("po.html", function (err, html) {
      res.write(html);
      console.log('sending html');
      res.end();
    });

  }

});

server.listen(80);
</code>```

Body:
I am trying to add a background image to a div by giving the background image property in my css the link provided by the api I am using. However, it does not work. If I try to access the image directly from chrome, I get nothing either. Here is my code:

function getData(responseData) {
    var poster = responseData.results[0].poster_path;
    appendToDom(poster);
}

function appendToDom(poster) {
    var aPoster = $('
');
    var movie_poster = 'url("' + poster + '")';
    console.log(movie_poster);
    aPoster.css({
        'float': 'left',
        'margin': 10,
        'margin-left': 37,
        'margin-top': 20,
        'width': 200,
        'height': 300,
        'font-size': 36,
        'color': 'black',
        'background-size': '200px 300px',
        'background-image': movie_poster //'url("./../images/question.jpg")'
    })
    $(main).append(aPoster);
}

My console.log returns url("/rwn876MeqienhOVSSjtUPnwxn0Z.jpg") which is the url I expect. I am working with The Movie DataBase API if that helps.

Thanks for all the help in advance!

Hey guys! I finally figured it out. Here's my final js file with a list of posters that are attached to a certain name displayed.

$('#search').keypress(function(e) {
        if (e.which == 13) {
            var movie = $('#search-input').val();
            $('form#login').submit();
            console.log('onclick fun', movie)
            makeCall(movie);
            return false;
        }
    });

    function makeCall(aMovie) {
        console.log('makecall', aMovie);

        link = url + aMovie;
        console.log(link);
        $.ajax({
            method: "GET",
            url: link,
            success: function(data) {
                console.log("the data -->", data);
                getData(data);
            },
        })
    }

    function getData(responseData) {
        for (let i = 0; i < responseData.results.length; i++) {
            var poster = responseData.results[i].poster_path;
            appendToDom(poster);
        }
    }

    function appendToDom(poster) {
        var aPoster = $('
');
        var movie_poster = 'url("https://image.tmdb.org/t/p/w1280' + poster + '")';
        console.log(movie_poster);
        aPoster.css({
            'float': 'left',
            'margin': 10,
            'margin-left': 37,
            'margin-top': 20,
            'width': 200,
            'height': 300,
            'font-size': 36,
            'color': 'black',
            'background-size': '200px 300px',
        })

        if (poster === null) {
            aPoster.css({
                'background-image': 'url("./../images/question.jpg")'
            })
        } else {
            aPoster.css({
                'background-image': movie_poster //'url("https://image.tmdb.org/t/p/w1280/rwn876MeqienhOVSSjtUPnwxn0Z.jpg")' //'url("./../images/question.jpg")'
            })
        }
        $(main).append(aPoster);
    }

Body:
   html file .

 <!Doctype html>
    <html>

    <head>
      <Title>Image Background</Title>

    </head>

    <Body>
      <main></main>
      <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
      <script>
        $.getJSON("http://127.0.0.1/json", function(result) {
          console.log(result);
          getData(result);
        });

        function getData(responseData) {
          var poster = responseData.poster_path;
          appendToDom(poster);
        }

        function appendToDom(poster) {
          console.log(poster);
          var aPoster = $('<div>');
          var movie_poster = 'url("' + poster + '")';
          console.log(movie_poster);
          aPoster.css({
            'float': 'left',
            'margin': 10,
            'margin-left': 37,
            'margin-top': 20,
            'width': 200,
            'height': 300,
            'font-size': 36,
            'color': 'black',
            'background-size': '200px 300px',
            'background-image': movie_poster //'url("./../images/question.jpg")'
          })
          $("main").append(aPoster);
        }
      </script>
    </Body>

    </html>

simple backend.

var http = require('http');
var fs = require('fs');

var server = http.createServer(function (req, res) {
  console.log(req.url);

  if (req.url == "/json") {
    var j = {
      poster_path: "./public/images/foxxi.webp"
    }
    console.log('sending json');
    res.end(JSON.stringify(j));
  } else if (req.url == "/public/images/foxxi.webp") {
    fs.readFile("./public/images/foxxi.webp", function (err, image) {
      res.write(image);
      console.log('sending image');
      res.end();
    });

  } else {
    fs.readFile("po.html", function (err, html) {
      res.write(html);
      console.log('sending html');
      res.end();
    });

  }

});

server.listen(80);


来源: stackexchange

问:
App Engine Modeling Issue - Storing generated ID as number or string?
Say I have an blog app, with blog posts and comments.

```<code>class BlogPost(ndb.Model):
  title = ndb.StringProperty()
  description = ndb.TextProperty()
</code>```

I have another model for when user comments on a blog post:

```<code>class Comment(ndb.Model):
  username = ndb.StringProperty()
  blog_id = ndb.StringProperty()
  created = ndb.DateTimeProperty(auto_now_add=True)
</code>```

When I query for all the comments for a particular BlogPost, I do:

```<code>query = Comment.query(Comment.blog_id==blog_id).order(-Comment.created)
</code>```

Is this OK? My question is specifically if it is OK to store the blog_id as a string property rather than the original integer ID? I did this because it is an iOS app, and the long integer ID's was causing an integer overflow error in my iOS client.

Would this type of query scale no problem?

答:
The only problem I can see happening there is Comment.blog_id being a string and blog_id being a number, so you would be comparing a string with an int.
If blog_id is a string, then you are safe.
The way ndb/Datastore indexes works, your query will be the same with strings or integers (performance wise).

ContentLicense: CC BY-SA 3.0

Body:
Say I have an blog app, with blog posts and comments.

class BlogPost(ndb.Model):
  title = ndb.StringProperty()
  description = ndb.TextProperty()

I have another model for when user comments on a blog post:

class Comment(ndb.Model):
  username = ndb.StringProperty()
  blog_id = ndb.StringProperty()
  created = ndb.DateTimeProperty(auto_now_add=True)

When I query for all the comments for a particular BlogPost, I do:

query = Comment.query(Comment.blog_id==blog_id).order(-Comment.created)

Is this OK? My question is specifically if it is OK to store the blog_id as a string property rather than the original integer ID? I did this because it is an iOS app, and the long integer ID's was causing an integer overflow error in my iOS client.

Would this type of query scale no problem?


问:
Use reduce to sum attributes of objects in array
I have a class called Food; it's a very simple class, it just has name, price, and Kcal. I created three kinds of Food:

```<code>@Food1 = Food.new("Pear", 12, 120)
@Food2 = Food.new("Apple", 15, 100)
@Food3 = Food.new("Banana", 20, 200)
</code>```

Then I created an array of foods called Menu:

```<code>@Menu = [@Food1, @Food2, @Food3]
</code>```

I need to sum all the prices with the reduce method, and store them in @Food1. I have implemented the + method for the food class:

```<code>def + (other)
    @price + other.price
end
</code>```

And I am trying to do:

```<code>@Food1 = @Menu.reduce(:+)
</code>```

But it does not work. Do you have some idea how I can reach this?

答:
The simplest way is to write it as follows.

```<code>class Food
  attr_reader :price
  def initialize(name, price, kcal)
    @name, @price, @kcal = name, price, kcal
  end
end

food1 = Food.new("Pear",   12, 120)
food2 = Food.new("Apple",  15, 100)
food3 = Food.new("Banana", 20, 200)
menu = [food1, food2, food3]`enter code here`

menu.reduce(0) { |t,food| t+food.price }
  #=> 47
</code>```

or (for Ruby v2.4+)

```<code>menu.sum { |food| food.price }
</code>```

Notice that I didn't define food1, food2, food3 or menu as instance variables. There may be a reason for doing so, but not just to obtain the sum of the prices.

Food.new.price is an integer, for which Integer#+ is of course defined, so there is no particular reason to define and instance method + on the class.

Suppose you did add an instance method :+ to the class:

```<code>def +(other)
  price + other.price
end
</code>```

This would allow you to write

```<code>food1 + food2
  #=> 27
</code>```

(though it is not intuitive that prices are being summed). However, you cannot write

```<code>food1 + food2 + food3
</code>```

because food1 + food2 is first executed, returning 27, then an attempt is made to execute

```<code>27 + food3
</code>```

which is syntactic sugar for

```<code>27.+(food3)
</code>```

Here :+ is an Integer method, which does not accept food3 as an argument and therefore raises an exception.

Body:
I have a class called Food; it's a very simple class, it just has name, price, and Kcal. I created three kinds of Food:

@Food1 = Food.new("Pear", 12, 120)
@Food2 = Food.new("Apple", 15, 100)
@Food3 = Food.new("Banana", 20, 200)

Then I created an array of foods called Menu:

@Menu = [@Food1, @Food2, @Food3]

I need to sum all the prices with the reduce method, and store them in @Food1. I have implemented the + method for the food class:

def + (other)
    @price + other.price
end

And I am trying to do:

@Food1 = @Menu.reduce(:+)

But it does not work. Do you have some idea how I can reach this?

Body:
The simplest way is to write it as follows.

class Food
  attr_reader :price
  def initialize(name, price, kcal)
    @name, @price, @kcal = name, price, kcal
  end
end

food1 = Food.new("Pear",   12, 120)
food2 = Food.new("Apple",  15, 100)
food3 = Food.new("Banana", 20, 200)
menu = [food1, food2, food3]`enter code here`

menu.reduce(0) { |t,food| t+food.price }
  #=> 47

or (for Ruby v2.4+)

menu.sum { |food| food.price }

Notice that I didn't define food1, food2, food3 or menu as instance variables. There may be a reason for doing so, but not just to obtain the sum of the prices.

Food.new.price is an integer, for which Integer#+ is of course defined, so there is no particular reason to define and instance method + on the class.

Suppose you did add an instance method :+ to the class:

def +(other)
  price + other.price
end

This would allow you to write

food1 + food2
  #=> 27

(though it is not intuitive that prices are being summed). However, you cannot write

food1 + food2 + food3

because food1 + food2 is first executed, returning 27, then an attempt is made to execute

27 + food3

which is syntactic sugar for

27.+(food3)

Here :+ is an Integer method, which does not accept food3 as an argument and therefore raises an exception.


问:
Error:cannot convert float NaN to integer in pandas
I have the dataframe:

```<code>   a            b     c      d
0 nan           Y     nan   nan
1  1.27838e+06  N      3     96
2 nan           N      2    nan
3  284633       Y     nan    44
</code>```

I try to change the data which is non zero to interger type to avoid exponential data(1.27838e+06):

```<code>f=lambda x : int(x)
df['a']=np.where(df['a']==None,np.nan,df['a'].apply(f))
</code>```

But I get error also event thought I wish to change the dtype of not null value, anyone can point out my error? thanks

答:
As far as I have read in the pandas documentation, it is not possible to represent an integer NaN:

"In the absence of high performance NA support being built into NumPy from the ground up, the primary casualty is the ability to represent NAs in integer arrays."

As it is explained later, it is due to memory and performance reasons, and also so that the resulting Series continues to be “numeric”. One possibility is to use dtype=object arrays instead.

Body:
I have the dataframe:

   a            b     c      d
0 nan           Y     nan   nan
1  1.27838e+06  N      3     96
2 nan           N      2    nan
3  284633       Y     nan    44

I try to change the data which is non zero to interger type to avoid exponential data(1.27838e+06):

f=lambda x : int(x)
df['a']=np.where(df['a']==None,np.nan,df['a'].apply(f))

But I get error also event thought I wish to change the dtype of not null value, anyone can point out my error? thanks


问:
How to get iOS 10.3.2(14F89)
I need run my Project with Xcode7,but my iPhone iOS Version is 10.3.2(14F89),How to get iOS10.3.2(14F89) Device support files??</p>

答: you should update your Xcode to Xcode8,and it support your device.</p>

Title: How to get iOS 10.3.2(14F89)


问:
How do I get text that someone has entered into a text field and input this into my SQLite database?
So, I'm creating the log in activity for my new app. If a user is signing up, I will need to store the info that they enter into the sign up form to be stored inside of my SQLite database. How do I go about doing this? This is what I have so far: </p>

```<code>public class DatabaseHelper extends SQLiteOpenHelper {
    private static final String DB_NAME = "USERS";
    private static final int DB_VERSION = 1;

    DatabaseHelper(Context context){
        super(context,DB_NAME,null,DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE DATABASE USERS("
                + "_id INTEGER PRIMARY KEY AUTOINCREMENT, "
                + "USERNAME TEXT, "
                + "EMAIL_ADDRESS TEXT, "
                + "PASSWORD TEXT); ");
        insertUser(db, "");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    private static void insertUser (SQLiteDatabase db, String username, String email, String password){
        ContentValues userValues = new ContentValues();
        userValues.put("USERNAME", username);
        userValues.put("EMAIL_ADDRESS", email);
        userValues.put("PASSWORD", password);
        db.insert("USERS", null, userValues);
    };
}
</code>```

答:
You have make a query to fetch the records from SQLite database.

Here is a simple example to fetch all users:

```<code>public List<User> getAllUsers() {
    SQLiteDatabase db = this.getReadableDatabase();

    List<User> users = new ArrayList<>();

    Cursor cursor = db.query("USERS", null, null, null, null, null, null);
    if (cursor.moveToFirst()) {
        do {
            User user = new User();
            user.setUsername(cursor.getString(1));
            user.setEmail(cursor.getString(2));
            users.add(user);
        } while (cursor.moveToNext());
    }

    return users;
}
</code>```

You can read more about it in the following link:

http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/

Body:
So, I'm creating the log in activity for my new app. If a user is signing up, I will need to store the info that they enter into the sign up form to be stored inside of my SQLite database. How do I go about doing this? This is what I have so far:

public class DatabaseHelper extends SQLiteOpenHelper {
    private static final String DB_NAME = "USERS";
    private static final int DB_VERSION = 1;

    DatabaseHelper(Context context){
        super(context,DB_NAME,null,DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE DATABASE USERS("
                + "_id INTEGER PRIMARY KEY AUTOINCREMENT, "
                + "USERNAME TEXT, "
                + "EMAIL_ADDRESS TEXT, "
                + "PASSWORD TEXT); ");
        insertUser(db, "");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    private static void insertUser (SQLiteDatabase db, String username, String email, String password){
        ContentValues userValues = new ContentValues();
        userValues.put("USERNAME", username);
        userValues.put("EMAIL_ADDRESS", email);
        userValues.put("PASSWORD", password);
        db.insert("USERS", null, userValues);
    };
}

Body:
You have make a query to fetch the records from SQLite database.

Here is a simple example to fetch all users:

public List<User> getAllUsers() {
    SQLiteDatabase db = this.getReadableDatabase();

    List<User> users = new ArrayList<>();

    Cursor cursor = db.query("USERS", null, null, null, null, null, null);
    if (cursor.moveToFirst()) {
        do {
            User user = new User();
            user.setUsername(cursor.getString(1));
            user.setEmail(cursor.getString(2));
            users.add(user);
        } while (cursor.moveToNext());
    }

    return users;
}

You can read more about it in the following link:

http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/


问:
How can I detect browser and OS of user and use this to dynamically modify my MySQL database query from a PHP page
I need to be able to run a mysql query and omit certain results if the user is using a certain browser on a certain OS. My database query takes place from an AMFPHP service and I have a javascript browserDetect script that I can use to get user browser and OS.

Ideally I want to run the browserDetect script when the user arrives at my page and then store this in the PHP session variables but I cannot see how to pass the javascript vars to the PHP session. This would allow my database query script to look up the session and modify the query accordingly. I also tried to include the browser detect script in the AMFPHP script but this did not work - I realise that this a serverside vs client side problem.

What other solutions would work for me?

thanks

答:
you can set the results from browserDetect javascript to javascript cookie, and PHP is able to read cookie from that

details : How to read Javascript cookie with PHP

ContentLicense: CC BY-SA 2.5


问:
MacOS/OSx - Changing the metadata on an iTunes Library Song/Item Programatically
I'm able to programmatically (Swift) access the array of MLMediaObject-s in the iTunes MLMediaGroup.  But I don't see how I can change the metadata on the songs.  I'm calculating the beatsPerMinute (which is usually zero in iTunes) and I want to write it back to the iTunes library or item.  Does anyone know how I can do that.  The MediaLibrary  docs say "Access read-only collections of the user’s multimedia content," so I'm not sure if this is the correct approach.

Thanks in advance for you help

答:
As the documentation suggests, the MediaLibrary framework only provides read-only access to the user's media collection. It cannot be used to modify items in the library -- not even their metadata.

If you want to modify metadata, you need to go about it some other way. The only method I'm aware of would be to use AppleScript to retrieve and modify the appropriate item, e.g.

```<code>tell application "iTunes"
    set bpm of current track to 130
end tell
</code>```

Body:
As the documentation suggests, the MediaLibrary framework only provides read-only access to the user's media collection. It cannot be used to modify items in the library -- not even their metadata.

If you want to modify metadata, you need to go about it some other way. The only method I'm aware of would be to use AppleScript to retrieve and modify the appropriate item, e.g.

tell application "iTunes"
    set bpm of current track to 130
end tell


问:
Scrolling GridView causes GC_FOR_ALLOC free issues
I have a gridview with some images inside. Sometime when I'm scrolling, GC_FOR_ALLOC or heap is increased and I don't know why. I used a method to load a minimized image.

Might I use Picasso or a ViewHolder ? RecyclerView ?

The memory issues happened once or twice when I tested my app on my personal device although everything still ran.  But on an older smartphone ( less efficient) , the memory issues totally stopped the phone and other apps from running.

I see warnings on my "setTag" as though the problem is caused by a memory leak.

How can I repair the memory problems ?

MainActivity.java

```<code>public class MainActivity extends Activity {
GridView gridView;
MediaPlayer mPlayer;

@Override
public synchronized void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    boolean internetAcces = checkDataConnection();
    if(internetAcces == true){
        setContentView(R.layout.activity_main);
        AdView adView = (AdView) this.findViewById(R.id.adView);
        AdRequest adRequest1 = new AdRequest.Builder().build();
        adView.loadAd(adRequest1);
    }
    else{
        setContentView(R.layout.activity_main2);
    }
    gridView = (GridView)findViewById(R.id.gridview);
    gridView.setAdapter(new MyAdapter(this));
    gridView.setOnItemClickListener(new AdapterView.OnItemClickListener()
    {
            @Override
            public synchronized void onItemClick(AdapterView<?> parent, View view, int position, long id)
            {

                try{
                    if(mPlayer != null && mPlayer.isPlaying())
                    {
                        mPlayer.stop();
                        mPlayer.release();
                        playSong(position);
                    }
                    else
                    {
                        playSong(position);
                    }
                }catch(Exception ex){
                    //Toast.makeText(MainActivity.this, ex.getMessage(), Toast.LENGTH_SHORT).show();
                }

            }
    });

}

@Override
protected void onPause(){
    super.onPause();
}

@Override
protected void onStop() {
    super.onStop();
    System.exit(0);
}

@Override
protected void onDestroy(){
    super.onDestroy();
    System.exit(0);
}
</code>```

Here's MyAdapter.java

```<code>public final class MyAdapter extends BaseAdapter {
private final List<Item> mItems = new ArrayList<Item>(30);
private final LayoutInflater mInflater;
public Context context;

public MyAdapter(Context context) {
    mInflater = LayoutInflater.from(context);
    this.context = context;

    mItems.add(new Item("Hé pélo",       R.drawable.hepelo));
    mItems.add(new Item("Salut les losers",   R.drawable.salutleslosers));
    mItems.add(new Item("Arrête Abib", R.drawable.abib));
    mItems.add(new Item("Goût bite",      R.drawable.goutbite));
    mItems.add(new Item("Makassy",     R.drawable.makassy));
    mItems.add(new Item("Joris Lecon",      R.drawable.jorislecon));
    mItems.add(new Item("Cache la drogue",       R.drawable.cacheladrogue));
    mItems.add(new Item("Un peu trop tactile",   R.drawable.unpeutroptactile));
    mItems.add(new Item("Qui c'est qu'a touché à Dorian ?", R.drawable.dorian));
    mItems.add(new Item("T'es pas beau",      R.drawable.tespasbeau));
    mItems.add(new Item("Ta mère",     R.drawable.tamere));
    mItems.add(new Item("Je bute ce paquet de chips",     R.drawable.jebutecepaquetdechips));
    mItems.add(new Item("La maison du content",     R.drawable.lamaisonducontent));
    mItems.add(new Item("Mes péripétiiiiiies",     R.drawable.mesperipeties));
    mItems.add(new Item("La rapta babtou",     R.drawable.laraptababtou));
    mItems.add(new Item("Que vas-tu faire ?!",     R.drawable.bangbang));
    mItems.add(new Item("Oh les tétés !",     R.drawable.lestetes));
    mItems.add(new Item("Mollé mollé",     R.drawable.laraptababtou));
    mItems.add(new Item("Okéééé",     R.drawable.ok));
    mItems.add(new Item("Guillaume le thug",     R.drawable.guillaumelethug));
    mItems.add(new Item("C'est ma teub",     R.drawable.cestmateub));
    mItems.add(new Item("Je suis qu'un thug",     R.drawable.jsuisquunthug));
}

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

@Override
public Item getItem(int i) {
    return mItems.get(i);
}

@Override
public long getItemId(int i) {
    return mItems.get(i).drawableId;
}

@Override
public View getView(int i, View view, ViewGroup viewGroup) {
    View v = view;
    ImageView picture;
    TextView name;

    if (v == null) {
        v = mInflater.inflate(R.layout.grid_item, viewGroup, false);
        v.setTag(R.id.picture, v.findViewById(R.id.picture));
        v.setTag(R.id.text, v.findViewById(R.id.text));
    }

    picture = (ImageView) v.getTag(R.id.picture);

    name = (TextView) v.getTag(R.id.text);

    Item item = getItem(i);

    //picture.setImageResource(item.drawableId);
    picture.setImageBitmap(decodeSampledBitmapFromResource(context.getResources(),item.drawableId, 150, 150));

    name.setText(item.name);

    return v;}

public static int calculateInSampleSize(
        BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;

if (height > reqHeight || width > reqWidth) {

    final int halfHeight = height / 2;
    final int halfWidth = width / 2;

    // Calculate the largest inSampleSize value that is a power of 2 and keeps both
    // height and width larger than the requested height and width.
    while ((halfHeight / inSampleSize) > reqHeight
            && (halfWidth / inSampleSize) > reqWidth) {
        inSampleSize *= 2;
    }
}

return inSampleSize;}

public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
        int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}

private static class Item {
    public final String name;
    public final int drawableId;

    Item(String name, int drawableId) {
        this.name = name;
        this.drawableId = drawableId;
    }
}

}
</code>```

main_activity.xml :

```<code><LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<GridView
    android:id="@+id/gridview"
    android:layout_width="fill_parent"
    android:layout_height="0dp"
    android:layout_gravity="center"
    android:verticalSpacing="0dp"
    android:layout_weight="1"
    android:horizontalSpacing="0dp"
    android:stretchMode="columnWidth"
    android:numColumns="2"
    android:listSelector="@android:color/transparent"
    android:scrollingCache="false"
    android:animationCache="false"
 />

  <com.google.android.gms.ads.AdView
    android:id="@+id/adView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    ads:adSize="SMART_BANNER"
    ads:adUnitId="ca-app-pub-2373549811754777/2717783647"
   />
</code>```

grid_item.xml :

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
         android:layout_width="match_parent"
         android:layout_height="match_parent">
<com.slamingresources.laboiteamisterv.SquareImageView
    android:id="@+id/picture"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scaleType="centerCrop"
    />

<TextView
    android:id="@+id/text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:paddingTop="4dp"
    android:paddingBottom="5dp"
    android:layout_gravity="bottom"
    android:textColor="@android:color/white"
    android:background="#55000002"
    />
</code>```

Logcat :

```<code>11-20 03:21:45.878: I/dalvikvm-heap(16815): Clamp target GC heap from      128.451MB to 128.000MB
11-20 03:21:47.628: I/dalvikvm-heap(16815): Clamp target GC heap from 135.930MB to 128.000MB
11-20 03:21:47.688: D/dalvikvm(16815): GC_BEFORE_OOM freed 109065K, 85% free 20521K/131004K, paused 59ms, total 60ms
11-20 03:22:00.498: D/dalvikvm(16815): GC_FOR_ALLOC freed 3972K, 85% free 20494K/131004K, paused 24ms, total 24ms
</code>```

答:
I know this is old but for those that are still looking for same answers: you can use getcachedir() to store data temporarily in Android.

For more options see Android data storage.

Body:
I have a gridview with some images inside. Sometime when I'm scrolling, GC_FOR_ALLOC or heap is increased and I don't know why. I used a method to load a minimized image.

Might I use Picasso or a ViewHolder ? RecyclerView ?

The memory issues happened once or twice when I tested my app on my personal device although everything still ran.  But on an older smartphone ( less efficient) , the memory issues totally stopped the phone and other apps from running.

I see warnings on my "setTag" as though the problem is caused by a memory leak.

How can I repair the memory problems ?

MainActivity.java

public class MainActivity extends Activity {
GridView gridView;
MediaPlayer mPlayer;

@Override
public synchronized void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    boolean internetAcces = checkDataConnection();
    if(internetAcces == true){
        setContentView(R.layout.activity_main);
        AdView adView = (AdView) this.findViewById(R.id.adView);
        AdRequest adRequest1 = new AdRequest.Builder().build();
        adView.loadAd(adRequest1);
    }
    else{
        setContentView(R.layout.activity_main2);
    }
    gridView = (GridView)findViewById(R.id.gridview);
    gridView.setAdapter(new MyAdapter(this));
    gridView.setOnItemClickListener(new AdapterView.OnItemClickListener()
    {
            @Override
            public synchronized void onItemClick(AdapterView<?> parent, View view, int position, long id)
            {

                try{
                    if(mPlayer != null && mPlayer.isPlaying())
                    {
                        mPlayer.stop();
                        mPlayer.release();
                        playSong(position);
                    }
                    else
                    {
                        playSong(position);
                    }
                }catch(Exception ex){
                    //Toast.makeText(MainActivity.this, ex.getMessage(), Toast.LENGTH_SHORT).show();
                }

            }
    });

}

@Override
protected void onPause(){
    super.onPause();
}

@Override
protected void onStop() {
    super.onStop();
    System.exit(0);
}

@Override
protected void onDestroy(){
    super.onDestroy();
    System.exit(0);
}

Here's MyAdapter.java

public final class MyAdapter extends BaseAdapter {
private final List<Item> mItems = new ArrayList<Item>(30);
private final LayoutInflater mInflater;
public Context context;

public MyAdapter(Context context) {
    mInflater = LayoutInflater.from(context);
    this.context = context;

    mItems.add(new Item("Hé pélo",       R.drawable.hepelo));
    mItems.add(new Item("Salut les losers",   R.drawable.salutleslosers));
    mItems.add(new Item("Arrête Abib", R.drawable.abib));
    mItems.add(new Item("Goût bite",      R.drawable.goutbite));
    mItems.add(new Item("Makassy",     R.drawable.makassy));
    mItems.add(new Item("Joris Lecon",      R.drawable.jorislecon));
    mItems.add(new Item("Cache la drogue",       R.drawable.cacheladrogue));
    mItems.add(new Item("Un peu trop tactile",   R.drawable.unpeutroptactile));
    mItems.add(new Item("Qui c'est qu'a touché à Dorian ?", R.drawable.dorian));
    mItems.add(new Item("T'es pas beau",      R.drawable.tespasbeau));
    mItems.add(new Item("Ta mère",     R.drawable.tamere));
    mItems.add(new Item("Je bute ce paquet de chips",     R.drawable.jebutecepaquetdechips));
    mItems.add(new Item("La maison du content",     R.drawable.lamaisonducontent));
    mItems.add(new Item("Mes péripétiiiiiies",     R.drawable.mesperipeties));
    mItems.add(new Item("La rapta babtou",     R.drawable.laraptababtou));
    mItems.add(new Item("Que vas-tu faire ?!",     R.drawable.bangbang));
    mItems.add(new Item("Oh les tétés !",     R.drawable.lestetes));
    mItems.add(new Item("Mollé mollé",     R.drawable.laraptababtou));
    mItems.add(new Item("Okéééé",     R.drawable.ok));
    mItems.add(new Item("Guillaume le thug",     R.drawable.guillaumelethug));
    mItems.add(new Item("C'est ma teub",     R.drawable.cestmateub));
    mItems.add(new Item("Je suis qu'un thug",     R.drawable.jsuisquunthug));
}

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

@Override
public Item getItem(int i) {
    return mItems.get(i);
}

@Override
public long getItemId(int i) {
    return mItems.get(i).drawableId;
}

@Override
public View getView(int i, View view, ViewGroup viewGroup) {
    View v = view;
    ImageView picture;
    TextView name;

    if (v == null) {
        v = mInflater.inflate(R.layout.grid_item, viewGroup, false);
        v.setTag(R.id.picture, v.findViewById(R.id.picture));
        v.setTag(R.id.text, v.findViewById(R.id.text));
    }

    picture = (ImageView) v.getTag(R.id.picture);

    name = (TextView) v.getTag(R.id.text);

    Item item = getItem(i);

    //picture.setImageResource(item.drawableId);
    picture.setImageBitmap(decodeSampledBitmapFromResource(context.getResources(),item.drawableId, 150, 150));

    name.setText(item.name);

    return v;}

public static int calculateInSampleSize(
        BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;

if (height > reqHeight || width > reqWidth) {

    final int halfHeight = height / 2;
    final int halfWidth = width / 2;

    // Calculate the largest inSampleSize value that is a power of 2 and keeps both
    // height and width larger than the requested height and width.
    while ((halfHeight / inSampleSize) > reqHeight
            && (halfWidth / inSampleSize) > reqWidth) {
        inSampleSize *= 2;
    }
}

return inSampleSize;}

public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
        int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}

private static class Item {
    public final String name;
    public final int drawableId;

    Item(String name, int drawableId) {
        this.name = name;
        this.drawableId = drawableId;
    }
}

}

main_activity.xml :

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<GridView
    android:id="@+id/gridview"
    android:layout_width="fill_parent"
    android:layout_height="0dp"
    android:layout_gravity="center"
    android:verticalSpacing="0dp"
    android:layout_weight="1"
    android:horizontalSpacing="0dp"
    android:stretchMode="columnWidth"
    android:numColumns="2"
    android:listSelector="@android:color/transparent"
    android:scrollingCache="false"
    android:animationCache="false"
 />

  <com.google.android.gms.ads.AdView
    android:id="@+id/adView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    ads:adSize="SMART_BANNER"
    ads:adUnitId="ca-app-pub-2373549811754777/2717783647"
   />

grid_item.xml :

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
         android:layout_width="match_parent"
         android:layout_height="match_parent">
<com.slamingresources.laboiteamisterv.SquareImageView
    android:id="@+id/picture"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scaleType="centerCrop"
    />

<TextView
    android:id="@+id/text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:paddingTop="4dp"
    android:paddingBottom="5dp"
    android:layout_gravity="bottom"
    android:textColor="@android:color/white"
    android:background="#55000002"
    />

Logcat :

11-20 03:21:45.878: I/dalvikvm-heap(16815): Clamp target GC heap from      128.451MB to 128.000MB
11-20 03:21:47.628: I/dalvikvm-heap(16815): Clamp target GC heap from 135.930MB to 128.000MB
11-20 03:21:47.688: D/dalvikvm(16815): GC_BEFORE_OOM freed 109065K, 85% free 20521K/131004K, paused 59ms, total 60ms
11-20 03:22:00.498: D/dalvikvm(16815): GC_FOR_ALLOC freed 3972K, 85% free 20494K/131004K, paused 24ms, total 24ms


问:
Wordpress permalink not linking to content.php
I'm developing a Wordpress custom theme from scratch. I've managed to get a custom grid display to work in index.php. Each post shows an image with the post's title and category as subtitle. Here's index.php code:

<?php get_header(); ?>

    <?php
    $counter = 1; //start counter

    $grids = 2; //Grids per row

    query_posts($query_string . '&caller_get_posts=1&posts_per_page=12');

    if (have_posts()) : while (have_posts()) : the_post();
            ?>
            <?php
//Show the left hand side column
            if ($counter == 1) :
                ?>

                    " title="<?php the_title_attribute(); ?>">
                        <img src="<?php the_post_thumbnail_url(); ?>" class="img-responsive" style="width:100%;" alt="">
                    <?php the_title(); ?>
                     <?php
                     foreach ((get_the_category()) as $category) {
                         echo "
".$category->category_nicename. "
";
                     }
                     ?>

                <?php
//Show the right hand side column
            elseif ($counter == $grids) :
                ?>

                    " title="<?php the_title_attribute(); ?>">
                        <img src="<?php the_post_thumbnail_url(); ?>" class="img-responsive" style="width:100%;" alt="">
                    <?php the_title(); ?>
                     <?php
                     // heres just the name and permalink:
                     foreach ((get_the_category()) as $category) {
                         echo "
".$category->category_nicename. "
";
                     }
                     ?>

                <?php
                $counter = 0;
            endif;
            ?>
            <?php
            $counter++;
        endwhile;
    endif;
    ?>

<?php get_footer(); ?>```
</div>
</div>
</p>

<p>The post's thumbnail contains a link to the post's permalink, that should link to content.php. Here's content.php:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container" style="padding:100px;">
 <strong><?php the_title(); ?></strong>
        <?php
        foreach ((get_the_category()) as $category) {
            echo "<h5>" . $category->category_nicename . "</h5>";
        }
        ?>
        <h5> / <?php the_date(); ?> </h5>
        <h5> <?php the_content(); ?> </h5>
   </div></code>```

The problem is that when I click on the index.php thumbnail, it links to a smaller version of itself, instead of the content.php page. My guess is that I need to tell the permalink where to go but I can't really find where to put this configuration.

Thanks!

答:
In WordPress, the_permalink() or get_permalink() returns the single page URL for a post or page. It's a WordPress template hierarchy that single post pages will load the single.php file.

You've two options here,

1) Copy your code from content.php to single.php and you'll be good to go. Of course you need to include get_header() and get_footer() to make the page load properly.

2) In your single.php inside the loop, you can include content.php as template part. The following goes in your single.php, replacing the loop.

```<code>while ( have_posts() ) :
    the_post();
    get_template_part( 'content' );
endwhile;
</code>```

Also, in the code above, I am assuming your content.php is placed in the theme directory root.

Body:
I'm developing a Wordpress custom theme from scratch. I've managed to get a custom grid display to work in index.php. Each post shows an image with the post's title and category as subtitle. Here's index.php code:

<?php get_header(); ?>

    <?php
    $counter = 1; //start counter

    $grids = 2; //Grids per row

    query_posts($query_string . '&caller_get_posts=1&posts_per_page=12');

    if (have_posts()) : while (have_posts()) : the_post();
            ?>
            <?php
//Show the left hand side column
            if ($counter == 1) :
                ?>

                    <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
                        <img src="<?php the_post_thumbnail_url(); ?>" class="img-responsive" style="width:100%;" alt="">
                    <?php the_title(); ?>
                     <?php
                     foreach ((get_the_category()) as $category) {
                         echo "
".$category->category_nicename. "
";
                     }
                     ?>

                <?php
//Show the right hand side column
            elseif ($counter == $grids) :
                ?>

                    <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
                        <img src="<?php the_post_thumbnail_url(); ?>" class="img-responsive" style="width:100%;" alt="">
                    <?php the_title(); ?>
                     <?php
                     // heres just the name and permalink:
                     foreach ((get_the_category()) as $category) {
                         echo "
".$category->category_nicename. "
";
                     }
                     ?>

                <?php
                $counter = 0;
            endif;
            ?>
            <?php
            $counter++;
        endwhile;
    endif;
    ?>

<?php get_footer(); ?>

The post's thumbnail contains a link to the post's permalink, that should link to content.php. Here's content.php:

 <?php the_title(); ?>
        <?php
        foreach ((get_the_category()) as $category) {
            echo "
" . $category->category_nicename . "
";
        }
        ?>

 / <?php the_date(); ?>

 <?php the_content(); ?>

The problem is that when I click on the index.php thumbnail, it links to a smaller version of itself, instead of the content.php page. My guess is that I need to tell the permalink where to go but I can't really find where to put this configuration.

Thanks!

Body:
In WordPress, the_permalink() or get_permalink() returns the single page URL for a post or page. It's a WordPress template hierarchy that single post pages will load the single.php file.

You've two options here,

1) Copy your code from content.php to single.php and you'll be good to go. Of course you need to include get_header() and get_footer() to make the page load properly.

2) In your single.php inside the loop, you can include content.php as template part. The following goes in your single.php, replacing the loop.

while ( have_posts() ) :
    the_post();
    get_template_part( 'content' );
endwhile;

Also, in the code above, I am assuming your content.php is placed in the theme directory root.


问:
Requesting multiple values from graph at same time
In the code below l2 surprisingly returns the same value as l1, but since the optimizer is being requested in the list before l2, I expected the loss to be the new loss after training. Can I not request multiple values at the same time from the graph and expect consistent output?

import tensorflow as tf
import numpy as np

x = tf.placeholder(tf.float32, shape=[None, 10])
y = tf.placeholder(tf.float32, shape=[None, 2])

weight = tf.Variable(tf.random_uniform((10, 2), dtype=tf.float32))

loss = tf.nn.sigmoid_cross_entropy_with_logits(tf.matmul(x, weight), y)

optimizer = tf.train.AdamOptimizer(0.1).minimize(loss)

with tf.Session() as sess:
    tf.initialize_all_variables().run()

    X = np.random.rand(1, 10)
    Y = np.array([[0, 1]])

    # Evaluate loss before running training step
    l1 = sess.run([loss], feed_dict={x: X, y: Y})[0][0][0]
    print(l1) # 3.32393

    # Running the training step
    _, l2 = sess.run([optimizer, loss], feed_dict={x: X, y: Y})
    print(l2[0][0]) # 3.32393 -- didn't change?

    # Evaluate loss again after training step as sanity check
    l3 = sess.run([loss], feed_dict={x: X, y: Y})[0][0][0]
    print(l3) # 2.71041
```

答:
I've tested logistic regression implemented in tensorflow with three ways of session.run:

all together

res1, res2, res3 = sess.run([op1, op2, op3])

separately

res1 = sess.run(op1)

res2 = sess.run(op2)

res3 = sess.run(op3)

with dependencies

with tf.control_dependencies([op1]):

op2_after = tf.identity(op1)

op3_after = tf.identity(op1)

res1,res2,res3 = session.run([op1, op2_after, op3_after])

set batch size as 10000, the result is:

```<code>1: 0.05+ secs < 2: 0.11+ secs < 3: 0.25+ secs
</code>```

The main difference between 1 and 3 is only one mini-batch. It may not worth it to use 3 instead of 1.

Here is the test code (it is an LR example written by someone else...).

Here is the data

```<code>#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Jun  2 13:38:14 2017

@author: inse7en
"""

from __future__ import print_function
import numpy as np
import tensorflow as tf
from six.moves import cPickle as pickle
import time

pickle_file = '/Users/inse7en/Downloads/notMNIST.pickle'
with open(pickle_file, 'rb') as f:
  save = pickle.load(f)
  train_dataset = save['train_dataset']
  train_labels = save['train_labels']
  valid_dataset = save['valid_dataset']
  valid_labels = save['valid_labels']
  test_dataset = save['test_dataset']
  test_labels = save['test_labels']
  del save  # hint to help gc free up memory
  print('Training set', train_dataset.shape, train_labels.shape)
  print('Validation set', valid_dataset.shape, valid_labels.shape)
  print('Test set', test_dataset.shape, test_labels.shape)

image_size = 28
num_labels = 10

def reformat(dataset, labels):
  dataset = dataset.reshape((-1, image_size * image_size)).astype(np.float32)
  # Map 2 to [0.0, 1.0, 0.0 ...], 3 to [0.0, 0.0, 1.0 ...]
  labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32)
  return dataset, labels
train_dataset, train_labels = reformat(train_dataset, train_labels)
valid_dataset, valid_labels = reformat(valid_dataset, valid_labels)
test_dataset, test_labels = reformat(test_dataset, test_labels)
print('Training set', train_dataset.shape, train_labels.shape)
print('Validation set', valid_dataset.shape, valid_labels.shape)
print('Test set', test_dataset.shape, test_labels.shape)

# This is to expedite the process
train_subset = 10000
# This is a good beta value to start with
beta = 0.01

graph = tf.Graph()
with graph.as_default():
    # Input data.
    # They're all constants.
    tf_train_dataset = tf.constant(train_dataset[:train_subset, :])
    tf_train_labels = tf.constant(train_labels[:train_subset])
    tf_valid_dataset = tf.constant(valid_dataset)
    tf_test_dataset = tf.constant(test_dataset)

    # Variables
    # They are variables we want to update and optimize.
    weights = tf.Variable(tf.truncated_normal([image_size * image_size, num_labels]))
    biases = tf.Variable(tf.zeros([num_labels]))

    # Training computation.
    logits = tf.matmul(tf_train_dataset, weights) + biases
    # Original loss function
    loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels))
    # Loss function using L2 Regularization
    regularizer = tf.nn.l2_loss(weights)
    loss = tf.reduce_mean(loss + beta * regularizer)

    # Optimizer.
    optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss)

    # Predictions for the training, validation, and test data.
    train_prediction = tf.nn.softmax(logits)
    valid_prediction = tf.nn.softmax(tf.matmul(tf_valid_dataset, weights) + biases)
    test_prediction = tf.nn.softmax(tf.matmul(tf_test_dataset, weights) + biases)

    num_steps = 50

    def accuracy(predictions, labels):
        return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))
                / predictions.shape[0])

    with tf.Session(graph=graph) as session:
        # This is a one-time operation which ensures the parameters get initialized as
        # we described in the graph: random weights for the matrix, zeros for the
        # biases.
        tf.initialize_all_variables().run()
        print('Initialized')
        for step in range(num_steps):
            # Run the computations. We tell .run() that we want to run the optimizer,
            # and get the loss value and the training predictions returned as numpy
            # arrays.
            #_, l, predictions = session.run([optimizer, loss, train_prediction])

            start_time = time.time()
            with tf.control_dependencies([optimizer]):
                loss_after_optimizer = tf.identity(loss)
                predictions_after = tf.identity(train_prediction)
                regularizers_after = tf.identity(regularizer)

            _, l, predictions,regularizers = session.run([optimizer, loss_after_optimizer, predictions_after, regularizers_after])

            print("--- with dependencies: %s seconds ---" % (time.time() - start_time))
            #start_time = time.time()
            #opt = session.run(optimizer)
            #l = session.run(loss)
            #predictions = session.run(train_prediction)
            #regularizers = session.run(regularizer)

            #print("--- run separately: %s seconds ---" % (time.time() - start_time))

            #start_time = time.time()
            #_, l, predictions,regularizers = session.run([optimizer, loss, train_prediction, regularizer])

            #print("--- all together: %s seconds ---" % (time.time() - start_time))

            #if (step % 100 == 0):
                #print('Loss at step {}: {}'.format(step, l))
                #print('Training accuracy: {:.1f}'.format(accuracy(predictions,
                                                                  #train_labels[:train_subset, :])))
                # Calling .eval() on valid_prediction is basically like calling run(), but
                # just to get that one numpy array. Note that it recomputes all its graph
                # dependencies.

                # You don't have to do .eval above because we already ran the session for the
                # train_prediction
                #print('Validation accuracy: {:.1f}'.format(accuracy(valid_prediction.eval(),
                                                                    #valid_labels)))
        #print('Test accuracy: {:.1f}'.format(accuracy(test_prediction.eval(), test_labels)))
        #print(regularizer)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've tested logistic regression implemented in tensorflow with three ways of session.run:

all together

res1, res2, res3 = sess.run([op1, op2, op3])

separately

res1 = sess.run(op1)

res2 = sess.run(op2)

res3 = sess.run(op3)

with dependencies

with tf.control_dependencies([op1]):

op2_after = tf.identity(op1)

op3_after = tf.identity(op1)

res1,res2,res3 = session.run([op1, op2_after, op3_after])

set batch size as 10000, the result is:

1: 0.05+ secs < 2: 0.11+ secs < 3: 0.25+ secs

The main difference between 1 and 3 is only one mini-batch. It may not worth it to use 3 instead of 1.

Here is the test code (it is an LR example written by someone else...).

Here is the data

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Jun  2 13:38:14 2017

@author: inse7en
"""

from __future__ import print_function
import numpy as np
import tensorflow as tf
from six.moves import cPickle as pickle
import time

pickle_file = '/Users/inse7en/Downloads/notMNIST.pickle'
with open(pickle_file, 'rb') as f:
  save = pickle.load(f)
  train_dataset = save['train_dataset']
  train_labels = save['train_labels']
  valid_dataset = save['valid_dataset']
  valid_labels = save['valid_labels']
  test_dataset = save['test_dataset']
  test_labels = save['test_labels']
  del save  # hint to help gc free up memory
  print('Training set', train_dataset.shape, train_labels.shape)
  print('Validation set', valid_dataset.shape, valid_labels.shape)
  print('Test set', test_dataset.shape, test_labels.shape)

image_size = 28
num_labels = 10

def reformat(dataset, labels):
  dataset = dataset.reshape((-1, image_size * image_size)).astype(np.float32)
  # Map 2 to [0.0, 1.0, 0.0 ...], 3 to [0.0, 0.0, 1.0 ...]
  labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32)
  return dataset, labels
train_dataset, train_labels = reformat(train_dataset, train_labels)
valid_dataset, valid_labels = reformat(valid_dataset, valid_labels)
test_dataset, test_labels = reformat(test_dataset, test_labels)
print('Training set', train_dataset.shape, train_labels.shape)
print('Validation set', valid_dataset.shape, valid_labels.shape)
print('Test set', test_dataset.shape, test_labels.shape)

# This is to expedite the process
train_subset = 10000
# This is a good beta value to start with
beta = 0.01

graph = tf.Graph()
with graph.as_default():
    # Input data.
    # They're all constants.
    tf_train_dataset = tf.constant(train_dataset[:train_subset, :])
    tf_train_labels = tf.constant(train_labels[:train_subset])
    tf_valid_dataset = tf.constant(valid_dataset)
    tf_test_dataset = tf.constant(test_dataset)

    # Variables
    # They are variables we want to update and optimize.
    weights = tf.Variable(tf.truncated_normal([image_size * image_size, num_labels]))
    biases = tf.Variable(tf.zeros([num_labels]))

    # Training computation.
    logits = tf.matmul(tf_train_dataset, weights) + biases
    # Original loss function
    loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels))
    # Loss function using L2 Regularization
    regularizer = tf.nn.l2_loss(weights)
    loss = tf.reduce_mean(loss + beta * regularizer)

    # Optimizer.
    optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss)

    # Predictions for the training, validation, and test data.
    train_prediction = tf.nn.softmax(logits)
    valid_prediction = tf.nn.softmax(tf.matmul(tf_valid_dataset, weights) + biases)
    test_prediction = tf.nn.softmax(tf.matmul(tf_test_dataset, weights) + biases)

    num_steps = 50

    def accuracy(predictions, labels):
        return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))
                / predictions.shape[0])

    with tf.Session(graph=graph) as session:
        # This is a one-time operation which ensures the parameters get initialized as
        # we described in the graph: random weights for the matrix, zeros for the
        # biases.
        tf.initialize_all_variables().run()
        print('Initialized')
        for step in range(num_steps):
            # Run the computations. We tell .run() that we want to run the optimizer,
            # and get the loss value and the training predictions returned as numpy
            # arrays.
            #_, l, predictions = session.run([optimizer, loss, train_prediction])

            start_time = time.time()
            with tf.control_dependencies([optimizer]):
                loss_after_optimizer = tf.identity(loss)
                predictions_after = tf.identity(train_prediction)
                regularizers_after = tf.identity(regularizer)

            _, l, predictions,regularizers = session.run([optimizer, loss_after_optimizer, predictions_after, regularizers_after])

            print("--- with dependencies: %s seconds ---" % (time.time() - start_time))
            #start_time = time.time()
            #opt = session.run(optimizer)
            #l = session.run(loss)
            #predictions = session.run(train_prediction)
            #regularizers = session.run(regularizer)

            #print("--- run separately: %s seconds ---" % (time.time() - start_time))

            #start_time = time.time()
            #_, l, predictions,regularizers = session.run([optimizer, loss, train_prediction, regularizer])

            #print("--- all together: %s seconds ---" % (time.time() - start_time))

            #if (step % 100 == 0):
                #print('Loss at step {}: {}'.format(step, l))
                #print('Training accuracy: {:.1f}'.format(accuracy(predictions,
                                                                  #train_labels[:train_subset, :])))
                # Calling .eval() on valid_prediction is basically like calling run(), but
                # just to get that one numpy array. Note that it recomputes all its graph
                # dependencies.

                # You don't have to do .eval above because we already ran the session for the
                # train_prediction
                #print('Validation accuracy: {:.1f}'.format(accuracy(valid_prediction.eval(),
                                                                    #valid_labels)))
        #print('Test accuracy: {:.1f}'.format(accuracy(test_prediction.eval(), test_labels)))
        #print(regularizer)


问:
What is the function to get the system date and current date in Dynamics AX?
What are the function calls to get the System Date and Current Date using X++ in Microsoft Dynamics AX?</p>

答:
Use the static methods within class DateTimeUtil:

getSystemDateTime

utcNow

Both return UTC date and times, but will be converted to local time on display.

See Best Practice.


问:
dealing with 'undefined' properties in Meteor.method
I've created a function in my Meteor application, which is set to 'enrich' the data contained within a meteor collection. The function is meant to iterate over a collection, utilize the fullcontact API to pull additional data on all the client entries maintained within the db (i.e. LinkedIn Bio; no. of employees, etc.).

The issue lies around the fact that not all datapoint are available for all elements within the collection (e.g. a client may not have a LinkedIn profile). The function works for the initial couple of elements but eventually fails throwing a TypeError: Cannot read property '2' of undefined, because the data variable does not contain a LinkedIn Profile bio for the company (for this particular example).

What do you suggest as a workout? Any ideas? Your help would be much appreciated - I have been at this for a couple of hours.

```<code>Meteor.methods({
  enrichment() {
    var fullcontact = new FullContact(Meteor.settings.fullContact);
    for (var i = 1; i < customerDb.find({ company: "Qualify" }).count(); i++) {
      var url = customerDb.findOne( { company: "Qualify", 'item.clientId': i.toString() } )['item']['contact_website'];
      var data = fullcontact.company.domain(url);
      if ( data['status'] == 200 ) {
        customerDb.update ({
          company: "Qualify", 'item.clientId': i.toString()
        }, {
          $push: {
            bio: data['socialProfiles'][2]['bio'],
            keywords: data['organization']['keywords'],
            employees: data['organization']['approxEmployees'],
            domesticTrafficRank: data['traffic']['topCountryRanking'][0],
            globalTrafficRank: data['traffic']['ranking'][0]
          }
        });
      } else {
        console.log('Data could not be found on the company')
      }
    }
  }
});
</code>```

答:
Building on @chazsolo's suggestion, you can deal with potentially missing data and keys with javascript ANDs and ORs. This is a common defensive coding pattern.

Here each item will be replaced with an empty string if any of the parent keys are missing or the array element is missing. You can simplify this if you know more about what can be missing. Also you may want numbers instead of strings in some of these cases.

```<code>if ( data['status'] == 200 ) {
  const bio = data['socialProfiles'] && data['socialProfiles'][2] && data['socialProfiles'][2]['bio'] || '';
  const keywords = data['organization'] && data['organization']['keywords'] || '';
  const employees = data['organization'] && data['organization']['approxEmployees'] || '',
  const domesticTrafficRank = data['traffic'] && data['traffic']['topCountryRanking'] && data['traffic']['topCountryRanking'][0] || '',
  const globalTrafficRank = data['traffic'] && data['traffic']['ranking'] && data['traffic']['ranking][0] || '';

  customerDb.update (
    { company: "Qualify", 'item.clientId': i.toString() },
    { $push: { bio, keywords, employees, domesticTrafficRank, globalTrafficRank }}
  });
</code>```

Body:
I've created a function in my Meteor application, which is set to 'enrich' the data contained within a meteor collection. The function is meant to iterate over a collection, utilize the fullcontact API to pull additional data on all the client entries maintained within the db (i.e. LinkedIn Bio; no. of employees, etc.).

The issue lies around the fact that not all datapoint are available for all elements within the collection (e.g. a client may not have a LinkedIn profile). The function works for the initial couple of elements but eventually fails throwing a TypeError: Cannot read property '2' of undefined, because the data variable does not contain a LinkedIn Profile bio for the company (for this particular example).

What do you suggest as a workout? Any ideas? Your help would be much appreciated - I have been at this for a couple of hours.

Meteor.methods({
  enrichment() {
    var fullcontact = new FullContact(Meteor.settings.fullContact);
    for (var i = 1; i < customerDb.find({ company: "Qualify" }).count(); i++) {
      var url = customerDb.findOne( { company: "Qualify", 'item.clientId': i.toString() } )['item']['contact_website'];
      var data = fullcontact.company.domain(url);
      if ( data['status'] == 200 ) {
        customerDb.update ({
          company: "Qualify", 'item.clientId': i.toString()
        }, {
          $push: {
            bio: data['socialProfiles'][2]['bio'],
            keywords: data['organization']['keywords'],
            employees: data['organization']['approxEmployees'],
            domesticTrafficRank: data['traffic']['topCountryRanking'][0],
            globalTrafficRank: data['traffic']['ranking'][0]
          }
        });
      } else {
        console.log('Data could not be found on the company')
      }
    }
  }
});

Body:
Building on @chazsolo's suggestion, you can deal with potentially missing data and keys with javascript ANDs and ORs. This is a common defensive coding pattern.

Here each item will be replaced with an empty string if any of the parent keys are missing or the array element is missing. You can simplify this if you know more about what can be missing. Also you may want numbers instead of strings in some of these cases.

if ( data['status'] == 200 ) {
  const bio = data['socialProfiles'] && data['socialProfiles'][2] && data['socialProfiles'][2]['bio'] || '';
  const keywords = data['organization'] && data['organization']['keywords'] || '';
  const employees = data['organization'] && data['organization']['approxEmployees'] || '',
  const domesticTrafficRank = data['traffic'] && data['traffic']['topCountryRanking'] && data['traffic']['topCountryRanking'][0] || '',
  const globalTrafficRank = data['traffic'] && data['traffic']['ranking'] && data['traffic']['ranking][0] || '';

  customerDb.update (
    { company: "Qualify", 'item.clientId': i.toString() },
    { $push: { bio, keywords, employees, domesticTrafficRank, globalTrafficRank }}
  });


问:
Add advanced search data
can not search using two different fields, name and gender, can you add an advanced search with more imput?
Place the files and codes to help you better understand where to add advanced search imput

getdata.php

<?php

if(isset($_GET['page'])){
    //Include pagination class file
    include('Pagination.php');

    //Include database configuration file
    include('dbConfig.php');

    $start = !empty($_GET['page'])?$_GET['page']:0;
    $limit = 25;
     //set conditions for search
    $whereSQL = $orderSQL = '';
    $keywords = $_GET['keywords'];
    $keyname = $_GET['keyname'];
    $sortBy = $_GET['sortBy'];

    if(!empty($keyname)){
        $whereSQL = "WHERE name LIKE '%".$keyname."%'";
    }
     if(!empty($keywords)){
        $whereSQ = "WHERE member_group_id LIKE '".$keywords."'";
    }

    if(!empty($sortBy)){
        $orderSQL = " ORDER BY name ".$sortBy;
    }else{
        $orderSQL = " ORDER BY name DESC ";
    }

    //get number of rows
    $queryNum = $db->query("SELECT COUNT(*) as name FROM ILFREE_core_members ".$whereSQL.$whereSQ.$orderSQL);
    $resultNum = $queryNum->fetch_assoc();
    $rowCount = $resultNum['name'];

    //initialize pagination class
    $pagConfig = array(
        'currentPage' => $start,
        'totalRows' => $rowCount,
        'perPage' => $limit,
        'link_func' => 'searchFilter'
    );
    $pagination =  new Pagination($pagConfig);

    //get rows
    $query = $db->query("SELECT * FROM ILFREE_core_members $whereSQL $whereSQ $orderSQL LIMIT $start,$limit");

    if($query->num_rows > 0){ ?>

        <?php
while($row = $query->fetch_assoc()){
$GroupID = $row["member_group_id"];
$IDgroup = array('29','77','62','83','46','43','73','58','68','2','78','63','82','45','42','71','52','67','27','76','60','81','44','41','70','56','65');
$GETID = $row['member_id'];
$Name = $row["name"];
$photo = $row["pp_main_photo"];
$bannato = '7';

?>

<?php
// name

echo '
' . $Name . '
';

// foto
if(empty($photo)) { if(in_array($GroupID, $IDgroup)) {
echo ''; }
elseif ($bannato == $GroupID) {
echo ''; }
else {
echo ''; } }
else{
echo '';
}

?>

        <?php } ?>

        <?php echo $pagination->createLinks(); ?>
<?php } } ?>```
</div>
</div>
</p>

<p>index.php</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><!DOCTYPE HTML>
<html lang="en">
<head>

</head>
<body>

<div class="GET-search-panel">
    <input type="text" id="keyname" placeholder="name" onkeyup="searchFilter()"/>

    <input type="text" id="keywords" placeholder="Type keywords to filter GETs" onkeyup="searchFilter()"/>
    <select id="sortBy" onchange="searchFilter()">
        <option value="">Sort By</option>
        <option value="asc">Ascending</option>
        <option value="desc">Descending</option>
    </select>
</div>
<div class="GET-wrapper">
    <div id="GETs_content">
    <?php
    //Include pagination class file
    include('Pagination.php');

    //Include database configuration file
    include('dbConfig.php');

    $limit = 25;

    //get number of rows
    $queryNum = $db->query("SELECT COUNT(*) as ilfreexxx FROM ILFREE_core_members");
    $resultNum = $queryNum->fetch_assoc();
    $rowCount = $resultNum['ilfreexxx'];

    //initialize pagination class
    $pagConfig = array(
        'totalRows' => $rowCount,
        'perPage' => $limit,
        'link_func' => 'searchFilter'
    );
    $pagination =  new Pagination($pagConfig);

    //get rows
    $query = $db->query("SELECT * FROM ILFREE_core_members ORDER BY member_id DESC LIMIT $limit");

    if($query->num_rows > 0){ ?>
        <div class="GETs_list">

<?php

while($row = $query->fetch_assoc()){
$GroupID = $row["member_group_id"];
$IDgroup = array('29','77','62','83','46','43','73','58','68','2','78','63','82','45','42','71','52','67','27','76','60','81','44','41','70','56','65');
$GETID = $row['member_id'];
$Name = $row["name"];
$photo = $row["pp_main_photo"];
$bannato = '7';

?>
<div class="list_item">
<?php
// name

echo '<h2>' . $Name . '</h2>';

// foto
if(empty($photo)) { if(in_array($GroupID, $IDgroup)) {
echo '<img src="http://www.ilfree.it/uploads/file/search_femmina.png"/>'; }
elseif ($bannato == $GroupID) {
echo '<img src="http://www.ilfree.it/uploads/file/ban.png"/>'; }
else {
echo '<img src="http://www.ilfree.it/uploads/file/search_maschio.png"/>'; } }
else{
echo '<img src="http://www.ilfree.it/uploads/profile_photos/' . $photo . '"/>';
}

?>

            </div>
        <?php } ?>
        </div>   </div>
        <?php echo $pagination->createLinks(); ?>
    <?php } ?>

</div>

<style>

body {
    background: #e7e7e7 url(http://carpanelli-art.com/wp-content/themes/pacifico/images/bgs/bg_i_4.jpg) repeat;
    font-family: "FS Albert Light", "Myriad Pro", "Helvetica Neue", Helvetica, Arial, sans-serif;
}
.GET-wrapper {
    padding: 10px;
    background: #fdfdfd;
    width: 70%;
    margin: 0 auto;
    border-radius: 6px;
}
.list_item {
    position: relative;
    float: left;
    border: 4px solid #f1f1f1;
    margin: 4px;
}
.list_item:hover {
       border: 4px solid #d6e9ff;

}
.list_item a {
    text-decoration: none;
    color: #b1b1b1;
   font-size: 10px;
    text-align: center;

}
.list_item a:hover {
       color: #8a8a8a;
}
.list_item img {
    width: 200px;
    height: 220px;
    display: list-item;
}

.list_item h2 {
    position: relative;
    margin: 0;
    background: #f4f5f9;
    border-bottom: 1px solid #f1f1f1;
    color: #3f4752;
    text-shadow: -1px -1px 0 #fff;
}
 #GETs_content {
    width: 70%;
        margin: 0 auto;
}
.GETs_list {display: inline-block;}
 div.pagination {
    font-family: "Lucida Sans", Geneva, Verdana, sans-serif;
    padding:20px;
    margin:7px;
    display: inline-block;
}
div.pagination a {
    margin: 2px;
    padding: 0.5em 0.64em 0.43em 0.64em;
    background-color: #ee4e4e;
    text-decoration: none;
    color: #fff;
}
div.pagination a:hover, div.pagination a:active {
    padding: 0.5em 0.64em 0.43em 0.64em;
    margin: 2px;
    background-color: #de1818;
    color: #fff;
}
div.pagination span.current {
    padding: 0.5em 0.64em 0.43em 0.64em;
    margin: 2px;
    background-color: #f6efcc;
    color: #6d643c;
}
div.pagination span.disabled {
    display:none;
}
</style>
            <!-- JavaScript -->
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script>
function searchFilter(page_num) {
    page_num = page_num?page_num:0;
    var keywords = $('#keywords').val();
    var keyname = $('#keyname').val();
    var sortBy = $('#sortBy').val();
    $.ajax({
        type: 'GET',
        url: 'getData.php',
        data:'page='+page_num+'&keyname='+keyname+'&keywords='+keywords+'&sortBy='+sortBy,
        beforeSend: function () {
            $('.loading-overlay').show();
        },
        success: function (html) {
            $('#GETs_content').html(html);
            $('.loading-overlay').fadeOut("slow");
        }
    });
}
</script>
</body>
</html></code>```

I look anxiously for your help

答:
You could build an array with all the conditional clauses, and then format that array into an appropriate SQL where clause.  It needs to be mentioned however that you are not escaping your input to SQL and are susceptible to SQL Injection attacks.  Here's some sample code for a very simple query builder.</p>

```<code>$start = !empty($_GET['page'])?$_GET['page']:0;
$limit = 25;

# Build array of orderings
$orderQueries = [];
if (isset($_GET['sortBy']) && !empty($_GET['sortBy'])) {
    $sortBy = $_GET['sortBy'];
    $orderQueries[] = "name $sortBy";
} else {
    $orderQueries[] = "name DESC";
}

# Build array of conditionals
$whereQueries = [];
if (isset($_GET['name']) && !empty($_GET['name'])) {
    $name = $_GET['name'];
    $whereQueries[] = "name LIKE '%$name%'";
}
if (isset($_GET['age']) && !empty($_GET['age'])) {
    $age = $_GET['age'];
    $whereQueries[] = "age = $age";
}
if (isset($_GET['keywords']) && !empty($_GET['keywords'])) {
    $keywords = $_GET['keywords'];
    $whereQueries[] = "member_group_id LIKE '$keywords'";
}

# Construct "WHERE ..." part of query
$whereSQL = 'WHERE ';
$firstLoop = true;
foreach ($whereQueries as $q) {
    if (!$firstLoop) {  # Avoid prepending "AND" on the first loop
        $firstLoop = false;
        $q = " AND $q";
    }
    $whereSQL .= $q;
}

# Construct "ORDER BY ..." part of query
$orderSQL = 'ORDER BY ';
$firstLoop = true;
foreach ($orderQueries as $q) {
    if (!$firstLoop) {
        $firstLoop = false;
        $q = ", $q";  # Avoid prepending "," on the first loop
    }
    $orderSQL .= " $q"
}
$query = $db->query("SELECT * FROM ILFREE_core_members $whereSQL  $orderSQL LIMIT $start,$limit");
</code>```

Title: Add advanced search data

Body:
can not search using two different fields, name and gender, can you add an advanced search with more imput?
Place the files and codes to help you better understand where to add advanced search imput

getdata.php

<?php

if(isset($_GET['page'])){
    //Include pagination class file
    include('Pagination.php');

    //Include database configuration file
    include('dbConfig.php');

    $start = !empty($_GET['page'])?$_GET['page']:0;
    $limit = 25;
     //set conditions for search
    $whereSQL = $orderSQL = '';
    $keywords = $_GET['keywords'];
    $keyname = $_GET['keyname'];
    $sortBy = $_GET['sortBy'];

    if(!empty($keyname)){
        $whereSQL = "WHERE name LIKE '%".$keyname."%'";
    }
     if(!empty($keywords)){
        $whereSQ = "WHERE member_group_id LIKE '".$keywords."'";
    }

    if(!empty($sortBy)){
        $orderSQL = " ORDER BY name ".$sortBy;
    }else{
        $orderSQL = " ORDER BY name DESC ";
    }

    //get number of rows
    $queryNum = $db->query("SELECT COUNT(*) as name FROM ILFREE_core_members ".$whereSQL.$whereSQ.$orderSQL);
    $resultNum = $queryNum->fetch_assoc();
    $rowCount = $resultNum['name'];

    //initialize pagination class
    $pagConfig = array(
        'currentPage' => $start,
        'totalRows' => $rowCount,
        'perPage' => $limit,
        'link_func' => 'searchFilter'
    );
    $pagination =  new Pagination($pagConfig);

    //get rows
    $query = $db->query("SELECT * FROM ILFREE_core_members $whereSQL $whereSQ $orderSQL LIMIT $start,$limit");

    if($query->num_rows > 0){ ?>

        <?php
while($row = $query->fetch_assoc()){
$GroupID = $row["member_group_id"];
$IDgroup = array('29','77','62','83','46','43','73','58','68','2','78','63','82','45','42','71','52','67','27','76','60','81','44','41','70','56','65');
$GETID = $row['member_id'];
$Name = $row["name"];
$photo = $row["pp_main_photo"];
$bannato = '7';

?>

<?php
// name

echo '
' . $Name . '
';

// foto
if(empty($photo)) { if(in_array($GroupID, $IDgroup)) {
echo ''; }
elseif ($bannato == $GroupID) {
echo ''; }
else {
echo ''; } }
else{
echo '';
}

?>

        <?php } ?>

        <?php echo $pagination->createLinks(); ?>
<?php } } ?>

index.php

<!DOCTYPE HTML>

    <input type="text" id="keyname" placeholder="name" onkeyup="searchFilter()"/>

    <input type="text" id="keywords" placeholder="Type keywords to filter GETs" onkeyup="searchFilter()"/>
    <select id="sortBy" onchange="searchFilter()">
        <option value="">Sort By</option>
        <option value="asc">Ascending</option>
        <option value="desc">Descending</option>
    </select>

    <?php
    //Include pagination class file
    include('Pagination.php');

    //Include database configuration file
    include('dbConfig.php');

    $limit = 25;

    //get number of rows
    $queryNum = $db->query("SELECT COUNT(*) as ilfreexxx FROM ILFREE_core_members");
    $resultNum = $queryNum->fetch_assoc();
    $rowCount = $resultNum['ilfreexxx'];

    //initialize pagination class
    $pagConfig = array(
        'totalRows' => $rowCount,
        'perPage' => $limit,
        'link_func' => 'searchFilter'
    );
    $pagination =  new Pagination($pagConfig);

    //get rows
    $query = $db->query("SELECT * FROM ILFREE_core_members ORDER BY member_id DESC LIMIT $limit");

    if($query->num_rows > 0){ ?>

<?php

while($row = $query->fetch_assoc()){
$GroupID = $row["member_group_id"];
$IDgroup = array('29','77','62','83','46','43','73','58','68','2','78','63','82','45','42','71','52','67','27','76','60','81','44','41','70','56','65');
$GETID = $row['member_id'];
$Name = $row["name"];
$photo = $row["pp_main_photo"];
$bannato = '7';

?>

<?php
// name

echo '
' . $Name . '
';

// foto
if(empty($photo)) { if(in_array($GroupID, $IDgroup)) {
echo ''; }
elseif ($bannato == $GroupID) {
echo ''; }
else {
echo ''; } }
else{
echo '';
}

?>

        <?php } ?>

        <?php echo $pagination->createLinks(); ?>
    <?php } ?>

I look anxiously for your help

Body:
You could build an array with all the conditional clauses, and then format that array into an appropriate SQL where clause.  It needs to be mentioned however that you are not escaping your input to SQL and are susceptible to SQL Injection attacks.  Here's some sample code for a very simple query builder.

$start = !empty($_GET['page'])?$_GET['page']:0;
$limit = 25;

# Build array of orderings
$orderQueries = [];
if (isset($_GET['sortBy']) && !empty($_GET['sortBy'])) {
    $sortBy = $_GET['sortBy'];
    $orderQueries[] = "name $sortBy";
} else {
    $orderQueries[] = "name DESC";
}

# Build array of conditionals
$whereQueries = [];
if (isset($_GET['name']) && !empty($_GET['name'])) {
    $name = $_GET['name'];
    $whereQueries[] = "name LIKE '%$name%'";
}
if (isset($_GET['age']) && !empty($_GET['age'])) {
    $age = $_GET['age'];
    $whereQueries[] = "age = $age";
}
if (isset($_GET['keywords']) && !empty($_GET['keywords'])) {
    $keywords = $_GET['keywords'];
    $whereQueries[] = "member_group_id LIKE '$keywords'";
}

# Construct "WHERE ..." part of query
$whereSQL = 'WHERE ';
$firstLoop = true;
foreach ($whereQueries as $q) {
    if (!$firstLoop) {  # Avoid prepending "AND" on the first loop
        $firstLoop = false;
        $q = " AND $q";
    }
    $whereSQL .= $q;
}

# Construct "ORDER BY ..." part of query
$orderSQL = 'ORDER BY ';
$firstLoop = true;
foreach ($orderQueries as $q) {
    if (!$firstLoop) {
        $firstLoop = false;
        $q = ", $q";  # Avoid prepending "," on the first loop
    }
    $orderSQL .= " $q"
}
$query = $db->query("SELECT * FROM ILFREE_core_members $whereSQL  $orderSQL LIMIT $start,$limit");


问:
The glyphicons height not matching with select2 dropdown
When i add select2 dropdown the glyphicons icon height was not same

This is the html code

```<code> <form class="well form-horizontal" action=" " method="post" id="user_edit">

  <div class="form-group">
        <label class="col-md-1 nopadding control-label"></label>
        <div class="col-md-8 nopadding inputGroupContainer">
            <div class="input-group field-width">

             <span class="input-group-addon" >
              <i class="fa fa-venus-mars" ></i></span>
               <select name="gender" id="gender" class="gender form-control
     js-example-basic-single">
                    <option value="">Not Telling</option>
                    <option value="m">Male</option>
                    <option value="f">Female</option>
                </select>

            </div>
        </div>
    </div>
    </form>
</code>```

The js file

```<code>$(document).ready(function() {
    $(".js-example-basic-single").select2();
});
</code>```

The css file i add for select2

```<code>.glyphicon{
color:#007bcc;
 }
 .select2-selection__rendered{
 line-height: 32px!important;
 }
 [class^='select2'] {
 border-radius: 0px !important;
 }

 .select2-selection__arrow{
  height: 34px;!important;
  }
 .select2-container--default .select2-selection--single{
 background-color: #eeeeee !important;
 height: 34px!important;
 font-size: 15px;!important;
  margin-top: 0.5px!important;
 margin-left: -1px!important;

 }
</code>```

When i zoom the page more than 100% the height same.

答:
Remove margin-top: 0.5px!important; from .select2-container--default .select2-selection--single

$(document).ready(function() {
    $(".js-example-basic-single").select2();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.glyphicon{
color:#007bcc;
 }
 .select2-selection__rendered{
 line-height: 32px!important;
 }
 [class^='select2'] {
 border-radius: 0px !important;
 }

 .select2-selection__arrow{
  height: 34px;!important;
  }
 .select2-container--default .select2-selection--single{
 background-color: #eeeeee !important;
 height: 34px!important;
 font-size: 15px;!important;

 margin-left: -1px!important;

 }</code>```

    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css">
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
     <form class="well form-horizontal" action=" " method="post" id="user_edit">

               <select name="gender" id="gender" class="gender form-control
     js-example-basic-single">
                    <option value="">Not Telling</option>
                    <option value="m">Male</option>
                    <option value="f">Female</option>
                </select>

    </form>```

Body:
When i add select2 dropdown the glyphicons icon height was not same

This is the html code

 <form class="well form-horizontal" action=" " method="post" id="user_edit">

               <select name="gender" id="gender" class="gender form-control
     js-example-basic-single">
                    <option value="">Not Telling</option>
                    <option value="m">Male</option>
                    <option value="f">Female</option>
                </select>

    </form>

The js file

$(document).ready(function() {
    $(".js-example-basic-single").select2();
});

The css file i add for select2

.glyphicon{
color:#007bcc;
 }
 .select2-selection__rendered{
 line-height: 32px!important;
 }
 [class^='select2'] {
 border-radius: 0px !important;
 }

 .select2-selection__arrow{
  height: 34px;!important;
  }
 .select2-container--default .select2-selection--single{
 background-color: #eeeeee !important;
 height: 34px!important;
 font-size: 15px;!important;
  margin-top: 0.5px!important;
 margin-left: -1px!important;

 }

When i zoom the page more than 100% the height same.

Body:
Remove margin-top: 0.5px!important; from .select2-container--default .select2-selection--single

$(document).ready(function() {
    $(".js-example-basic-single").select2();
});

.glyphicon{
color:#007bcc;
 }
 .select2-selection__rendered{
 line-height: 32px!important;
 }
 [class^='select2'] {
 border-radius: 0px !important;
 }

 .select2-selection__arrow{
  height: 34px;!important;
  }
 .select2-container--default .select2-selection--single{
 background-color: #eeeeee !important;
 height: 34px!important;
 font-size: 15px;!important;

 margin-left: -1px!important;

 }

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css">
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
     <form class="well form-horizontal" action=" " method="post" id="user_edit">
  <div class="form-group">
        <label class="col-md-1 nopadding control-label"></label>
        <div class="col-md-8 nopadding inputGroupContainer">
            <div class="input-group field-width">
             <span class="input-group-addon" >
              <i class="fa fa-venus-mars" ></i></span>
               <select name="gender" id="gender" class="gender form-control
     js-example-basic-single">
                    <option value="">Not Telling</option>
                    <option value="m">Male</option>
                    <option value="f">Female</option>
                </select>
            </div>
        </div>
    </div>
    </form>


答:
Pandas doesn't have the ability to store NaN values for integers. Strictly speaking, you could have a column with mixed data types, but this can be computationally inefficient. So if you insist, you can do</p>

```<code>df['a'] = df['a'].astype('O')
df.loc[df['a'].notnull(), 'a'] = df.loc[df['a'].notnull(), 'a'].astype(int)
</code>```

Title: Error:cannot convert float NaN to integer in pandas

Body:
Pandas doesn't have the ability to store NaN values for integers. Strictly speaking, you could have a column with mixed data types, but this can be computationally inefficient. So if you insist, you can do

df['a'] = df['a'].astype('O')
df.loc[df['a'].notnull(), 'a'] = df.loc[df['a'].notnull(), 'a'].astype(int)


问:
How do I calculate the number of permutations in base 3 combinatorics?
I've never been much for math and I'm hoping that someone can help me out with the following.

I have 5 boxes:

```<code> 1   2   3   4   5
[ ] [ ] [ ] [ ] [ ]
</code>```

The boxes can either be white, gray, or black (or think of it as 0, 1, 2)

How many possible states can the box set be in?

What is the pseudocode (or in any language) to generate all the possible outcomes??

ie...

```<code>00000
00001
00011
00111
</code>```

etc, etc...

I really appreciate any help anyone can give me with this.

答:
Your problem needs nothing more than the rule of product in combinatorics.

You can choose the state of the first box in 3 ways, and the state of the second box in 3 ways, and ... and the state of the 5th box in 3 ways. The number of ways in which you can set the state of all the boxes is the product of all the five (equal) numbers of ways, i.e. 3x3x3x3x3 = 35.

Similar question: how many numbers can you form with 5 digits in the decimal system, counting the leading zeros? That is, how many numbers are there from 00000 to 99999? You can choose the first digit in 10 ways (0...9), and so on and so on, and the answer is 10x10x10x10x10 = 100000, as you already know.

OwnerDisplayName: Michael

Body:
I've never been much for math and I'm hoping that someone can help me out with the following.

I have 5 boxes:

 1   2   3   4   5
[ ] [ ] [ ] [ ] [ ]

The boxes can either be white, gray, or black (or think of it as 0, 1, 2)

How many possible states can the box set be in?

What is the pseudocode (or in any language) to generate all the possible outcomes??

ie...

00000
00001
00011
00111

etc, etc...

I really appreciate any help anyone can give me with this.

LastEditorDisplayName: Jimmy

OwnerDisplayName: Federico Ramponi


问:
How do I replace the default text on an InputField in Unity?
When I create a new InputField on a screen and give it some default text, the text field returns nothing until I edit it. Looking at the debugger, the text field is actually "".

Once I edit the field at play time, it now equals what I input. But when I come back around to activate that screen again and I want to reset it, setting each of these fields to "" again does not show the original default text, it blanks them out. How do I reset the original text? Where does it live?

答:
Input fields have 2 children attached:
Placeholder with a Text component attached which says: Enter text...
and a Text with a Text component which says nothing.

If you change the Text in the Text child you will have a default value, but this will show in place of the placeholder text.

It can be done in code if you want the placeholder to be shown when there.

Example:

```<code>public InputField inputField; //this is the input field that you are typing into.

public void ButtonPress()
{
    //when this button is pressed it will set the value or a default
    if(inputField.Text == "")
    {
        //insert default information
    }
    else
    {
        //enter the rest of the function here
    }
}
</code>```

I hope this helps.

Body:
Input fields have 2 children attached:
Placeholder with a Text component attached which says: Enter text...
and a Text with a Text component which says nothing.

If you change the Text in the Text child you will have a default value, but this will show in place of the placeholder text.

It can be done in code if you want the placeholder to be shown when there.

Example:

public InputField inputField; //this is the input field that you are typing into.

public void ButtonPress()
{
    //when this button is pressed it will set the value or a default
    if(inputField.Text == "")
    {
        //insert default information
    }
    else
    {
        //enter the rest of the function here
    }
}

I hope this helps.


问:
Page readable by file_get_contents but not cURL
I'm creating an API endpoint in PHP, and have a page that outputs JSON, let's call it example.com/stats. When a user tries to return the data, it's only successful when they use file_get_contents(), when users try to reach it using cURL they receive a NULL response. How should I be serving JSON data in PHP so that it's compatible with both file_get_contents and curl?

More info below.

SOURCE for /stats

```<code>header('Content-type: application/json');
echo '{"status":"error", "message":"invalid operation"}';
</code>```

When I try to read this page from another server via file_get_contents() everything works fine.

```<code>function fgc($receive_url){
$fgc = json_decode(file_get_contents($receive_url), true);
return $fgc;
}

$out = fgc("https://example.com/stats");
var_dump($out);

//returns: array(2) { ["status"]=> string(5) "error" ["message"]=> string(17) "invalid operation" }
</code>```

When I try doing the same thing but with cURL I get NULL.

```<code>function curlit($receive_url){
$ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, $receive_url);
$ccc = curl_exec($ch);
$json = json_decode($ccc, true);
return $json;
}

$out = curlit("https://example.com/stats");
var_dump($out);
</code>```

Please note other sites that display JSON work fine with my cURL function, it's specifically the data I'm serving from example.com/stats that fails when using cURL. I thought using the header application/json would be enough to allow this data to be reachable via cURL. Any ideas what could be wrong on the serving side? Why would file get contents work but not curl? Maybe cURL is displaying a result before the page is done loading? I tried removing the application/json header but that made no difference.

答:
Maybe your server has disabled cURL, try to check it with function_exists:

```<code>var_dump(function_exists('curl_version'));
</code>```

Body:
I'm creating an API endpoint in PHP, and have a page that outputs JSON, let's call it example.com/stats. When a user tries to return the data, it's only successful when they use file_get_contents(), when users try to reach it using cURL they receive a NULL response. How should I be serving JSON data in PHP so that it's compatible with both file_get_contents and curl?

More info below.

SOURCE for /stats

header('Content-type: application/json');
echo '{"status":"error", "message":"invalid operation"}';

When I try to read this page from another server via file_get_contents() everything works fine.

function fgc($receive_url){
$fgc = json_decode(file_get_contents($receive_url), true);
return $fgc;
}

$out = fgc("https://example.com/stats");
var_dump($out);

//returns: array(2) { ["status"]=> string(5) "error" ["message"]=> string(17) "invalid operation" }

When I try doing the same thing but with cURL I get NULL.

function curlit($receive_url){
$ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, $receive_url);
$ccc = curl_exec($ch);
$json = json_decode($ccc, true);
return $json;
}

$out = curlit("https://example.com/stats");
var_dump($out);

Please note other sites that display JSON work fine with my cURL function, it's specifically the data I'm serving from example.com/stats that fails when using cURL. I thought using the header application/json would be enough to allow this data to be reachable via cURL. Any ideas what could be wrong on the serving side? Why would file get contents work but not curl? Maybe cURL is displaying a result before the page is done loading? I tried removing the application/json header but that made no difference.

Body:
Maybe your server has disabled cURL, try to check it with function_exists:

var_dump(function_exists('curl_version'));