问:
Java script, PHP
I have a scenario where I need to execute a logout function in php, this function deletes the user from DB and informs another application through sockets. This function should be called when the user closes the browser or tab. I have tried various scenarios posted by others and nothing seems to work in chrome(Version 57.0.2987.110) and firefox.
Following is the examples I tried along with links,
My sample Code

```<code><script type="text/javascript">
var str = 'delete';// this will be set to 'Apply' if the form is submitted.
function logout(){
    location.href = 'Logout.php';
}
function pageHidden(evt){
    if (str==='delete')
        logout();
}

    window.addEventListener("pagehide", pageHidden, false);
    </script >
</code>```

Examples I tried....

```<code>// 1st approach
//window.addEventListener("beforeunload", function (e) {
///   var confirmationMessage = "Do you want to leave?";

//    (e || window.event).returnValue = confirmationMessage;
    //  return confirmationMessage;
//  });

// 2nd approach
     //  window.onbeforeunload = myUnloadEvent;
     // function myUnloadEvent() {
     //     console.log("Do your actions in here")
     //  }
// 3rd approach

$(window).on('beforeunload', function() {
  return 'Your own message goes here...';
});
</code>```

checked the following urls
1. window.onunload is not working properly in Chrome browser. Can any one help me?
2. https://webkit.org/blog/516/webkit-page-cache-ii-the-unload-event/ - I followed this approach. Tried some other approaches as well.
3. I can't trigger the unload event in Chrome etc....

Any help is much appreciated, because if the user closes the browser an entry remains in the DB and this is not allowing any new user to login.

答:
The correct way to logout is related to how they are logged in.

In PHP, the login state is typically managed by sessions. By default the timeout is 24 minutes of inactivity, but you can easily reduce it.

When a user logs out, you typically reset one or more session variables, and, while you’re at it, kill off the current session, and delete the session cookie.

However, you cannot rely on a user to log out, and many typically just wander off. This is why there is always a relatively short timeout on sessions.

If you want to automatically logout when the tab is closed, you will need JavaScript to intercept the process with window.onbeforeunload and then use Ajax to send the logout to the server.

As regards the database, you normally do not record the login state in the database. You may record the login time, and if you like, the logout time, but remember that may be never.

Title: Java script, PHP

Body:
I have a scenario where I need to execute a logout function in php, this function deletes the user from DB and informs another application through sockets. This function should be called when the user closes the browser or tab. I have tried various scenarios posted by others and nothing seems to work in chrome(Version 57.0.2987.110) and firefox.
Following is the examples I tried along with links,
My sample Code

Examples I tried....

// 1st approach
//window.addEventListener("beforeunload", function (e) {
///   var confirmationMessage = "Do you want to leave?";

//    (e || window.event).returnValue = confirmationMessage;
    //  return confirmationMessage;
//  });

// 2nd approach
     //  window.onbeforeunload = myUnloadEvent;
     // function myUnloadEvent() {
     //     console.log("Do your actions in here")
     //  }
// 3rd approach

$(window).on('beforeunload', function() {
  return 'Your own message goes here...';
});

checked the following urls
1. window.onunload is not working properly in Chrome browser. Can any one help me?
2. https://webkit.org/blog/516/webkit-page-cache-ii-the-unload-event/ - I followed this approach. Tried some other approaches as well.
3. I can't trigger the unload event in Chrome etc....

Any help is much appreciated, because if the user closes the browser an entry remains in the DB and this is not allowing any new user to login.


来源: stackexchange

问:
Find item page in PagingAndSortingRepository in Spring Data JPA
I am using the PagingAndSortingRepository in a classic bean to fetch a list of object.

```<code>Specfication s = ...
Pageable p = ..
return repository.findAll(s, p);
</code>```

Is there a way to find out directly what page will be a given item using a given Pageable and Sort object, or have I to compute it myself ?

Thanks.

答:
Is there a way to find out directly what page will be a given item using a given Pageable and Sort object, or have I to compute it myself?

You'll have to do that yourself. I wouldn't even know how to do that except iterating over all elements that come before the one you are looking for.

ContentLicense: CC BY-SA 3.0

Body:
I am using the PagingAndSortingRepository in a classic bean to fetch a list of object.

Specfication s = ...
Pageable p = ..
return repository.findAll(s, p);

Is there a way to find out directly what page will be a given item using a given Pageable and Sort object, or have I to compute it myself ?

Thanks.


问:
Unable to insert the data in Android SQlite Database

I am unable to insert the records in Android Sqlite database,
  exception thrown is shown below :

```<code>07-28 14:22:08.781: E/Database(403): Error inserting id=1 phone_number=999000 name=John
07-28 14:22:08.781: E/Database(403): android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed
07-28 14:22:08.781: E/Database(403):    at android.database.sqlite.SQLiteStatement.native_execute(Native Method)
07-28 14:22:08.781: E/Database(403):    at android.database.sqlite.SQLiteStatement.execute(SQLiteStatement.java:61)
07-28 14:22:08.781: E/Database(403):    at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1582)
07-28 14:22:08.781: E/Database(403):    at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1426)
07-28 14:22:08.781: E/Database(403):    at com.example.dbtest.DBHelper.insertContact(DBHelper.java:47)
07-28 14:22:08.781: E/Database(403):    at com.example.dbtest.MainActivity.onCreate(MainActivity.java:22)
07-28 14:22:08.781: E/Database(403):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
07-28 14:22:08.781: E/Database(403):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
07-28 14:22:08.781: E/Database(403):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
07-28 14:22:08.781: E/Database(403):    at android.app.ActivityThread.access$1500(ActivityThread.java:117)
07-28 14:22:08.781: E/Database(403):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
07-28 14:22:08.781: E/Database(403):    at android.os.Handler.dispatchMessage(Handler.java:99)
07-28 14:22:08.781: E/Database(403):    at android.os.Looper.loop(Looper.java:123)
07-28 14:22:08.781: E/Database(403):    at android.app.ActivityThread.main(ActivityThread.java:3683)
07-28 14:22:08.781: E/Database(403):    at java.lang.reflect.Method.invokeNative(Native Method)
07-28 14:22:08.781: E/Database(403):    at java.lang.reflect.Method.invoke(Method.java:507)
07-28 14:22:08.781: E/Database(403):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
07-28 14:22:08.781: E/Database(403):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
07-28 14:22:08.781: E/Database(403):    at dalvik.system.NativeStart.main(Native Method)
07-28 14:22:08.781: D/ContactsMaster ::(403): inserted
</code>```

insertQuery function are listed below :

```<code>public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_NAME + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT," + KEY_PH_NO + " TEXT" + ")";
        db.execSQL(CREATE_CONTACTS_TABLE);
    }

public void insertContact(){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();

        values.put(KEY_ID, "1");
        values.put(KEY_NAME, "Rajan");
        values.put(KEY_PH_NO, "9990008973");

        db.insert(TABLE_NAME, null, values);
        db.close();
    }
</code>```

The code when executed return exception. Database is created successfully but i am not able to insert the records into it.

答:
becuase when SQLite try to insert by ID if record ID has been exist take Error.

Try to use some solution:

New Function By No ID Argument and Add AutoIncrement into id

Add Auto Increment: KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,

Remove: values.put(KEY_ID, "1");

New Function By Last ID to insert
see this

Body:
I am unable to insert the records in Android Sqlite database,
  exception thrown is shown below :

07-28 14:22:08.781: E/Database(403): Error inserting id=1 phone_number=999000 name=John
07-28 14:22:08.781: E/Database(403): android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed
07-28 14:22:08.781: E/Database(403):    at android.database.sqlite.SQLiteStatement.native_execute(Native Method)
07-28 14:22:08.781: E/Database(403):    at android.database.sqlite.SQLiteStatement.execute(SQLiteStatement.java:61)
07-28 14:22:08.781: E/Database(403):    at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1582)
07-28 14:22:08.781: E/Database(403):    at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1426)
07-28 14:22:08.781: E/Database(403):    at com.example.dbtest.DBHelper.insertContact(DBHelper.java:47)
07-28 14:22:08.781: E/Database(403):    at com.example.dbtest.MainActivity.onCreate(MainActivity.java:22)
07-28 14:22:08.781: E/Database(403):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
07-28 14:22:08.781: E/Database(403):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
07-28 14:22:08.781: E/Database(403):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
07-28 14:22:08.781: E/Database(403):    at android.app.ActivityThread.access$1500(ActivityThread.java:117)
07-28 14:22:08.781: E/Database(403):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
07-28 14:22:08.781: E/Database(403):    at android.os.Handler.dispatchMessage(Handler.java:99)
07-28 14:22:08.781: E/Database(403):    at android.os.Looper.loop(Looper.java:123)
07-28 14:22:08.781: E/Database(403):    at android.app.ActivityThread.main(ActivityThread.java:3683)
07-28 14:22:08.781: E/Database(403):    at java.lang.reflect.Method.invokeNative(Native Method)
07-28 14:22:08.781: E/Database(403):    at java.lang.reflect.Method.invoke(Method.java:507)
07-28 14:22:08.781: E/Database(403):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
07-28 14:22:08.781: E/Database(403):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
07-28 14:22:08.781: E/Database(403):    at dalvik.system.NativeStart.main(Native Method)
07-28 14:22:08.781: D/ContactsMaster ::(403): inserted

insertQuery function are listed below :

public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_NAME + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT," + KEY_PH_NO + " TEXT" + ")";
        db.execSQL(CREATE_CONTACTS_TABLE);
    }

public void insertContact(){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();

        values.put(KEY_ID, "1");
        values.put(KEY_NAME, "Rajan");
        values.put(KEY_PH_NO, "9990008973");

        db.insert(TABLE_NAME, null, values);
        db.close();
    }

