问:
PHP : Retrieve multiple data from mysql, an esasier way?
I have a php code about retrieving multiple lines from mysql database that works very well. But I find it too heavy. The following is only one extract, as i use the same method for each single word from the database. Do you have better solution? Can I make just one statement for all the page, and just put the requested ID at the correct place? Thank you for any help.

```<code>  <?php
    $dbname = 'xxxx';
    $dbuser = 'xxxx';
    $dbpass = 'xxxx';
    $dbhost = 'localhost';
    $conn = new mysqli($dbhost,$dbuser,$dbpass,$dbname);
    if ($conn->connect_error)
    {
    echo "connection error" ;
    }
    $sql = "SELECT * FROM test WHERE id='1'";
    $result = $conn->query($sql);
    ?>
    <?php
    if ($result->num_rows > 0) {
    while($data = $result-   >fetch_assoc())
    {
    echo $data['FR']."<br>";
    }
    } else {
    echo "---";
                                        }
    ?>

                 </h3><a href="index.html" title="">FR|</a>
                    <a href="index_en.html" title="">EN|</a>
                    <a href="index_es.html" title="">ES|</a>
                    <a href="index_cn.html" title="">CHI</a>
                 </div>

                    <nav role="navigation" class="main-nav">
                    <ul>
                        <li class="active">
    <a href="index.html" title=""><?  php
    $conn = new mysqli($dbhost,$dbuser,$dbpass,$dbname);
    if ($conn->connect_error)
    {
    echo "connection error" ;
    }
    $sql = "SELECT * FROM test WHERE id='59'";
    $result = $conn->query($sql);

    ?>
    <?php
    if ($result->num_rows > 0) { while($data = $result->fetch_assoc())
    {echo $data['FR']."<br>"; } } else {echo "---"; }?>

    <?php
    $conn = new mysqli($dbhost,$dbuser,$dbpass,$dbname);
    if ($conn->connect_error)
    {
    echo "Problemes de connexion a la base de données " ;
    }
    $sql = "SELECT * FROM test WHERE id='60'";
    $result = $conn->query($sql);
    ?>
    <?php
    if ($result->num_rows > 0) { while($data = $result->fetch_assoc())
    {echo $data['FR']."<br>"; } } else {echo "---"; }?>
    <?php
    $conn = new mysqli($dbhost,$dbuser,$dbpass,$dbname);
    if ($conn->connect_error)
    {
    echo "connection error" ;
    }
    $sql = "SELECT * FROM test WHERE id='61'";
    $result = $conn->query($sql);
    ?>
</code>```

答:
Ok, Finally i choose Raymond's method, just customizing the code to my mysql version. I will reuse the code wherever i have data in block. Thanks a lot.</p>

```<code>enter code here

$sql = "SELECT * FROM test WHERE id IN ('59','60','61')";
$result = $conn->query($sql);

?>
<?php
if ($result->num_rows > 0) { while($data = $result->fetch_assoc())
{echo $data['FR']. "<br>"; }    } else {echo "---"; }?></a></li>
</code>```

Body:
I have a php code about retrieving multiple lines from mysql database that works very well. But I find it too heavy. The following is only one extract, as i use the same method for each single word from the database. Do you have better solution? Can I make just one statement for all the page, and just put the requested ID at the correct place? Thank you for any help.

  <?php
    $dbname = 'xxxx';
    $dbuser = 'xxxx';
    $dbpass = 'xxxx';
    $dbhost = 'localhost';
    $conn = new mysqli($dbhost,$dbuser,$dbpass,$dbname);
    if ($conn->connect_error)
    {
    echo "connection error" ;
    }
    $sql = "SELECT * FROM test WHERE id='1'";
    $result = $conn->query($sql);
    ?>
    <?php
    if ($result->num_rows > 0) {
    while($data = $result-   >fetch_assoc())
    {
    echo $data['FR']."
";
    }
    } else {
    echo "---";
                                        }
    ?>

FR|
                    EN|
                    ES|
                    CHI

    <?  php
    $conn = new mysqli($dbhost,$dbuser,$dbpass,$dbname);
    if ($conn->connect_error)
    {
    echo "connection error" ;
    }
    $sql = "SELECT * FROM test WHERE id='59'";
    $result = $conn->query($sql);

    ?>
    <?php
    if ($result->num_rows > 0) { while($data = $result->fetch_assoc())
    {echo $data['FR']."
"; } } else {echo "---"; }?>

    <?php
    $conn = new mysqli($dbhost,$dbuser,$dbpass,$dbname);
    if ($conn->connect_error)
    {
    echo "Problemes de connexion a la base de données " ;
    }
    $sql = "SELECT * FROM test WHERE id='60'";
    $result = $conn->query($sql);
    ?>
    <?php
    if ($result->num_rows > 0) { while($data = $result->fetch_assoc())
    {echo $data['FR']."
"; } } else {echo "---"; }?>
    <?php
    $conn = new mysqli($dbhost,$dbuser,$dbpass,$dbname);
    if ($conn->connect_error)
    {
    echo "connection error" ;
    }
    $sql = "SELECT * FROM test WHERE id='61'";
    $result = $conn->query($sql);
    ?>

Body:
Ok, Finally i choose Raymond's method, just customizing the code to my mysql version. I will reuse the code wherever i have data in block. Thanks a lot.

enter code here

$sql = "SELECT * FROM test WHERE id IN ('59','60','61')";
$result = $conn->query($sql);

?>
<?php
if ($result->num_rows > 0) { while($data = $result->fetch_assoc())
{echo $data['FR']. "<br>"; }    } else {echo "---"; }?></a></li>


来源: stackexchange

问:
New Layout For New Page in Orchard CMS
is there a way to display a new page with a new layout?
Right now what I'm doing is to create a new module but without using [Themed]
I'm looking for a simpler way to do it?
Thanks</p>

答:
Assumed by layout you mean theme you can implement Orchard.Themes.IThemeSelector to select a specific theme. Here is an example which shows a theme selector which picks the theme based on a ThemePickerPart:

```<code>public class ThemePickerPartThemeSelector : Orchard.Themes.IThemeSelector
{
  public ThemePickerPartThemeSelector(Orchard.ContentManagement.IContentManager aContentManager)
  {
    mContentManager = aContentManager;
  }

  public Orchard.Themes.ThemeSelectorResult GetTheme(System.Web.Routing.RequestContext aContext)
  {
    // get current content item, based on http://www.ideliverable.com/blog/getting-the-current-content-item-in-orchard
    object lID;

    if (aContext.RouteData.Values.TryGetValue("id", out lID))
    {
      string lIDStr = lID as string;

      if (lIDStr != null)
      {
        int lContentID;

        if(int.TryParse(lIDStr as string, out lContentID))
        {
          // try to get theme from theme picker part
          var lContentItem = mContentManager.Get(lContentID, Orchard.ContentManagement.VersionOptions.Published);

          if (lContentItem != null)
          {
            var lThemePickerPart = lContentItem.As<ThemePickerPart>();

            if (lThemePickerPart != null)
            {
              if (!string.IsNullOrEmpty(lThemePickerPart.ThemeId))
              {
                // return selected theme
                var lResult = new Orchard.Themes.ThemeSelectorResult {Priority = -3, ThemeName = lThemePickerPart.ThemeId};

                return lResult;
              }
            }
          }
        }
      }
    }

    return null; // use configured theme
  }

  // private
    private Orchard.ContentManagement.IContentManager mContentManager;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: New Layout For New Page in Orchard CMS

Body:
Assumed by layout you mean theme you can implement Orchard.Themes.IThemeSelector to select a specific theme. Here is an example which shows a theme selector which picks the theme based on a ThemePickerPart:

public class ThemePickerPartThemeSelector : Orchard.Themes.IThemeSelector
{
  public ThemePickerPartThemeSelector(Orchard.ContentManagement.IContentManager aContentManager)
  {
    mContentManager = aContentManager;
  }

  public Orchard.Themes.ThemeSelectorResult GetTheme(System.Web.Routing.RequestContext aContext)
  {
    // get current content item, based on http://www.ideliverable.com/blog/getting-the-current-content-item-in-orchard
    object lID;

    if (aContext.RouteData.Values.TryGetValue("id", out lID))
    {
      string lIDStr = lID as string;

      if (lIDStr != null)
      {
        int lContentID;

        if(int.TryParse(lIDStr as string, out lContentID))
        {
          // try to get theme from theme picker part
          var lContentItem = mContentManager.Get(lContentID, Orchard.ContentManagement.VersionOptions.Published);

          if (lContentItem != null)
          {
            var lThemePickerPart = lContentItem.As<ThemePickerPart>();

            if (lThemePickerPart != null)
            {
              if (!string.IsNullOrEmpty(lThemePickerPart.ThemeId))
              {
                // return selected theme
                var lResult = new Orchard.Themes.ThemeSelectorResult {Priority = -3, ThemeName = lThemePickerPart.ThemeId};

                return lResult;
              }
            }
          }
        }
      }
    }

    return null; // use configured theme
  }

  // private
    private Orchard.ContentManagement.IContentManager mContentManager;
}


问:
How do I extend the values of a specific dictionary item with overlapping keys?
So I have a dictionary "db" which equals

```<code>{('ALI', 'MALE'): [(2011, 200, None), (2012, 200, None), (2013, 200, None),
(2014, 200, None), (2015, 200, None)], ('BOB', 'MALE'): [(2012, 200, None),
(2013, 200, None), (2014, 200, None)], ('LUKE', 'MALE'): [(2013, 200, None),
(2015, 200, None)], ('JEFF', 'MALE'): [(2014, 200, None)]}
</code>```

I need to create a function that takes the database, a name, a gender, a year, a count, and a rank (which may sometimes equal None) and update the dictionary db with the new info. Here is what I have so far.

```<code>def add_name(db, name, gender, year, count, rank=None):
    db.update({(name, gender): [(year, count, rank)]})
    return None
</code>```

The problem however, is that if I add an item that has a key that already exists in db, say for example "('BOB','MALE')", the .update method will overwrite the values associated with that key and replace them with the values from the function.

In the event of keys that overlap, how can I simply append the values instead?

答:
try this:</p>

```<code>def add_name(db, name, gender, year, count, rank=None):
    # check if the key (name, gender) in db. if it's in, append
    if (name, gender) in db:
        db[(name, gender)].append((year, count, rank))
    # else new a key
    else:
        db[(name, gender)] = [(year, count, rank)]
    return None
</code>```

Body:
So I have a dictionary "db" which equals

{('ALI', 'MALE'): [(2011, 200, None), (2012, 200, None), (2013, 200, None),
(2014, 200, None), (2015, 200, None)], ('BOB', 'MALE'): [(2012, 200, None),
(2013, 200, None), (2014, 200, None)], ('LUKE', 'MALE'): [(2013, 200, None),
(2015, 200, None)], ('JEFF', 'MALE'): [(2014, 200, None)]}

I need to create a function that takes the database, a name, a gender, a year, a count, and a rank (which may sometimes equal None) and update the dictionary db with the new info. Here is what I have so far.

def add_name(db, name, gender, year, count, rank=None):
    db.update({(name, gender): [(year, count, rank)]})
    return None

The problem however, is that if I add an item that has a key that already exists in db, say for example "('BOB','MALE')", the .update method will overwrite the values associated with that key and replace them with the values from the function.

In the event of keys that overlap, how can I simply append the values instead?

Body:
try this:

def add_name(db, name, gender, year, count, rank=None):
    # check if the key (name, gender) in db. if it's in, append
    if (name, gender) in db:
        db[(name, gender)].append((year, count, rank))
    # else new a key
    else:
        db[(name, gender)] = [(year, count, rank)]
    return None


问:
Android - Firebase rename file(SHA-1) before upload
Everyone, I need to rename file before uploading to Firebase Storage
with multiple image upload and encode to sha-1  (imagename + uid + current time):

915731b2094b1cb23c1b176ef8633947f737804b,fdf15718d6d988ce188bdc8debcb7d5998229db3

Multi Select Image i get from this link https://github.com/donglua/PhotoPicker

Mainboard Post Class (Class To Post to Firebase Storage and stamp to Firebase Database but now i don't have to put sha1hash to Firebase Database

```<code>   private static final String TAG = "MainboardPost";
private static final int MAP_REQUEST_CODE = 334;
private static final int ADD_PHOTO_REQUEST = 335;
private Toolbar toolbar;
private TextView cancle;
private Mainboard post;
private PhotoAdapter photoAdapter;
private ArrayList<String> selectedPhotos = new ArrayList<>();
Button img_btn,map_btn,removeMapBtn;
RelativeLayout layout_img , layout_map ;
private RecyclerView recyclerView;
EditText header , body;

private UploadTask mUploadtask;

ImageButton addMapBtn;
FrameLayout frameLayout;

private FirebaseStorage storageRef;
private StorageReference mStorage , folderRef;
private DatabaseReference mDatabase;

// รับค่าlat lon เพื่อโพส
private String loc_latlon;
private String loc_address;

private FirebaseAuth mAuth;

GoogleMap map;
Marker mMarker;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.view_mainbard_post);
    toolbar = (Toolbar) findViewById(R.id.toolbar_post); //Custom toolbar
    setSupportActionBar(toolbar);  //  Class Actionbar ให้ใช้ Toolbar แทนของระบบ
    getSupportActionBar().setDisplayShowTitleEnabled(false); // ซ่อนชื่อแอพบน Toolbar

    mAuth = FirebaseAuth.getInstance();

    mDatabase = FirebaseDatabase.getInstance().getReference();

    storageRef = FirebaseStorage.getInstance();
    mStorage = storageRef.getReference();
    folderRef = mStorage.child("mainboard");

    frameLayout = (FrameLayout)findViewById(R.id.map_frame);
    removeMapBtn = (Button)findViewById(R.id.remove_btn);
    addMapBtn = (ImageButton)findViewById(R.id.addmap_btn);
    layout_img = (RelativeLayout)findViewById(R.id.layout_add_photo);
    layout_map = (RelativeLayout)findViewById(R.id.layout_add_map);
    recyclerView = (RecyclerView)findViewById(R.id.addimg_view);
    header = (EditText)findViewById(R.id.topic);
    body = (EditText)findViewById(R.id.detail);
    photoAdapter = new PhotoAdapter(MainboardPost.this, selectedPhotos);

    img_btn = (Button)findViewById(R.id.add_img);
    img_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            layout_img.setVisibility(View.VISIBLE);
            layout_map.setVisibility(View.GONE);
        }
    });
    map_btn = (Button)findViewById(R.id.add_map);
    map_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            layout_map.setVisibility(View.VISIBLE);
            layout_img.setVisibility(View.GONE);

        }
    });

    cancle = (TextView) findViewById(R.id.toolbar_cancle);
    cancle.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });

    addMapBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainboardPost.this, MapsActivity.class);
            startActivityForResult(intent, MAP_REQUEST_CODE);
        }
    });

    removeMapBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            frameLayout.setVisibility(View.GONE);
            addMapBtn.setVisibility(View.VISIBLE);
        }
    });

    recyclerView.setLayoutManager(new StaggeredGridLayoutManager(4, OrientationHelper.VERTICAL));
    recyclerView.setAdapter(photoAdapter);

    recyclerView.addOnItemTouchListener(new RecyclerItemClick(MainboardPost.this,
            new RecyclerItemClick.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    if (photoAdapter.getItemViewType(position) == PhotoAdapter.TYPE_ADD) {
                        PhotoPicker.builder()
                                .setPhotoCount(PhotoAdapter.MAX)
                                .setShowCamera(true)
                                .setPreviewEnabled(false)
                                .setSelected(selectedPhotos)
                                .start(MainboardPost.this, REQUEST_CODE);
                    } else {
                        PhotoPreview.builder()
                                .setPhotos(selectedPhotos)
                                .setCurrentItem(position)
                                .start(MainboardPost.this, REQUEST_CODE);
                    }
                }
            }));

    setUpGoogleMap();

}

