问:
How to management team for update id, username in field id_team on other table

Summarize the problem

After sign in using the username = user,
I want to update the id_team field in the tb_user table by sending user id = id, username = update to the data.

by sending id user = id, username = user.
From the team management page. But the team management from the tb_team table.
tb_team table has no data, id user = id, username = user.
For use in the update

How to get or keep the session id user = id, username = user for use in conditions, the update, I want advice about this problem.

Provide background including what you've already tried

var saveidUser: String?
saveidUser  = ????   <——  I do not know how to send the  id, username
```

<ol start="3">
<li>Show some code
PHP code:</li>
</ol>

<pre class="lang-php prettyprint-override"><code>//Web Service
if (isset($_GET)) {
    if ($_GET['isAdd'] == 'true') {
        $idTeam = $_GET['idteam'];
        $idUser = $_GET['iduser']
        $User = $_GET['username'];

        UPDATE `tb_user` SET `id_team` = '$idTeam' WHERE `id` = '$iduser' and `username` = '$user'
        $result = mysqli_query($sql) or die mysql_error();
        if ($result) {
          echo $idTeam;
        } else {
          echo "False";
        }
    }
    else echo "Welcome";
}
</code>```

Swift code:

//swift code constant
class Myconstant {
    func findURLSaveidTeam(idTeam: String, idUser: String) -> String {
        let urlGetidTeam = "http://www.test.com/myWebService/updateidTeam.php?isAdd=true&idteam=\(idTeam)&iduser=\(idUser)"
        return urlGetidTeam
    }
}//My Constant

//swift code view controller management team
class getAllTeamViewController: UIViewController {
    var selectValue: String?
    var saveidTeam: String?
    var saveidUser: String?  <— for id, username

    @IBOutlet weak var hiddenidTeamTextField: UITextField!
    @IBOutlet weak var showSelectValuePickerView: UITextField!

    func saveValue(idteam: String, iduser: String ) -> Void {
        let myconstant_idTeam = Myconstant()
        let urlSaveData: String = myconstant_idTeam.findURLSaveidTeam(idTeam: idteam, idUser: iduser)
        print("urlSaveData ==>\(urlSaveData)")
        //Save Value Process
        let url = URL(string: urlSaveData)!
        let request = NSMutableURLRequest(url: url)
        let task = URLSession.shared.dataTask(with: request as URLRequest){ data,response, error in
            //Check nil value
            if error != nil {
                print("Error! Have nil value")
            }else{
                //Receive Value
                if let responseData = data {
                    let canReadData = NSString(data: responseData, encoding: String.Encoding.utf8.rawValue)
                    print("Can Read Data ==> \(String(describing: canReadData))")

                    //Show alert save success or failed upload to database on log panel
                    let myResponse = canReadData
                    if((myResponse) != nil){
                      print("Save Success")
                    }else{
                      print("Cannot Upload")
                    }//if
                }//if
            }//if
        }//End task
        task.resume()
    }//saveValue

    //Save Button
    @IBAction func SavevaluePicker(_ sender: UIButton) {
        selectValue = showSelectValuePickerView.text
        saveidTeam = hiddenidTeamTextField.text
        saveidUser  = ????   <——  I do not know how to send the  id,username

        //Call use function checkSpace
        if(checkSpace(picker: selectValue!)){
            print("Have Space")
        }else{
            print("No Space")
            //Call function Save data to database
            saveValue(idteam: saveidTeam!, iduser: saveidUser!)
        }//if
    }// SavevaluePicker
}//Main Class
```

<ol start="4">
<li>Describe expected and actual results including any error messages
Value from show log panel       </li>
</ol>

```     NameTeam database ==>2 - AvengersEndgame
```

Image team management page

答:
You need to start the session at the time of login success.
after successful login, define a session variable by giving it the value of user id.
and make a check in the start of the page that either session variable is created or not
if the session variable is not created then redirect to login page else redirect to your desired page.

At the time of logout, you need to undefine the session variable.

Body:
Summarize the problem

After sign in using the username = user,
I want to update the id_team field in the tb_user table by sending user id = id, username = update to the data.

by sending id user = id, username = user.
From the team management page. But the team management from the tb_team table.
tb_team table has no data, id user = id, username = user.
For use in the update

How to get or keep the session id user = id, username = user for use in conditions, the update, I want advice about this problem.

Provide background including what you've already tried

var saveidUser: String?
saveidUser  = ????   <——  I do not know how to send the  id, username

Show some code
PHP code:

//Web Service
if (isset($_GET)) {
    if ($_GET['isAdd'] == 'true') {
        $idTeam = $_GET['idteam'];
        $idUser = $_GET['iduser']
        $User = $_GET['username'];

        UPDATE `tb_user` SET `id_team` = '$idTeam' WHERE `id` = '$iduser' and `username` = '$user'
        $result = mysqli_query($sql) or die mysql_error();
        if ($result) {
          echo $idTeam;
        } else {
          echo "False";
        }
    }
    else echo "Welcome";
}

Swift code:

//swift code constant
class Myconstant {
    func findURLSaveidTeam(idTeam: String, idUser: String) -> String {
        let urlGetidTeam = "http://www.test.com/myWebService/updateidTeam.php?isAdd=true&idteam=\(idTeam)&iduser=\(idUser)"
        return urlGetidTeam
    }
}//My Constant

//swift code view controller management team
class getAllTeamViewController: UIViewController {
    var selectValue: String?
    var saveidTeam: String?
    var saveidUser: String?  <— for id, username

    @IBOutlet weak var hiddenidTeamTextField: UITextField!
    @IBOutlet weak var showSelectValuePickerView: UITextField!

    func saveValue(idteam: String, iduser: String ) -> Void {
        let myconstant_idTeam = Myconstant()
        let urlSaveData: String = myconstant_idTeam.findURLSaveidTeam(idTeam: idteam, idUser: iduser)
        print("urlSaveData ==>\(urlSaveData)")
        //Save Value Process
        let url = URL(string: urlSaveData)!
        let request = NSMutableURLRequest(url: url)
        let task = URLSession.shared.dataTask(with: request as URLRequest){ data,response, error in
            //Check nil value
            if error != nil {
                print("Error! Have nil value")
            }else{
                //Receive Value
                if let responseData = data {
                    let canReadData = NSString(data: responseData, encoding: String.Encoding.utf8.rawValue)
                    print("Can Read Data ==> \(String(describing: canReadData))")

                    //Show alert save success or failed upload to database on log panel
                    let myResponse = canReadData
                    if((myResponse) != nil){
                      print("Save Success")
                    }else{
                      print("Cannot Upload")
                    }//if
                }//if
            }//if
        }//End task
        task.resume()
    }//saveValue

    //Save Button
    @IBAction func SavevaluePicker(_ sender: UIButton) {
        selectValue = showSelectValuePickerView.text
        saveidTeam = hiddenidTeamTextField.text
        saveidUser  = ????   <——  I do not know how to send the  id,username

        //Call use function checkSpace
        if(checkSpace(picker: selectValue!)){
            print("Have Space")
        }else{
            print("No Space")
            //Call function Save data to database
            saveValue(idteam: saveidTeam!, iduser: saveidUser!)
        }//if
    }// SavevaluePicker
}//Main Class

Describe expected and actual results including any error messages
Value from show log panel

     NameTeam database ==>2 - AvengersEndgame

Image team management page


来源: stackexchange

问:
firebase deploy --only hosting gives Error: HTTP Error: 410, Unknown Error
this is my log  :

```<code> [info] === Deploying to 'test-123'...
    [info]
    [info] i  deploying hosting
    [info] i  hosting: preparing public directory for upload...
    [debug] [2018-10-25T15:39:54.587Z] >>> HTTP REQUEST PUT https://deploy.firebase.com/v1/hosting/test-123/uploads/-LPfsRseOoTTgVVj-keR?fileCount=81&message=

     Thu Oct 25 2018 21:09:54 GMT+0530 (India Standard Time)
    [debug] [2018-10-25T15:40:00.337Z] <<< HTTP RESPONSE 410
    [debug] [2018-10-25T15:40:00.337Z] <<< HTTP RESPONSE BODY undefined
    [debug] [2018-10-25T15:40:00.339Z] TypeError: Cannot read property 'error' of undefined
        at module.exports (C:\Users\user\AppData\Roaming\npm\node_modules\firebase-tools\lib\responseToError.js:10:13)
        at Request._callback (C:\Users\user\AppData\Roaming\npm\node_modules\firebase-tools\lib\api.js:47:25)
        at Request.self.callback (C:\Users\user\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\request\request.js:186:22)
        at emitTwo (events.js:126:13)
        at Request.emit (events.js:214:7)
        at Request.<anonymous> (C:\Users\user\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\request\request.js:1163:10)
        at emitOne (events.js:116:13)
        at Request.emit (events.js:211:7)
        at IncomingMessage.<anonymous> (C:\Users\user\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\request\request.js:1085:12)
        at Object.onceWrapper (events.js:313:30)
    [error]
    [error] Error: An unexpected error has occurred.
</code>```

till yesterday everything was fine

when i deploy functions one by one or all at the same time everything works fine

please suggest something if someone knows about it

it says HTTPS ERROR 410 which i googled and found out that means the resource has moved

so the url requested might not be working but when i put that in browser its working fine

and i upgraded node, all npm modules still no luck

答:
This worked for me:

Upgrade firebase npm update -g firebase-tools

Log out firebase logout

Log back in firebase login

Deploy firebase deploy

ContentLicense: CC BY-SA 4.0

Body:
this is my log  :

 [info] === Deploying to 'test-123'...
    [info]
    [info] i  deploying hosting
    [info] i  hosting: preparing public directory for upload...
    [debug] [2018-10-25T15:39:54.587Z] >>> HTTP REQUEST PUT https://deploy.firebase.com/v1/hosting/test-123/uploads/-LPfsRseOoTTgVVj-keR?fileCount=81&message=

     Thu Oct 25 2018 21:09:54 GMT+0530 (India Standard Time)
    [debug] [2018-10-25T15:40:00.337Z] <<< HTTP RESPONSE 410
    [debug] [2018-10-25T15:40:00.337Z] <<< HTTP RESPONSE BODY undefined
    [debug] [2018-10-25T15:40:00.339Z] TypeError: Cannot read property 'error' of undefined
        at module.exports (C:\Users\user\AppData\Roaming\npm\node_modules\firebase-tools\lib\responseToError.js:10:13)
        at Request._callback (C:\Users\user\AppData\Roaming\npm\node_modules\firebase-tools\lib\api.js:47:25)
        at Request.self.callback (C:\Users\user\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\request\request.js:186:22)
        at emitTwo (events.js:126:13)
        at Request.emit (events.js:214:7)
        at Request.<anonymous> (C:\Users\user\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\request\request.js:1163:10)
        at emitOne (events.js:116:13)
        at Request.emit (events.js:211:7)
        at IncomingMessage.<anonymous> (C:\Users\user\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\request\request.js:1085:12)
        at Object.onceWrapper (events.js:313:30)
    [error]
    [error] Error: An unexpected error has occurred.

till yesterday everything was fine

when i deploy functions one by one or all at the same time everything works fine

please suggest something if someone knows about it

it says HTTPS ERROR 410 which i googled and found out that means the resource has moved

so the url requested might not be working but when i put that in browser its working fine

and i upgraded node, all npm modules still no luck


问:
Convert a string to list of list of dicts python
I am new to python. I have a string which is taken from my sqlite database. I want to convert the string to a list of list of dicts. I tried ast and json library but it fails.

Here's the string:

```<code>a = '"[[{"plugin_type":"input","plugin":"mysql","dbname":"smackcoders","user":"root","password":"root","tbname":"agg_csv","host":"localhost","id":"mysql1","limit_count":5},{"plugin_type":"filter","plugin":"metrics","input_from":"mysql1","id":"metrics","field_name":"count_result", "field":"state","value":"kerala","action":"count","send_data_immediately":True},{"plugin_type":"output","plugin":"elastic","id":"elastic_search","input_from":"metrics","ind":"neww10","doc_typ":"sm23"}]]"'
</code>```

Here the code i tried:

```<code>import ast
import json
a = '"[[{"plugin_type":"input","plugin":"mysql","dbname":"smackcoders","user":"root","password":"root","tbname":"agg_csv","host":"localhost","id":"mysql1","limit_count":5},{"plugin_type":"filter","plugin":"metrics","input_from":"mysql1","id":"metrics","field_name":"count_result", "field":"state","value":"kerala","action":"count","send_data_immediately":True},{"plugin_type":"output","plugin":"elastic","id":"elastic_search","input_from":"metrics","ind":"neww10","doc_typ":"sm23"}]]"'
a = a.replace("[[","[").replace("]]","]")
print(a)