The code when executed return exception. Database is created successfully but i am not able to insert the records into it.


问:
Get folder next to parent folder in either Path.GetDirectory or Server.MapPath
Consider the two paths, one in a solution and the other in IIS:

Solution Path:

C:\Users\userid\Desktop\File\Solution\RootName\ Folder1 \Folder1a\the.aspx

IIS path

C:\inetpub\wwwroot\RootName\webApplication\ Folder1 \Folder1a\the.aspx

Is there a way using Directory or Server or anything at all to get the FIRST folder name after the Parent Directory?

ie in the given above, Folder1 is the first folder after the parent folder.

I can get the opposite, which is the containing folder name from a filepath (in this example, Folder1a) and I can iterate it to get to the answer :

Path.GetFileName(Path.GetDirectoryName(file));

But the problem is, folders can be nested at any amount: (folder1a\folder1a1\folder1a1a...)

How can I get the first folder name after the Parent Directory given a file path?

as an aside,
If there is no foldername (ex. Folder1 does not exist) the answer should output "" (empty)

答:
Use .. to go to previous directory, example:

```<code>C:\test\..\
</code>```

is equivalent to:

```<code>C:\
</code>```

Use Directory.GetDirectories to find sub Directories. It has an overload where you can pass search patterns as well:

```<code>string[] GetDirectories(string path, string searchPattern)
</code>```

searchPattern
      Type: System.String

The search string to match against the names of subdirectories in path.
  This parameter can contain a combination of valid literal and
  wildcard characters (see Remarks), but doesn't support regular
  expressions.

Body:
Use .. to go to previous directory, example:

C:\test\..\

is equivalent to:

C:\

Use Directory.GetDirectories to find sub Directories. It has an overload where you can pass search patterns as well:

string[] GetDirectories(string path, string searchPattern)

searchPattern
      Type: System.String

The search string to match against the names of subdirectories in path.
  This parameter can contain a combination of valid literal and
  wildcard characters (see Remarks), but doesn't support regular
  expressions.


问:
Right to left number input
I want to create an input where numbers are input from right to left but the text is aligned right.  I played with the dir attribute and text-align but have had no luck so far.

Here's a jsfiddle.

```<code><input type="number" dir="rtl">
</code>```

答:
Here is the fiddle.
https://jsfiddle.net/pbgjtgm8/

Use both direction and text-align properties.

```<code><input class="right" type="number">
    .right {
        direction: rtl;
        unicode-bidi: bidi-override;
        text-align: left;
    }
</code>```

Title: Right to left number input

Body:
I want to create an input where numbers are input from right to left but the text is aligned right.  I played with the dir attribute and text-align but have had no luck so far.

Here's a jsfiddle.

<input type="number" dir="rtl">

Body:
Here is the fiddle.
https://jsfiddle.net/pbgjtgm8/

Use both direction and text-align properties.

<input class="right" type="number">
    .right {
        direction: rtl;
        unicode-bidi: bidi-override;
        text-align: left;
    }


问:
Reason to take more loading time of asp.net page and how to reduce it
I have the following queries regarding the loading time of asp.net page.
Anyone can help.
What are the possibilities of asp.net page consuming more loading time?.
How to reduce the loading time of asp.net web page?</p>

答:
Five possibilities I can think of (aside from some advanced caching techniques and such):

Improper sizing of the web server for ASP.NET (i.e. thought a server sized for classic ASP would be fine)

Forgetting to remove  from the web.config and getting less than optimal code.

JIT for the first visit

Code embedded in the page (as opposed to the compiled code-behind) that requires compilation before and in addition to the JIT.

ViewState (for ASP.NET WebForms) gets too big.
Hope it will help


问:
MarkLogic-no data reflected in View
I am very new to MarkLogic and still exploring its various capabilities. I have ingested a sample csv file using MLCP and can see the each of the rows stored as a document. I then successfully created a view on this data, so that I could create reports in Tableau. However the view seems to be empty and I cant figure out why. Any inputs would be appreciated - so thanks in advance.

The curl command used to create the view is as below:

```<code>curl -X POST  --anyauth --user admin:admin --header "Content-Type:application/json"
-d '
{
     "view-name": "view_sales",
     "element-scope":{"namespace-uri":"", "localname":"sales"},
     "column": [
       {
         "column-name": "Country",
         "element-reference": {
            "namespace-uri": "",
            "localname": "Country",
            "scalar-type": "string"
         }
       },
       { "column-name": "Product",
         "element-reference": {
            "namespace-uri": "",
            "localname": "Product",
            "scalar-type": "string"
         }
       },
       {
         "column-name": "Fiscal_Year",
         "element-reference": {
            "namespace-uri": "",
            "localname": "Fiscal_Year",
            "scalar-type": "int"
         }
    },
       {
         "column-name": "Total_Rev",
         "element-reference": {
            "namespace-uri": "",
            "localname": "Total_Rev",
            "scalar-type": "decimal"         }
       }
     ]
   }'
http://192.168.44.12:8002/manage/v2/databases/Sales/view-schemas/Schema_Sales/views?format=json
</code>```

答: Found the issue. I had defined the element scope incorrectly. Once I rectified that, I was able to view the data!</p>

Title: MarkLogic-no data reflected in View

Body:
I am very new to MarkLogic and still exploring its various capabilities. I have ingested a sample csv file using MLCP and can see the each of the rows stored as a document. I then successfully created a view on this data, so that I could create reports in Tableau. However the view seems to be empty and I cant figure out why. Any inputs would be appreciated - so thanks in advance.

The curl command used to create the view is as below:

curl -X POST  --anyauth --user admin:admin --header "Content-Type:application/json"
-d '
{
     "view-name": "view_sales",
     "element-scope":{"namespace-uri":"", "localname":"sales"},
     "column": [
       {
         "column-name": "Country",
         "element-reference": {
            "namespace-uri": "",
            "localname": "Country",
            "scalar-type": "string"
         }
       },
       { "column-name": "Product",
         "element-reference": {
            "namespace-uri": "",
            "localname": "Product",
            "scalar-type": "string"
         }
       },
       {
         "column-name": "Fiscal_Year",
         "element-reference": {
            "namespace-uri": "",
            "localname": "Fiscal_Year",
            "scalar-type": "int"
         }
    },
       {
         "column-name": "Total_Rev",
         "element-reference": {
            "namespace-uri": "",
            "localname": "Total_Rev",
            "scalar-type": "decimal"         }
       }
     ]
   }'
http://192.168.44.12:8002/manage/v2/databases/Sales/view-schemas/Schema_Sales/views?format=json


问:
Javascript slideshow that changes background img of an element
trying to make a slideshow that utilizes background-image: property. Here is what I have so far.

```<code><div id="headerContent">
        <div id="rightArrow"></div><!-- end of rightArrow-->
        <div id="leftArrow"></div><!-- end of leftArrow-->
    </div><!-- end of headerContent-->

document.getElementById("headerContent").setAttribute('style', 'background:url(images/home-header-1.png) no-repeat !important');

document.getElementById("rightArrow").addEventListener("click", changeImageRight);

function changeImageRight () {
    var i = 0;

    if(i == 0) {
        document.getElementById("headerContent").setAttribute('style', 'background:url(images/home-header-1.png) no-repeat !important');
        i++;
    }
    else if (i == 1)
     {
        document.getElementById("headerContent").setAttribute('style', 'background:url(images/home-header-2.png) no-repeat !important');
        i++;
    }
    else if (i == 2) {
        document.getElementById("headerContent").setAttribute('style', 'background:url(images/home-header-3.png) no-repeat !important');
        i++;
    }
    else {
        document.getElementById("headerContent").setAttribute('style', 'background:url(images/home-header-1.png) no-repeat !important');
        i++;
    }

}
</code>```

as you can see I increment i++ to change the background image. However, as it stands this doesn't do anything, and no image is displayed. And I included the !important attribute because it's the only way I can get the placeholder img to show at the start.

答:
The issue is that you are declaring the index variable i inside your changeImageRight method. Meaning that each time the method is called, i always starts out as set to 0.