//Menu Item ขวามือสุดของ Toolbar
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_post, menu);
    return true;
}

private void setUpGoogleMap() {
    if (new GooglePlayServiceCheck().isGooglePlayInstalled(MainboardPost.this)) {

        SupportMapFragment map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapView2));
        map.getMapAsync(this);//after getting map call async method, this method will call onMapReady(GoogleMap map) method
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case MAP_REQUEST_CODE:
            if (resultCode == Activity.RESULT_OK) {
                //Location Fetched
                double lat = data.getDoubleExtra("location_lat", 0);
                double lng = data.getDoubleExtra("location_lng", 0);

                loc_latlon = lat + "," + lng;

                Log.e("Selected Lat-lng", lat + " - " + lng);
                frameLayout.setVisibility(View.VISIBLE);
                addMapBtn.setVisibility(View.GONE);
                //Here after getting lat lng add marker to ur google map using fetched lat lng
                setPickedLocationOverMap(lat, lng);
                //
            }
            break;
        case REQUEST_CODE:
            if (resultCode == RESULT_OK &&
                    (requestCode == REQUEST_CODE || requestCode == PhotoPreview.REQUEST_CODE)) {
                List<String> photos = null;
                if (data != null) {
                    photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                }
                selectedPhotos.clear();

                if (photos != null) {

                    selectedPhotos.addAll(photos);
                }
                photoAdapter.notifyDataSetChanged();
            }
            break;
    }
}

private void setPickedLocationOverMap(double lat, double lng) {
    // Needs to call MapsInitializer before doing any CameraUpdateFactory calls
    MapsInitializer.initialize(this.getApplicationContext());
    // Updates the location and zoom of the MapView
    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 17);
    if (map != null)
        map.animateCamera(cameraUpdate);

}

@Override
public void onMapReady(GoogleMap googleMap) {
    this.map = googleMap;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    submitPost();
    return true;
}

@Override
public void onClick(View view) {
    switch (view.getId()){
        case R.id.button_upload_resume:
            Helper.mProgressDialog.show();
            mUploadtask.resume();
            break;
    }
}

private void submitPost() {

    final String title = header.getText().toString().trim();
    final String detail = body.getText().toString().trim();

    if (loc_latlon == null){
        loc_latlon = "";
    }

    if (loc_address == null){
        loc_address = "";
    }

    if (!TextUtils.isEmpty(title) && !TextUtils.isEmpty(detail)){
        final String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
        mDatabase.child("user").child(userId).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                User user = dataSnapshot.getValue(User.class);
                if (user == null){
                    Log.e(TAG, "User " + userId + " is unexpectedly null");
                    Toast.makeText(MainboardPost.this,
                            "Error: could not fetch user.",
                            Toast.LENGTH_SHORT).show();

                }else {
                    writenewpost(title , detail , loc_latlon , loc_address);

                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.w(TAG, "getUser:onCancelled", databaseError.toException());
            }
        });
    }
    for (String imagePath : selectedPhotos){
        Uri file =  Uri.fromFile(new File(imagePath));
        StorageReference imageRef = folderRef.child(file.getLastPathSegment());
        mUploadtask = imageRef.putFile(file);

    }

}

private void writenewpost(String mbTitle , String mbBody, String mbLocation , String mbAddress )

{

    String key = mDatabase.child("mainboard").push().getKey();
    PostMainboard mainboard_post = new PostMainboard(mbTitle, mbBody , mbLocation , mbAddress);

    Map<String, Object>postvalue = mainboard_post.toMap();
    Map<String, Object>childUpdates = new HashMap<>();
    childUpdates.put("/mainboard/" + key , postvalue);

    mDatabase.updateChildren(childUpdates);
}
</code>```

Mainboard Post Model

```<code>public String mb_address;
public String mb_body;
public String mb_location;
public String mb_pic;
public String mb_title ;

public PostMainboard(){

}

public PostMainboard( String mb_title ,String mb_body,String mb_location,String mb_address , String mb_pic)

{
    this.mb_address = mb_address;
    this.mb_body = mb_body;
    this.mb_location = mb_location;
    this.mb_pic = mb_pic;
    this.mb_title = mb_title;
}