# using json library- fails
# jdata = json.loads(a)
# for d in jdata:
#     for key, value in d.iteritems():
#         print (key, value)

#using ast library - it also fails
# res = [ast.literal_eval(x) for x in a]
</code>```

I tried this link convert string to dict and convert str to list of list

But in my case, I have a list of list of dicts which is in the form of string. How to make it possible.

I want the same as the output but it should be in list of list of dicts.

Required Output:

```<code>[[{"plugin_type":"input","plugin":"mysql","dbname":"smackcoders","user":"root","password":"root","tbname":"agg_csv","host":"localhost","id":"mysql1","limit_count":5},{"plugin_type":"filter","plugin":"metrics","input_from":"mysql1","id":"metrics","field_name":"count_result", "field":"state","value":"kerala","action":"count","send_data_immediately":True},{"plugin_type":"output","plugin":"elastic","id":"elastic_search","input_from":"metrics","ind":"neww10","doc_typ":"sm23"}]]
</code>```

Body:
I am new to python. I have a string which is taken from my sqlite database. I want to convert the string to a list of list of dicts. I tried ast and json library but it fails.

Here's the string:

a = '"[[{"plugin_type":"input","plugin":"mysql","dbname":"smackcoders","user":"root","password":"root","tbname":"agg_csv","host":"localhost","id":"mysql1","limit_count":5},{"plugin_type":"filter","plugin":"metrics","input_from":"mysql1","id":"metrics","field_name":"count_result", "field":"state","value":"kerala","action":"count","send_data_immediately":True},{"plugin_type":"output","plugin":"elastic","id":"elastic_search","input_from":"metrics","ind":"neww10","doc_typ":"sm23"}]]"'

Here the code i tried:

import ast
import json
a = '"[[{"plugin_type":"input","plugin":"mysql","dbname":"smackcoders","user":"root","password":"root","tbname":"agg_csv","host":"localhost","id":"mysql1","limit_count":5},{"plugin_type":"filter","plugin":"metrics","input_from":"mysql1","id":"metrics","field_name":"count_result", "field":"state","value":"kerala","action":"count","send_data_immediately":True},{"plugin_type":"output","plugin":"elastic","id":"elastic_search","input_from":"metrics","ind":"neww10","doc_typ":"sm23"}]]"'
a = a.replace("[[","[").replace("]]","]")
print(a)

# using json library- fails
# jdata = json.loads(a)
# for d in jdata:
#     for key, value in d.iteritems():
#         print (key, value)

#using ast library - it also fails
# res = [ast.literal_eval(x) for x in a]

I tried this link convert string to dict and convert str to list of list

But in my case, I have a list of list of dicts which is in the form of string. How to make it possible.

I want the same as the output but it should be in list of list of dicts.

Required Output:

[[{"plugin_type":"input","plugin":"mysql","dbname":"smackcoders","user":"root","password":"root","tbname":"agg_csv","host":"localhost","id":"mysql1","limit_count":5},{"plugin_type":"filter","plugin":"metrics","input_from":"mysql1","id":"metrics","field_name":"count_result", "field":"state","value":"kerala","action":"count","send_data_immediately":True},{"plugin_type":"output","plugin":"elastic","id":"elastic_search","input_from":"metrics","ind":"neww10","doc_typ":"sm23"}]]

Body:
Try this.

a = '"[[{"plugin_type":"input","plugin":"mysql","dbname":"smackcoders","user":"root","password":"root","tbname":"agg_csv","host":"localhost","id":"mysql1","limit_count":5},{"plugin_type":"filter","plugin":"metrics","input_from":"mysql1","id":"metrics","field_name":"count_result", "field":"state","value":"kerala","action":"count","send_data_immediately":True},{"plugin_type":"output","plugin":"elastic","id":"elastic_search","input_from":"metrics","ind":"neww10","doc_typ":"sm23"}]]"'

a=a.strip('"')
a=eval(a)


问:
Location with Timeout
We needed a location service for our app that was available from anyplace.
We used s singletone with Application context for system services and more, and has two basic methods start and stop which listen to location providers and stop listening respectively.

We have getLastLocation method that retrieves the current most updated and accurate location we could find.

We have another method that gives me a headache :-)

Location getLocationWithWait(Class c) which supposed to get a location if available, if not it will return null and will create a Timer for 45 seconds.if the 45 seconds have passed and no location was found then the timer will broadcast to the class given in the parameter a 'no location' broadcast, otherwise if the location callbacks will be called they will cancel the timer and will send 'location found' broadcast to the class in the parameter.
So here are my questions:

i started to think the whole
architecture here is wrong, any
better way to implement a location
service to cater ANY Activity in my
application ?

i used a Timer an not Handler since
the singletone i use is NOT an
activity so i have no Looper an
creating a thread with looper looks
to me just as bad as creating
another Thread for the timer... i
did wanted to use the Activity
instead, but then... if the activity
pauses and resumes i need to keep
track of the timer's remaining time.

the broadcasts may also be of a
problem since if the activty pauses
it will miss the broadcast and then
i need to keep track in my
singletone after several states,
StickyBroadcast may solve it but
that one i can't send to specific
class but to the whole system only.

So finally will it be any advantage to make this class a Service ?(to be honest i thought of maybe one advantage but not much) i want a location service with timeout much like google do in their "My Location" in maps.

10x.

答:
Wouldn't it be better to use a LocationListener, as described in Requesting Location Updates?

You can then use a 'FastFix' in onResume()

Without knowing a bit more about your requirements, it's difficult to make more specific suggestions.

Hope this helps,

Phil Lello

ContentLicense: CC BY-SA 3.0

Title: Location with Timeout


问:
Problem with using keyboard module and turtle together
I am writing a script to read my keystrokes and draw simple shapes in turtle.
To record keystrokes, I am using the keyboard module and I am using turtle for drawing.

I am getting struck due to the use of threading in the keyboard module.

What I am currently doing is-

I added hotkeys using keyboard.add_hotkey method.

If I am pressing a certain key, that letter is added to a list (named data) for later use.

When I press the combination of Ctrl+Shift+S, the save function is called. In the save function, a turtle window is instantiated, and the list data is popped one letter at a time. The shape is drawn according to the letter popped.

When the list gets empty, I save the drawing and close the turtle window.

The problem that I am facing is that once the save function is called, the program stops listening to other calls. It is perhaps due to the use of threads in keyboard module.

The code is attached here-

```<code>def start():
    #turtle.mainloop()
    s=turtle.Screen().setup( width = WIDTH, height = HEIGHT, startx = 0, starty = 0)
    global t
    t=turtle.Turtle()
    turtle.ht()
    t.ht()

def save():

    start()
    global t
    global data
    t.speed(0)

    while data:
        fun = data.pop()

        if fun=='c':
            draw_circle()
        elif fun=='r':
            draw_rectangle()
        elif fun=='p':
            draw_polygon()
        elif fun=='h':
            draw_hexagon()
        elif fun=='t':
            draw_triangle()
        elif fun=='m':
            draw_pentagon()

    ts = turtle.getscreen()
    ts.getcanvas().postscript(file="drawing.eps")
    img = Image.open('drawing.eps')
    img.save('drawing.png')
    turtle.bye()

def push_fun(fun):
    data.append(fun)

if __name__=='__main__':
    keyboard.add_hotkey('ctrl+shift+s', save)
    keyboard.add_hotkey('ctrl+shift+e', exit)
    keyboard.add_hotkey('ctrl+shift+p', send_to_server)
    # keyboard.add_hotkey('ctrl+shift+s', save, args=(data))
    keyboard.add_hotkey('c', push_fun, args=('c',))
    keyboard.add_hotkey('s', push_fun, args=('t',))
    keyboard.add_hotkey('h', push_fun, args=('h',))
    keyboard.add_hotkey('p', push_fun, args=('p',))
    keyboard.add_hotkey('r', push_fun, args=('r',))
    keyboard.wait()
</code>```

After the save function is called, the program remains in the keyboard.wait() part but does not listen to any other key press.

答:
you can end the wait by setting a key to press like:

```<code>keyboard.wait('space')
</code>```

but keyboard.wait() without any keys given blocks all keystrokes forever

I'm not sure why you even put it there, I'm not even sure why it picks anything up at all, but I think you can do this:

```<code>if __name__=='__main__':
    '''your keystrokes'''
    while True: #or set a timer or something
        pass