You want to have the value of i persist between each call to changeImageRight. To do so, just declare the variable outside the function. You can do so by moving the line var i = 0; above the line with function changeImageRight () {

Body:
trying to make a slideshow that utilizes background-image: property. Here is what I have so far.

document.getElementById("headerContent").setAttribute('style', 'background:url(images/home-header-1.png) no-repeat !important');

document.getElementById("rightArrow").addEventListener("click", changeImageRight);

function changeImageRight () {
    var i = 0;

    if(i == 0) {
        document.getElementById("headerContent").setAttribute('style', 'background:url(images/home-header-1.png) no-repeat !important');
        i++;
    }
    else if (i == 1)
     {
        document.getElementById("headerContent").setAttribute('style', 'background:url(images/home-header-2.png) no-repeat !important');
        i++;
    }
    else if (i == 2) {
        document.getElementById("headerContent").setAttribute('style', 'background:url(images/home-header-3.png) no-repeat !important');
        i++;
    }
    else {
        document.getElementById("headerContent").setAttribute('style', 'background:url(images/home-header-1.png) no-repeat !important');
        i++;
    }

}

as you can see I increment i++ to change the background image. However, as it stands this doesn't do anything, and no image is displayed. And I included the !important attribute because it's the only way I can get the placeholder img to show at the start.


问:
Angular bootstrap modal is resetting the child views
I am new to angular and have a situation where we have nested views and one of the view has link(s) to open a modal

But the issue is that when the modal opens up one of the views in the background is getting reset..dont know why and how can we resolve it?

[Plnkr][1] :
http://embed.plnkr.co/dliyNd5EaobgkFNA8Xxg/

will really appriciate the help..

so the issue if if we open child1 on the page and then click on open modal it actually clears the child 1 view

答:
You have defined a home.modal1 state, and trying to redirect to it by ui-sref in view2.html. As it didn't have a template to show, so you will see a blank page which looks like the child views are resetted.

I have add a template for home.modal1 state with your plunker to help you confirm that.

You can change the ui-sref to ng-click and define a function in view2.html controller which calls the $modal.open to open the modal.


问:
scala reflection
I want to create a hashmap to store parameters names and their values. The parameters however are with different types. I could use HashMap[String, Any], but I wouldn't know which types they are later on.  Is there anyway I can recovery the type information? Or is there any better way to store  pair?</p>

答:
Do you want access to the static type information, or the dynamic type information?  If you're after the former, you can use typed keys. Something along these lines should work:

```<code>final class Key[T]

object Registry {
   private var backingMap: Map[Key[_], _] = Map.empty

   def put[T](k: Key[T], v: T) = backingMap += (k -> v)

   def get[T](k: Key[T]): Option[T] = backingMap get k map (_.asInstanceOf[T])
}

scala> val strKey = new Key[String]
strKey: Key[String] = Key@31028a

scala> val intKey = new Key[Int]
intKey: Key[Int] = Key@7ae77ca4

scala> Registry.put(strKey, "asdf")

scala> Registry.get(strKey)
res0: Option[String] = Some(asdf)

scala> Registry.put(intKey, "asdf")
<console>:10: error: type mismatch;
 found   : Key[Int]
 required: Key[Any]
       Registry.put(intKey, "asdf")
</code>```

Alternately, you can use untyped keys and store the type information in the Map using manifests (as Daniel suggested):

```<code>class Registry[K] {
   import scala.reflect.Manifest

   private var _map= Map.empty[K,(Manifest[_], Any)]

   def put[T](key: K, item: T)(implicit m: Manifest[T]) {
      _map += (key -> (m, item))
   }

   def get[T](key:K)(implicit m : Manifest[T]): Option[T] = {
      for ((om, v) <- _map get key if om <:< m)
         yield v.asInstanceOf[T]
   }
}
</code>```

The latter approach has the advantage that you can use anything as a key, and you don't have to pass the original typed key objects around.  However, it has the drawback that you must specify the value type when you call the get method. If you specify the wrong type you'll get None just as if the key is not in the Registry at all, whereas with typed keys you're guaranteed to get any value associated with a key.

ContentLicense: CC BY-SA 2.5

Title: scala reflection

Body:
Do you want access to the static type information, or the dynamic type information?  If you're after the former, you can use typed keys. Something along these lines should work:

final class Key[T]

object Registry {
   private var backingMap: Map[Key[_], _] = Map.empty

   def put[T](k: Key[T], v: T) = backingMap += (k -> v)

   def get[T](k: Key[T]): Option[T] = backingMap get k map (_.asInstanceOf[T])
}

scala> val strKey = new Key[String]
strKey: Key[String] = Key@31028a

scala> val intKey = new Key[Int]
intKey: Key[Int] = Key@7ae77ca4

scala> Registry.put(strKey, "asdf")

scala> Registry.get(strKey)
res0: Option[String] = Some(asdf)

scala> Registry.put(intKey, "asdf")
<console>:10: error: type mismatch;
 found   : Key[Int]
 required: Key[Any]
       Registry.put(intKey, "asdf")

Alternately, you can use untyped keys and store the type information in the Map using manifests (as Daniel suggested):

class Registry[K] {
   import scala.reflect.Manifest

   private var _map= Map.empty[K,(Manifest[_], Any)]

   def put[T](key: K, item: T)(implicit m: Manifest[T]) {
      _map += (key -> (m, item))
   }

   def get[T](key:K)(implicit m : Manifest[T]): Option[T] = {
      for ((om, v) <- _map get key if om <:< m)
         yield v.asInstanceOf[T]
   }
}

The latter approach has the advantage that you can use anything as a key, and you don't have to pass the original typed key objects around.  However, it has the drawback that you must specify the value type when you call the get method. If you specify the wrong type you'll get None just as if the key is not in the Registry at all, whereas with typed keys you're guaranteed to get any value associated with a key.


答:
Try this:</p>

```<code>string filename = string.Format("{0}{1}", System.AppDomain.CurrentDomain.BaseDirectory, @"Folder1\Folder1a\the.aspx");
</code>```

Title: Get folder next to parent folder in either Path.GetDirectory or Server.MapPath

Body:
Consider the two paths, one in a solution and the other in IIS:

Solution Path:

C:\Users\userid\Desktop\File\Solution\RootName\ Folder1 \Folder1a\the.aspx

IIS path

C:\inetpub\wwwroot\RootName\webApplication\ Folder1 \Folder1a\the.aspx

Is there a way using Directory or Server or anything at all to get the FIRST folder name after the Parent Directory?

ie in the given above, Folder1 is the first folder after the parent folder.

I can get the opposite, which is the containing folder name from a filepath (in this example, Folder1a) and I can iterate it to get to the answer :

Path.GetFileName(Path.GetDirectoryName(file));

But the problem is, folders can be nested at any amount: (folder1a\folder1a1\folder1a1a...)

How can I get the first folder name after the Parent Directory given a file path?

as an aside,
If there is no foldername (ex. Folder1 does not exist) the answer should output "" (empty)

Body:
Try this:

string filename = string.Format("{0}{1}", System.AppDomain.CurrentDomain.BaseDirectory, @"Folder1\Folder1a\the.aspx");


问:
metricbeat unable to send data - write: connection reset by peer
I am trying to send sys metric with metricbeat to my logstash server on SSL.

When I try connecting the server logstash port I can connect but in metricbeat logfile I am getting following error:

```<code>2017-03-10T12:27:22Z ERR Failed to publish events caused by: write tcp [private_ip]:51105->[logstash-public-ip]:5044: write: connection reset by peer

2017-03-10T12:27:22Z INFO Error publishing events (retrying): write tcp [private_ip]:51105->[logstash-public-ip]:5044 write: connection reset by peer
</code>```

There is no SSL related error. client and servers are able to connect and authenticate each other with their names and the SSL certificate. There are issues with read failed for filebeat on elasticsearch site but the method couldn't solve the issue.
Any help would be great

答: There have been a lot of issues with timeouts that caused similar problem for many people. I would suggest increasing the client_inactivity_timeout in logstash config file to a value that could eliminate timeouts problem (like 86400 for 24h, or 0 to disable it totally)

Body:
I am trying to send sys metric with metricbeat to my logstash server on SSL.

When I try connecting the server logstash port I can connect but in metricbeat logfile I am getting following error:

2017-03-10T12:27:22Z ERR Failed to publish events caused by: write tcp [private_ip]:51105->[logstash-public-ip]:5044: write: connection reset by peer

2017-03-10T12:27:22Z INFO Error publishing events (retrying): write tcp [private_ip]:51105->[logstash-public-ip]:5044 write: connection reset by peer

There is no SSL related error. client and servers are able to connect and authenticate each other with their names and the SSL certificate. There are issues with read failed for filebeat on elasticsearch site but the method couldn't solve the issue.
Any help would be great


问:
How can a Windows program temporarily change its time zone?
I've written a function to return the time_t value corresponding to midnight on a given day. When there is no midnight for a given day, it returns the earliest time available; that situation can occur, for example, when Egypt enters daylight-saving time. This year, the time change takes effect at midnight on the night of April 29, so the clock goes directly from 23:59 to 01:00.

Now I'm writing unit tests for this function, and one of the tests should replicate the Egypt scenario. In Unix, I can accomplish it like this:

```<code>putenv("TZ", "Egypt", true);
tzset();
</code>```

After doing that, further calls to localtime behave as if they're in Egypt instead of Minnesota, and my tests pass. Merely setting the environment variable doesn't have any effect on Windows, though. What can I do to make the unit test think it's somewhere else without affecting the rest of the programs running on the system?

答: Please don't call SetTimeZoneInformation - there is no thread or process-specific notion of a time zone in Windows. As others say, the easiest way is to mock out the timezone code - with Pex/Mocks, you can mock out even static methods, which means you can hook the standard .NET Timezone code to replace it with your own. If you're using C/C++, you just need to wire up the code to have the TZ info be mockable.</p>

Body:
I've written a function to return the time_t value corresponding to midnight on a given day. When there is no midnight for a given day, it returns the earliest time available; that situation can occur, for example, when Egypt enters daylight-saving time. This year, the time change takes effect at midnight on the night of April 29, so the clock goes directly from 23:59 to 01:00.

Now I'm writing unit tests for this function, and one of the tests should replicate the Egypt scenario. In Unix, I can accomplish it like this:

putenv("TZ", "Egypt", true);
tzset();

After doing that, further calls to localtime behave as if they're in Egypt instead of Minnesota, and my tests pass. Merely setting the environment variable doesn't have any effect on Windows, though. What can I do to make the unit test think it's somewhere else without affecting the rest of the programs running on the system?


问:
how to hide cc , bcc in mail box form initially
I have developed a mail box form where i want to hide cc , bcc option initially. cc, bcc will when i click on their option.
I am not able to do this.

<form class="inbox-compose form-horizontal" id="fileupload" action="#" method="POST" enctype="multipart/form-data">

        <button class="btn green">
            Send</button>
        <button class="btn default inbox-discard-btn">Discard</button>
        <button class="btn default">Draft</button>

        To:

            <input type="text" class="form-control" name="to">

                 Cc
                 Bcc

        Cc:

            <input type="text" name="cc" class="form-control">

        Bcc:

            <input type="text" name="bcc" class="form-control">

        Subject:

            <input type="text" class="form-control" name="subject">

        <textarea class="inbox-editor inbox-wysihtml5 form-control" name="message" rows="12"></textarea>```

Please help me to make my form better

答:
You can use the hide class to hide sections that you would like to hide initially.

HTML

```<code><form class="inbox-compose form-horizontal" id="fileupload" action="#" method="POST" enctype="multipart/form-data">
    <div class="inbox-compose-btn">
        <button class="btn green">
            <i class="fa fa-check"></i>Send</button>
        <button class="btn default inbox-discard-btn">Discard</button>
        <button class="btn default">Draft</button>
    </div>
    <div class="inbox-form-group mail-to">
        <label class="control-label">To:</label>
        <div class="controls controls-to">
            <input type="text" class="form-control" name="to">
            <span class="inbox-cc-bcc">
              <span class="inbox-cc" style="cursor: pointer;cursor: hand;"> Cc </span>
                <span class="inbox-bcc" style="cursor: pointer;cursor: hand;"> Bcc </span>
            </span>
        </div>
    </div>
    <div id="divCC" class="inbox-form-group input-cc display-hide hide">

        <label class="control-label">Cc:</label>
        <div class="controls controls-cc">
            <input type="text" name="cc" class="form-control"> </div>
    </div>
    <div id="divBCC" class="inbox-form-group input-bcc display-hide hide">

        <label class="control-label">Bcc:</label>
        <div class="controls controls-bcc">
            <input type="text" name="bcc" class="form-control"> </div>
    </div>
    <div class="inbox-form-group">
        <label class="control-label">Subject:</label>
        <div class="controls">
            <input type="text" class="form-control" name="subject"> </div>
    </div>
    <div class="inbox-form-group">
    <textarea class="inbox-editor inbox-wysihtml5 form-control" name="message" rows="12"></textarea></div>

    <div id="push"></div>
</form>
</code>```

jQuery

```<code> $('.inbox-bcc').click(function(){
     console.log('bcc');
     $('#divBCC').toggleClass('hide');
 });
});
</code>```

Here is a working fiddle: http://www.codeply.com/go/iPH6UVoHkc

Hope this helps!

Body:
I have developed a mail box form where i want to hide cc , bcc option initially. cc, bcc will when i click on their option.
I am not able to do this.

<form class="inbox-compose form-horizontal" id="fileupload" action="#" method="POST" enctype="multipart/form-data">

        <button class="btn green">
            Send</button>
        <button class="btn default inbox-discard-btn">Discard</button>
        <button class="btn default">Draft</button>

        To:

            <input type="text" class="form-control" name="to">

                 Cc
                 Bcc

        Cc:

            <input type="text" name="cc" class="form-control">

        Bcc:

            <input type="text" name="bcc" class="form-control">

        Subject:

            <input type="text" class="form-control" name="subject">

        <textarea class="inbox-editor inbox-wysihtml5 form-control" name="message" rows="12"></textarea>

Please help me to make my form better

Body:
You can use the hide class to hide sections that you would like to hide initially.

HTML

<form class="inbox-compose form-horizontal" id="fileupload" action="#" method="POST" enctype="multipart/form-data">
    <div class="inbox-compose-btn">
        <button class="btn green">
            <i class="fa fa-check"></i>Send</button>
        <button class="btn default inbox-discard-btn">Discard</button>
        <button class="btn default">Draft</button>
    </div>
    <div class="inbox-form-group mail-to">
        <label class="control-label">To:</label>
        <div class="controls controls-to">
            <input type="text" class="form-control" name="to">
            <span class="inbox-cc-bcc">
              <span class="inbox-cc" style="cursor: pointer;cursor: hand;"> Cc </span>
                <span class="inbox-bcc" style="cursor: pointer;cursor: hand;"> Bcc </span>
            </span>
        </div>
    </div>
    <div id="divCC" class="inbox-form-group input-cc display-hide hide">

        <label class="control-label">Cc:</label>
        <div class="controls controls-cc">
            <input type="text" name="cc" class="form-control"> </div>
    </div>
    <div id="divBCC" class="inbox-form-group input-bcc display-hide hide">

        <label class="control-label">Bcc:</label>
        <div class="controls controls-bcc">
            <input type="text" name="bcc" class="form-control"> </div>
    </div>
    <div class="inbox-form-group">
        <label class="control-label">Subject:</label>
        <div class="controls">
            <input type="text" class="form-control" name="subject"> </div>
    </div>
    <div class="inbox-form-group">
    <textarea class="inbox-editor inbox-wysihtml5 form-control" name="message" rows="12"></textarea></div>

    <div id="push"></div>
</form>

jQuery

 $('.inbox-bcc').click(function(){
     console.log('bcc');
     $('#divBCC').toggleClass('hide');
 });
});

Here is a working fiddle: http://www.codeply.com/go/iPH6UVoHkc

Hope this helps!


问:
How to generate time based UUIDs?
I want to generate time-based universally unique identifier (UUID) in Java.

The method java.util.UUID.randomUUID() generates a UUID Version 4 where 122 of the 128 bits are from a cryptographically-strong random number generator.

How to generate a Version 1 (time based) UUID ? Is there a separate library for that or is it some how provided in the Java 7 API and I am missing it.

答:
```<code>String timeuuid = com.datastax.driver.core.utils.UUIDs.timeBased().toString();
</code>```

have a look at
https://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/utils/UUIDs.html

ContentLicense: CC BY-SA 4.0

Title: How to generate time based UUIDs?

Body:
String timeuuid = com.datastax.driver.core.utils.UUIDs.timeBased().toString();

have a look at
https://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/utils/UUIDs.html


问:
Codeigniter : how to update mulitiple record where id
I have been looking for ways but find suitable speckle. so, i have table product and I show along with his ID. and I put in a form. and when I press the update button then what had been updated in the form of their corresponding id.

my view :

```<code><?php echo form_open('stock/updating_stock');?>
  <div class="panel-body scroll-menu" style="margin-top:0px;height:170px;padding-top:5px;">
    <?php foreach($critical_plus_warning as $data){?>
      <input type="hidden" name="id_product[]" value="<?php echo $data->id_product;?>">
      <h5 class="hidden-xs"><b><?php echo $data->product_name;?></b> <input type="text" class="pull-right" style="width:10%;margin-left:10px;text-align:center;" name="update_stock[]" value="<?php echo $data->stock?>">
      <?php
      $stock = $data->stocks;
      if($stock < 10){
        echo "<label style='font-size:13px;' class='label label-danger pull-right'>$stock</label>";
      }else{
        echo "<label style='font-size:13px;' class='label label-warning pull-right'>$stock</label>";
      }
      ?>
      </h5>
      <h5 class="hidden-lg"><b><?php $limited_word = word_limiter($data->product_name,3); echo $limited_word; ?></b> <input class="pull-right" type="text" style="width:10%;margin-left:10px;text-align:center;" name="update_stock[]" value="<?php echo $data->stocks?>">
      <?php
      $stock = $data->stocks;
      if($stock < 10){
        echo "<label style='font-size:13px;' class='label label-danger pull-right'>$stock</label>";
      }else{
        echo "<label style='font-size:13px;' class='label label-warning pull-right'>$stock</label>";
      }
      ?>
      </h5>
    <?php }?>
  </div>
  <div class="col-xs-12" style="margin-top:-5px;background-color:white;padding:6px;background-color:white;box-shadow:0px 0px 8px 0px #bababa;"><button type="submit" name="submit" class="btn btn-success">Save data</button></div>
  <?php echo form_close();?>