@Exclude
public Map<String , Object> toMap(){
    HashMap<String, Object> result = new HashMap<>();
    result.put("mb_title" , mb_title);
    result.put("mb_body" , mb_body);
    result.put("mb_location" , mb_location);
    result.put("mb_address" , mb_address);
    result.put("mb_pic" , mb_pic);
    return result;
}
</code>```

}

答:
Below is a support class for creating a SHA-1 certificate. This maybe helpful for you .

1.Create a class named SHA1Hash.java and paste below code. Imports necessary package.

```<code>public class SHA1Hash {

    private static String convertToHex(byte[] data) {
        StringBuilder buf = new StringBuilder();
        for (byte b : data) {
            int halfbyte = (b >>> 4) & 0x0F;
            int two_halfs = 0;
            do {
                buf.append((0 <= halfbyte) && (halfbyte <= 9) ? (char) ('0' + halfbyte) : (char) ('a' + (halfbyte - 10)));
                halfbyte = b & 0x0F;
            } while (two_halfs++ < 1);
        }
        return buf.toString();
    }

    public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        md.update(text.getBytes("iso-8859-1"), 0, text.length());
        byte[] sha1hash = md.digest();
        return convertToHex(sha1hash);
    }
}
</code>```

2. Use this call method as below to create SHA1 Certificate Using datetime and your necessary String value .

```<code>        public static String getDateTimeHash(String uid, String imageName){
            final String HASH_KEY = uid+imageName;
            String hashString = "";
            String timeInMilliSeconds = String.valueOf(System.currentTimeMillis());
            try {
               hashString =  SHA1Hash.SHA1(timeInMilliSeconds.concat(HASH_KEY));
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            Log.d("Utils","Hash Value is "+hashString);
            return  hashString ;
        }
</code>```

Edited the uses method according your need . You can pass imageName+uid+currentTime as String  as the method takes String type of value

 Your final code :

```<code>private static final String TAG = "MainboardPost";
private static final int MAP_REQUEST_CODE = 334;
private static final int ADD_PHOTO_REQUEST = 335;
private Toolbar toolbar;
private TextView cancle;
private Mainboard post;
private PhotoAdapter photoAdapter;
private ArrayList<String> selectedPhotos = new ArrayList<>();
Button img_btn,map_btn,removeMapBtn;
RelativeLayout layout_img , layout_map ;
private RecyclerView recyclerView;
EditText header , body;

private UploadTask mUploadtask;

ImageButton addMapBtn;
FrameLayout frameLayout;

private FirebaseStorage storageRef;
private StorageReference mStorage , folderRef;
private DatabaseReference mDatabase;

// รับค่าlat lon เพื่อโพส
private String loc_latlon;
private String loc_address;

private FirebaseAuth mAuth;

GoogleMap map;
Marker mMarker;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.view_mainbard_post);
    toolbar = (Toolbar) findViewById(R.id.toolbar_post); //Custom toolbar
    setSupportActionBar(toolbar);  //  Class Actionbar ให้ใช้ Toolbar แทนของระบบ
    getSupportActionBar().setDisplayShowTitleEnabled(false); // ซ่อนชื่อแอพบน Toolbar

    mAuth = FirebaseAuth.getInstance();

    mDatabase = FirebaseDatabase.getInstance().getReference();

    storageRef = FirebaseStorage.getInstance();
    mStorage = storageRef.getReference();
    folderRef = mStorage.child("mainboard");

    frameLayout = (FrameLayout)findViewById(R.id.map_frame);
    removeMapBtn = (Button)findViewById(R.id.remove_btn);
    addMapBtn = (ImageButton)findViewById(R.id.addmap_btn);
    layout_img = (RelativeLayout)findViewById(R.id.layout_add_photo);
    layout_map = (RelativeLayout)findViewById(R.id.layout_add_map);
    recyclerView = (RecyclerView)findViewById(R.id.addimg_view);
    header = (EditText)findViewById(R.id.topic);
    body = (EditText)findViewById(R.id.detail);
    photoAdapter = new PhotoAdapter(MainboardPost.this, selectedPhotos);

    img_btn = (Button)findViewById(R.id.add_img);
    img_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            layout_img.setVisibility(View.VISIBLE);
            layout_map.setVisibility(View.GONE);
        }
    });
    map_btn = (Button)findViewById(R.id.add_map);
    map_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            layout_map.setVisibility(View.VISIBLE);
            layout_img.setVisibility(View.GONE);

        }
    });

    cancle = (TextView) findViewById(R.id.toolbar_cancle);
    cancle.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });

    addMapBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainboardPost.this, MapsActivity.class);
            startActivityForResult(intent, MAP_REQUEST_CODE);
        }
    });

    removeMapBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            frameLayout.setVisibility(View.GONE);
            addMapBtn.setVisibility(View.VISIBLE);
        }
    });

    recyclerView.setLayoutManager(new StaggeredGridLayoutManager(4, OrientationHelper.VERTICAL));
    recyclerView.setAdapter(photoAdapter);

    recyclerView.addOnItemTouchListener(new RecyclerItemClick(MainboardPost.this,
            new RecyclerItemClick.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    if (photoAdapter.getItemViewType(position) == PhotoAdapter.TYPE_ADD) {
                        PhotoPicker.builder()
                                .setPhotoCount(PhotoAdapter.MAX)
                                .setShowCamera(true)
                                .setPreviewEnabled(false)
                                .setSelected(selectedPhotos)
                                .start(MainboardPost.this, REQUEST_CODE);
                    } else {
                        PhotoPreview.builder()
                                .setPhotos(selectedPhotos)
                                .setCurrentItem(position)
                                .start(MainboardPost.this, REQUEST_CODE);
                    }
                }
            }));

    setUpGoogleMap();

}

//Menu Item ขวามือสุดของ Toolbar
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_post, menu);
    return true;
}

private void setUpGoogleMap() {
    if (new GooglePlayServiceCheck().isGooglePlayInstalled(MainboardPost.this)) {

        SupportMapFragment map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapView2));
        map.getMapAsync(this);//after getting map call async method, this method will call onMapReady(GoogleMap map) method
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case MAP_REQUEST_CODE:
            if (resultCode == Activity.RESULT_OK) {
                //Location Fetched
                double lat = data.getDoubleExtra("location_lat", 0);
                double lng = data.getDoubleExtra("location_lng", 0);

                loc_latlon = lat + "," + lng;

                Log.e("Selected Lat-lng", lat + " - " + lng);
                frameLayout.setVisibility(View.VISIBLE);
                addMapBtn.setVisibility(View.GONE);
                //Here after getting lat lng add marker to ur google map using fetched lat lng
                setPickedLocationOverMap(lat, lng);
                //
            }
            break;
        case REQUEST_CODE:
            if (resultCode == RESULT_OK &&
                    (requestCode == REQUEST_CODE || requestCode == PhotoPreview.REQUEST_CODE)) {
                List<String> photos = null;
                if (data != null) {
                    photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                }
                selectedPhotos.clear();

                if (photos != null) {

                    selectedPhotos.addAll(photos);
                }
                photoAdapter.notifyDataSetChanged();
            }
            break;
    }
}

private void setPickedLocationOverMap(double lat, double lng) {
    // Needs to call MapsInitializer before doing any CameraUpdateFactory calls
    MapsInitializer.initialize(this.getApplicationContext());
    // Updates the location and zoom of the MapView
    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 17);
    if (map != null)
        map.animateCamera(cameraUpdate);

}

@Override
public void onMapReady(GoogleMap googleMap) {
    this.map = googleMap;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    submitPost();
    return true;
}

@Override
public void onClick(View view) {
    switch (view.getId()){
        case R.id.button_upload_resume:
            Helper.mProgressDialog.show();
            mUploadtask.resume();
            break;
    }
}

private void submitPost() {

    final String title = header.getText().toString().trim();
    final String detail = body.getText().toString().trim();
final String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();

    if (loc_latlon == null){
        loc_latlon = "";
    }

    if (loc_address == null){
        loc_address = "";
    }

    if (!TextUtils.isEmpty(title) && !TextUtils.isEmpty(detail)){

        mDatabase.child("user").child(userId).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                User user = dataSnapshot.getValue(User.class);
                if (user == null){
                    Log.e(TAG, "User " + userId + " is unexpectedly null");
                    Toast.makeText(MainboardPost.this,
                            "Error: could not fetch user.",
                            Toast.LENGTH_SHORT).show();

                }else {
                    writenewpost(title , detail , loc_latlon , loc_address);

                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.w(TAG, "getUser:onCancelled", databaseError.toException());
            }
        });
    }
    for (String imagePath : selectedPhotos){
        Uri file =  Uri.fromFile(new File(imagePath));
         String imageName=imagePath.substring(imagePath.lastIndexOf("/")+1);
         Log.d("ImageName" , imageName) ;
         String hashImageName = getDateTimeHash(userId, imageName);
         Log.d("HashImageName" , hashImageName);
        StorageReference imageRef = folderRef.child(hashImageName);
        mUploadtask = imageRef.putFile(file);

    }

}

private void writenewpost(String mbTitle , String mbBody, String mbLocation , String mbAddress )

{

    String key = mDatabase.child("mainboard").push().getKey();
    PostMainboard mainboard_post = new PostMainboard(mbTitle, mbBody , mbLocation , mbAddress);

    Map<String, Object>postvalue = mainboard_post.toMap();
    Map<String, Object>childUpdates = new HashMap<>();
    childUpdates.put("/mainboard/" + key , postvalue);

    mDatabase.updateChildren(childUpdates);
}