</code>```

you didn't give me the whole code so I can't make sure it works

you also need to global the list data in the push_fun function

I hope it helps :)

Body:
I am writing a script to read my keystrokes and draw simple shapes in turtle.
To record keystrokes, I am using the keyboard module and I am using turtle for drawing.

I am getting struck due to the use of threading in the keyboard module.

What I am currently doing is-

I added hotkeys using keyboard.add_hotkey method.

If I am pressing a certain key, that letter is added to a list (named data) for later use.

When I press the combination of Ctrl+Shift+S, the save function is called. In the save function, a turtle window is instantiated, and the list data is popped one letter at a time. The shape is drawn according to the letter popped.

When the list gets empty, I save the drawing and close the turtle window.

The problem that I am facing is that once the save function is called, the program stops listening to other calls. It is perhaps due to the use of threads in keyboard module.

The code is attached here-

def start():
    #turtle.mainloop()
    s=turtle.Screen().setup( width = WIDTH, height = HEIGHT, startx = 0, starty = 0)
    global t
    t=turtle.Turtle()
    turtle.ht()
    t.ht()

def save():

    start()
    global t
    global data
    t.speed(0)

    while data:
        fun = data.pop()

        if fun=='c':
            draw_circle()
        elif fun=='r':
            draw_rectangle()
        elif fun=='p':
            draw_polygon()
        elif fun=='h':
            draw_hexagon()
        elif fun=='t':
            draw_triangle()
        elif fun=='m':
            draw_pentagon()

    ts = turtle.getscreen()
    ts.getcanvas().postscript(file="drawing.eps")
    img = Image.open('drawing.eps')
    img.save('drawing.png')
    turtle.bye()

def push_fun(fun):
    data.append(fun)

if __name__=='__main__':
    keyboard.add_hotkey('ctrl+shift+s', save)
    keyboard.add_hotkey('ctrl+shift+e', exit)
    keyboard.add_hotkey('ctrl+shift+p', send_to_server)
    # keyboard.add_hotkey('ctrl+shift+s', save, args=(data))
    keyboard.add_hotkey('c', push_fun, args=('c',))
    keyboard.add_hotkey('s', push_fun, args=('t',))
    keyboard.add_hotkey('h', push_fun, args=('h',))
    keyboard.add_hotkey('p', push_fun, args=('p',))
    keyboard.add_hotkey('r', push_fun, args=('r',))
    keyboard.wait()

After the save function is called, the program remains in the keyboard.wait() part but does not listen to any other key press.

Body:
you can end the wait by setting a key to press like:

keyboard.wait('space')

but keyboard.wait() without any keys given blocks all keystrokes forever

I'm not sure why you even put it there, I'm not even sure why it picks anything up at all, but I think you can do this:

if __name__=='__main__':
    '''your keystrokes'''
    while True: #or set a timer or something
        pass

you didn't give me the whole code so I can't make sure it works

you also need to global the list data in the push_fun function

I hope it helps :)


问:
Why generating SEO friendly URL is not working using routes in Codeigniter?
I am developing an application using Codeigniter,and I am trying to generate SEO friendly URLs but nothing is working fine.

I have tried the following code in routes file:

```<code>$route['default_controller'] = "main";
$route['404_override'] = '';
$route['add-quiz']     = 'main/add_quiz/';
$route['category-wise-questions/(:any)']    = 'category_wise_questions/$1';
</code>```

Eventhough it generates:

http://localhost/appname/main/add_quiz

instead of:

http://localhost/appname/main/add-quiz

答:
$route['main/add-quiz'] ='main/add_quiz/'; Should work.
 I have tried something like:
$route['mumbai/piles-doctor'] = 'mumbai/piles_doctor'; which has worked perfectly.

No need to update .htaccess.

Also make sure, translate_uri_dashes is set to its default value 'False'.
$route['translate_uri_dashes'] = FALSE;

Though others can refer a better solution here stackoverflow answer

Body:
I am developing an application using Codeigniter,and I am trying to generate SEO friendly URLs but nothing is working fine.

I have tried the following code in routes file:

$route['default_controller'] = "main";
$route['404_override'] = '';
$route['add-quiz']     = 'main/add_quiz/';
$route['category-wise-questions/(:any)']    = 'category_wise_questions/$1';

Eventhough it generates:

http://localhost/appname/main/add_quiz

instead of:

http://localhost/appname/main/add-quiz


问:
How to align text to the center of a parent Align widget
I'm having troubles aligning the text to the center of the box.
I've tried to add FractionalOffset.center to align the column to the parent Align but it does not seem to make a difference. Since the second Align is within the first Align, I don't understand why FractionalOffset.center does not work.

Image:

Code:

  @override
  Widget build(BuildContext context) {
    ThemeData themeData = Theme.of(context);
    return Container(
      height: 30.0,
      child: Padding(
        padding: EdgeInsets.all(0.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Expanded(
              child: Align(
                alignment: FractionalOffset.bottomLeft,
                child: AspectRatio(
                  aspectRatio: 1.0,
                  child: Stack(
                    children: <Widget>[
                      Positioned.fill(
                        child: AnimatedBuilder(
                          animation: controller,
                          builder: (BuildContext context, Widget child) {
                            return CustomPaint(
                                painter: TimerPainter(
                              animation: controller,
                              backgroundColor: Colors.white,
                              color: themeData.indicatorColor,
                            ));
                          },
                        ),
                      ),
                      Align(
                        alignment: FractionalOffset.center,
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: <Widget>[
                            AnimatedBuilder(
                                animation: controller,
                                builder: (BuildContext context, Widget child) {
                                  return Text(
                                    timerString.substring(2),
                                    style: TextStyle(color: Colors.white)
                                  );
                                }),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
```

答:
I could suggest you a lot of things, but I'll make something better. I'm gonna show you how to "debug" when you get stuck like this.

You see the lastest Align component? Wrap it in a Container, pass it a color, like Colors.red so you can see where this Align really is.

After that, you could do some workaround, since your child (Text) is not behaving like you're expecting, problem is it parent's fault. Remember this analogy.

With that in mind, you could check every component's father, first, your AnimatedBuilder, you could wrap it in a Center component, or do the same trick passing a color and wrap it in a Container to check where he is positioned after all in the Stack, and so on, and so on.

If is not your AnimatedBuilder's behaviours fault, then check for his parent up in the tree till you find it.

Hope this have helped


问:
Finding minimum value between 2 numbers without comparision operators
I have seen the following method which gives the minimum value b/w 2 numbers without relational operators

```<code>y + ((x - y) & ((x - y) >>(sizeof(int) * CHAR_BIT - 1)))
</code>```

In here if x=6 and y=4 x-y=2 is positive and shifting this value 31 times to the right gives 0.(as sign bit is 0 for +ve numbers) and the eqn becomes

```<code>y + ((x-y)&0)
</code>```

From the above eqn we get y as min value which is true.

But for the case where x=4 and y=6, x-y=-2 and shifting it 31 times to right gives 1 and the eqn becomes:

```<code>y + ((x-y)&1)
</code>```

As per my understanding bitwise & of -2 and 1 becomes 0 and the eqn gives o/p as y(6) instead of x(4). Can someone explain?

Full code: https://www.geeksforgeeks.org/compute-the-minimum-or-maximum-max-of-two-integers-without-branching/

Thanks

答:
The explanation given on the said website is wrong. When x < y

```<code>(x - y) >> 31 = 0b1...1 (32 ones) (*)
</code>```

And then

```<code>y + ((x - y) & 0b1...1) = y + (x - y) = x
</code>```

(*) Note that the right shift of a negative number is implementation-defined. Typically, it performs an arithmetic right shift, filling all binary digits with the most significant one which is 1 for a negative number in two's complement representation.

Body:
I have seen the following method which gives the minimum value b/w 2 numbers without relational operators

y + ((x - y) & ((x - y) >>(sizeof(int) * CHAR_BIT - 1)))

In here if x=6 and y=4 x-y=2 is positive and shifting this value 31 times to the right gives 0.(as sign bit is 0 for +ve numbers) and the eqn becomes

y + ((x-y)&0)

From the above eqn we get y as min value which is true.

But for the case where x=4 and y=6, x-y=-2 and shifting it 31 times to right gives 1 and the eqn becomes:

y + ((x-y)&1)

As per my understanding bitwise & of -2 and 1 becomes 0 and the eqn gives o/p as y(6) instead of x(4). Can someone explain?

Full code: https://www.geeksforgeeks.org/compute-the-minimum-or-maximum-max-of-two-integers-without-branching/

Thanks

Body:
The explanation given on the said website is wrong. When x < y

(x - y) >> 31 = 0b1...1 (32 ones) (*)

And then

y + ((x - y) & 0b1...1) = y + (x - y) = x

(*) Note that the right shift of a negative number is implementation-defined. Typically, it performs an arithmetic right shift, filling all binary digits with the most significant one which is 1 for a negative number in two's complement representation.


问:
Parse JSON with map of list
I am new to scala and JSON parsing and need some help. I need to parse the complex JSON (below) to get the values of "name" in "dimension" key i.e I need PLATFORM and OS_VERSION.

I tried multiple options, but it is not working. Any help is appreciated

This is a snippet of the code I tried, but I am not able to proceed further in parsing the list. I believe the 'ANY' keyword is causing some mismatch / issues.

```<code>import org.json4s._
import org.json4s.jackson.JsonMethods._

implicit val formats = org.json4s.DefaultFormats

val mapJSON = parse(tmp).extract[Map[String, Any]]
println(mapJSON)

//for ((k,v) <- mapJSON) printf("key: %s, value: %s\n", k, v)

val list_map = mapJSON("dimensions")
</code>```

```<code>{
  "uuid": "uuidddd",
  "last_modified": 1559080222953,
  "version": "2.6.1.0",
  "name": "FULL_DAY_2_mand_date",
  "is_draft": false,
  "model_name": "FULL_DAY_1_may05",
  "description": "",
  "null_string": null,
  "dimensions": [
    {
      "name": "PLATFORM",
      "table": "tbl1",
      "column": "PLATFORM",
      "derived": null
    },
    {
      "name": "OS_VERSION",
      "table": "tbl1",
      "column": "OS_VERSION",
      "derived": null
    },
  ],
  "measures": [
    {
      "name": "_COUNT_",
      "function": {
        "expression": "COUNT",
        "parameter": {
          "type": "constant",
          "value": "1"
        },
        "returntype": "bigint"
      }
    },
    {
      "name": "UU",
      "function": {
        "expression": "COUNT_DISTINCT",
        "parameter": {
          "type": "column",
          "value": "tbl1.USER_ID"
        },
        "returntype": "hllc(12)"
      }
    },
    {
      "name": "CONT_SIZE",
      "function": {
        "expression": "SUM",
        "parameter": {
          "type": "column",
          "value": "tbl1.SIZE"
        },
        "returntype": "bigint"
      }
    },
    {
      "name": "CONT_COUNT",
      "function": {
        "expression": "SUM",
        "parameter": {
          "type": "column",
          "value": "tbl1.COUNT"
        },
        "returntype": "bigint"
      }
    }
  ],
  "dictionaries": [],
  "rowkey": {
    "rowkey_columns": [
      {
        "column": "tbl1.OS_VERSION",
        "encoding": "dict",
        "encoding_version": 1,
        "isShardBy": false
      },
      {
        "column": "tbl1.PLATFORM",
        "encoding": "dict",
        "encoding_version": 1,
        "isShardBy": false
      },
      {
        "column": "tbl1.DEVICE_FAMILY",
        "encoding": "dict",
        "encoding_version": 1,
        "isShardBy": false
      }
    ]
  },
  "hbase_mapping": {
    "column_family": [
      {
        "name": "F1",
        "columns": [
          {
            "qualifier": "M",
            "measure_refs": [
              "_COUNT_",
              "CONT_SIZE",
              "CONT_COUNT"
            ]
          }
        ]
      },
      {
        "name": "F2",
        "columns": [
          {
            "qualifier": "M",
            "measure_refs": [
              "UU"
            ]
          }
        ]
      }
    ]
  },
  "aggregation_groups": [
    {
      "includes": [
        "tbl1.PLATFORM",
        "tbl1.OS_VERSION"
      ],
      "select_rule": {
        "hierarchy_dims": [],
        "mandatory_dims": [
          "tbl1.DATE_HR"
        ],
        "joint_dims": []
      }
    }
  ],
  "signature": "ttrrs==",
  "notify_list": [],
  "status_need_notify": [
    "ERROR",
    "DISCARDED",
    "SUCCEED"
  ],
  "partition_date_start": 0,
  "partition_date_end": 3153600000000,
  "auto_merge_time_ranges": [
    604800000,
    2419200000
  ],
  "volatile_range": 0,
  "retention_range": 0,
  "engine_type": 4,
  "storage_type": 2,
  "override_kylin_properties": {
    "job.queuename": "root.production.P0",
    "is-mandatory-only-valid": "true"
  },
  "cuboid_black_list": [],
  "parent_forward": 3,
  "mandatory_dimension_set_list": [],
  "snapshot_table_desc_list": []
}
</code>```

答:
You need to make more specific classes for parsing the data, something like this:</p>

```<code>case class Dimension(name: String, table: String, column: String)
case class AllData(uuid: String, dimensions: List[Dimension])

val data = parse(tmp).extract[AllData]
val names = data.dimensions.map(_.name)
</code>```

Title: Parse JSON with map of list

Body:
I am new to scala and JSON parsing and need some help. I need to parse the complex JSON (below) to get the values of "name" in "dimension" key i.e I need PLATFORM and OS_VERSION.

I tried multiple options, but it is not working. Any help is appreciated

This is a snippet of the code I tried, but I am not able to proceed further in parsing the list. I believe the 'ANY' keyword is causing some mismatch / issues.