</code>```

and my controller :

```<code>function updating_stock(){

    $id = $this->input->post('id_product');
    $stok = $this->input->post('update_stock');
    $user = $this->data['id'];

    for($i=0;$i<count($id);$i++){
    $data = array(
       array(
        'id'        => $id,
        'stok'      => $stok,
        'diubah'    => $user,
        'tgl_diubah'=> date('Y:m:d H:i:s'),
        ),
    );
    }
    //print_r($data);
    $this->stok_adm->update_stok($data);
}
</code>```

and my models :

```<code>function update_stok($data){
    $this->db->update_batch($this->table, $data,'id_product');
    return $this->db->affected_rows();
}
</code>```

答:
Try this:

Controller

```<code>function updating_stock(){

$id = $this->input->post('id_product');
$stok = $this->input->post('update_stock');
$user = $this->data['id'];

for($i=0;$i<count($id);$i++){
$data = array(
   array(
    'id'        => $id,
    'stok'      => $stok,
    'diubah'    => $user,
    'tgl_diubah'=> date('Y:m:d H:i:s'),
    ),
);
}
//print_r($data);
$this->stok_adm->update_stok($data,$id);
</code>```

}

Model:

```<code>function update_stok($data,$id){
$this->db->update_batch($this->table, $data,'id_product');
return $this->db->affected_rows();
</code>```

}

Body:
I have been looking for ways but find suitable speckle. so, i have table product and I show along with his ID. and I put in a form. and when I press the update button then what had been updated in the form of their corresponding id.

my view :

<?php echo form_open('stock/updating_stock');?>

    <?php foreach($critical_plus_warning as $data){?>
      <input type="hidden" name="id_product[]" value="<?php echo $data->id_product;?>">

<?php echo $data->product_name;?> <input type="text" class="pull-right" style="width:10%;margin-left:10px;text-align:center;" name="update_stock[]" value="<?php echo $data->stock?>">
      <?php
      $stock = $data->stocks;
      if($stock < 10){
        echo "$stock";
      }else{
        echo "$stock";
      }
      ?>

<?php $limited_word = word_limiter($data->product_name,3); echo $limited_word; ?> <input class="pull-right" type="text" style="width:10%;margin-left:10px;text-align:center;" name="update_stock[]" value="<?php echo $data->stocks?>">
      <?php
      $stock = $data->stocks;
      if($stock < 10){
        echo "$stock";
      }else{
        echo "$stock";
      }
      ?>

    <?php }?>

<button type="submit" name="submit" class="btn btn-success">Save data</button>

  <?php echo form_close();?>

and my controller :

function updating_stock(){

    $id = $this->input->post('id_product');
    $stok = $this->input->post('update_stock');
    $user = $this->data['id'];

    for($i=0;$i<count($id);$i++){
    $data = array(
       array(
        'id'        => $id,
        'stok'      => $stok,
        'diubah'    => $user,
        'tgl_diubah'=> date('Y:m:d H:i:s'),
        ),
    );
    }
    //print_r($data);
    $this->stok_adm->update_stok($data);
}

and my models :

function update_stok($data){
    $this->db->update_batch($this->table, $data,'id_product');
    return $this->db->affected_rows();
}

Body:
Try this:

Controller

function updating_stock(){

$id = $this->input->post('id_product');
$stok = $this->input->post('update_stock');
$user = $this->data['id'];

for($i=0;$i<count($id);$i++){
$data = array(
   array(
    'id'        => $id,
    'stok'      => $stok,
    'diubah'    => $user,
    'tgl_diubah'=> date('Y:m:d H:i:s'),
    ),
);
}
//print_r($data);
$this->stok_adm->update_stok($data,$id);

}

Model:

function update_stok($data,$id){
$this->db->update_batch($this->table, $data,'id_product');
return $this->db->affected_rows();

}


问:
Android : How to write camera intent in android nougat
In my android application I have to take images using the camera when a button is clicked. It is working perfectly in all Android versions except Android 7 (Nougat). When I choose the camera option, the app is exiting even if the permissions are granted. I think the problem is in the camera-calling Intent. Below is my code.

```<code>camera = (ImageView) dialog.findViewById(R.id.camera);

camera.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        clickCamera();
        dialog.dismiss();
    }
});