public static String getDateTimeHash(String uid, String imageName){
            final String HASH_KEY = uid+imageName;
            String hashString = "";
            String timeInMilliSeconds = String.valueOf(System.currentTimeMillis());
            try {
               hashString =  SHA1Hash.SHA1(timeInMilliSeconds.concat(HASH_KEY));
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            Log.d("Utils","Hash Value is "+hashString);
            return  hashString ;
        }
</code>```

Hope this is helpful for you. Thanks

Body:
Everyone, I need to rename file before uploading to Firebase Storage
with multiple image upload and encode to sha-1  (imagename + uid + current time):

915731b2094b1cb23c1b176ef8633947f737804b,fdf15718d6d988ce188bdc8debcb7d5998229db3

Multi Select Image i get from this link https://github.com/donglua/PhotoPicker

Mainboard Post Class (Class To Post to Firebase Storage and stamp to Firebase Database but now i don't have to put sha1hash to Firebase Database

   private static final String TAG = "MainboardPost";
private static final int MAP_REQUEST_CODE = 334;
private static final int ADD_PHOTO_REQUEST = 335;
private Toolbar toolbar;
private TextView cancle;
private Mainboard post;
private PhotoAdapter photoAdapter;
private ArrayList<String> selectedPhotos = new ArrayList<>();
Button img_btn,map_btn,removeMapBtn;
RelativeLayout layout_img , layout_map ;
private RecyclerView recyclerView;
EditText header , body;

private UploadTask mUploadtask;

ImageButton addMapBtn;
FrameLayout frameLayout;

private FirebaseStorage storageRef;
private StorageReference mStorage , folderRef;
private DatabaseReference mDatabase;

// รับค่าlat lon เพื่อโพส
private String loc_latlon;
private String loc_address;

private FirebaseAuth mAuth;

GoogleMap map;
Marker mMarker;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.view_mainbard_post);
    toolbar = (Toolbar) findViewById(R.id.toolbar_post); //Custom toolbar
    setSupportActionBar(toolbar);  //  Class Actionbar ให้ใช้ Toolbar แทนของระบบ
    getSupportActionBar().setDisplayShowTitleEnabled(false); // ซ่อนชื่อแอพบน Toolbar

    mAuth = FirebaseAuth.getInstance();

    mDatabase = FirebaseDatabase.getInstance().getReference();

    storageRef = FirebaseStorage.getInstance();
    mStorage = storageRef.getReference();
    folderRef = mStorage.child("mainboard");

    frameLayout = (FrameLayout)findViewById(R.id.map_frame);
    removeMapBtn = (Button)findViewById(R.id.remove_btn);
    addMapBtn = (ImageButton)findViewById(R.id.addmap_btn);
    layout_img = (RelativeLayout)findViewById(R.id.layout_add_photo);
    layout_map = (RelativeLayout)findViewById(R.id.layout_add_map);
    recyclerView = (RecyclerView)findViewById(R.id.addimg_view);
    header = (EditText)findViewById(R.id.topic);
    body = (EditText)findViewById(R.id.detail);
    photoAdapter = new PhotoAdapter(MainboardPost.this, selectedPhotos);

    img_btn = (Button)findViewById(R.id.add_img);
    img_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            layout_img.setVisibility(View.VISIBLE);
            layout_map.setVisibility(View.GONE);
        }
    });
    map_btn = (Button)findViewById(R.id.add_map);
    map_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            layout_map.setVisibility(View.VISIBLE);
            layout_img.setVisibility(View.GONE);

        }
    });

    cancle = (TextView) findViewById(R.id.toolbar_cancle);
    cancle.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });

    addMapBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainboardPost.this, MapsActivity.class);
            startActivityForResult(intent, MAP_REQUEST_CODE);
        }
    });

    removeMapBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            frameLayout.setVisibility(View.GONE);
            addMapBtn.setVisibility(View.VISIBLE);
        }
    });

    recyclerView.setLayoutManager(new StaggeredGridLayoutManager(4, OrientationHelper.VERTICAL));
    recyclerView.setAdapter(photoAdapter);

    recyclerView.addOnItemTouchListener(new RecyclerItemClick(MainboardPost.this,
            new RecyclerItemClick.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    if (photoAdapter.getItemViewType(position) == PhotoAdapter.TYPE_ADD) {
                        PhotoPicker.builder()
                                .setPhotoCount(PhotoAdapter.MAX)
                                .setShowCamera(true)
                                .setPreviewEnabled(false)
                                .setSelected(selectedPhotos)
                                .start(MainboardPost.this, REQUEST_CODE);
                    } else {
                        PhotoPreview.builder()
                                .setPhotos(selectedPhotos)
                                .setCurrentItem(position)
                                .start(MainboardPost.this, REQUEST_CODE);
                    }
                }
            }));

    setUpGoogleMap();

}

//Menu Item ขวามือสุดของ Toolbar
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_post, menu);
    return true;
}

private void setUpGoogleMap() {
    if (new GooglePlayServiceCheck().isGooglePlayInstalled(MainboardPost.this)) {

        SupportMapFragment map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapView2));
        map.getMapAsync(this);//after getting map call async method, this method will call onMapReady(GoogleMap map) method
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case MAP_REQUEST_CODE:
            if (resultCode == Activity.RESULT_OK) {
                //Location Fetched
                double lat = data.getDoubleExtra("location_lat", 0);
                double lng = data.getDoubleExtra("location_lng", 0);

                loc_latlon = lat + "," + lng;

                Log.e("Selected Lat-lng", lat + " - " + lng);
                frameLayout.setVisibility(View.VISIBLE);
                addMapBtn.setVisibility(View.GONE);
                //Here after getting lat lng add marker to ur google map using fetched lat lng
                setPickedLocationOverMap(lat, lng);
                //
            }
            break;
        case REQUEST_CODE:
            if (resultCode == RESULT_OK &&
                    (requestCode == REQUEST_CODE || requestCode == PhotoPreview.REQUEST_CODE)) {
                List<String> photos = null;
                if (data != null) {
                    photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                }
                selectedPhotos.clear();

                if (photos != null) {

                    selectedPhotos.addAll(photos);
                }
                photoAdapter.notifyDataSetChanged();
            }
            break;
    }
}

private void setPickedLocationOverMap(double lat, double lng) {
    // Needs to call MapsInitializer before doing any CameraUpdateFactory calls
    MapsInitializer.initialize(this.getApplicationContext());
    // Updates the location and zoom of the MapView
    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 17);
    if (map != null)
        map.animateCamera(cameraUpdate);

}

@Override
public void onMapReady(GoogleMap googleMap) {
    this.map = googleMap;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    submitPost();
    return true;
}

@Override
public void onClick(View view) {
    switch (view.getId()){
        case R.id.button_upload_resume:
            Helper.mProgressDialog.show();
            mUploadtask.resume();
            break;
    }
}

private void submitPost() {

    final String title = header.getText().toString().trim();
    final String detail = body.getText().toString().trim();

    if (loc_latlon == null){
        loc_latlon = "";
    }

    if (loc_address == null){
        loc_address = "";
    }

    if (!TextUtils.isEmpty(title) && !TextUtils.isEmpty(detail)){
        final String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
        mDatabase.child("user").child(userId).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                User user = dataSnapshot.getValue(User.class);
                if (user == null){
                    Log.e(TAG, "User " + userId + " is unexpectedly null");
                    Toast.makeText(MainboardPost.this,
                            "Error: could not fetch user.",
                            Toast.LENGTH_SHORT).show();

                }else {
                    writenewpost(title , detail , loc_latlon , loc_address);

                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.w(TAG, "getUser:onCancelled", databaseError.toException());
            }
        });
    }
    for (String imagePath : selectedPhotos){
        Uri file =  Uri.fromFile(new File(imagePath));
        StorageReference imageRef = folderRef.child(file.getLastPathSegment());
        mUploadtask = imageRef.putFile(file);

    }

}

private void writenewpost(String mbTitle , String mbBody, String mbLocation , String mbAddress )

{

    String key = mDatabase.child("mainboard").push().getKey();
    PostMainboard mainboard_post = new PostMainboard(mbTitle, mbBody , mbLocation , mbAddress);

    Map<String, Object>postvalue = mainboard_post.toMap();
    Map<String, Object>childUpdates = new HashMap<>();
    childUpdates.put("/mainboard/" + key , postvalue);

    mDatabase.updateChildren(childUpdates);
}

Mainboard Post Model

public String mb_address;
public String mb_body;
public String mb_location;
public String mb_pic;
public String mb_title ;

public PostMainboard(){

}

public PostMainboard( String mb_title ,String mb_body,String mb_location,String mb_address , String mb_pic)

{
    this.mb_address = mb_address;
    this.mb_body = mb_body;
    this.mb_location = mb_location;
    this.mb_pic = mb_pic;
    this.mb_title = mb_title;
}

@Exclude
public Map<String , Object> toMap(){
    HashMap<String, Object> result = new HashMap<>();
    result.put("mb_title" , mb_title);
    result.put("mb_body" , mb_body);
    result.put("mb_location" , mb_location);
    result.put("mb_address" , mb_address);
    result.put("mb_pic" , mb_pic);
    return result;
}

}

Body:
Below is a support class for creating a SHA-1 certificate. This maybe helpful for you .

1.Create a class named SHA1Hash.java and paste below code. Imports necessary package.

public class SHA1Hash {

    private static String convertToHex(byte[] data) {
        StringBuilder buf = new StringBuilder();
        for (byte b : data) {
            int halfbyte = (b >>> 4) & 0x0F;
            int two_halfs = 0;
            do {
                buf.append((0 <= halfbyte) && (halfbyte <= 9) ? (char) ('0' + halfbyte) : (char) ('a' + (halfbyte - 10)));
                halfbyte = b & 0x0F;
            } while (two_halfs++ < 1);
        }
        return buf.toString();
    }

    public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        md.update(text.getBytes("iso-8859-1"), 0, text.length());
        byte[] sha1hash = md.digest();
        return convertToHex(sha1hash);
    }
}

2. Use this call method as below to create SHA1 Certificate Using datetime and your necessary String value .

        public static String getDateTimeHash(String uid, String imageName){
            final String HASH_KEY = uid+imageName;
            String hashString = "";
            String timeInMilliSeconds = String.valueOf(System.currentTimeMillis());
            try {
               hashString =  SHA1Hash.SHA1(timeInMilliSeconds.concat(HASH_KEY));
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            Log.d("Utils","Hash Value is "+hashString);
            return  hashString ;
        }

Edited the uses method according your need . You can pass imageName+uid+currentTime as String  as the method takes String type of value

 Your final code :

private static final String TAG = "MainboardPost";
private static final int MAP_REQUEST_CODE = 334;
private static final int ADD_PHOTO_REQUEST = 335;
private Toolbar toolbar;
private TextView cancle;
private Mainboard post;
private PhotoAdapter photoAdapter;
private ArrayList<String> selectedPhotos = new ArrayList<>();
Button img_btn,map_btn,removeMapBtn;
RelativeLayout layout_img , layout_map ;
private RecyclerView recyclerView;
EditText header , body;

private UploadTask mUploadtask;

ImageButton addMapBtn;
FrameLayout frameLayout;

private FirebaseStorage storageRef;
private StorageReference mStorage , folderRef;
private DatabaseReference mDatabase;

// รับค่าlat lon เพื่อโพส
private String loc_latlon;
private String loc_address;

private FirebaseAuth mAuth;

GoogleMap map;
Marker mMarker;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.view_mainbard_post);
    toolbar = (Toolbar) findViewById(R.id.toolbar_post); //Custom toolbar
    setSupportActionBar(toolbar);  //  Class Actionbar ให้ใช้ Toolbar แทนของระบบ
    getSupportActionBar().setDisplayShowTitleEnabled(false); // ซ่อนชื่อแอพบน Toolbar

    mAuth = FirebaseAuth.getInstance();

    mDatabase = FirebaseDatabase.getInstance().getReference();

    storageRef = FirebaseStorage.getInstance();
    mStorage = storageRef.getReference();
    folderRef = mStorage.child("mainboard");

    frameLayout = (FrameLayout)findViewById(R.id.map_frame);
    removeMapBtn = (Button)findViewById(R.id.remove_btn);
    addMapBtn = (ImageButton)findViewById(R.id.addmap_btn);
    layout_img = (RelativeLayout)findViewById(R.id.layout_add_photo);
    layout_map = (RelativeLayout)findViewById(R.id.layout_add_map);
    recyclerView = (RecyclerView)findViewById(R.id.addimg_view);
    header = (EditText)findViewById(R.id.topic);
    body = (EditText)findViewById(R.id.detail);
    photoAdapter = new PhotoAdapter(MainboardPost.this, selectedPhotos);

    img_btn = (Button)findViewById(R.id.add_img);
    img_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            layout_img.setVisibility(View.VISIBLE);
            layout_map.setVisibility(View.GONE);
        }
    });
    map_btn = (Button)findViewById(R.id.add_map);
    map_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            layout_map.setVisibility(View.VISIBLE);
            layout_img.setVisibility(View.GONE);

        }
    });

    cancle = (TextView) findViewById(R.id.toolbar_cancle);
    cancle.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });

    addMapBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainboardPost.this, MapsActivity.class);
            startActivityForResult(intent, MAP_REQUEST_CODE);
        }
    });

    removeMapBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            frameLayout.setVisibility(View.GONE);
            addMapBtn.setVisibility(View.VISIBLE);
        }
    });

    recyclerView.setLayoutManager(new StaggeredGridLayoutManager(4, OrientationHelper.VERTICAL));
    recyclerView.setAdapter(photoAdapter);

    recyclerView.addOnItemTouchListener(new RecyclerItemClick(MainboardPost.this,
            new RecyclerItemClick.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    if (photoAdapter.getItemViewType(position) == PhotoAdapter.TYPE_ADD) {
                        PhotoPicker.builder()
                                .setPhotoCount(PhotoAdapter.MAX)
                                .setShowCamera(true)
                                .setPreviewEnabled(false)
                                .setSelected(selectedPhotos)
                                .start(MainboardPost.this, REQUEST_CODE);
                    } else {
                        PhotoPreview.builder()
                                .setPhotos(selectedPhotos)
                                .setCurrentItem(position)
                                .start(MainboardPost.this, REQUEST_CODE);
                    }
                }
            }));

    setUpGoogleMap();

}

//Menu Item ขวามือสุดของ Toolbar
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_post, menu);
    return true;
}

private void setUpGoogleMap() {
    if (new GooglePlayServiceCheck().isGooglePlayInstalled(MainboardPost.this)) {

        SupportMapFragment map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapView2));
        map.getMapAsync(this);//after getting map call async method, this method will call onMapReady(GoogleMap map) method
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case MAP_REQUEST_CODE:
            if (resultCode == Activity.RESULT_OK) {
                //Location Fetched
                double lat = data.getDoubleExtra("location_lat", 0);
                double lng = data.getDoubleExtra("location_lng", 0);

                loc_latlon = lat + "," + lng;

                Log.e("Selected Lat-lng", lat + " - " + lng);
                frameLayout.setVisibility(View.VISIBLE);
                addMapBtn.setVisibility(View.GONE);
                //Here after getting lat lng add marker to ur google map using fetched lat lng
                setPickedLocationOverMap(lat, lng);
                //
            }
            break;
        case REQUEST_CODE:
            if (resultCode == RESULT_OK &&
                    (requestCode == REQUEST_CODE || requestCode == PhotoPreview.REQUEST_CODE)) {
                List<String> photos = null;
                if (data != null) {
                    photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                }
                selectedPhotos.clear();

                if (photos != null) {

                    selectedPhotos.addAll(photos);
                }
                photoAdapter.notifyDataSetChanged();
            }
            break;
    }
}

private void setPickedLocationOverMap(double lat, double lng) {
    // Needs to call MapsInitializer before doing any CameraUpdateFactory calls
    MapsInitializer.initialize(this.getApplicationContext());
    // Updates the location and zoom of the MapView
    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 17);
    if (map != null)
        map.animateCamera(cameraUpdate);

}

@Override
public void onMapReady(GoogleMap googleMap) {
    this.map = googleMap;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    submitPost();
    return true;
}

@Override
public void onClick(View view) {
    switch (view.getId()){
        case R.id.button_upload_resume:
            Helper.mProgressDialog.show();
            mUploadtask.resume();
            break;
    }
}

private void submitPost() {

    final String title = header.getText().toString().trim();
    final String detail = body.getText().toString().trim();
final String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();

    if (loc_latlon == null){
        loc_latlon = "";
    }

    if (loc_address == null){
        loc_address = "";
    }

    if (!TextUtils.isEmpty(title) && !TextUtils.isEmpty(detail)){

        mDatabase.child("user").child(userId).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                User user = dataSnapshot.getValue(User.class);
                if (user == null){
                    Log.e(TAG, "User " + userId + " is unexpectedly null");
                    Toast.makeText(MainboardPost.this,
                            "Error: could not fetch user.",
                            Toast.LENGTH_SHORT).show();

                }else {
                    writenewpost(title , detail , loc_latlon , loc_address);

                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.w(TAG, "getUser:onCancelled", databaseError.toException());
            }
        });
    }
    for (String imagePath : selectedPhotos){
        Uri file =  Uri.fromFile(new File(imagePath));
         String imageName=imagePath.substring(imagePath.lastIndexOf("/")+1);
         Log.d("ImageName" , imageName) ;
         String hashImageName = getDateTimeHash(userId, imageName);
         Log.d("HashImageName" , hashImageName);
        StorageReference imageRef = folderRef.child(hashImageName);
        mUploadtask = imageRef.putFile(file);

    }

}

private void writenewpost(String mbTitle , String mbBody, String mbLocation , String mbAddress )

{

    String key = mDatabase.child("mainboard").push().getKey();
    PostMainboard mainboard_post = new PostMainboard(mbTitle, mbBody , mbLocation , mbAddress);

    Map<String, Object>postvalue = mainboard_post.toMap();
    Map<String, Object>childUpdates = new HashMap<>();
    childUpdates.put("/mainboard/" + key , postvalue);

    mDatabase.updateChildren(childUpdates);
}

public static String getDateTimeHash(String uid, String imageName){
            final String HASH_KEY = uid+imageName;
            String hashString = "";
            String timeInMilliSeconds = String.valueOf(System.currentTimeMillis());
            try {
               hashString =  SHA1Hash.SHA1(timeInMilliSeconds.concat(HASH_KEY));
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            Log.d("Utils","Hash Value is "+hashString);
            return  hashString ;
        }

Hope this is helpful for you. Thanks


问:
JS iterate over an object and remove the enabled false
I have a dynamic object with the following structure:

```<code>{
 a: {
  someKey: {
    propOne: '',
    enabled: true
  }
 },
 b: {
  someKey: {
    propOne: '',
    enabled: false
  }
 },
c: {
  someKey: {
    propOne: '',
    enabled: false
  }
 },
   someKey: {
      ab: {
        propOne: '',
        enabled: true
      }
     }
    }
</code>```

I need to remove the tree with the enabled false. So in the above example the result should be:

```<code> const result = {
     a: {
      someKey: {
        propOne: '',
        enabled: true
      }
     },

   d: {
      someKey: {
        propOne: '',
        enabled: true
      }
     }
    }
</code>```

How can I do this?

答:
you can use delete :

```<code>   var atocken = {
     a: {
      ab: {
        propOne: '',
        enabled: true
      }
     },
     b: {
      ab: {
        propOne: '',
        enabled: false
      }
     }
    }

    if(atocken.b.ab.enabled === false)
    {
      delete atocken.b;
    }
</code>```

Body:
I have a dynamic object with the following structure:

{
 a: {
  someKey: {
    propOne: '',
    enabled: true
  }
 },
 b: {
  someKey: {
    propOne: '',
    enabled: false
  }
 },
c: {
  someKey: {
    propOne: '',
    enabled: false
  }
 },
   someKey: {
      ab: {
        propOne: '',
        enabled: true
      }
     }
    }

I need to remove the tree with the enabled false. So in the above example the result should be:

 const result = {
     a: {
      someKey: {
        propOne: '',
        enabled: true
      }
     },

   d: {
      someKey: {
        propOne: '',
        enabled: true
      }
     }
    }

How can I do this?

Body:
you can use delete :

   var atocken = {
     a: {
      ab: {
        propOne: '',
        enabled: true
      }
     },
     b: {
      ab: {
        propOne: '',
        enabled: false
      }
     }
    }

    if(atocken.b.ab.enabled === false)
    {
      delete atocken.b;
    }


问:
Fetch array value - JQuery
Consider that i have the following html

```<code><input type="text" id="other_floor_plans" name="other_floor_plans[]" value="["Pool","Office","Sprinkler","Boiler"]">
</code>```

To fetch the values i use

```<code>a = $('#other_floor_plans').val()
</code>```

It returns the following

```<code>"["Pool","Office","Sprinkler","Boiler"]"
</code>```

If i use a[0], it returns "[" as output. I need to get "Pool" as the first value.

How to accomplish this?

答:
Your value is a type of string which has a correct JSON syntax. Just parse with JSON.parse into the array and use your syntax.

const value = '["Pool","Office","Sprinkler","Boiler"]';
const array = JSON.parse(value);

console.log(array[0]);```

Title: Fetch array value - JQuery

Body:
Consider that i have the following html

<input type="text" id="other_floor_plans" name="other_floor_plans[]" value="["Pool","Office","Sprinkler","Boiler"]">

To fetch the values i use

a = $('#other_floor_plans').val()

It returns the following

"["Pool","Office","Sprinkler","Boiler"]"

If i use a[0], it returns "[" as output. I need to get "Pool" as the first value.

How to accomplish this?


问:
why is this insertion into a heap faster than insertion into an unsorted list?
After inserting 100000000 elements into my heap and unsorted list, it seems that the heap insertion is actually faster (12 seconds vs 20 seconds). Why is this? I believe heap insertion is O(logn) while unsorted list insertion is O(1). I also noticed that my heap insertion implementation doesn't actually scale with the number of inputs. This also confuses me.

Here is the code that I ran:

```<code>int main ()
{
    clock_t unsortedStart;
    clock_t heapStart;

    double unsortedDuration;
    double heapDuration;

    int num_pushes = 100000000;
    int interval = 10000;

    ofstream unsorted ("unsorted.txt");
    ofstream heap ("heap.txt");

    UnsortedPQ<int> unsortedPQ;
    HeapPQ<int> heapPQ;

    unsortedStart = clock();

    for (int i = 0; i < num_pushes; ++i)
    {
        if (i % interval == 0) {
            unsortedDuration = ( clock() - unsortedStart ) / (double) CLOCKS_PER_SEC;
            unsorted << unsortedDuration << " " << i << endl;
        }

        unsortedPQ.insertItem(rand() % 100);
    }

    heapStart = clock();
    for (int i = 0; i < num_pushes; ++i)
    {
        if (i % interval == 0) {
            heapDuration = ( clock() - heapStart ) / (double) CLOCKS_PER_SEC;
            heap << heapDuration << " " << i << endl;
        }
        heapPQ.insertItem(rand() % 100);
    }
    return 0;
}
</code>```

This is the heap implementation of insert (uses std::vector):

```<code>template <class T>
void HeapPQ<T>::insertItem(T data) {
    //insert into back of heap (std::vector)
    dataArray.push_back(data);
    int i = dataArray.size() - 1;

    //sifts the inserted element up
    while (i != 0 && dataArray[(i - 1) / 2] > dataArray[i]) {
        swap(dataArray[i], dataArray[(i - 1) / 2]);
        i = (i - 1) / 2;
    }
}
</code>```

This is the unsorted list implementation of insert (uses std::list):

```<code>//pushes element to the back of a std::list
template <class T>
void UnsortedPQ<T>::insertItem(T data) { dataList.push_back(data); }
</code>```

答:
The insertion into the heap is O(logn), that mean every insertion could take at most O(logn) steps. It does not mean it has to.

In your example average cost of inserting an element is O(1). Why that?

For simplicity, let's assume you insert only 0a and 1s in a random order (in your current version only numbers 0..99 (rand() % 100) are inserted - the calculation is more complex, but the behavior stays the same). After 2*n elements are inserted, there would be about n 0s and n 1s in the heap,  and the heap would look as follows:

```<code>                                 0
                                0 0
                               00 00
                          ...............
                         0 0 0  0  0  0  0
                       11 11 11 11 11 11 11
</code>```

So basically, 1s are all at the last level k and 0s are at levels 0..k-1.

if 1 is inserted, there is nothing to do (there are no 2s above).

if 0 is inserted there is at most one swap (1s may be in the level above the last level, but 2 levels above).

That meas in average we need only 0.5 swaps and not k.

Having the same asymptotic running time, it is all down to the (amortized) costs for inserting in a vector and in a list. The list seems to be slower (my assumption would be, that for every insert it needs to allocate an element on the heap via new and this is a quite slow operation. The costs depend on other factors, e.g. the size of the inserted objects, and thus it may vary which one is faster).

Let's take a closer look at your case, where the numbers are generated by a uniform dstribution [0..99]. After n>>100 insertions we will have the following situation (there is some hand-waving involved, but the gist should be clear):

the last level (k-th) of the heap has n/2 elements and consists of numbers 50..99. So for 50% of possible numbers (i.e. 50..99) no shift is needed.

the second last level (k-1-th)  of the heap has n/4 elements and consists of numbers 25..49. That means for 25% of possible numbers exactly 1 shift is needed.

the level k-2  has n/8 elements and consists of numbers 13..24.

The levels above log 100/log 2 have only 0s inside. So the maximal number of shifts possible is m=log 100/log 2, independent of n - the number of elements in the heap.

So worst case costs for the insertion would be log 100/log 2, the average costs are even smaller:

```<code>E(insertion)=0*1/2+1*1/4+2*1/8+...<=1.0
</code>```

i.e. on average we have less than 1 shift per insertion.

NB: It does not mean, that inserting in the heap has amortized costs of O(1) - if you would insert the numbers not in random order, but first all 99s, then 98s, ..., then 0s you would have costs of O(log n) per insertion.

Body:
After inserting 100000000 elements into my heap and unsorted list, it seems that the heap insertion is actually faster (12 seconds vs 20 seconds). Why is this? I believe heap insertion is O(logn) while unsorted list insertion is O(1). I also noticed that my heap insertion implementation doesn't actually scale with the number of inputs. This also confuses me.

Here is the code that I ran:

int main ()
{
    clock_t unsortedStart;
    clock_t heapStart;

    double unsortedDuration;
    double heapDuration;

    int num_pushes = 100000000;
    int interval = 10000;

    ofstream unsorted ("unsorted.txt");
    ofstream heap ("heap.txt");

    UnsortedPQ<int> unsortedPQ;
    HeapPQ<int> heapPQ;

    unsortedStart = clock();

    for (int i = 0; i < num_pushes; ++i)
    {
        if (i % interval == 0) {
            unsortedDuration = ( clock() - unsortedStart ) / (double) CLOCKS_PER_SEC;
            unsorted << unsortedDuration << " " << i << endl;
        }

        unsortedPQ.insertItem(rand() % 100);
    }

    heapStart = clock();
    for (int i = 0; i < num_pushes; ++i)
    {
        if (i % interval == 0) {
            heapDuration = ( clock() - heapStart ) / (double) CLOCKS_PER_SEC;
            heap << heapDuration << " " << i << endl;
        }
        heapPQ.insertItem(rand() % 100);
    }
    return 0;
}

This is the heap implementation of insert (uses std::vector):

template <class T>
void HeapPQ<T>::insertItem(T data) {
    //insert into back of heap (std::vector)
    dataArray.push_back(data);
    int i = dataArray.size() - 1;

    //sifts the inserted element up
    while (i != 0 && dataArray[(i - 1) / 2] > dataArray[i]) {
        swap(dataArray[i], dataArray[(i - 1) / 2]);
        i = (i - 1) / 2;
    }
}

This is the unsorted list implementation of insert (uses std::list):

//pushes element to the back of a std::list
template <class T>
void UnsortedPQ<T>::insertItem(T data) { dataList.push_back(data); }

Body:
The insertion into the heap is O(logn), that mean every insertion could take at most O(logn) steps. It does not mean it has to.

In your example average cost of inserting an element is O(1). Why that?

For simplicity, let's assume you insert only 0a and 1s in a random order (in your current version only numbers 0..99 (rand() % 100) are inserted - the calculation is more complex, but the behavior stays the same). After 2*n elements are inserted, there would be about n 0s and n 1s in the heap,  and the heap would look as follows:

                                 0
                                0 0
                               00 00
                          ...............
                         0 0 0  0  0  0  0
                       11 11 11 11 11 11 11

So basically, 1s are all at the last level k and 0s are at levels 0..k-1.

if 1 is inserted, there is nothing to do (there are no 2s above).

if 0 is inserted there is at most one swap (1s may be in the level above the last level, but 2 levels above).

That meas in average we need only 0.5 swaps and not k.

Having the same asymptotic running time, it is all down to the (amortized) costs for inserting in a vector and in a list. The list seems to be slower (my assumption would be, that for every insert it needs to allocate an element on the heap via new and this is a quite slow operation. The costs depend on other factors, e.g. the size of the inserted objects, and thus it may vary which one is faster).

Let's take a closer look at your case, where the numbers are generated by a uniform dstribution [0..99]. After n>>100 insertions we will have the following situation (there is some hand-waving involved, but the gist should be clear):

the last level (k-th) of the heap has n/2 elements and consists of numbers 50..99. So for 50% of possible numbers (i.e. 50..99) no shift is needed.

the second last level (k-1-th)  of the heap has n/4 elements and consists of numbers 25..49. That means for 25% of possible numbers exactly 1 shift is needed.

the level k-2  has n/8 elements and consists of numbers 13..24.

The levels above log 100/log 2 have only 0s inside. So the maximal number of shifts possible is m=log 100/log 2, independent of n - the number of elements in the heap.

So worst case costs for the insertion would be log 100/log 2, the average costs are even smaller:

E(insertion)=0*1/2+1*1/4+2*1/8+...<=1.0

i.e. on average we have less than 1 shift per insertion.

NB: It does not mean, that inserting in the heap has amortized costs of O(1) - if you would insert the numbers not in random order, but first all 99s, then 98s, ..., then 0s you would have costs of O(log n) per insertion.


答:
In case of an extending the list, you need to access the dict key and append to the existing list:

```<code>def add_name(db, name, gender, year, count, rank=None):
    if (db, name) in db:
        db[(name, gender)].append((year, count, rank))
    else:
        db.update({(name, gender): [(year, count, rank)]})
</code>```

This will check if the item exists in the db, and append if it does.
Bye the way, why do you return None? You don't have to return something from the function

Title: How do I extend the values of a specific dictionary item with overlapping keys?

Body:
In case of an extending the list, you need to access the dict key and append to the existing list:

def add_name(db, name, gender, year, count, rank=None):
    if (db, name) in db:
        db[(name, gender)].append((year, count, rank))
    else:
        db.update({(name, gender): [(year, count, rank)]})

This will check if the item exists in the db, and append if it does.
Bye the way, why do you return None? You don't have to return something from the function


答:
You can use setdefault:

```<code>def add_name(db, name, gender, year, count, rank=None):
    db.setdefault((name, gender), []).append((year, count, rank))
    return None
</code>```

or use a defaultdict to begin with:

```<code>from collections import defaultdict
db = defaultdict(list)

def add_name(db, name, gender, year, count, rank=None):
    db[(name, gender)].append((year, count, rank))
    return None
</code>```

Body:
You can use setdefault:

def add_name(db, name, gender, year, count, rank=None):
    db.setdefault((name, gender), []).append((year, count, rank))
    return None

or use a defaultdict to begin with:

from collections import defaultdict
db = defaultdict(list)

def add_name(db, name, gender, year, count, rank=None):
    db[(name, gender)].append((year, count, rank))
    return None


问:
get value off sent and received local area connection
hi guys i have a some problem about getting value received and sent in local area connection

I want get this value

i have code like this

```<code>public static void DisplayDnsConfiguration()
    {
        NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
        foreach (NetworkInterface adapter in adapters)
        {
            IPInterfaceProperties properties = adapter.GetIPProperties();
            Console.WriteLine(adapter.Description);
            Console.WriteLine("  DNS suffix .............................. : {0}",
                properties.DnsSuffix);
            Console.WriteLine("  DNS enabled ............................. : {0}",
                properties.IsDnsEnabled);
            Console.WriteLine("  Dynamically configured DNS .............. : {0}",
                properties.IsDynamicDnsEnabled);
        }
        Console.WriteLine();
    }
</code>```

and my question is, how can i get that value using this code, because many people sugest me to use NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();

please help me i don't know what i have to do next

and sory for my bad english

答:
You can use performance counters as stated in this stackoverflow answer.

Code:

private static void ShowNetworkTraffic() {
  PerformanceCounterCategory performanceCounterCategory = new PerformanceCounterCategory("Network Interface");
  string instance = performanceCounterCategory.GetInstanceNames()[0]; // 1st NIC !
  PerformanceCounter performanceCounterSent = new PerformanceCounter("Network Interface", "Bytes Sent/sec", instance);
  PerformanceCounter performanceCounterReceived = new PerformanceCounter("Network Interface", "Bytes Received/sec", instance);

  for (int i = 0; i < 10; i++) {
    Console.WriteLine("bytes sent: {0}k\tbytes received: {1}k", performanceCounterSent.NextValue() / 1024, performanceCounterReceived.NextValue() / 1024);
    Thread.Sleep(500);
  }
}```

Body:
hi guys i have a some problem about getting value received and sent in local area connection

I want get this value

i have code like this

public static void DisplayDnsConfiguration()
    {
        NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
        foreach (NetworkInterface adapter in adapters)
        {
            IPInterfaceProperties properties = adapter.GetIPProperties();
            Console.WriteLine(adapter.Description);
            Console.WriteLine("  DNS suffix .............................. : {0}",
                properties.DnsSuffix);
            Console.WriteLine("  DNS enabled ............................. : {0}",
                properties.IsDnsEnabled);
            Console.WriteLine("  Dynamically configured DNS .............. : {0}",
                properties.IsDynamicDnsEnabled);
        }
        Console.WriteLine();
    }

and my question is, how can i get that value using this code, because many people sugest me to use NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();

please help me i don't know what i have to do next

and sory for my bad english


问:
spring data JPA(Hibernate) Projections
I am using Spring Boot with Spring Data JPA. In many places in my query, I am using Projections since I don't want all columns to be fetched from DB.

Projections are interface based like :

```<code>public interface VeryBasicProjection {
    String getTitle();
    String getUrl();
}
</code>```

So my question is whether it actually fetches just two columns or it fetches all columns and then just set these two columns in projections?

答:
Spring Data tries it's best to just select those parts that are actually used.

In your case, it actually should just select the two values using a custom SQL statement.

If your interface contains a collection this does not work (without a rather complex query logic), so Spring Data falls back on selecting the complete entity and extracting the values required for the projection. Or at least it will once this issue is merged.

You can always verify this behavior by checking the generated SQL in the logs.

Title: spring data JPA(Hibernate) Projections

Body:
I am using Spring Boot with Spring Data JPA. In many places in my query, I am using Projections since I don't want all columns to be fetched from DB.

Projections are interface based like :

public interface VeryBasicProjection {
    String getTitle();
    String getUrl();
}

So my question is whether it actually fetches just two columns or it fetches all columns and then just set these two columns in projections?


问:
Can I create a service that plugs directly to my controller or maybe component
I may be wrong, but I was under the impression that I could access my service and have it display the data directly.

I.e. I can inject my service and have read/write access to it from multiple components, Its easy enough to do, but if I want the services data to be displayed, I need to copy it to the controller to let $scope/vm/this to then hook it into the HTML template. but that means any changes that happen at the DOM level, need to be watched/triggered to tell the service that it changed, Which I'd like to be automatic.

I'm essentially trying to save time asking if it can be done, Its something I've been curious about, has anyone set it up before and got it working? Would you be so kind as to elaborate?

答:
At this case, you can create service as you always do, but then assign it to $rootScope property(for example service) at run method, so you can use it via service.name or service.test literals at your templates without restrictions, because all $scopes are inherited from $rootScope. Also you not need to inject service to your particular controller, you can use it at once via template:

var app = angular.module('app', []);

app.factory('myservice', function(){
  return {
    test: function(){
      console.log(this.name);
    },
    name: 'Tom'
  };
}).controller('ctrl', function($scope, myservice){
  $scope.local = 'from local ctrl';
  $scope.serviceName = function(){
    return myservice.name;
  }
})

app.run(function(myservice, $rootScope){
  $rootScope.service = myservice;
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app='app' ng-controller='ctrl'>
  <input type='text' ng-model='service.name'/>
  {{serviceName()}}
  <br>
  <input type='button' ng-click='service.test()' value='service.test'/>
  <br>
  <br>
  <input type='text' ng-model='local'/>
<div></code>```

Body:
At this case, you can create service as you always do, but then assign it to $rootScope property(for example service) at run method, so you can use it via service.name or service.test literals at your templates without restrictions, because all $scopes are inherited from $rootScope. Also you not need to inject service to your particular controller, you can use it at once via template:

var app = angular.module('app', []);

app.factory('myservice', function(){
  return {
    test: function(){
      console.log(this.name);
    },
    name: 'Tom'
  };
}).controller('ctrl', function($scope, myservice){
  $scope.local = 'from local ctrl';
  $scope.serviceName = function(){
    return myservice.name;
  }
})

app.run(function(myservice, $rootScope){
  $rootScope.service = myservice;
})

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app='app' ng-controller='ctrl'>
  <input type='text' ng-model='service.name'/>
  {{serviceName()}}
  <br>
  <input type='button' ng-click='service.test()' value='service.test'/>
  <br>
  <br>
  <input type='text' ng-model='local'/>
<div>


问:
As it is referenced in the xpath to a one more view tag
I'm using scrapy framework and I can not load the other data from my analyzed webpage, it has a tag to see more. Could you tell me what you could do about it, thank you.

import scrapy
from scrapy.spiders import CrawlSpider,Rule
from scrapy.linkextractors import LinkExtractor
from prueba1.items import Prueba1Item
from scrapy.exceptions import CloseSpider

class PruebaSpider(CrawlSpider):
    name = 'prueba1'
    item_count = 0
    allowed_domain = ['http://www.abc.com.py/']
    start_urls = ['http://www.abc.com.py/buscar/?buscar=Santiago+Pe%C3%B1a'
    'http://www.abc.com.py/buscar/?buscar=Santi+Pe%C3%B1a',
    'http://www.abc.com.py/buscar/?buscar=santiago+pe%C3%B1a',
    'http://www.abc.com.py/buscar/?buscar=santi+pe%C3%B1a']

    rules = {

    Rule(LinkExtractor(allow =(),canonicalize = True, unique =
    True,restrict_xpaths=('//html/body/div/a[@id="load-more"]'))),
    Rule(LinkExtractor(allow =(),canonicalize = True, unique =
    True,restrict_xpaths=('//div[@class="article"]')),
    callback = 'parse_item', follow=True)
    }

    def parse_item(self, response):
        ml_item=Prueba1Item()

        ml_item['article'] = response.xpath('normalize-space(//h1)').extract()
        ml_item['fecha'] = response.xpath('normalize-
        space(//small)').extract()
       ml_item['contenido'] = response.xpath('normalize-
       space(//p[@class="summary"])').extract()
       ml_item['contenido2'] = response.xpath('normalize-
       space(//div[@class="text"])').extract()
       ml_item['url'] = response.xpath('normalize-
       space(//link/@href)').extract()
       ml_item['comentarioFacebook'] = response.xpath('normalize-
       space(//div[@class="_30o4"]/span/span[@class="_5mdd"])').extract()

       self .item_count += 1
       if self.item_count > 50:
           raise CloseSpider('item_exceeded')
        yield ml_item
```

According to the search results I have more than 4000 results but I can not bring more than 50 with this code.

答:
The contents are loaded dynamically using json in this format:

   {
      "titulo": "Tuma se suma a Marito",
      "copete": "El diputado \u00d3scar Tuma oficializ\u00f3 su respaldo a la candidatura de Mario Abdo Ben\u00edtez a la presidencia, ya que sus reportes indicaron que el candidato de Colorado A\u00f1etet\u00e9 tiene mayor intenci\u00f3n de votos. El 100% de su dirigencia se lo pidi\u00f3, dice. ",
      "publicacion": "09-11-2017 08:00",
      "imagen": "2017\/10\/02\/el-diputado-scar-tuma-inscribio-ayer-las-precandidaturas-de-su-movimiento-tu-asuncion-en-la-junta-de-gobierno--200750000000-1634915.jpg",
      "url": "nacionales\/tuma-se-suma-a-marito-1648202.html",
      "autor": "",
      "hits": "3163",
      "comentarios": "1",
      "corte_url": "https:\/\/s3-sa-east-1.amazonaws.com\/assets.abc.com.py\/2017\/10\/02\/_146_162_1542245.jpg",
      "corte_width": 146,
      "corte_height": 162,
      "autor_nombre": null,
      "autor_url": "http:\/\/www.abc.com.py\/autor\/-.html",
      "total": "4861"
    }
```

Therefore you can get the data in json format directly from the url below without using Xpath or css selector(try open this url in your browser):
http://www.abc.com.py/ajax.php?seccion=busqueda-avanzada&tipo=4&tipoplant=0&buscar=Santiago+Pe%C3%B1a&desde=&hasta=&seccion-noticia=&temas=&begin=0&limit=7&aditional=

I believe it's not difficult to modify the url to get the data you want and put them into your scripts, for example, get 10 items from the second item, just change begin to 2 and limit to 10:

http://www.abc.com.py/ajax.php?seccion=busqueda-avanzada&tipo=4&tipoplant=0&buscar=Santiago+Pe%C3%B1a&desde=&hasta=&seccion-noticia=&temas=&begin=2&limit=10&aditional=

Body:
I'm using scrapy framework and I can not load the other data from my analyzed webpage, it has a tag to see more. Could you tell me what you could do about it, thank you.

import scrapy
from scrapy.spiders import CrawlSpider,Rule
from scrapy.linkextractors import LinkExtractor
from prueba1.items import Prueba1Item
from scrapy.exceptions import CloseSpider

class PruebaSpider(CrawlSpider):
    name = 'prueba1'
    item_count = 0
    allowed_domain = ['http://www.abc.com.py/']
    start_urls = ['http://www.abc.com.py/buscar/?buscar=Santiago+Pe%C3%B1a'
    'http://www.abc.com.py/buscar/?buscar=Santi+Pe%C3%B1a',
    'http://www.abc.com.py/buscar/?buscar=santiago+pe%C3%B1a',
    'http://www.abc.com.py/buscar/?buscar=santi+pe%C3%B1a']

    rules = {

    Rule(LinkExtractor(allow =(),canonicalize = True, unique =
    True,restrict_xpaths=('//html/body/div/a[@id="load-more"]'))),
    Rule(LinkExtractor(allow =(),canonicalize = True, unique =
    True,restrict_xpaths=('//div[@class="article"]')),
    callback = 'parse_item', follow=True)
    }

    def parse_item(self, response):
        ml_item=Prueba1Item()

        ml_item['article'] = response.xpath('normalize-space(//h1)').extract()
        ml_item['fecha'] = response.xpath('normalize-
        space(//small)').extract()
       ml_item['contenido'] = response.xpath('normalize-
       space(//p[@class="summary"])').extract()
       ml_item['contenido2'] = response.xpath('normalize-
       space(//div[@class="text"])').extract()
       ml_item['url'] = response.xpath('normalize-
       space(//link/@href)').extract()
       ml_item['comentarioFacebook'] = response.xpath('normalize-
       space(//div[@class="_30o4"]/span/span[@class="_5mdd"])').extract()

       self .item_count += 1
       if self.item_count > 50:
           raise CloseSpider('item_exceeded')
        yield ml_item

According to the search results I have more than 4000 results but I can not bring more than 50 with this code.

Body:
The contents are loaded dynamically using json in this format:

   {
      "titulo": "Tuma se suma a Marito",
      "copete": "El diputado \u00d3scar Tuma oficializ\u00f3 su respaldo a la candidatura de Mario Abdo Ben\u00edtez a la presidencia, ya que sus reportes indicaron que el candidato de Colorado A\u00f1etet\u00e9 tiene mayor intenci\u00f3n de votos. El 100% de su dirigencia se lo pidi\u00f3, dice. ",
      "publicacion": "09-11-2017 08:00",
      "imagen": "2017\/10\/02\/el-diputado-scar-tuma-inscribio-ayer-las-precandidaturas-de-su-movimiento-tu-asuncion-en-la-junta-de-gobierno--200750000000-1634915.jpg",
      "url": "nacionales\/tuma-se-suma-a-marito-1648202.html",
      "autor": "",
      "hits": "3163",
      "comentarios": "1",
      "corte_url": "https:\/\/s3-sa-east-1.amazonaws.com\/assets.abc.com.py\/2017\/10\/02\/_146_162_1542245.jpg",
      "corte_width": 146,
      "corte_height": 162,
      "autor_nombre": null,
      "autor_url": "http:\/\/www.abc.com.py\/autor\/-.html",
      "total": "4861"
    }

Therefore you can get the data in json format directly from the url below without using Xpath or css selector(try open this url in your browser):
http://www.abc.com.py/ajax.php?seccion=busqueda-avanzada&tipo=4&tipoplant=0&buscar=Santiago+Pe%C3%B1a&desde=&hasta=&seccion-noticia=&temas=&begin=0&limit=7&aditional=

I believe it's not difficult to modify the url to get the data you want and put them into your scripts, for example, get 10 items from the second item, just change begin to 2 and limit to 10:

http://www.abc.com.py/ajax.php?seccion=busqueda-avanzada&tipo=4&tipoplant=0&buscar=Santiago+Pe%C3%B1a&desde=&hasta=&seccion-noticia=&temas=&begin=2&limit=10&aditional=


问:
Color alpha-channel in DataGridView
How do I color a cell in a datagridview with the alpha-channel?
RGB works ok, but when specifying the alpha I get distorted numbers instead. I make this color change in the cellPainting event.

```<code> e.CellStyle.BackColor = Color.FromArgb(120, 255, 0, 0)
</code>```

答:
Well, it's working.  Your screen shot shows the cell in the 3rd row getting different values and getting repainted without the BackColor erasing what was there before.  It's several digits drawn on top of each other, looks like a 4, 5 and 6.  You get more interesting effects by making the DGV smaller so a horizontal scrollbar appears.  Dragging it produces a 'smear' of digits.

This just doesn't work very well, not sure why you want to do this.  You want a good opaque background to draw new values on.  That requires an alpha of 255.

ContentLicense: CC BY-SA 2.5

Title: Color alpha-channel in DataGridView

Body:
How do I color a cell in a datagridview with the alpha-channel?
RGB works ok, but when specifying the alpha I get distorted numbers instead. I make this color change in the cellPainting event.

 e.CellStyle.BackColor = Color.FromArgb(120, 255, 0, 0)


问:
Modify keyword not working Drools
I am testing infinite loops using Modify keyword.

But it is not re triggering the rule.

Rule 1:

```<code>rule "Entitle for promotion"

when
$i: EmployeeFinancialFact(rating==Rating.ONE.getRating())
then
  PromotionFact $promotion=new PromotionFact($i.getEmpID(),$i.getEmpName());
  insert($promotion);
end
</code>```

Rule 2:

```<code>rule "Print EmployeeFinancialFact name entitled for promotion"

when
$p:  PromotionFact()
then
modify($p) {setSentForApproval(true);}
end
</code>```

I am expecting RHS of rule 2 will re-trigger the rule 2 again but it is getting fired only once.

Can anyone please tell me the reason.

答:
The first obvious question would be if you are sure your rules are indeed getting executed (sounds like a silly question, but it has solved many many issues here in SO).

Some other relevant questions are:

which version of Drools are you using?

Is PromotionFact a java class? or a defined declaration in your DRL?

Do you know if Property Reactive is enabled in your kbase? It used to be disabled in versions < 7, but since version 7 is enabled by default.

Hope it helps,

Title: Modify keyword not working Drools

Body:
I am testing infinite loops using Modify keyword.

But it is not re triggering the rule.

Rule 1:

rule "Entitle for promotion"

when
$i: EmployeeFinancialFact(rating==Rating.ONE.getRating())
then
  PromotionFact $promotion=new PromotionFact($i.getEmpID(),$i.getEmpName());
  insert($promotion);
end

Rule 2:

rule "Print EmployeeFinancialFact name entitled for promotion"

when
$p:  PromotionFact()
then
modify($p) {setSentForApproval(true);}
end

I am expecting RHS of rule 2 will re-trigger the rule 2 again but it is getting fired only once.

Can anyone please tell me the reason.


问:
Profile doesn't include certificate
Using Xcode 9.1, after building an iOS app, I try to archive it.
But I get the following error message:

Provisioning profile "MyAppProfile" doesn't include signing
  certificate "iPhone Developer: My Name (X1YZ2AB3CD)".

What is the simplest way to solve this?

答:
Try enabling automatic signing. It will take care these things mostly.
The reason for this error is you may have chosen a developer certificate(which the provisioning profile doesn't intended to use with) for distributing/release build.</p>

ContentLicense: CC BY-SA 4.0

Title: Profile doesn't include certificate


问:
Pipes within components from shared module
I have been building myself an application in NG and run across a problem using a pipe in a component, from a shared module.

Shared Module (cut all the other stuff out):

```<code>import { NgModule } from '@angular/core';
import { FilterByPipe, OrderByPipe } from './pipes/index';

@NgModule({
    imports: [],
    declarations: [FilterByPipe],

    exports: [
        //Pipes
        FilterByPipe,
    ],

    providers: [FilterByPipe]

})
export class SharedModule { }
</code>```

My question, how can I use the exported pipe FilterByPipe from within another components code? i.e.

```<code>export class ViewSomethingComponent implements OnInit {
    constructor(private _filterBy: FilterByPipe)

    filterSomething(data){ this._filterBy.transform(data,{a:'value'})}
}
</code>```

I have tried importing the pipe directly, but that gives me dependency issues as its not provided from the parent module. Besides adding the pip to the parent module, and then using it as a provider for dependency injection, is there no other way to use a pipe exported by a shared component?

答:
Import SharedModule to your root AppModule.

Then you can easily use your FilterByPipe in any component within AppModule.

```<code>import { FilterByPipe } from '@angular/common';
class FilterByPipe {
  constructor(private fillterPipe: FilterByPipe) {}
  transformData(data) {
    this.fillterPipe.transform(data);
  }
}
</code>```

And add following, or you will get an error

```<code>providers: [FilterByPipe]
</code>```

Body:
I have been building myself an application in NG and run across a problem using a pipe in a component, from a shared module.

Shared Module (cut all the other stuff out):

import { NgModule } from '@angular/core';
import { FilterByPipe, OrderByPipe } from './pipes/index';

@NgModule({
    imports: [],
    declarations: [FilterByPipe],

    exports: [
        //Pipes
        FilterByPipe,
    ],

    providers: [FilterByPipe]

})
export class SharedModule { }

My question, how can I use the exported pipe FilterByPipe from within another components code? i.e.

export class ViewSomethingComponent implements OnInit {
    constructor(private _filterBy: FilterByPipe)

    filterSomething(data){ this._filterBy.transform(data,{a:'value'})}
}

I have tried importing the pipe directly, but that gives me dependency issues as its not provided from the parent module. Besides adding the pip to the parent module, and then using it as a provider for dependency injection, is there no other way to use a pipe exported by a shared component?

Body:
Import SharedModule to your root AppModule.

Then you can easily use your FilterByPipe in any component within AppModule.

import { FilterByPipe } from '@angular/common';
class FilterByPipe {
  constructor(private fillterPipe: FilterByPipe) {}
  transformData(data) {
    this.fillterPipe.transform(data);
  }
}

And add following, or you will get an error

providers: [FilterByPipe]


问:
Web-scraping HTML, javascript is not being executed, therefore missing pieces of HTML. How do I execute all script tags to edit the DOM?
I am using Selenium to try and get the HTML doc nested in all iframe tags. I am able to get the HTML within the iframe but there are  tags that I believe are not being executed, leaving me without all the source code I want. Is there a way to get the HTML execute the javascript and then work with the new HTML after the javascript has run?

Code:

```<code>from bs4 import BeautifulSoup
import requests
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
import time

browser = webdriver.Chrome('C:/Users/G/chromedriver.exe')

browser.get("http://www.reddit.com")

time.sleep(1)

innerHTML = browser.execute_script("return document.body.innerHTML")

time.sleep(1)

iframes = browser.find_elements_by_tag_name("iframe")

time.sleep(1)

for iframe in iframes:

    browser.switch_to_default_content()
    browser.switch_to_frame(iframe)

    source = browser.page_source

    time.sleep(1)

    print(source)
</code>```

答:
If I have understood your Question correctly you are trying to get the innerHTML nested within all  tags, so first we need to switch_to_frame first and Selenium can only switch_to_frame if the frame is visible. To achieve that you can use the following code block :

```<code>iframes = driver.find_elements_by_tag_name("iframe")
for iframe in iframes:
    WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it("iframe"))
    print(driver.page_source)
    driver.switch_to_default_content()
</code>```

Body:
I am using Selenium to try and get the HTML doc nested in all iframe tags. I am able to get the HTML within the iframe but there are  tags that I believe are not being executed, leaving me without all the source code I want. Is there a way to get the HTML execute the javascript and then work with the new HTML after the javascript has run?

Code:

from bs4 import BeautifulSoup
import requests
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
import time

browser = webdriver.Chrome('C:/Users/G/chromedriver.exe')

browser.get("http://www.reddit.com")

time.sleep(1)

innerHTML = browser.execute_script("return document.body.innerHTML")

time.sleep(1)

iframes = browser.find_elements_by_tag_name("iframe")

time.sleep(1)

for iframe in iframes:

    browser.switch_to_default_content()
    browser.switch_to_frame(iframe)

    source = browser.page_source

    time.sleep(1)

    print(source)

Body:
If I have understood your Question correctly you are trying to get the innerHTML nested within all <iframe> tags, so first we need to switch_to_frame first and Selenium can only switch_to_frame if the frame is visible. To achieve that you can use the following code block :

iframes = driver.find_elements_by_tag_name("iframe")
for iframe in iframes:
    WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it("iframe"))
    print(driver.page_source)
    driver.switch_to_default_content()


问:
Is it possible to receive an SMS from Android emulator?
I was wondering if there is a way to receive an SMS from Android emulator, perhaps on a TCP port.
I know it's possible to send SMS to emulator by opening a TCP socket on the emulator port and using "send sms" command, but is it also possible to receive an SMS this way?

I'll elaborate - I have a java application running on a Tomcat server. I also have an Android emulator running on the same machine. I can send SMS messages from the application to the emulator using the "sms send" command. Can I also receive SMS messages in some way?

答:
Friend, refer to this answer provided in a blog (with additional info from authentication token does not match ~/.emulator_console_auth_token)

Just connect the emulator using telnet and there we can emulate SMS. Below are the steps to emulate SMS:

Step 1: Start the emulator (with any desired options). Open a new terminal / command shell and type :

```<code>adb devices
</code>```

Note the number after emulator (emulator-5554). This is the port number.

Step 2: Connect to the console using the telnet command:

```<code>telnet localhost 5554
</code>```

Step 3: You will then need to authenticate the session. Find the auth_token in ~/.emulator_console_auth_token and copy the text in the file. Return to the telnet console and enter:

```<code>auth {contents_of_token_file}
</code>```

Step 4: After you have authenticated the shell you can emulate SMS with the command:

```<code>sms send <phonesender> <textmessage>
</code>```

For More Info Refer to this link

If you send SMS from the emulator, see this http://mobiforge.com/developing/story/sms-messaging-android

Body:
Friend, refer to this answer provided in a blog (with additional info from authentication token does not match ~/.emulator_console_auth_token)

Just connect the emulator using telnet and there we can emulate SMS. Below are the steps to emulate SMS:

Step 1: Start the emulator (with any desired options). Open a new terminal / command shell and type :

adb devices

Note the number after emulator (emulator-5554). This is the port number.

Step 2: Connect to the console using the telnet command:

telnet localhost 5554

Step 3: You will then need to authenticate the session. Find the auth_token in ~/.emulator_console_auth_token and copy the text in the file. Return to the telnet console and enter:

auth {contents_of_token_file}

Step 4: After you have authenticated the shell you can emulate SMS with the command:

sms send <phonesender> <textmessage>

For More Info Refer to this link

If you send SMS from the emulator, see this http://mobiforge.com/developing/story/sms-messaging-android