import org.json4s._
import org.json4s.jackson.JsonMethods._

implicit val formats = org.json4s.DefaultFormats

val mapJSON = parse(tmp).extract[Map[String, Any]]
println(mapJSON)

//for ((k,v) <- mapJSON) printf("key: %s, value: %s\n", k, v)

val list_map = mapJSON("dimensions")

{
  "uuid": "uuidddd",
  "last_modified": 1559080222953,
  "version": "2.6.1.0",
  "name": "FULL_DAY_2_mand_date",
  "is_draft": false,
  "model_name": "FULL_DAY_1_may05",
  "description": "",
  "null_string": null,
  "dimensions": [
    {
      "name": "PLATFORM",
      "table": "tbl1",
      "column": "PLATFORM",
      "derived": null
    },
    {
      "name": "OS_VERSION",
      "table": "tbl1",
      "column": "OS_VERSION",
      "derived": null
    },
  ],
  "measures": [
    {
      "name": "_COUNT_",
      "function": {
        "expression": "COUNT",
        "parameter": {
          "type": "constant",
          "value": "1"
        },
        "returntype": "bigint"
      }
    },
    {
      "name": "UU",
      "function": {
        "expression": "COUNT_DISTINCT",
        "parameter": {
          "type": "column",
          "value": "tbl1.USER_ID"
        },
        "returntype": "hllc(12)"
      }
    },
    {
      "name": "CONT_SIZE",
      "function": {
        "expression": "SUM",
        "parameter": {
          "type": "column",
          "value": "tbl1.SIZE"
        },
        "returntype": "bigint"
      }
    },
    {
      "name": "CONT_COUNT",
      "function": {
        "expression": "SUM",
        "parameter": {
          "type": "column",
          "value": "tbl1.COUNT"
        },
        "returntype": "bigint"
      }
    }
  ],
  "dictionaries": [],
  "rowkey": {
    "rowkey_columns": [
      {
        "column": "tbl1.OS_VERSION",
        "encoding": "dict",
        "encoding_version": 1,
        "isShardBy": false
      },
      {
        "column": "tbl1.PLATFORM",
        "encoding": "dict",
        "encoding_version": 1,
        "isShardBy": false
      },
      {
        "column": "tbl1.DEVICE_FAMILY",
        "encoding": "dict",
        "encoding_version": 1,
        "isShardBy": false
      }
    ]
  },
  "hbase_mapping": {
    "column_family": [
      {
        "name": "F1",
        "columns": [
          {
            "qualifier": "M",
            "measure_refs": [
              "_COUNT_",
              "CONT_SIZE",
              "CONT_COUNT"
            ]
          }
        ]
      },
      {
        "name": "F2",
        "columns": [
          {
            "qualifier": "M",
            "measure_refs": [
              "UU"
            ]
          }
        ]
      }
    ]
  },
  "aggregation_groups": [
    {
      "includes": [
        "tbl1.PLATFORM",
        "tbl1.OS_VERSION"
      ],
      "select_rule": {
        "hierarchy_dims": [],
        "mandatory_dims": [
          "tbl1.DATE_HR"
        ],
        "joint_dims": []
      }
    }
  ],
  "signature": "ttrrs==",
  "notify_list": [],
  "status_need_notify": [
    "ERROR",
    "DISCARDED",
    "SUCCEED"
  ],
  "partition_date_start": 0,
  "partition_date_end": 3153600000000,
  "auto_merge_time_ranges": [
    604800000,
    2419200000
  ],
  "volatile_range": 0,
  "retention_range": 0,
  "engine_type": 4,
  "storage_type": 2,
  "override_kylin_properties": {
    "job.queuename": "root.production.P0",
    "is-mandatory-only-valid": "true"
  },
  "cuboid_black_list": [],
  "parent_forward": 3,
  "mandatory_dimension_set_list": [],
  "snapshot_table_desc_list": []
}

Body:
You need to make more specific classes for parsing the data, something like this:

case class Dimension(name: String, table: String, column: String)
case class AllData(uuid: String, dimensions: List[Dimension])

val data = parse(tmp).extract[AllData]
val names = data.dimensions.map(_.name)


问:
Nested Interface and Implementing class behavior
This is about access specifier for classes that implements nested interface. More details follow:

```<code>interface Fun{
    interface NestedFun{
        void nestedFunction();
    }
    void function();
}

class A implements Fun{
    class B implements Fun.NestedFun{
        //implements functionality
    }

    // implements functionality
}
</code>```

What would be the access specifier for class B as we know that by default, nested interfaces are static. Would that make the class implementing such interface static?

答:
No.

All static means in the context of a class is that it is a nested class without an implicit reference to the instance of the outer class which created it.

Whether or not a reference exists in a class is down to implementation; interfaces aren't concerned with implementation.

Body:
This is about access specifier for classes that implements nested interface. More details follow:

interface Fun{
    interface NestedFun{
        void nestedFunction();
    }
    void function();
}

class A implements Fun{
    class B implements Fun.NestedFun{
        //implements functionality
    }

    // implements functionality
}

What would be the access specifier for class B as we know that by default, nested interfaces are static. Would that make the class implementing such interface static?


问:
How to get the "LastLogon" time stamp for users from Active Directory
I am creating an app to display the users last logon time stamp as well as date created and a few other info.  How do I get the lastlogon to display in my listview?

I have tried various solutions on SO as well as various other websites but none seems to be working

This is the code I am using to display the information needed

```<code>lvwListView.Clear();
lvwListView.Columns.Add("Name", 175, HorizontalAlignment.Left);
lvwListView.Columns.Add("LanID", 100, HorizontalAlignment.Left);
lvwListView.Columns.Add("Email", 225, HorizontalAlignment.Left);
lvwListView.Columns.Add("Phone Number", 150, HorizontalAlignment.Left);
lvwListView.Columns.Add("When Created", 150, HorizontalAlignment.Left);
lvwListView.Columns.Add("Last Logon", 150, HorizontalAlignment.Left);

if (results != null)
{
    foreach (Principal p in results)
    {
        itmListItem = new ListViewItem();
        itmListItem.Text = p.Name;
        itmListItem.SubItems.Add(p.SamAccountName);

        if (p.StructuralObjectClass == "user")
        {
            var uP = (UserPrincipal)p;
            if (uP != null)
            {
                itmListItem.SubItems.Add(uP.EmailAddress);
            }
        }

        var creationDate = string.Empty;
        var telephoneNumber = string.Empty;
        var lastLogon = string.Empty;
        var prop = string.Empty;
        var directoryEntry = p.GetUnderlyingObject() as DirectoryEntry;
        prop = "whenCreated";
        if (directoryEntry.Properties.Contains(prop))
        {
            creationDate = directoryEntry.Properties[prop].Value.ToString();
        }
        prop = "telephoneNumber";
        if (directoryEntry.Properties.Contains(prop))
        {
            telephoneNumber = directoryEntry.Properties[prop].Value.ToString();
        }
        prop = "lastLogon";
        if (directoryEntry.Properties.Contains(prop))
        {
            lastLogon = directoryEntry.Properties[prop].Value.ToString();
        }

        itmListItem.SubItems.Add(telephoneNumber);
        itmListItem.SubItems.Add(creationDate);
        itmListItem.SubItems.Add(lastLogon);
        lvwListView.Items.Add(itmListItem);
        lvwListView.Refresh();
        itmListItem = null;
        this.Text = Application.ProductName + " (" + groupName + ")";
    }

    ctx.Dispose();
}
</code>```

The code above displays the Name, LanId, Email, phone number and when created perfectly, but for the lastlogon it displays System._ComObject.

I don't fully understand why it will display the WhenCreated but not the lastLogon?

答:
WhenCreated is stored as String (Generalized-Time) type, whereas Last-Logon is stored as Interval syntax, which is convertible to an IADsLargeInteger.

Here's an example extension that will convert that to a familiar System.DateTime:

```<code>public static class ActiveDirectoryExtensions
{
    public static DateTime GetLastLogon(this DirectoryEntry entry)
    {
        var activeDirectoryLargeInteger = (IAdsLargeInteger)entry.Properties["lastLogon"].Value;
        return DateTime.FromFileTimeUtc((activeDirectoryLargeInteger.HighPart << 32) + activeDirectoryLargeInteger.LowPart);
    }

    [ComImport, Guid("9068270b-0939-11d1-8be1-00c04fd8d503"), InterfaceType(ComInterfaceType.InterfaceIsDual)]
    internal interface IAdsLargeInteger
    {
        long HighPart { get; set; }

        long LowPart { get; set; }
    }
}
</code>```

Usage:

var lastLogon = directoryEntry.GetLastLogon()

Body:
I am creating an app to display the users last logon time stamp as well as date created and a few other info.  How do I get the lastlogon to display in my listview?

I have tried various solutions on SO as well as various other websites but none seems to be working

This is the code I am using to display the information needed

lvwListView.Clear();
lvwListView.Columns.Add("Name", 175, HorizontalAlignment.Left);
lvwListView.Columns.Add("LanID", 100, HorizontalAlignment.Left);
lvwListView.Columns.Add("Email", 225, HorizontalAlignment.Left);
lvwListView.Columns.Add("Phone Number", 150, HorizontalAlignment.Left);
lvwListView.Columns.Add("When Created", 150, HorizontalAlignment.Left);
lvwListView.Columns.Add("Last Logon", 150, HorizontalAlignment.Left);

if (results != null)
{
    foreach (Principal p in results)
    {
        itmListItem = new ListViewItem();
        itmListItem.Text = p.Name;
        itmListItem.SubItems.Add(p.SamAccountName);

        if (p.StructuralObjectClass == "user")
        {
            var uP = (UserPrincipal)p;
            if (uP != null)
            {
                itmListItem.SubItems.Add(uP.EmailAddress);
            }
        }

        var creationDate = string.Empty;
        var telephoneNumber = string.Empty;
        var lastLogon = string.Empty;
        var prop = string.Empty;
        var directoryEntry = p.GetUnderlyingObject() as DirectoryEntry;
        prop = "whenCreated";
        if (directoryEntry.Properties.Contains(prop))
        {
            creationDate = directoryEntry.Properties[prop].Value.ToString();
        }
        prop = "telephoneNumber";
        if (directoryEntry.Properties.Contains(prop))
        {
            telephoneNumber = directoryEntry.Properties[prop].Value.ToString();
        }
        prop = "lastLogon";
        if (directoryEntry.Properties.Contains(prop))
        {
            lastLogon = directoryEntry.Properties[prop].Value.ToString();
        }

        itmListItem.SubItems.Add(telephoneNumber);
        itmListItem.SubItems.Add(creationDate);
        itmListItem.SubItems.Add(lastLogon);
        lvwListView.Items.Add(itmListItem);
        lvwListView.Refresh();
        itmListItem = null;
        this.Text = Application.ProductName + " (" + groupName + ")";
    }

    ctx.Dispose();
}

The code above displays the Name, LanId, Email, phone number and when created perfectly, but for the lastlogon it displays System._ComObject.

I don't fully understand why it will display the WhenCreated but not the lastLogon?

Body:
WhenCreated is stored as String (Generalized-Time) type, whereas Last-Logon is stored as Interval syntax, which is convertible to an IADsLargeInteger.

Here's an example extension that will convert that to a familiar System.DateTime:

public static class ActiveDirectoryExtensions
{
    public static DateTime GetLastLogon(this DirectoryEntry entry)
    {
        var activeDirectoryLargeInteger = (IAdsLargeInteger)entry.Properties["lastLogon"].Value;
        return DateTime.FromFileTimeUtc((activeDirectoryLargeInteger.HighPart << 32) + activeDirectoryLargeInteger.LowPart);
    }