private void clickCamera() { // 1 for icon and 2 for attachment
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(MainActivity.this, new String[] { Manifest.permission.CAMERA }, MY_REQUEST_CODE);
    } else {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, MY_REQUEST_CODE_STORAGE);
        } else {
            currentImageUri = getImageFileUri();
            Intent intentPicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intentPicture.putExtra(MediaStore.EXTRA_OUTPUT, currentImageUri); // set the image file name
            // start the image capture Intent
            startActivityForResult(intentPicture, REQUEST_CAMERA);  // 1 for REQUEST_CAMERA (icon) and 2 for REQUEST_CAMERA_ATT (attachment)
        }
    }
}

private static Uri getImageFileUri(){
    // Create a storage directory for the images
    // To be safe(r), you should check that the SD card is mounted
    // using Environment.getExternalStorageState() before doing this

    imagePath = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyProject");
    if (!imagePath.exists()) {
        if (!imagePath.mkdirs()) {
            return null;
        } else {
            // create new folder
        }
    }

    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    File image = new File(imagePath, "MyProject_" + timeStamp + ".jpg");

    if (!image.exists()) {
        try {
            image.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // Create an File Uri
    return Uri.fromFile(image);
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_REQUEST_CODE: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // permission was granted, yay! Do the
                // contacts-related task you need to do.
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(MainActivity.this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, MY_REQUEST_CODE_STORAGE);
                } else {
                    currentImageUri = getImageFileUri();
                    Intent intentPicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    intentPicture.putExtra(MediaStore.EXTRA_OUTPUT, currentImageUri); // set the image file name
                    // start the image capture Intent
                    startActivityForResult(intentPicture, REQUEST_CAMERA);
                }
            } else {
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
                Toast.makeText(this, "Doesn't have permission... ", Toast.LENGTH_SHORT).show();
            }
            return;
        }
        case MY_REQUEST_CODE_STORAGE: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                currentImageUri = getImageFileUri();
                Intent intentPicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intentPicture.putExtra(MediaStore.EXTRA_OUTPUT, currentImageUri); // set the image file name
                // start the image capture Intent
                startActivityForResult(intentPicture, REQUEST_CAMERA);
            } else {
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
                Toast.makeText(this, "Doesn't have permission...", Toast.LENGTH_SHORT).show();
            }
            return;
        }
    }
}
</code>```

What is the problem here for Nougat? Is it because of the Uri returned by getImageFileUri()?

答: Use File Provider it will help you</p>

Body:
In my android application I have to take images using the camera when a button is clicked. It is working perfectly in all Android versions except Android 7 (Nougat). When I choose the camera option, the app is exiting even if the permissions are granted. I think the problem is in the camera-calling Intent. Below is my code.

camera = (ImageView) dialog.findViewById(R.id.camera);

camera.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        clickCamera();
        dialog.dismiss();
    }
});

private void clickCamera() { // 1 for icon and 2 for attachment
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(MainActivity.this, new String[] { Manifest.permission.CAMERA }, MY_REQUEST_CODE);
    } else {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, MY_REQUEST_CODE_STORAGE);
        } else {
            currentImageUri = getImageFileUri();
            Intent intentPicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intentPicture.putExtra(MediaStore.EXTRA_OUTPUT, currentImageUri); // set the image file name
            // start the image capture Intent
            startActivityForResult(intentPicture, REQUEST_CAMERA);  // 1 for REQUEST_CAMERA (icon) and 2 for REQUEST_CAMERA_ATT (attachment)
        }
    }
}

private static Uri getImageFileUri(){
    // Create a storage directory for the images
    // To be safe(r), you should check that the SD card is mounted
    // using Environment.getExternalStorageState() before doing this

    imagePath = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyProject");
    if (!imagePath.exists()) {
        if (!imagePath.mkdirs()) {
            return null;
        } else {
            // create new folder
        }
    }

    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    File image = new File(imagePath, "MyProject_" + timeStamp + ".jpg");

    if (!image.exists()) {
        try {
            image.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // Create an File Uri
    return Uri.fromFile(image);
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_REQUEST_CODE: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // permission was granted, yay! Do the
                // contacts-related task you need to do.
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(MainActivity.this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, MY_REQUEST_CODE_STORAGE);
                } else {
                    currentImageUri = getImageFileUri();
                    Intent intentPicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    intentPicture.putExtra(MediaStore.EXTRA_OUTPUT, currentImageUri); // set the image file name
                    // start the image capture Intent
                    startActivityForResult(intentPicture, REQUEST_CAMERA);
                }
            } else {
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
                Toast.makeText(this, "Doesn't have permission... ", Toast.LENGTH_SHORT).show();
            }
            return;
        }
        case MY_REQUEST_CODE_STORAGE: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                currentImageUri = getImageFileUri();
                Intent intentPicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intentPicture.putExtra(MediaStore.EXTRA_OUTPUT, currentImageUri); // set the image file name
                // start the image capture Intent
                startActivityForResult(intentPicture, REQUEST_CAMERA);
            } else {
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
                Toast.makeText(this, "Doesn't have permission...", Toast.LENGTH_SHORT).show();
            }
            return;
        }
    }
}

What is the problem here for Nougat? Is it because of the Uri returned by getImageFileUri()?

Body: Use File Provider it will help you


问:
how to bind checkboxes in ember with a list
I have a model where I have a list of all countries as below -

```<code>[{"code":"US", "name":"USA"}]
</code>```

selected counties will be pass on as a list like below -

```<code>["US", "CA"]
</code>```

my template has a list of checkboxes like below -

```<code>{{#validatable-control label="Countries" error=errors.Countries}}
    {{log "All: "}} {{log model.AllCountries}}
    {{log "Selected: "}} {{log model.Countries}}
    {{#each model.AllCountries as |country|}} {{log "country: "}} {{log country.Code}} {{log country.Name}}
        <label class="checkbox-inline">{{input type="checkbox" checked=(mut (get model.Countries country.Code))}}{{country.Name}}</label>
    {{/each}}
{{/validatable-control}}
</code>```

the code above doesn't work as intended and I am trying to figure out how to configure the checkbox to achieve what I need. Any ideas?

答:
country.Code => replace it with country.code - propertyName is case sensitive.

Introduced isSelected property for every country,

```<code>{{#each model.AllCountries as |country|}}
 <label class="checkbox-inline">
  {{input type="checkbox" checked=(mut (get country 'isSelected'))}}      {{country.name}}
 </label>
{{/each}}
</code>```

I implemented in ember-twiddle, have a look at it.

Body:
I have a model where I have a list of all countries as below -

[{"code":"US", "name":"USA"}]

selected counties will be pass on as a list like below -

["US", "CA"]

my template has a list of checkboxes like below -

{{#validatable-control label="Countries" error=errors.Countries}}
    {{log "All: "}} {{log model.AllCountries}}
    {{log "Selected: "}} {{log model.Countries}}
    {{#each model.AllCountries as |country|}} {{log "country: "}} {{log country.Code}} {{log country.Name}}
        {{input type="checkbox" checked=(mut (get model.Countries country.Code))}}{{country.Name}}
    {{/each}}
{{/validatable-control}}

the code above doesn't work as intended and I am trying to figure out how to configure the checkbox to achieve what I need. Any ideas?

Body:
country.Code => replace it with country.code - propertyName is case sensitive.

Introduced isSelected property for every country,

{{#each model.AllCountries as |country|}}
 <label class="checkbox-inline">
  {{input type="checkbox" checked=(mut (get country 'isSelected'))}}      {{country.name}}
 </label>
{{/each}}

I implemented in ember-twiddle, have a look at it.


问:
C++ Win32 programing. How can I send an array elemens to a listbox?
If I have string(data in this case) I am using sendmessage like this:

```<code>SendMessage(GetDlgItem(hWnd,IDC_LISTBOX),LB_ADDSTRING,0,(LPARAM)data);
</code>```

But how to do it with array of strings or integers?

答: You have to iterate through the array, sending each string individually.  And you have to convert integers to strings before you can send them.</p>

Body:
If I have string(data in this case) I am using sendmessage like this:

SendMessage(GetDlgItem(hWnd,IDC_LISTBOX),LB_ADDSTRING,0,(LPARAM)data);

But how to do it with array of strings or integers?


问:
Android Studio Corrupts Base64 String When Trying To Upload
So I am testing methods to upload an image to a php server. One of the methods was to convert the image to a Base64 String and upload it and then decode it when needed.

When I uploaded a picture I noticed that there was a difference in the Strings. Some spaces were missing and some next lines were misplaced.

Before I sent the string to the server the string is okay and then it goes through a _POST command in the php file and then it is inserted into the database using INSERT INTO.

I suspect that the header that I use changes the string when I try to upload it. the header is /x-www-form-urlencoded. I tried using /json but if the json object is converted to string it changes the original string. So what header do I need to use so the string won't change? Or is there another method to upload a picture to a MySQL database?

This is the method I use to upload the string to the server:

```<code>ImageString = getStringImage(bitmap);
String ImageUploadString="image="+ImageString;
final OkHttpClient client = new OkHttpClient();
MediaType contentType = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");

RequestBody body = RequestBody.create(contentType, imageUploadString));
Request request = new Request.Builder().url(uploadURL).post(body).build();
Response response = null;
try {
    response = client.newCall(request).execute();
} catch (IOException e) {
    e.printStackTrace();
}
try {
    String json = response.body().string();
} catch (IOException e) {
    e.printStackTrace();
}
</code>```

Edit: this is the php file that I use to insert the picture:

```<code><?php
$response = array();
if (isset($_POST['image']))
{
$image = $_POST['image'];
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
$result = $db->query("INSERT INTO images(image) VALUES('$image')");
if ($result) {
$response["success"] = 1;
$response["message"] = "Product successfully created.";
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
echo json_encode($response);
}
} else {
$response["success"] = 0;
$response["message"] = "missing fields";
echo json_encode($response);
}
?>
</code>```

答:
For image uploads you can always go for multipart part upload rather than converting it into base64. If you are using retrofit, the implementation will be easier.

I am adding the php and the android code to do it. I assume you are using httpurlconnection and not retrofit.

PHP

```<code>  <?php
            $target_dir = "uploads/";
            $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
            $uploadOk = 1;
            $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
            // Check if image file is a actual image or fake image
            if(isset($_POST["submit"])) {
                $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
                if($check !== false) {
                    echo "File is an image - " . $check["mime"] . ".";
                    $uploadOk = 1;
                } else {
                    echo "File is not an image.";
                    $uploadOk = 0;
                }
            }
            // Check if file already exists
            if (file_exists($target_file)) {
                echo "Sorry, file already exists.";
                $uploadOk = 0;
            }
            // Check file size
            if ($_FILES["fileToUpload"]["size"] > 500000) {
                echo "Sorry, your file is too large.";
                $uploadOk = 0;
            }
            // Allow certain file formats
            if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
            && $imageFileType != "gif" ) {
                echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
                $uploadOk = 0;
            }
            // Check if $uploadOk is set to 0 by an error
            if ($uploadOk == 0) {
                echo "Sorry, your file was not uploaded.";
            // if everything is ok, try to upload file
            } else {
                if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
                    echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
                } else {
                    echo "Sorry, there was an error uploading your file.";
                }
            }
            ?>
</code>```

Android

```<code>fileInputStream = new FileInputStream(new File(_filePath));

        URL url = new URL(urlServer);
        connection = (HttpURLConnection) url.openConnection();

        // Allow Inputs & Outputs
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        // Enable POST method
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type",
                "multipart/form-data;boundary=" + boundary);
        outputStream = new DataOutputStream(
                connection.getOutputStream());
        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
        outputStream
                .writeBytes("Content-Disposition: form-data; name=\"fileToUpload\";filename=\""
                        + _filePath + "\"" + lineEnd);
        outputStream.writeBytes(lineEnd);

        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        // Read file
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        // int contentLength = bytesAvailable+
        // header.getBytes().length+footer.getBytes().length;

        while (bytesRead > 0) {
            outputStream.write(buffer, 0, bufferSize);

            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        outputStream.writeBytes(lineEnd);
        outputStream.writeBytes(twoHyphens + boundary + twoHyphens
                + lineEnd);
</code>```

I also suggest you to use retrofit as a lot of network handling are done by the library itself.

Body:
So I am testing methods to upload an image to a php server. One of the methods was to convert the image to a Base64 String and upload it and then decode it when needed.

When I uploaded a picture I noticed that there was a difference in the Strings. Some spaces were missing and some next lines were misplaced.

Before I sent the string to the server the string is okay and then it goes through a _POST command in the php file and then it is inserted into the database using INSERT INTO.

I suspect that the header that I use changes the string when I try to upload it. the header is /x-www-form-urlencoded. I tried using /json but if the json object is converted to string it changes the original string. So what header do I need to use so the string won't change? Or is there another method to upload a picture to a MySQL database?

This is the method I use to upload the string to the server:

ImageString = getStringImage(bitmap);
String ImageUploadString="image="+ImageString;
final OkHttpClient client = new OkHttpClient();
MediaType contentType = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");

RequestBody body = RequestBody.create(contentType, imageUploadString));
Request request = new Request.Builder().url(uploadURL).post(body).build();
Response response = null;
try {
    response = client.newCall(request).execute();
} catch (IOException e) {
    e.printStackTrace();
}
try {
    String json = response.body().string();
} catch (IOException e) {
    e.printStackTrace();
}

Edit: this is the php file that I use to insert the picture:

<?php
$response = array();
if (isset($_POST['image']))
{
$image = $_POST['image'];
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
$result = $db->query("INSERT INTO images(image) VALUES('$image')");
if ($result) {
$response["success"] = 1;
$response["message"] = "Product successfully created.";
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
echo json_encode($response);
}
} else {
$response["success"] = 0;
$response["message"] = "missing fields";
echo json_encode($response);
}
?>

Body:
For image uploads you can always go for multipart part upload rather than converting it into base64. If you are using retrofit, the implementation will be easier.

I am adding the php and the android code to do it. I assume you are using httpurlconnection and not retrofit.

PHP

  <?php
            $target_dir = "uploads/";
            $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
            $uploadOk = 1;
            $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
            // Check if image file is a actual image or fake image
            if(isset($_POST["submit"])) {
                $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
                if($check !== false) {
                    echo "File is an image - " . $check["mime"] . ".";
                    $uploadOk = 1;
                } else {
                    echo "File is not an image.";
                    $uploadOk = 0;
                }
            }
            // Check if file already exists
            if (file_exists($target_file)) {
                echo "Sorry, file already exists.";
                $uploadOk = 0;
            }
            // Check file size
            if ($_FILES["fileToUpload"]["size"] > 500000) {
                echo "Sorry, your file is too large.";
                $uploadOk = 0;
            }
            // Allow certain file formats
            if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
            && $imageFileType != "gif" ) {
                echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
                $uploadOk = 0;
            }
            // Check if $uploadOk is set to 0 by an error
            if ($uploadOk == 0) {
                echo "Sorry, your file was not uploaded.";
            // if everything is ok, try to upload file
            } else {
                if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
                    echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
                } else {
                    echo "Sorry, there was an error uploading your file.";
                }
            }
            ?>

Android

fileInputStream = new FileInputStream(new File(_filePath));

        URL url = new URL(urlServer);
        connection = (HttpURLConnection) url.openConnection();

        // Allow Inputs & Outputs
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        // Enable POST method
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type",
                "multipart/form-data;boundary=" + boundary);
        outputStream = new DataOutputStream(
                connection.getOutputStream());
        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
        outputStream
                .writeBytes("Content-Disposition: form-data; name=\"fileToUpload\";filename=\""
                        + _filePath + "\"" + lineEnd);
        outputStream.writeBytes(lineEnd);

        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        // Read file
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        // int contentLength = bytesAvailable+
        // header.getBytes().length+footer.getBytes().length;

        while (bytesRead > 0) {
            outputStream.write(buffer, 0, bufferSize);

            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        outputStream.writeBytes(lineEnd);
        outputStream.writeBytes(twoHyphens + boundary + twoHyphens
                + lineEnd);

I also suggest you to use retrofit as a lot of network handling are done by the library itself.


问:
How to return the correct content-type for JSON in CakePHP?
I'm trying to set the content-type header for a JSON response accessed with an AJAX GET request. I've followed tutorials on blogs and the bakery but I always receive 'text/html' back from CakePHP. How do I set the content-type header correctly?

Here's my code at the moment:

```<code>public function admin_controller_actions_ajax()
{
    Configure::write('debug', 0);
    if ($this->RequestHandler->isGet()) {
        $this->autoRender = FALSE;

        $aco_id = $this->params['url']['aco_id'];
        $aro_id = $this->params['url']['aro_id'];

        assert('$aco_id != NULL && $aro_id != NULL &&
                is_numeric($aco_id) && is_numeric($aro_id)');

        $actions = $this->Resource->getActionsForController($aco_id, $aro_id);

        assert('is_array($actions) && is_array($actions[0])');

        /* I made RequestHandler part of the $components property */
        $this->RequestHandler->setContent('json');
        $this->RequestHandler->respondAs('json'); /* I've tried 'json', 'JSON', 'application/json' but none of them work */

        $this->set('json_content', json_encode(array('response' => $actions[0])));
        $this->layout = NULL;
        $this->render('/json/default');
    }
}

/* json/default.ctp */
<?php echo $json_content; ?>
</code>```

Any help would be appreciated.

Thanks,

--
Isaac

答:
After reading this and this, I got the following to return "Content-Type:application/json":

```<code>Configure::write('debug', 0);
$this->RequestHandler->respondAs('json');
$this->autoRender = false;
echo json_encode($data);
</code>```

With JQuery's $.getJSON method, I'm still getting

```<code>Resource interpreted as image but transferred with MIME type text/html.
</code>```

But at least my data is parsing.

OwnerDisplayName: Isaac Alston

Body:
I'm trying to set the content-type header for a JSON response accessed with an AJAX GET request. I've followed tutorials on blogs and the bakery but I always receive 'text/html' back from CakePHP. How do I set the content-type header correctly?

Here's my code at the moment:

public function admin_controller_actions_ajax()
{
    Configure::write('debug', 0);
    if ($this->RequestHandler->isGet()) {
        $this->autoRender = FALSE;

        $aco_id = $this->params['url']['aco_id'];
        $aro_id = $this->params['url']['aro_id'];

        assert('$aco_id != NULL && $aro_id != NULL &&
                is_numeric($aco_id) && is_numeric($aro_id)');

        $actions = $this->Resource->getActionsForController($aco_id, $aro_id);

        assert('is_array($actions) && is_array($actions[0])');

        /* I made RequestHandler part of the $components property */
        $this->RequestHandler->setContent('json');
        $this->RequestHandler->respondAs('json'); /* I've tried 'json', 'JSON', 'application/json' but none of them work */

        $this->set('json_content', json_encode(array('response' => $actions[0])));
        $this->layout = NULL;
        $this->render('/json/default');
    }
}

/* json/default.ctp */
<?php echo $json_content; ?>

Any help would be appreciated.

Thanks,

--
Isaac

Body:
After reading this and this, I got the following to return "Content-Type:application/json":

Configure::write('debug', 0);
$this->RequestHandler->respondAs('json');
$this->autoRender = false;
echo json_encode($data);

With JQuery's $.getJSON method, I'm still getting

Resource interpreted as image but transferred with MIME type text/html.

But at least my data is parsing.


问:
Golang code to get all the pod details on my setup
I have a setup where k8s is running. When i run the "curl http://< host-ip>/api/v1/pods" i get all the pod details running on my setup. I need to do something similar using the k8s client instead, using the token/certificate authentication.

I did see some code which is similar "How can I create a simple client app with the Kubernetes Go library?" but this is not helping me much.

答:
It's well know that the official Go client for k8s is a little messy.
I recommend you take a look to this library looks much better:
https://amdatu.org/infra/goclient/gettingstarted/

godocs:
https://godoc.org/bitbucket.org/amdatulabs/amdatu-kubernetes-go/client


问:
Ingest csv file times in BQ
In doing tests with ingesting files directly from GCS to bigquery, we get much better performance over streaming inserts. However, the performance also fluctuates much more,

For example, we tested loading large CSV into BQ (10M rows, 2GB): loaded in 2.275 min the first time but ~ 8 minutes the second time. Why is there such a fluctuation in the import times?

https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load

Update: This turned out to be a change in a threshold value:

Turned out it depends on MaxError property. The time I got CSV imported in 2 min was when MaxError too low and some errors (like too long fields) prevented it for parsing CSV file fully. I have raised MaxError to 1000 since.

Tried couple of times, and it takes 7-8 minutes to complete parsing with this threshold value set.

答: Load is basically a query on federated data sources, with the results saved to the destination table. Performance of a query is dependent on the load of the backend system. Felipe explains this well in BigQuery Performance.</p>

Title: Ingest csv file times in BQ


问:
Guice Request-scoped injection without a servlet (in an RPC server)
For background, I'm processing RPC requests in a Thrift service (though my question isn't Thrift-specific).  What I want seems like it should be simple, but I can find no examples: how do I reuse com.google.inject.servlet.RequestScoped bindings without starting from scratch?

Clearly I could follow the instructions for creating a custom Scope.  But that seems overly complicated.  What I want to do: when processing an incoming (Thrift) RPC, create a new RequestContext for each incoming call; then, use standard RequestScoped injection while processing it.

Basically, it seems my code should look (loosely) like this:

```<code>void main() {
// Configure appropriate bindings, create injector
Injector injector = Guice.createInjector(new ServerHandlerModule());

ThriftServer server = new ThriftServer.ThriftServerBuilder("MyService", port).withThreadCount(threads).build();`
server.start(new MyService.Processor(new MyHandler()));

// For each incoming request, Thrift will call the appropriate method on the (singleton) instance of MyHandler.
// Let's say MyHandler exposes a method void ProcessInput()
}

class MyHandler {

@Override
void ProcessInput(Input myInput) {  // myInput was constructed by Thrift
  // I want the following instance of RequestContext to be injected
  // (provided by Guice) as (say) a constructor arg to any constructor
  // needing one when that construction happens in this thread.
  RequestContext rc = new RequestContext(myInput);
  doWork();
  }
</code>```

答:
Guice provides a utility class for doing just that: ServletScopes.

If you are using Java 7+:

```<code>void ProcessInput(Input myInput) {
    RequestScoper scope = ServletScopes.scopeRequest(Collections.emptyMap());
    try ( RequestScoper.CloseableScope ignored = scope.open() ) {
        doWork();
    }
}
</code>```

Body:
For background, I'm processing RPC requests in a Thrift service (though my question isn't Thrift-specific).  What I want seems like it should be simple, but I can find no examples: how do I reuse com.google.inject.servlet.RequestScoped bindings without starting from scratch?

Clearly I could follow the instructions for creating a custom Scope.  But that seems overly complicated.  What I want to do: when processing an incoming (Thrift) RPC, create a new RequestContext for each incoming call; then, use standard RequestScoped injection while processing it.

Basically, it seems my code should look (loosely) like this:

void main() {
// Configure appropriate bindings, create injector
Injector injector = Guice.createInjector(new ServerHandlerModule());

ThriftServer server = new ThriftServer.ThriftServerBuilder("MyService", port).withThreadCount(threads).build();`
server.start(new MyService.Processor(new MyHandler()));

// For each incoming request, Thrift will call the appropriate method on the (singleton) instance of MyHandler.
// Let's say MyHandler exposes a method void ProcessInput()
}

class MyHandler {

@Override
void ProcessInput(Input myInput) {  // myInput was constructed by Thrift
  // I want the following instance of RequestContext to be injected
  // (provided by Guice) as (say) a constructor arg to any constructor
  // needing one when that construction happens in this thread.
  RequestContext rc = new RequestContext(myInput);
  doWork();
  }

Body:
Guice provides a utility class for doing just that: ServletScopes.

If you are using Java 7+:

void ProcessInput(Input myInput) {
    RequestScoper scope = ServletScopes.scopeRequest(Collections.emptyMap());
    try ( RequestScoper.CloseableScope ignored = scope.open() ) {
        doWork();
    }
}


问:
How to stop Eclipse from trying to run XML files?
I'm mostly using Eclipse for Android development these days, and have developed good muscle memory for Ctrl-F11 to run my app. Problem is, if I happen to be editing an XML file (like manifest or layout) when I hit that key combination, Eclipse does something that I find inscrutable... It attempts to "run" my XML file, creating an erroneous output file (called something like layout.out.xml) that I then have to delete, adding a useless XML launch configuration to my history, and generally being a pain in my butt.

It's no big deal, but it is an ongoing annoyance. Does anyone know how to disable "run" for XML in Eclipse? I've tried to find a config item for it, but Eclipse's options are such a rabbit hole that I haven't had any luck there myself.

Thanks!

答: My solution is uninstall XSL plugin.</p>

Body: My solution is uninstall XSL plugin.


问:
Wrong number of bind variables complication in Ruby
I have a table in which I get all the listings of the table through the Ruby Find Function.

```<code>conditions = [Project.in_used_projects(:alias => "projects") + " AND name LIKE ? test"]
projects = Project.find(:all, :conditions => conditions)
</code>```

But the moment I add "AND name LIKE ? test", I get wrong number of bind variables. The function Project.in_used_projects returns the value: projects.status = 2

I can't just change the Project.in_used_projects to project.status = 2 because the value is different for every project.
The error I get is:

```<code>wrong number of bind variables (0 for 1) in: (projects.status = 2) AND name LIKE ? test
</code>```

I know to bind variables the format needs to be: (Parameter, Parameter, Variable, Variable) but I need it to be (Paramters, Variable, Paramter, Variable)

Any ideas?

答:
It seems to me you do have the wrong number of bind variables. You have 1 question mark, but 0 bind variables. Assuming you are looking for a name with "test" in it somewhere, you need to put "test" as a bind variable, or hard code it, like this (0 bind variables, 0 slots):

```<code>[Project.in_used_projects(:alias => "projects") + " AND name LIKE '%test%'"]
</code>```

Or like this (1 bind variable, 1 slot):

```<code>[Project.in_used_projects(:alias => "projects") + " AND name LIKE ?", '%test%']
</code>```

Body:
I have a table in which I get all the listings of the table through the Ruby Find Function.

conditions = [Project.in_used_projects(:alias => "projects") + " AND name LIKE ? test"]
projects = Project.find(:all, :conditions => conditions)

But the moment I add "AND name LIKE ? test", I get wrong number of bind variables. The function Project.in_used_projects returns the value: projects.status = 2

I can't just change the Project.in_used_projects to project.status = 2 because the value is different for every project.
The error I get is:

wrong number of bind variables (0 for 1) in: (projects.status = 2) AND name LIKE ? test

I know to bind variables the format needs to be: (Parameter, Parameter, Variable, Variable) but I need it to be (Paramters, Variable, Paramter, Variable)

Any ideas?

Body:
It seems to me you do have the wrong number of bind variables. You have 1 question mark, but 0 bind variables. Assuming you are looking for a name with "test" in it somewhere, you need to put "test" as a bind variable, or hard code it, like this (0 bind variables, 0 slots):

[Project.in_used_projects(:alias => "projects") + " AND name LIKE '%test%'"]

Or like this (1 bind variable, 1 slot):

[Project.in_used_projects(:alias => "projects") + " AND name LIKE ?", '%test%']


问:
Drawing a right triangle (Python 3)
I'm having a bit of an issue. I'm trying to make this program output a right triangle based on the height and symbol that is specified by the user, but whenever I enter the symbol and height desired the program will output the correct shape, but upside-down. I've been having some difficulties getting a firm grasp of loops and through trial and error, this is the best I could come up with thus far. Could someone help a brother out, please. Thank yous in advance.

```<code>triangle_char = input('Enter a character:\n')
triangle_height = int(input('Enter triangle height:\n'))
print('')

for i in range (len(triangle_char)):
    for j in range (triangle_height):
        print((triangle_char) * triangle_height )
        triangle_height -= 1
</code>```

This code will return this output when character is '*' and height is 5:

```<code>*****
****
***
**
*
</code>```

The expected output when those values are entered should be:

```<code>*
**
***
****
*****
</code>```

答:
First your loops are both off; you are assigning values to i and j and not using them.

Second, the first loop is useless. If you input 3 characters it will repeat the block 3 times, but the variable triangle_height is decreased to 0 at the first pass, so nothing will be printed at the next iteration.
Just remove this line

Third: You say that you need the triangle reversed, so, instead of decreasing triangle_height, use the value you assing to j in the for loop and forget about decreasing the variable.
Since range starts counting from 0 you need to add 1 to it in the print statement:

```<code>triangle_char = input('Enter a character: ')
triangle_height = int(input('Enter triangle height: '))
print('')

for j in range (triangle_height):
    print((triangle_char) * (j + 1))
</code>```

I have also replaced /n with a space in the input() methods because it looked pretty bad.

Title: Drawing a right triangle (Python 3)

Body:
I'm having a bit of an issue. I'm trying to make this program output a right triangle based on the height and symbol that is specified by the user, but whenever I enter the symbol and height desired the program will output the correct shape, but upside-down. I've been having some difficulties getting a firm grasp of loops and through trial and error, this is the best I could come up with thus far. Could someone help a brother out, please. Thank yous in advance.

triangle_char = input('Enter a character:\n')
triangle_height = int(input('Enter triangle height:\n'))
print('')

for i in range (len(triangle_char)):
    for j in range (triangle_height):
        print((triangle_char) * triangle_height )
        triangle_height -= 1

This code will return this output when character is '*' and height is 5:

*****
****
***
**
*

The expected output when those values are entered should be:

*
**
***
****
*****

Body:
First your loops are both off; you are assigning values to i and j and not using them.

Second, the first loop is useless. If you input 3 characters it will repeat the block 3 times, but the variable triangle_height is decreased to 0 at the first pass, so nothing will be printed at the next iteration.
Just remove this line

Third: You say that you need the triangle reversed, so, instead of decreasing triangle_height, use the value you assing to j in the for loop and forget about decreasing the variable.
Since range starts counting from 0 you need to add 1 to it in the print statement:

triangle_char = input('Enter a character: ')
triangle_height = int(input('Enter triangle height: '))
print('')

for j in range (triangle_height):
    print((triangle_char) * (j + 1))

I have also replaced /n with a space in the input() methods because it looked pretty bad.


问:
How do I change the color of the tab bar for one view controller?
I have a bar tint of white in app delegate for my tab bar, but I need it to be clear on one of the selected indexes. I add the below code to the view controller that needs to be clear, but it stays clear. How do I have it so this only applies to one tab.</p>

```<code>let tabBar = self.tabBarController?.tabBar
tabBar?.barTintColor = UIColor.clear
tabBar?.backgroundImage = UIImage()
tabBar?.shadowImage = UIImage()
</code>```

答:
If you have UITabBarControllerDelegate you can use

```<code>func tabBarController(_ tabBarController: UITabBarController,
                      didSelect viewController: UIViewController) {

    guard let index = self.viewControllers?.index(where: { $0 == viewController }) else {
        return
    }
    if index == 1 {
        self.tabBar.barTintColor = .black
    } else {
        self.tabBar.barTintColor = .yellow
    }
}
</code>```

Im'm checkig by index because i have navigation controller and this is easier for me, you can try to use

```<code>if viewController is MyViewController {
    self.tabBar.barTintColor = .black
} else {
    self.tabBar.barTintColor = .yellow
}
</code>```

Body:
I have a bar tint of white in app delegate for my tab bar, but I need it to be clear on one of the selected indexes. I add the below code to the view controller that needs to be clear, but it stays clear. How do I have it so this only applies to one tab.

let tabBar = self.tabBarController?.tabBar
tabBar?.barTintColor = UIColor.clear
tabBar?.backgroundImage = UIImage()
tabBar?.shadowImage = UIImage()

Body:
If you have UITabBarControllerDelegate you can use

func tabBarController(_ tabBarController: UITabBarController,
                      didSelect viewController: UIViewController) {

    guard let index = self.viewControllers?.index(where: { $0 == viewController }) else {
        return
    }
    if index == 1 {
        self.tabBar.barTintColor = .black
    } else {
        self.tabBar.barTintColor = .yellow
    }
}

Im'm checkig by index because i have navigation controller and this is easier for me, you can try to use

if viewController is MyViewController {
    self.tabBar.barTintColor = .black
} else {
    self.tabBar.barTintColor = .yellow
}


问:
How do I change where `cargo install` places binaries?
I am installing racer, rustfmt & rustsym

cargo install racer
cargo install rustfmt
cargo install rustsym
```

The packages are being installed in C:\Users\<UserName>\.cargo, but I want it to be C:\Rust\.cargo.

答:
The easiest way is via --root:

```<code>cargo install --root C:\Rust.cargo racer
</code>```

CARGO_HOME and others can be set to override this too. Consult the documentation or How can the location of cargo's configuration directory be overridden?.

Body:
I am installing racer, rustfmt & rustsym

cargo install racer
cargo install rustfmt
cargo install rustsym

The packages are being installed in C:\Users\<UserName>\.cargo, but I want it to be C:\Rust\.cargo.

Body:
The easiest way is via --root:

cargo install --root C:\Rust.cargo racer

CARGO_HOME and others can be set to override this too. Consult the documentation or How can the location of cargo's configuration directory be overridden?.


问:
FOSUserBundle ignore password field
So I'm using the FOSUserBundle with LDAP as my authentication method, and I'm wondering whether there is a way to remove/ignore the password field for my FOSUser entity?

I realize removal might not be ideal (in case it messes with internal logic), but the column is never used, and I'm forced to fill it when I'm creating FOSUsers from fixtures:

```<code>$user = new FOSUser();

$user->setDn($item["dn"]);
$user->setEnabled(1);
$user->setUsername($item["samaccountname"][0]);
$user->setUsernameCanonical(strtolower($item["samaccountname"][0]));
$user->setEmail($item["mail"][0]);
$user->setEmailCanonical(strtolower($item["mail"][0]));
$user->setDepartment($ldap_groups[$matches[1]]);
$user->setDepartmentDn($group);
$user->setPassword('blank'); // Is there away to avoid this?

$manager->persist($user);
</code>```

答:
You could actually remove the password, but you have to keep a getPassword() as that is defined in the UserInterface. In case you want to keep it, e.g. when you allow for multiple login types where you will need it again. I recommend setting the field as nullable. If you are using annotations it's as simple as adding nullable=true to the column:

```<code>/**
 * @ORM\Column(type="string", name="password", nullable=true)
 */
</code>```

Title: FOSUserBundle ignore password field

Body:
So I'm using the FOSUserBundle with LDAP as my authentication method, and I'm wondering whether there is a way to remove/ignore the password field for my FOSUser entity?

I realize removal might not be ideal (in case it messes with internal logic), but the column is never used, and I'm forced to fill it when I'm creating FOSUsers from fixtures:

$user = new FOSUser();

$user->setDn($item["dn"]);
$user->setEnabled(1);
$user->setUsername($item["samaccountname"][0]);
$user->setUsernameCanonical(strtolower($item["samaccountname"][0]));
$user->setEmail($item["mail"][0]);
$user->setEmailCanonical(strtolower($item["mail"][0]));
$user->setDepartment($ldap_groups[$matches[1]]);
$user->setDepartmentDn($group);
$user->setPassword('blank'); // Is there away to avoid this?

$manager->persist($user);

Body:
You could actually remove the password, but you have to keep a getPassword() as that is defined in the UserInterface. In case you want to keep it, e.g. when you allow for multiple login types where you will need it again. I recommend setting the field as nullable. If you are using annotations it's as simple as adding nullable=true to the column:

/**
 * @ORM\Column(type="string", name="password", nullable=true)
 */