    [ComImport, Guid("9068270b-0939-11d1-8be1-00c04fd8d503"), InterfaceType(ComInterfaceType.InterfaceIsDual)]
    internal interface IAdsLargeInteger
    {
        long HighPart { get; set; }

        long LowPart { get; set; }
    }
}

Usage:

var lastLogon = directoryEntry.GetLastLogon()


问:
Matcher.Find() returns false when it should be true
```<code>        String s = "test";
        Pattern pattern = Pattern.compile("\\n((\\w+\\s*[^\\n]){0,2})(\\b" + s + "\\b\\s)((\\w+\\s*){0,2})\\n?");
        Matcher matcher = pattern.matcher(searchableText);
        boolean topicTitleFound = matcher.find();
        startIndex = 0;
        while (topicTitleFound) {
            int i = searchableText.indexOf(matcher.group(0));
            if (i > startIndex) {
                builder.append(documentText.substring(startIndex, i - 1));
        ...
</code>```

This is the text that I tacle:

Some text comes here

  topicTitle test :

test1 : testing123

test2 : testing456

test3 : testing789

test4 : testing9097

When I'm testing this regex on http://regexpal.com/ or http://www.regexplanet.com I clearly find the title that is saying: "topicTitle test". But in my java code topicTitleFound returns false.

Please help

答: Your regex is a bit hard to decrypt - not really obvious what you're trying to do. One thing that springs to mind is that your regex expects the match to start with a newline, and your sample text doesn't.</p>

Body:
        String s = "test";
        Pattern pattern = Pattern.compile("\\n((\\w+\\s*[^\\n]){0,2})(\\b" + s + "\\b\\s)((\\w+\\s*){0,2})\\n?");
        Matcher matcher = pattern.matcher(searchableText);
        boolean topicTitleFound = matcher.find();
        startIndex = 0;
        while (topicTitleFound) {
            int i = searchableText.indexOf(matcher.group(0));
            if (i > startIndex) {
                builder.append(documentText.substring(startIndex, i - 1));
        ...

This is the text that I tacle:

Some text comes here

  topicTitle test :

test1 : testing123

test2 : testing456

test3 : testing789

test4 : testing9097

When I'm testing this regex on http://regexpal.com/ or http://www.regexplanet.com I clearly find the title that is saying: "topicTitle test". But in my java code topicTitleFound returns false.

Please help


问:
CSC: error CS0041: Unexpected error writing debug information -- 'Operation is not supported on this platform.'
Just downloaded Visual Studio Professional for Mac and I cannot seem to build anything as I always get the same error:

```<code>/Library/Frameworks/Mono.framework/Versions/4.8.0/lib/mono/xbuild/14.0/bin/Microsoft.CSharp.targets (CoreCompile target) ->

CSC: error CS0041: Unexpected error writing debug information -- 'Operation is not supported on this platform.'

 19 Warning(s)
 1 Error(s)
</code>```

Not sure what to change on my project to get things to compile.

答:
After I deleted the line

```<code><DebugType>pdbonly</DebugType>
</code>```

from the .csproj file, the build became successful.

Body:
Just downloaded Visual Studio Professional for Mac and I cannot seem to build anything as I always get the same error:

/Library/Frameworks/Mono.framework/Versions/4.8.0/lib/mono/xbuild/14.0/bin/Microsoft.CSharp.targets (CoreCompile target) ->

CSC: error CS0041: Unexpected error writing debug information -- 'Operation is not supported on this platform.'

 19 Warning(s)
 1 Error(s)

Not sure what to change on my project to get things to compile.

Body:
After I deleted the line

<DebugType>pdbonly</DebugType>

from the .csproj file, the build became successful.


问:
How to show Gif in UWP in Xamarin Forms?
I want to show GIF in my Xamarin forms app. I tried FFImageLoading but it shows GIF in android and iOS but not in UWP. So is there any way I can show GIF in UWP?</p>

答:
How to show Gif in UWP in Xamarin Forms?

As @agicandre1981 mentioned Basic GIF animation features will be merged, you could wait for the following update.

And UWP native image control supports GIF image, So you could use OnPlatform xaml tag  to create different image control for per platform like the following.

```<code><OnPlatform>
    <On Platform="UWP">
        <Image
    HeightRequest="200"
    HorizontalOptions="Center"
    Source="test.gif"
    VerticalOptions="Center"
    WidthRequest="200"
    />
    </On>
    <On Platform="Android">
        <ffimageloading:CachedImage HorizontalOptions="Center" VerticalOptions="Center"
    WidthRequest="300" HeightRequest="300"
    DownsampleToViewSize="true"
    Source = "Test.gif"/>
    </On>
    <On Platform="iOS">
        <ffimageloading:CachedImage HorizontalOptions="Center" VerticalOptions="Center"
    WidthRequest="300" HeightRequest="300"
    DownsampleToViewSize="true"
    Source = "Test.gif"/>
    </On>
</OnPlatform>
</code>```

Body:
How to show Gif in UWP in Xamarin Forms?

As @agicandre1981 mentioned Basic GIF animation features will be merged, you could wait for the following update.

And UWP native image control supports GIF image, So you could use OnPlatform xaml tag  to create different image control for per platform like the following.

<OnPlatform>
    <On Platform="UWP">
        <Image
    HeightRequest="200"
    HorizontalOptions="Center"
    Source="test.gif"
    VerticalOptions="Center"
    WidthRequest="200"
    />
    </On>
    <On Platform="Android">
        <ffimageloading:CachedImage HorizontalOptions="Center" VerticalOptions="Center"
    WidthRequest="300" HeightRequest="300"
    DownsampleToViewSize="true"
    Source = "Test.gif"/>
    </On>
    <On Platform="iOS">
        <ffimageloading:CachedImage HorizontalOptions="Center" VerticalOptions="Center"
    WidthRequest="300" HeightRequest="300"
    DownsampleToViewSize="true"
    Source = "Test.gif"/>
    </On>
</OnPlatform>


问:
SFTP: Copy/Download all files in a folder recursively from remote server
i got a code that can download files from remote directory to local directory but it gives following error.

please explain meaning of the error and how to resolve it. it shows problem in second line.

my code

```<code>import paramiko, os
paramiko.util.log_to_file('/tmp/paramiko.log')
from stat import S_ISDIR
host = "ip"
port = 22
transport = paramiko.Transport((host, port))
password = "mypassword"
username = "username"
transport.connect(username = username, password = password)
sftp = paramiko.SFTPClient.from_transport(transport)
def sftp_walk(remotepath):
    path=remotepath
    files=[]
    folders=[]
    for f in sftp.listdir_attr(remotepath):
        if S_ISDIR(f.st_mode):
            folders.append(f.filename)
        else:
            files.append(f.filename)
    if files:
        yield path, files
    for folder in folders:
        new_path=os.path.join(remotepath,folder)
        for x in sftp_walk(new_path):
            yield x

for path,files  in sftp_walk("." or '/remotepath/'):
    for file in files:
        #sftp.get(remote, local) line for dowloading.
        sftp.get(os.path.join(os.path.join(path,file)), '/local path/')
</code>```

error i am getting:

```<code>C:\Users\Rohan\PycharmProjects\untitled1\venv\Scripts\python.exe C:/Users/Rohan/PycharmProjects/untitled1/tyu.py
Traceback (most recent call last):
  File "C:/Users/Rohan/PycharmProjects/untitled1/tyu.py", line 2, in <module>
    paramiko.util.log_to_file('/tmp/paramiko.log')
  File "C:\Users\Rohan\PycharmProjects\untitled1\venv\lib\site-packages\paramiko\util.py", line 252, in log_to_file
    f = open(filename, "a")
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/paramiko.log'

Process finished with exit code 1
</code>```

答:
```<code>import os
import pysftp
from stat import S_IMODE, S_ISDIR, S_ISREG

cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
sftp=pysftp.Connection('192.168.X.X', username='username',password='password',cnopts=cnopts)

def get_r_portable(sftp, remotedir, localdir, preserve_mtime=False):
    for entry in sftp.listdir(remotedir):
        remotepath = remotedir + "/" + entry
        localpath = os.path.join(localdir, entry)
        mode = sftp.stat(remotepath).st_mode
        if S_ISDIR(mode):
            try:
                os.mkdir(localpath)
            except OSError:
                pass
            get_r_portable(sftp, remotepath, localpath, preserve_mtime)
        elif S_ISREG(mode):
            sftp.get(remotepath, localpath, preserve_mtime=preserve_mtime)

remote_path=input("enter the remote_path: ")
local_path=input("enter the local_path: ")

get_r_portable(sftp, remote_path, local_path, preserve_mtime=False)
</code>```

Body:
i got a code that can download files from remote directory to local directory but it gives following error.

please explain meaning of the error and how to resolve it. it shows problem in second line.

my code

import paramiko, os
paramiko.util.log_to_file('/tmp/paramiko.log')
from stat import S_ISDIR
host = "ip"
port = 22
transport = paramiko.Transport((host, port))
password = "mypassword"
username = "username"
transport.connect(username = username, password = password)
sftp = paramiko.SFTPClient.from_transport(transport)
def sftp_walk(remotepath):
    path=remotepath
    files=[]
    folders=[]
    for f in sftp.listdir_attr(remotepath):
        if S_ISDIR(f.st_mode):
            folders.append(f.filename)
        else:
            files.append(f.filename)
    if files:
        yield path, files
    for folder in folders:
        new_path=os.path.join(remotepath,folder)
        for x in sftp_walk(new_path):
            yield x

for path,files  in sftp_walk("." or '/remotepath/'):
    for file in files:
        #sftp.get(remote, local) line for dowloading.
        sftp.get(os.path.join(os.path.join(path,file)), '/local path/')

error i am getting:

C:\Users\Rohan\PycharmProjects\untitled1\venv\Scripts\python.exe C:/Users/Rohan/PycharmProjects/untitled1/tyu.py
Traceback (most recent call last):
  File "C:/Users/Rohan/PycharmProjects/untitled1/tyu.py", line 2, in <module>
    paramiko.util.log_to_file('/tmp/paramiko.log')
  File "C:\Users\Rohan\PycharmProjects\untitled1\venv\lib\site-packages\paramiko\util.py", line 252, in log_to_file
    f = open(filename, "a")
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/paramiko.log'

Process finished with exit code 1


问:
Is it able to ignore/disable the first step Get source in vNext Build?
Here is our situation-- sometimes we need to run a vNext build without needing to pull any source code from TFS server.

But we don't want to change the workspace mappings. Is there a related setting simply ignore or disable the get source step in the build definition. Unlike any other task, the "Get sources" task added automatically when you create a new build definition, which is not able to disable or remove the task by right click it.

Any suggestion appreciated!

答:
I tried using agent.source.skip = true (instead of Build.SyncSources = false),

and it seems to keep the variables.

Found here: https://github.com/Microsoft/azure-pipelines-agent/issues/1465


问:
Storing word documents
I'm working on job site (using asp.net 3.5) in which a user can upload one or more resumes.
Database is sql server 2005.
Whats the recommendation regarding storage of these documents?
Shall i store it as a blob in the database or just store the path in database and keep the document in the physical folder?
Can someone please mention the pros and cons of each wrt performance and scalability?

Thanks!

答: There's nothing to say you can't do both - parse the doc & store important meta info (such as contact info, frequently used words, etc) into indexed columns, store a path to the document. That is what I did for a high availability (upto 21M impressions/month) db, but we were serving media files, but the file size & principal is about the same.</p>

OwnerDisplayName: Patrick

ContentLicense: CC BY-SA 2.5

Title: Storing word documents

OwnerDisplayName: Pikesville Paesano


问:
how to make a gemset in RVM the default?
I'm trying to make a gemset the default whenever I start a new terminal in Mac OS X:

```<code>rvm use 1.9.3@rails3.2 --create --default
</code>```

That seems to work, the rails3.2 gemset becomes the current gemset:

```<code>$ rvm gemset list

gemsets for ruby-1.9.3-p0 (found in /Users/me/.rvm/gems/ruby-1.9.3-p0)
   global
=> rails3.2

$
</code>```

But when I open up a new terminal, the rails3.2 gemset is no longer the current:

```<code>$ rvm gemset list

gemsets for ruby-1.9.3-p0 (found in /Users/me/.rvm/gems/ruby-1.9.3-p0)
   global
   rails3.2

$
</code>```

What do I do?

答:
rubyracer related issue might as well come with libv8.
To get around this issue:
Step 1: Run the following command to uninstall any existing installation of libv8:

```<code>gem uninstall libv8
</code>```

Install rubyracer by running the following command:

```<code>gem install therubyracer -v 0.12.2
</code>```

Install libv8 by running the following command:

```<code>gem install libv8 -v 3.16.14.15 -- --with-system-v8
</code>```

Try bundle install now:

```<code>bundle install
</code>```

Body:
I'm trying to make a gemset the default whenever I start a new terminal in Mac OS X:

rvm use 1.9.3@rails3.2 --create --default

That seems to work, the rails3.2 gemset becomes the current gemset:

$ rvm gemset list

gemsets for ruby-1.9.3-p0 (found in /Users/me/.rvm/gems/ruby-1.9.3-p0)
   global
=> rails3.2

$

But when I open up a new terminal, the rails3.2 gemset is no longer the current:

$ rvm gemset list

gemsets for ruby-1.9.3-p0 (found in /Users/me/.rvm/gems/ruby-1.9.3-p0)
   global
   rails3.2

$

What do I do?

Body:
rubyracer related issue might as well come with libv8.
To get around this issue:
Step 1: Run the following command to uninstall any existing installation of libv8:

gem uninstall libv8

Install rubyracer by running the following command:

gem install therubyracer -v 0.12.2

Install libv8 by running the following command:

gem install libv8 -v 3.16.14.15 -- --with-system-v8

Try bundle install now:

bundle install


Title: Function that give me all date list of a month

Body:
Is there a function that could list me all dates in a specified month(year)

that is:

proper_function("January",2019)

result is

 [1] "2019-01-01" "2019-01-02" "2019-01-03" "2019-01-04" "2019-01-05" "2019-01-06" "2019-01-07"
 [8] "2019-01-08" "2019-01-09" "2019-01-10" "2019-01-11" "2019-01-12" "2019-01-13" "2019-01-14"
[15] "2019-01-15" "2019-01-16" "2019-01-17" "2019-01-18" "2019-01-19" "2019-01-20" "2019-01-21"
[22] "2019-01-22" "2019-01-23" "2019-01-24" "2019-01-25" "2019-01-26" "2019-01-27" "2019-01-28"
[29] "2019-01-29" "2019-01-30" "2019-01-31"

I could write a simple program since except for Feb each month has fixed dates for any year, but I suppose there should be some exist function in some basic packages

Body:
You can use the lubridate package. You just have to provide the month in the following format:

proper_function <- function(x) {
  x <- as_date(x)
  y <- days_in_month(x)
  as_date(1:y, origin = x-1)
}
x <- c("2012-02-01")
proper_function(x)
 [1] "2012-02-01" "2012-02-02" "2012-02-03" "2012-02-04" "2012-02-05" "2012-02-06" "2012-02-07" "2012-02-08"
 [9] "2012-02-09" "2012-02-10" "2012-02-11" "2012-02-12" "2012-02-13" "2012-02-14" "2012-02-15" "2012-02-16"
[17] "2012-02-17" "2012-02-18" "2012-02-19" "2012-02-20" "2012-02-21" "2012-02-22" "2012-02-23" "2012-02-24"
[25] "2012-02-25" "2012-02-26" "2012-02-27" "2012-02-28" "2012-02-29"


问:
How to attach storage volume with elasticsearch nodes in kubernetes?
I am doing setup of Elasticseach on Kubernetes. I have created the cluster of Elasticsearch of 2 nodes. I want to attach storage with both of these nodes. like 80Gi with the first node and 100Gi with the second node.
My Kubernetes cluster is on EC2 and I am using EBS as storage.</p>

答:
In order to attach persistence, you need:

A StorageClass Object (Define the Storage)

A PersistentVolume Object (Provision the Storage)

A PersistentVolumeClaim Object (Attach the storage)

With each Node in ElasticSearch that you can attached with the pods in deployment\pod object definition.

An easier way is deploying ES cluster using Helm Chart.


问:
Matlab kalman filter in python
is there a filter function of kalman in Python that works in the same way as the Kalman function of matlab?

```<code>[kest] = kalman(sys,Qn,Rn)
</code>```

The idea is that the function receives as parameters a space of states and the respective weight matrices (it is to implement an LQR controller)

答:
You can use the pyKalman library. See the sin example followed by the filter example.

It is not exactly like Matlab but it is easy enough to use.

Title: Matlab kalman filter in python

Body:
is there a filter function of kalman in Python that works in the same way as the Kalman function of matlab?

[kest] = kalman(sys,Qn,Rn)

The idea is that the function receives as parameters a space of states and the respective weight matrices (it is to implement an LQR controller)


问:
Handling the backStack with multiple fragments & activities
From SplashActivity I am opening a DashboardFragment. Now from DashboardFragment to ServiceListActivity and from ServiceListActivity to EditServiceActivity.

Now when going back from EditServiceActivity to ServiceListActivity it's fine but when going back from ServiceListActivity to DashboardFragment  instead of going to DashboardFragment, the app is closed. Why is it happening?

答:
Put your sample code and debug log,
For reference I put sample code,
when activity transfer one to another you have to clear stack like

```<code>Intent intent= new Intent(Activity.this,class.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
</code>```

then you should specify to every activity where to go when you press back button, so override method onBackPressed(); like

```<code> @Override
public void onBackPressed()
{
    Intent intent=new Intent(Activity.this, Activity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(intent);
    finish();
}
</code>```

Body:
Put your sample code and debug log,
For reference I put sample code,
when activity transfer one to another you have to clear stack like

Intent intent= new Intent(Activity.this,class.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();

then you should specify to every activity where to go when you press back button, so override method onBackPressed(); like

 @Override
public void onBackPressed()
{
    Intent intent=new Intent(Activity.this, Activity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(intent);
    finish();
}


问:
Which OpenGL version is most stable and currently used?
I've been thinking of making an additional wrapper for my project to use OpenGL rather then Allegro. I was not sure which OpenGL version to go for since I know that some computers cannot run recent versions such as v4.4. Also, I need a version which compiles no problem in Linux, Windows, Mac.</p>

答:
It's less about operating systems, and more about video card drivers.

I think 1.4 is the highest version which enjoys support by all consumer graphics systems: ATI (AMD), nVidia, and Intel IGP.  Intel is definitely the limiting factor here, even when ATI or nVidia doesn't have hardware support, they release OpenGL 4.1 drivers which use software to emulate the missing features.  Not so with Intel.


问:
Get value from an input
How i get the value Flu with input name gejala_id0 in django from my input like this :

```<code><form method="POST" action="/diagnosis/response/" enctype="multipart/form-data" class="AVAST_PAM_nonloginform">
    <input type="hidden" name="csrfmiddlewaretoken" value="B09UeUu83ADaQQkFe2GpIV5TyO5ruEZNA1zwJJ7zgMxCRR7I0Ing4Y7wQRR22NQj">
            <ul id="id_gejala_id0">
                <li>
                    <label for="id_gejala_id0_0">
                        <input type="checkbox" name="gejala_id0" value="Flu" id="id_gejala_id0_0">
                        Flu
                    </label>
                </li>
            </ul>
</code>```

答:
Try this.</p>

```<code>request.POST.get('gejala_id0')
</code>```

Title: Get value from an input

Body:
How i get the value Flu with input name gejala_id0 in django from my input like this :

<form method="POST" action="/diagnosis/response/" enctype="multipart/form-data" class="AVAST_PAM_nonloginform">
    <input type="hidden" name="csrfmiddlewaretoken" value="B09UeUu83ADaQQkFe2GpIV5TyO5ruEZNA1zwJJ7zgMxCRR7I0Ing4Y7wQRR22NQj">

                        <input type="checkbox" name="gejala_id0" value="Flu" id="id_gejala_id0_0">
                        Flu

Body:
Try this.

request.POST.get('gejala_id0')


答:
It is not efficient and slower on many architectures than the "normal" way. I should also mention that it is not readable and very error prone.

example:

```<code>int foo(int x, int y)
{
    return (y + ((x - y) & ((x - y) >>(sizeof(int) * CHAR_BIT - 1))));
}

int foo1(int x, int y)
{
    return x > y ? y : x;
}
</code>```

and the resulting code (ARM Cortex):

```<code>foo:
        sub     r0, r0, r1
        and     r0, r0, r0, asr #31
        add     r0, r0, r1
        bx      lr
foo1:
        cmp     r0, r1
        movge   r0, r1
        bx      lr
</code>```

or x86

```<code>foo:
        sub     edi, esi
        mov     eax, edi
        sar     eax, 31
        and     eax, edi
        add     eax, esi
        ret
foo1:
        cmp     edi, esi
        mov     eax, esi
        cmovle  eax, edi
        ret
</code>```

Title: Finding minimum value between 2 numbers without comparision operators

Body:
I have seen the following method which gives the minimum value b/w 2 numbers without relational operators

y + ((x - y) & ((x - y) >>(sizeof(int) * CHAR_BIT - 1)))

In here if x=6 and y=4 x-y=2 is positive and shifting this value 31 times to the right gives 0.(as sign bit is 0 for +ve numbers) and the eqn becomes

y + ((x-y)&0)

From the above eqn we get y as min value which is true.

But for the case where x=4 and y=6, x-y=-2 and shifting it 31 times to right gives 1 and the eqn becomes:

y + ((x-y)&1)

As per my understanding bitwise & of -2 and 1 becomes 0 and the eqn gives o/p as y(6) instead of x(4). Can someone explain?

Full code: https://www.geeksforgeeks.org/compute-the-minimum-or-maximum-max-of-two-integers-without-branching/

Thanks

Body:
It is not efficient and slower on many architectures than the "normal" way. I should also mention that it is not readable and very error prone.

example:

int foo(int x, int y)
{
    return (y + ((x - y) & ((x - y) >>(sizeof(int) * CHAR_BIT - 1))));
}

int foo1(int x, int y)
{
    return x > y ? y : x;
}

and the resulting code (ARM Cortex):

foo:
        sub     r0, r0, r1
        and     r0, r0, r0, asr #31
        add     r0, r0, r1
        bx      lr
foo1:
        cmp     r0, r1
        movge   r0, r1
        bx      lr

or x86

foo:
        sub     edi, esi
        mov     eax, edi
        sar     eax, 31
        and     eax, edi
        add     eax, esi
        ret
foo1:
        cmp     edi, esi
        mov     eax, esi
        cmovle  eax, edi
        ret


问:
How can I achieve row level security in SQL Server 2014
Is there any way to get row-level security in SQL Server 2014?

My problem is:

I have a table with data for multiple regions

I created a view for each region

Specific user will have access to specific region views

But without giving access to the underlying table, those users are unable to access the views

I need to restrict users to view only certain rows. Are there any possibilities to do so?

答:
The same SQL query returns results based on identity. No special database code required. You can control how the rows and columns return, and even aggregation. For example, the SQL below will return different results for managers, analysts, and developers.
select * from employee_salaries;</p>


问:
How can I solve this "UserWarning: Attempting to use a closed FileWriter " error when trying to train my object detection model
I have made an object detection model which trained perfectly but now I removed some images from the training set to add newer better images and I'm getting the following errors

```<code>C:\Users\Swayam\Anaconda3\envs\tensor\lib\site-
packages\tensorflow\python\summary\writer\writer.py:386: UserWarning:
Attempting to use a closed FileWriter. The operation will be a noop
unless
the FileWriter is explicitly reopened.
warnings.warn("Attempting to use a closed FileWriter. "
</code>```

The following code is already present to reopen the FileWriter:

```<code> def reopen(self):
     self.event_writer.reopen()
     self._closed = False
</code>```

答:
The maximum number of steps in the training which was 200000 was reached and so it could not train further.
Need to change the limit in the python file</p>

Body:
I have made an object detection model which trained perfectly but now I removed some images from the training set to add newer better images and I'm getting the following errors

C:\Users\Swayam\Anaconda3\envs\tensor\lib\site-
packages\tensorflow\python\summary\writer\writer.py:386: UserWarning:
Attempting to use a closed FileWriter. The operation will be a noop
unless
the FileWriter is explicitly reopened.
warnings.warn("Attempting to use a closed FileWriter. "

The following code is already present to reopen the FileWriter:

 def reopen(self):
     self.event_writer.reopen()
     self._closed = False


问:
Finding minimum value between 2 numbers without comparision operators
I have seen the following method which gives the minimum value b/w 2 numbers without relational operators

```<code>y + ((x - y) & ((x - y) >>(sizeof(int) * CHAR_BIT - 1)))
</code>```

In here if x=6 and y=4 x-y=2 is positive and shifting this value 31 times to the right gives 0.(as sign bit is 0 for +ve numbers) and the eqn becomes

```<code>y + ((x-y)&0)
</code>```

From the above eqn we get y as min value which is true.

But for the case where x=4 and y=6, x-y=-2 and shifting it 31 times to right gives 1 and the eqn becomes:

```<code>y + ((x-y)&1)
</code>```

As per my understanding bitwise & of -2 and 1 becomes 0 and the eqn gives o/p as y(6) instead of x(4). Can someone explain?

Full code: https://www.geeksforgeeks.org/compute-the-minimum-or-maximum-max-of-two-integers-without-branching/

Thanks

答: Until new standard would be approved the representation of signed integers is implementation-based, and >> on them as well ( << is an UB). Let assume that   platform got signed values as complements of 2, then -2 in binary is 11111111111111111111111111111110. Shifting it to right 31 times may actually result in value of all bits set (which equals to -1) or in value 1, depends on implementation. It should be static_cast to unsigned to be shifted in definite way.


问:
How do I call `with` directly on an object thats been fetched through a route with the same results as if it were fetched through `where`?
How do I call with directly on an object thats been automagically fetched through a route with the same results as if it were fetched through where?

Let me explain through code!

My route (same in both):

Route::get('post/{post}', 'PostsController@show');

Alternative 1:

My Controller:

```<code>public function show(Post $post){
    $postWithComments = Post::where('id', $post->id)->with('comments')->first();
}
</code>```

Output: The comments of the intended post.

Alternative 2:

My Controller:

```<code>public function show(Post $post){
    $postWithComments = $post->with('comments')->first();
}
</code>```

Output: The comments from the first of ALL posts.

Desired output: Same as alternative one.

How can I modify the query in alternative 2 to output the same as alternative 1?
I am thinking that it is unnecessary to make first the where-request as I already have the object loaded. So I am thinking that I would want to do this to reduce DB calls. Or am I thinking wrong?

答:
There are two ways to solve this:

Query related data with lazy loading:

```<code>$post->comments; // this did the trick - comments for post will queried here
return $post;  // here posts already has comments collection
</code>```

Setup model binding and use eager loading:

At your Post model add resolveRouteBinding method:

```<code>class Post extends Model
{
    public function resolveRouteBinding($id)
    {
        return $this->where('id', $id)->with(['comments'])->first();
    }
}
</code>```

Then your controller will recieve Post instance with already loaded comments

Body:
How do I call with directly on an object thats been automagically fetched through a route with the same results as if it were fetched through where?

Let me explain through code!

My route (same in both):

Route::get('post/{post}', 'PostsController@show');

Alternative 1:

My Controller:

public function show(Post $post){
    $postWithComments = Post::where('id', $post->id)->with('comments')->first();
}

Output: The comments of the intended post.

Alternative 2:

My Controller:

public function show(Post $post){
    $postWithComments = $post->with('comments')->first();
}

Output: The comments from the first of ALL posts.

Desired output: Same as alternative one.

How can I modify the query in alternative 2 to output the same as alternative 1?
I am thinking that it is unnecessary to make first the where-request as I already have the object loaded. So I am thinking that I would want to do this to reduce DB calls. Or am I thinking wrong?

Body:
There are two ways to solve this:

Query related data with lazy loading:

$post->comments; // this did the trick - comments for post will queried here
return $post;  // here posts already has comments collection

Setup model binding and use eager loading:

At your Post model add resolveRouteBinding method:

class Post extends Model
{
    public function resolveRouteBinding($id)
    {
        return $this->where('id', $id)->with(['comments'])->first();
    }
}

Then your controller will recieve Post instance with already loaded comments


问:
Unable to exec in a pod using kubernetes-cli in Python even after using stream api
I am following the official documentation and to my surprise, the request just won't work.

I tried reading multiple questions and answers but in vain. I had set stream api to use but the error did not go away.

My code is:

```<code>from __future__ import print_function
import time
import kubernetes.client
from kubernetes.client.rest import ApiException
from pprint import pprint
from kubernetes import client, config, stream
stream = stream.stream

# Configure API key authorization: BearerToken
configuration = kubernetes.client.Configuration()
configuration.host = "https://my_aws_server.amazonaws.com"
configuration.verify_ssl = False
configuration.api_key['authorization'] = "some_token"
# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
configuration.api_key_prefix['authorization'] = 'Bearer'
configuration.debug = True

api_instance = kubernetes.client.CoreV1Api(
    kubernetes.client.ApiClient(configuration))
name = 'jupyter-ankita'  # str | name of the PodExecOptions
namespace = 'jhub'  # str | object name and auth scope, such as for teams and projects
# str | Command is the remote command to execute. argv array. Not executed within a shell. (optional)
command = 'echo "hail aviral"'
# bool | Redirect the standard error stream of the pod for this call. Defaults to true. (optional)
stderr = True
# bool | Redirect the standard input stream of the pod for this call. Defaults to false. (optional)
stdin = True
# bool | Redirect the standard output stream of the pod for this call. Defaults to true. (optional)
stdout = True
# bool | TTY if true indicates that a tty will be allocated for the exec call. Defaults to false. (optional)
tty = True

try:
    api_response = stream(api_instance.connect_post_namespaced_pod_exec(
        name, namespace, command=command, stderr=stderr, stdin=stdin, stdout=stdout)
    )
    pprint(api_response)
except ApiException as e:
    print("Exception when calling CoreV1Api->connect_post_namespaced_pod_exec: %s\n" % e)

</code>```

I want the command to run but instead, I am facing an error:

```<code>Exception when calling CoreV1Api->connect_post_namespaced_pod_exec: (400)
Reason: Bad Request
HTTP response headers: HTTPHeaderDict({'Audit-Id': '88df8863-61b1-4fe7-9d39-d0e6059ea993', 'Content-Type': 'application/json', 'Date': 'Tue, 28 May 2019 14:04:38 GMT', 'Content-Length': '139'})
HTTP response body: {"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"Upgrade request required","reason":"BadRequest","code":400}
</code>```

My SSL client is updated, I am using Python3.7 from the brew on a MacOS.

Also used on Ubuntu, same error.

The versions are:

```<code>Client Version: version.Info{Major:"1", Minor:"12", GitVersion:"v1.12.3", GitCommit:"some_no", GitTreeState:"clean", BuildDate:"2018-11-27T01:14:37Z", GoVersion:"go1.11.2", Compiler:"gc", Platform:"darwin/amd64"}
Server Version: version.Info{Major:"1", Minor:"12+", GitVersion:"v1.12.6-eks-d69f1b", GitCommit:"some_no", GitTreeState:"clean", BuildDate:"2019-02-28T20:26:10Z", GoVersion:"go1.10.8", Compiler:"gc", Platform:"linux/amd64"}
</code>```

UPDATE:
I changed my functions to:

```<code>api_response = stream( api_instance.connect_post_namespaced_pod_exec, name, namespace, command=command, stderr=stderr, stdin=stdin, stdout=stdout )
</code>```

and it was able to exec. But, now I am facing the following error:

```<code>('rpc error: code = 2 desc = oci runtime error: exec failed: '
 'container_linux.go:262: starting container process caused "exec: \\"echo '
 '\\\\\\"hail aviral\\\\\\"\\": executable file not found in $PATH"\n'
 '\r\n')
</code>```

It is saying that the exec failed.

答:
Missing entry point for the remote command execution.
Try this one:</p>

```<code>command = [
    '/bin/sh',
    '-c',
    'echo hail aviral']
</code>```

Body:
I am following the official documentation and to my surprise, the request just won't work.

I tried reading multiple questions and answers but in vain. I had set stream api to use but the error did not go away.

My code is:

from __future__ import print_function
import time
import kubernetes.client
from kubernetes.client.rest import ApiException
from pprint import pprint
from kubernetes import client, config, stream
stream = stream.stream

# Configure API key authorization: BearerToken
configuration = kubernetes.client.Configuration()
configuration.host = "https://my_aws_server.amazonaws.com"
configuration.verify_ssl = False
configuration.api_key['authorization'] = "some_token"
# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
configuration.api_key_prefix['authorization'] = 'Bearer'
configuration.debug = True

api_instance = kubernetes.client.CoreV1Api(
    kubernetes.client.ApiClient(configuration))
name = 'jupyter-ankita'  # str | name of the PodExecOptions
namespace = 'jhub'  # str | object name and auth scope, such as for teams and projects
# str | Command is the remote command to execute. argv array. Not executed within a shell. (optional)
command = 'echo "hail aviral"'
# bool | Redirect the standard error stream of the pod for this call. Defaults to true. (optional)
stderr = True
# bool | Redirect the standard input stream of the pod for this call. Defaults to false. (optional)
stdin = True
# bool | Redirect the standard output stream of the pod for this call. Defaults to true. (optional)
stdout = True
# bool | TTY if true indicates that a tty will be allocated for the exec call. Defaults to false. (optional)
tty = True

try:
    api_response = stream(api_instance.connect_post_namespaced_pod_exec(
        name, namespace, command=command, stderr=stderr, stdin=stdin, stdout=stdout)
    )
    pprint(api_response)
except ApiException as e:
    print("Exception when calling CoreV1Api->connect_post_namespaced_pod_exec: %s\n" % e)

I want the command to run but instead, I am facing an error:

Exception when calling CoreV1Api->connect_post_namespaced_pod_exec: (400)
Reason: Bad Request
HTTP response headers: HTTPHeaderDict({'Audit-Id': '88df8863-61b1-4fe7-9d39-d0e6059ea993', 'Content-Type': 'application/json', 'Date': 'Tue, 28 May 2019 14:04:38 GMT', 'Content-Length': '139'})
HTTP response body: {"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"Upgrade request required","reason":"BadRequest","code":400}

My SSL client is updated, I am using Python3.7 from the brew on a MacOS.

Also used on Ubuntu, same error.

The versions are:

Client Version: version.Info{Major:"1", Minor:"12", GitVersion:"v1.12.3", GitCommit:"some_no", GitTreeState:"clean", BuildDate:"2018-11-27T01:14:37Z", GoVersion:"go1.11.2", Compiler:"gc", Platform:"darwin/amd64"}
Server Version: version.Info{Major:"1", Minor:"12+", GitVersion:"v1.12.6-eks-d69f1b", GitCommit:"some_no", GitTreeState:"clean", BuildDate:"2019-02-28T20:26:10Z", GoVersion:"go1.10.8", Compiler:"gc", Platform:"linux/amd64"}

UPDATE:
I changed my functions to:

api_response = stream( api_instance.connect_post_namespaced_pod_exec, name, namespace, command=command, stderr=stderr, stdin=stdin, stdout=stdout )

and it was able to exec. But, now I am facing the following error:

('rpc error: code = 2 desc = oci runtime error: exec failed: '
 'container_linux.go:262: starting container process caused "exec: \\"echo '
 '\\\\\\"hail aviral\\\\\\"\\": executable file not found in $PATH"\n'
 '\r\n')

It is saying that the exec failed.

Body:
Missing entry point for the remote command execution.
Try this one:

command = [
    '/bin/sh',
    '-c',
    'echo hail aviral']


问:
How do you insert and retrieve an array value out of a MySQL database with PHP?
So I have a PHP array "$shared" with values [0, 1, 2] (I'm just using this as an example).
I want to insert and retrieve this array from my  MySQL database, but its not working.

Currently I'm using this code to insert it:

```<code>mysqli_query($dbhandle, "INSERT INTO table (arraytest) VALUES ('$shared')");
</code>```

And after the above code the value in 'table' in column 'arraytest' is 'Array' instead of [0, 1, 2] or however an array should look like in a MySQL database.

After inserting the array into my database, I want to retrieve it, and am currently using this code:

```<code>$id='2';

$result = mysqli_query($dbhandle, "SELECT arraytest FROM table");

while ($row = mysqli_fetch_array($result)) {

$shared=$row{'arraytest'};

if(in_array($id, $shared)){

    echo 'Value is in the array. Success!';

}

}
</code>```

I did some researching online, and have not found a way to do this specifically.

I want to insert a PHP array() into one cell in the table in the database,
and then I want to retrieve that array from the database and check if a certain value is in the array which I previously inserted into the database.

P.S. I am not trying to retrieve an entire column of values from the database as an array. This is what i have found on google when i search for an answer, and it is not what i want to do.

答:
How to retrieve the array data from the database? I am inserted the array data using PHP implode function.

```<code>$val=implode(',',$val);
</code>```

I am inserted into the MySQL database.

Body:
So I have a PHP array "$shared" with values [0, 1, 2] (I'm just using this as an example).
I want to insert and retrieve this array from my  MySQL database, but its not working.

Currently I'm using this code to insert it:

mysqli_query($dbhandle, "INSERT INTO table (arraytest) VALUES ('$shared')");

And after the above code the value in 'table' in column 'arraytest' is 'Array' instead of [0, 1, 2] or however an array should look like in a MySQL database.

After inserting the array into my database, I want to retrieve it, and am currently using this code:

$id='2';

$result = mysqli_query($dbhandle, "SELECT arraytest FROM table");

while ($row = mysqli_fetch_array($result)) {

$shared=$row{'arraytest'};

if(in_array($id, $shared)){

    echo 'Value is in the array. Success!';

}

}

I did some researching online, and have not found a way to do this specifically.

I want to insert a PHP array() into one cell in the table in the database,
and then I want to retrieve that array from the database and check if a certain value is in the array which I previously inserted into the database.

P.S. I am not trying to retrieve an entire column of values from the database as an array. This is what i have found on google when i search for an answer, and it is not what i want to do.

Body:
How to retrieve the array data from the database? I am inserted the array data using PHP implode function.

$val=implode(',',$val);

I am inserted into the MySQL database.


问:
Remove Line If It Contains Exact String From Line Of Another File
I have a large file and would like to remove any lines from the file that contain an exact string listed in another file. However, the string must match exactly (I'm sorry I don't know how to describe this better).

Here is the file:

```<code>one@email.com,name,surname,city,state
two@email.com,name,surname,city,state
three@email.com,name,surname,city,state
anotherone@email.com,name,surname,city,state
</code>```

And here is the example list to filter with:

```<code>one@email.com
three@email.com
</code>```

The desired output is:

```<code>two@email.com,name,surname,city,state
anotherone@email.com,name,surname,city,state
</code>```

I have tried to do this using the following:

```<code>grep -v -f 2.txt 1.txt > 3.txt
</code>```

However this produces the output:

```<code>two@email.com,name,surname,city,state
</code>```

I assume it's doing this because "anotherone@email.com" contains "one@email.com". I've searched for a way to include beginning of the line, but not found anything suitable.

I'm open to doing in something other than grep too, I used grep because I couldn't figure it out any other way.

答:
If you only like to print lines from first file that does not contains data from second file in the first field, then this should do:

```<code>$cat file
one@email.com,name,surname,city,state
two@email.com,name,surname,city,state
three@email.com,name,surname,city,state
anotherone@email.com,name,surname,city,state
$cat filter
one@email.com
three@email.com

awk -F, 'NR==FNR {a[$0]++;next} !($1 in a)' filter file
two@email.com,name,surname,city,state
anotherone@email.com,name,surname,city,state
</code>```

For every line in the filter this creates an array a with the name and value to 1

Like a[one@email.com]=1 and a[three@email.com]=1

Then awk test line by line in the file against the array, giving

```<code>a[one@email.com]=1
a[two@email.com]=
a[three@email.com]=1
a[anotherone@email.com]=
</code>```

Then print all line from the file without 1

```<code>two@email.com,name,surname,city,state
anotherone@email.com,name,surname,city,state
</code>```

Body:
I have a large file and would like to remove any lines from the file that contain an exact string listed in another file. However, the string must match exactly (I'm sorry I don't know how to describe this better).

Here is the file:

one@email.com,name,surname,city,state
two@email.com,name,surname,city,state
three@email.com,name,surname,city,state
anotherone@email.com,name,surname,city,state

And here is the example list to filter with:

one@email.com
three@email.com

The desired output is:

two@email.com,name,surname,city,state
anotherone@email.com,name,surname,city,state

I have tried to do this using the following:

grep -v -f 2.txt 1.txt > 3.txt

However this produces the output:

two@email.com,name,surname,city,state

I assume it's doing this because "anotherone@email.com" contains "one@email.com". I've searched for a way to include beginning of the line, but not found anything suitable.

I'm open to doing in something other than grep too, I used grep because I couldn't figure it out any other way.

Body:
If you only like to print lines from first file that does not contains data from second file in the first field, then this should do:

$cat file
one@email.com,name,surname,city,state
two@email.com,name,surname,city,state
three@email.com,name,surname,city,state
anotherone@email.com,name,surname,city,state
$cat filter
one@email.com
three@email.com

awk -F, 'NR==FNR {a[$0]++;next} !($1 in a)' filter file
two@email.com,name,surname,city,state
anotherone@email.com,name,surname,city,state

For every line in the filter this creates an array a with the name and value to 1

Like a[one@email.com]=1 and a[three@email.com]=1

Then awk test line by line in the file against the array, giving

a[one@email.com]=1
a[two@email.com]=
a[three@email.com]=1
a[anotherone@email.com]=

Then print all line from the file without 1

two@email.com,name,surname,city,state
anotherone@email.com,name,surname,city,state


问:
Optimising Matrix Calculation in C
I'm trying to find the most efficient method for multiplying a Matrix by its transpose. Any ideas on the most efficient mathematical formula?</p>

答:
You can improve your first solution, by initializing A and B matrix in the same for loop.

n * k is also calculated two times, you can store it into a variable to save some time.

It is better to use B[i + n * j] += ... instead of B[i + n * j] = B[i + n * j] + ..., because in the first one, B[i + n * j] is read once, when at the second on it is read twice.

```<code>void print_unmodified()
{
    unsigned int n = 64u;
    unsigned int A[N_MAX];
    unsigned int B[N_MAX];

    /* Initializing the A and B matrix with values 1->64^2 */
    for (int i = 0; i < (n * n); i++)
    {
        A[i] = i + 1;
        B[i] = 0u;
    }

    /* Matrix Multiplication B = A*A' */
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            int index = i + n*j;
            for (int k = 0; k < n; k++)
            {
                int p = n * k;
                B[index] += A[i + p] * A[j + p];
            }
        }
    }
}
</code>```

Title: Optimising Matrix Calculation in C

Body:
You can improve your first solution, by initializing A and B matrix in the same for loop.

n * k is also calculated two times, you can store it into a variable to save some time.

It is better to use B[i + n * j] += ... instead of B[i + n * j] = B[i + n * j] + ..., because in the first one, B[i + n * j] is read once, when at the second on it is read twice.

void print_unmodified()
{
    unsigned int n = 64u;
    unsigned int A[N_MAX];
    unsigned int B[N_MAX];

    /* Initializing the A and B matrix with values 1->64^2 */
    for (int i = 0; i < (n * n); i++)
    {
        A[i] = i + 1;
        B[i] = 0u;
    }

    /* Matrix Multiplication B = A*A' */
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            int index = i + n*j;
            for (int k = 0; k < n; k++)
            {
                int p = n * k;
                B[index] += A[i + p] * A[j + p];
            }
        }
    }
}


问:
How to read content of JSON file uploaded to google cloud storage using node js
I manually upload the JSON file to google cloud storage by creating a new project. I am able to read the metadata for a file but I don't know how to read the JSON content.

The code I used to read the metadata is:

```<code>var Storage = require('@google-cloud/storage');
const storage = Storage({
    keyFilename: 'service-account-file-path',
    projectId: 'project-id'
});
storage
    .bucket('project-name')
    .file('file-name')
    .getMetadata()
    .then(results => {
        console.log("results is", results[0])
    })
    .catch(err => {
        console.error('ERROR:', err);
    });
</code>```

Can someone guide me to the way to read the JSON file content?

答:
There exists a convenient method:'download' to download a file into memory or to a local destination. You may use download method as follows:</p>

```<code>const bucketName='bucket name here';
const fileName='file name here';
const storage = new Storage.Storage();
const file = storage.bucket(bucketName).file(fileName);

file.download(function(err, contents) {
     console.log("file err: "+err);
     console.log("file data: "+contents);
});
</code>```

Body:
I manually upload the JSON file to google cloud storage by creating a new project. I am able to read the metadata for a file but I don't know how to read the JSON content.

The code I used to read the metadata is:

var Storage = require('@google-cloud/storage');
const storage = Storage({
    keyFilename: 'service-account-file-path',
    projectId: 'project-id'
});
storage
    .bucket('project-name')
    .file('file-name')
    .getMetadata()
    .then(results => {
        console.log("results is", results[0])
    })
    .catch(err => {
        console.error('ERROR:', err);
    });

Can someone guide me to the way to read the JSON file content?

Body:
There exists a convenient method:'download' to download a file into memory or to a local destination. You may use download method as follows:

const bucketName='bucket name here';
const fileName='file name here';
const storage = new Storage.Storage();
const file = storage.bucket(bucketName).file(fileName);

file.download(function(err, contents) {
     console.log("file err: "+err);
     console.log("file data: "+contents);
});