text:
Q: Creating new dataframes with rows of groups I would like to extract the rows of each dataframe of my group and create new dataframes from them such that a new dataframe only consists of the first rows of the group, another new dataframe the second rows, another for the third rows and so on.. For instance, my dataframe is:
raw_data = {'regiment': ['Nighthawks', 'Nighthawks', 'Nighthawks', 'Nighthawks', 'Dragoons', 'Dragoons', 'Dragoons', 'Dragoons', 'Scouts', 'Scouts', 'Scouts', 'Scouts'],
    'name': ['Miller', 'Jacobson', 'Ali', 'Milner', 'Cooze', 'Jacon', 'Ryaner', 'Sone', 'Sloan', 'Piger', 'Riani', 'Ali'],
    'preTestScore': [4, 24, 31, 2, 3, 4, 24, 31, 2, 3, 2, 3],
    'postTestScore': [25, 94, 57, 62, 70, 25, 94, 57, 62, 70, 62, 70]}
df = pd.DataFrame(raw_data, columns = ['regiment', 'name', 'preTestScore', 'postTestScore'])
df

      regiment      name  preTestScore  postTestScore
0   Nighthawks    Miller             4             25
1   Nighthawks  Jacobson            24             94
2   Nighthawks       Ali            31             57
3   Nighthawks    Milner             2             62
4     Dragoons     Cooze             3             70
5     Dragoons     Jacon             4             25
6     Dragoons    Ryaner            24             94
7     Dragoons      Sone            31             57
8       Scouts     Sloan             2             62
9       Scouts     Piger             3             70
10      Scouts     Riani             2             62
11      Scouts       Ali             3             70

and I grouped it as:
gb = df.groupby("regiment")

   regiment   name  preTestScore  postTestScore
8    Scouts  Sloan             2             62
9    Scouts  Piger             3             70
10   Scouts  Riani             2             62
11   Scouts    Ali             3             70
------------------
     regiment      name  preTestScore  postTestScore
0  Nighthawks    Miller             4             25
1  Nighthawks  Jacobson            24             94
2  Nighthawks       Ali            31             57
3  Nighthawks    Milner             2             62
------------------
   regiment    name  preTestScore  postTestScore
4  Dragoons   Cooze             3             70
5  Dragoons   Jacon             4             25
6  Dragoons  Ryaner            24             94
7  Dragoons    Sone            31             57
------------------

I want to create dataframes such as:
dataframe with the first rows:
    regiment        name         preTestScore  postTestScore
8    Scouts        Sloan              2             62
0    Nighthawks    Miller             4             25
4    Dragoons      Cooze              3             70

dataframe with the second rows:
   regiment          name        preTestScore  postTestScore
9    Scouts         Piger             3             70
1    Nighthawks    Jacobson           24            94
5    Dragoons       Jacon             4             25

and so on.
I was thinking of using Group.apply() but I'm not too sure.
Thank you very much!

A: Dictionaries are of course unordered.  Given that the sample data only has four rows per regiment, here is the ranking of the top four, which uses nth on the groupby.  The result was created using a dictionary comprehension iterating through range four (0, 1, 2, 3), taking the nth row of such value, and translating the value back to its ordinal name (e.g. 0 equals 'first').
d = {n: ordinal for n, ordinal in zip(
             range(5), ['first', 'second', 'third', 'fourth', 'fifth'])}

top_n = 4
>>> {d[n]: df.groupby(['regiment']).nth(n) for n in range(top_n)}
{'first':               name  postTestScore  preTestScore
 regiment
 Dragoons     Cooze             70             3
 Nighthawks  Miller             25             4
 Scouts       Sloan             62             2,
 'fourth':               name  postTestScore  preTestScore
 regiment
 Dragoons      Sone             57            31
 Nighthawks  Milner             62             2
 Scouts         Ali             70             3,
 'second':                 name  postTestScore  preTestScore
 regiment
 Dragoons       Jacon             25             4
 Nighthawks  Jacobson             94            24
 Scouts         Piger             70             3,
 'third':               name  postTestScore  preTestScore
 regiment
 Dragoons    Ryaner             94            24
 Nighthawks     Ali             57            31
 Scouts       Riani             62             2}

For rows of different length:
df = df.iloc[1:-1, :]  # Drop first and last row.
>>> {d[n]: df.groupby(['regiment']).nth(n).reindex(sorted(df.regiment.unique()))
     for n in range(top_n)}
{'first':                 name  postTestScore  preTestScore
 regiment
 Dragoons       Cooze             70             3
 Nighthawks  Jacobson             94            24
 Scouts         Sloan             62             2,
 'fourth':             name  postTestScore  preTestScore
 regiment
 Dragoons    Sone             57            31
 Nighthawks   NaN            NaN           NaN
 Scouts       NaN            NaN           NaN,
 'second':              name  postTestScore  preTestScore
 regiment
 Dragoons    Jacon             25             4
 Nighthawks    Ali             57            31
 Scouts      Piger             70             3,
 'third':               name  postTestScore  preTestScore
 regiment
 Dragoons    Ryaner             94            24
 Nighthawks  Milner             62             2
 Scouts       Riani             62             2}

A: groupby on custom index, use dicts to store
In [67]: {x:g for x,g in df.sort_values(by='regiment',ascending=False).groupby(df.index%4)}
Out[67]:
{0:      regiment    name  preTestScore  postTestScore
 8      Scouts   Sloan             2             62
 0  Nighthawks  Miller             4             25
 4    Dragoons   Cooze             3             70,
 1:      regiment      name  preTestScore  postTestScore
 9      Scouts     Piger             3             70
 1  Nighthawks  Jacobson            24             94
 5    Dragoons     Jacon             4             25,
 2:       regiment    name  preTestScore  postTestScore
 10      Scouts   Riani             2             62
 2   Nighthawks     Ali            31             57
 6     Dragoons  Ryaner            24             94,
 3:       regiment    name  preTestScore  postTestScore
 11      Scouts     Ali             3             70
 3   Nighthawks  Milner             2             62
 7     Dragoons    Sone            31             57}

Or list
In [71]: grps = [g for _,g in (df.sort_values(by='regiment',ascending=False)
                                 .groupby(df.index%4))]

In [72]: grps[0]
Out[72]:
     regiment    name  preTestScore  postTestScore
8      Scouts   Sloan             2             62
0  Nighthawks  Miller             4             25
4    Dragoons   Cooze             3             70

In [73]: grps[1]
Out[73]:
     regiment      name  preTestScore  postTestScore
9      Scouts     Piger             3             70
1  Nighthawks  Jacobson            24             94
5    Dragoons     Jacon             4             25

A: You could probably do this with a nested groupby with cumcount, e.g. this will group all the first occurrences of the regiments, all the second occurrences of the regiments, etc.:
In []:
[g for _, g in df.groupby(df.groupby('regiment').cumcount())]

Out[]:
[     regiment    name  preTestScore  postTestScore
 0  Nighthawks  Miller             4             25
 4    Dragoons   Cooze             3             70
 8      Scouts   Sloan             2             62,
      regiment      name  preTestScore  postTestScore
 1  Nighthawks  Jacobson            24             94
 5    Dragoons     Jacon             4             25
 9      Scouts     Piger             3             70,
       regiment    name  preTestScore  postTestScore
 2   Nighthawks     Ali            31             57
 6     Dragoons  Ryaner            24             94
 10      Scouts   Riani             2             62,
       regiment    name  preTestScore  postTestScore
 3   Nighthawks  Milner             2             62
 7     Dragoons    Sone            31             57
 11      Scouts     Ali             3             70]


text:
Q: "Enjoy!" Enjoy what? Why is it that Americans invite all and sundry to "Enjoy!" without including an object noun in the sentence, when the dative case of the verb 'to enjoy' clearly demands one to be correct?

A: Enjoy is used as an absolute verb here, which means that the object is implied but not stated.
There is another famous example also: if looks could kill... Here, the transitive kill is used as an absolute verb.
Though, there is a history behind the good wish "Enjoy!" meaning "Enjoy your meal!" and it is derived from a Yiddish phrase. An article in The New York Times talks about the history of this phrase and mentions the first absolute use of the transitive enjoy:

In his 1986 book, "Yiddish and English," Random House lexicographer Sol Steinmetz cites this 1968 quotation of furrier Jacques Kaplan by Marylin Bender in The New York Times: "It's a dancing over the volcano attitude, an enjoy-enjoy philosophy." That reduplication is typical of Yiddish -- Es, es means "Eat, eat" -- and the friendly command of Enjoy! comes from Hob anoe , a Yiddish phrase derived from the German hob , "have," and the Hebrew hanoe , "enjoyment."
The earliest example of the absolute use of the transitive enjoy comes from an essay by English author John Ruskin in "The Eagle's Nest," in 1872: "It is appointed for all men to enjoy, but for few to achieve."
http://www.nytimes.com/1992/05/24/magazine/on-language-enjoy.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android Install on Device Failure [INSTALL_CANCELED_BY_USER] I'm using Android Studio to connect to run app in my Xiaomi Redmi Note 3G device. My device is already found in the Choose Device Dialog, but I keep getting the [INSTALL_CANCELED_BY_USER] error :
Waiting for device.
Target device: xiaomi-hm_note_1w-SSE6Y97PFYQCRK45
Uploading file
local path: C:\Users\Anthony\AndroidStudioProjects\UASProject\app\build\outputs\apk\app-debug.apk
remote path: /data/local/tmp/com.si.UASPROJECT
Installing com.si.UASPROJECT
DEVICE SHELL COMMAND: pm install -r "/data/local/tmp/com.si.UASPROJECT"
pkg: /data/local/tmp/com.si.UASPROJECT
Failure [INSTALL_CANCELED_BY_USER]

I tried looking for solutions online, but there's no mention of Failure [INSTALL_CANCELED_BY_USER] error.

A: In my case I turn on "Install via USB" and also make sure "USB Debugging" is on.

A: if you are at MIUI 8.

Follow the steps

Step 1: Settings > Additional Settings > Privacy: Check the Unknown Sources option.
Step 2: Settings > Additional Settings > Developer Options > Turn On USB Debugging
Step 3: Settings > Additional Settings > Developer Options > install Via USB
Step 4: Settings > Additional Settings > Developer Options > Turn off MIUI Optimization.
Step 5: Restart your Mobile.

A: I had an error of Session 'app': Error Installing APKs in Redmi 3S 6.0.1 MIUI Global 8.2. After turning OFF Instant Run in Android Studio, the error did not occur again. For this, Go to File Menu->Settings->Build, Execution, Deployment->Instant Run->Check OFF Enable Instant Run.
But I wanted to use Instant Run features, so,
Go to Settings-> Additional settings->Developer options->Turn off MIUI optimization. Restart phone.
Both of the above methods worked. If the error still occurs, check to Turn on USB debugging and Install via USB.

A: *

*Open Security App pre-installed in MIUI

*Then click Optimize. Try to achieve 100% score.

*Activate developer's option by clicking multiple times on MIUI version. (Everyone knows how to do this)

*Then Disable WiFi and switch on install via USB under Developers option while you are connected through Mobile data and under your Xiaomi account.

A: I have same problem before, here is my solution:
Step 1: Go to "Setting" → find "Developer options" in System, and click.
Step 2: TURN ON "Verify apps over USB" in Debbuging section.
Step 3: Try "Run app" in Android Studio again!

A: "Install via USB" wont work if your Xiaomi phone is running MIUI 8 or above. Looks like when you try to Enable this option, your phone trys to connect to some chinese server and fails.
I got a work around and it worked for me. Idea is to connect to Chinese-Shanghai server through VPN. Try the following:
1.Install PlexVPN from Playstore and login into it. You will a 24 hr free VPN service.
2.Select China-Shanghai server and connect.
3.From developer option in your Xiaomi phone, Enable "Install via USB".
You can then disconnect the VPN and logout from PlexVPN.
Enjoy!!

A:
IF YOU HAVE TRIED EVERYTHING, TRY THESE STEPS ALSO

Step 0: Turn On MIUI Optimization & Restart.
Step 1: Settings > Additional Settings > Privacy: Check the Unknown Sources option.
Step 2: Settings > Additional Settings > Developer Options > Turn On USB Debugging
Step 3: Settings > Additional Settings > Developer Options > install Via USB
Step 4: Settings > Additional Settings > Developer Options > Turn off MIUI Optimization.
Step 5: Restart your Mobile.

A:
Turn off Miui Optimizations on Developer Settings, then Restart the phone.

A: Sometimes it happens because the user does not accept the installation in time. You can turn off "Monitor apps installed by USB" to override user confirmation.

A: Go to Settings-> Additional settings->Developer options->Turn off MIUI optimization
You must Turn on USB debugging and Install via USB
Hope it help

A: Follow the steps

*

*Go to settings -> Additional Settings -> Developer Options(if not found then tap MIUI version in About phone multiple times) -> Turn off MIUI optimization.

*GO to settings -> Mi Account -> Sign out(if signed in)-> developer options->turn on Install via USB(sign in page will open) -> Sign in to your mi Account
It should work,
if still these steps doesn't work for you then reboot your phone after these two steps

A: Happens to my Xiaomi phone after updated it to MIUI 8. Took me hours to figure it out!
Check the followings if you're a victim too:

*

*Go to Settings -> Permissions -> Install via USB: Uncheck your App if it's listed.

*Go to Settings -> Additional Settings -> Privacy: Check the Unknown Sources option.

*Finally go to Settings -> Additional Settings -> Developer options: Check the Install via USB option.

Update (MIUI 8):

Signin in to MI account is required to enable Install via USB option.

Update 2
For some devices (e.g. Redmi) you might need to turn off MIUI Optimization and reboot your phone.
Settings > Additional Settings > Developer Options > MIUI Optimization
P.S. don't update MIUI unless necessary!
May the victims saved

A: Step 1 : Turn on Developer Option (Settings > About Phone > Click 7 Times On "MIUI Version").
Step 2 : Connect Your Device via USB to PC
step 3 : Settings > Additional Settings >  Developer Options > Turn On USB Debugging.
Step 4 : Also You Should turn On Settings > Additional Settings >  Developer Options >  install Via USB
Enjoy Coding ... :-)

A: All the above instructions should work but if you're using MI Redmi Note 5A or later versions, you'll see that toggling "install via USB" toggles back off.
That's because the new versions somehow requires you to be in China. To fix this, download Windscribe VPN from playstore(it's free to use). Off your wifi and on mobile data. Connect to HongKong.
Go back and toggle "Install via USB". It'll work now. Disconnect the VPN.

A: *

*Go to "Setting" → find "Developer options" in System

*TURN OFF "Verify apps over USB" in Debbuging section.

A: I too faced similar issue after updating of Redmi to 8.5.7 OS but none of them mentioned above are worked. When I am trying to turn on Install via USB in developer options it is restricting.. So I did like following
Simply I did:

*

*Logout from Redmi account

*Relogin again

*Turn on Install via USB in developer options

Update: if you still unable to tun on just switch off Wi-Fi and turn on mobile data and try to switch it on.
This solved my issue.

A: in miui 9 u must have access to the INTERNET to make it work
Step 1 : Turn on Developer Option (Settings > About Phone > Click 7 Times On "MIUI Version").
Step 2 : Connect Your Device via USB to PC
step 3 : Settings > Additional Settings > Developer Options > Turn On USB Debugging.
Step 4 : Also You Should turn On Settings > Additional Settings > Developer Options > install Via USB

A: for check, sometime just need go to:

*

*Settings

*Permissions

*Install via USB (turn off your app if exist)
It was my case. Thanks @Jiyeh

A: You have to in able the install via USB mode, to do that
1.go to Settings=>Aditional setting=>Developer Options=>Install via USB tuggle it on, If you are having trouble tuggeling the option on,
2.You will have to insert a sim in and use a chineese VPN;
You can use a vpn of following setting:
tpye: L2TP/IPSec PSK
server address: vpn959922015.opengw.net
IPSec pre-sared key: vpn
username: vpn
password: vpn
3.And remember to turn on OEM unlocking in the developer options
and then appempt to turn on Install via USB;


text:
Q: Tricky parametrization problem Find $|r(1)|$ if $|r(0)| = 0$ and $(r \text{dot} r')(t) = 6t^2$ $\forall t$.
What is the trick for this one? How do I work backwards?

A: $$\frac{d}{dt}\left(\frac12\|\vec{r}\|^2\right)=\frac12\frac{d}{dt}\left(\vec{r}\cdot\vec{r}\right)=\vec{r}\cdot\dot{\vec{r}}$$
So if $\vec{r}\cdot\dot{\vec{r}}=6t^2$, we can integrate to find:
$$\frac12\|\vec{r}(1)\|^2-\frac12\|\vec{r}(0)\|^2=\int_0^16t^2\,dt\\
\implies \frac12\|\vec{r}(1)\|^2=2\\
\implies \|\vec{r}(1)\|=2.$$


text:
Q: Unit test case for file upload flask I have created a flask application, where I am uploading a file and then predicting the type of the file. I want to write unit test case for the same. I am new to unit test in python and therefore very confused!. There are 2 parts to my code, the first is the Main function, which then calls the classification method.
main.py - here the file is being uploaded and then we call the func_predict function which returns the output
upload_parser = api.parser()
upload_parser.add_argument('file', location='files',
                       type=FileStorage, required=True)
@api.route('/classification')
@api.expect(upload_parser)
class classification(Resource):

    def post(self):
    """
       predict the document
    """
        args = upload_parser.parse_args()
        uploaded_file = args['file']
        filename = uploaded_file.filename
        prediction,confidence = func_predict(uploaded_file)
        return {'file_name':filename,'prediction': prediction,'confidence':confidence}, 201

predict.py : this file contains the func_predict function which does the actual prediction work. It takes the uploaded file as an input
def func_predict(file):
    filename = file.filename #filename
    extension = os.path.splitext(filename)[1][1:].lower() #file_extension
    path = os.path.join(UPLOAD_FOLDER, filename) #store the temporary path of the file
    output = {}
    try:
    # Does some processing.... some lines which are not relevant and then returns the two values
    return (''.join(y_pred),max_prob)

Now my confusion is, How do i mock the uploaded file, the uploaded file is of FileStorage type. Also which method should i perform the testing for, should it be the '/classification' or the func_predict.
I have tried the below method, though I did not get any success in this.
I created a test.py file and imported the classification method from main.py and then passed a filename to the data
from flask import Flask, Request
import io
import unittest
from main import classification

class TestFileFail(unittest.TestCase):

    def test_1(self):

        app = Flask(__name__)
        app.debug = True
        app.request_class = MyRequest

        client = app.test_client()
        resp = client.post(
            '/classification',
            data = {
            'file': 'C:\\Users\\aswathi.nambiar\\Desktop\\Desktop docs\\W8_ECI_1.pdf'
        }, content_type='multipart/form-data'
    )
        print(resp.data)

        self.assertEqual(
        'ok',
        resp.data,
    )

if __name__ == '__main__':
    unittest.main()

I am completely lost! I know there have been earlier questions, but I am not able to figure out .

A: I have finally stumbled upon how to test it, in case anybody was looking out for something similar.
from predict_main_restplus import func_predict
from werkzeug.datastructures import FileStorage
file = None

def test_classification_correct():
    with open('W8-EXP_1.pdf', 'rb') as fp:
        file = FileStorage(fp)
        a , b = func_predict(file)
        assert (a, b) == ('W-8EXP',90.15652760121652)

So, here we are testing the prediction function in predict.py, it returns two values, prediction result and the confidence of the prediction. We can mock the upload using open(file) and then wrapping it with FileStorage. This worked for me.


text:
Q: Making all form inputs to be in readonly mode while clicking submit button I have a form when the submit button is clicked form's all inputs needs to be in read-only mode and hide submit button and also displays submitting text. For this I coded:

$(document).ready(function() {
  $("#submit_text").hide(); //Hiding submit_text
  $("#testsubmitbutton").click(function() {
    $("#testsubmitbutton").hide(); //Hiding submit button
    $("#submit_text").show(); //Showing submit_text

    $("#testform :input").prop('readonly', true); //Making all inputs to readonly

  });
});
.hiddenFramehideclass {
  position: absolute;
  top: -1px;
  left: -1px;
  width: 1px;
  height: 1px;
}

<form method="post" action="" enctype="multipart/form-data" id="testform" target="hiddenFrame">

  Question 1

Question?

      <input type="hidden" name="qid1" value="22">

        <input type="radio" name="radio1" id="checka1" value="A">

A

        <input type="radio" name="radio1" id="checkb1" value="B">

B

        <input type="radio" name="radio1" id="checkc1" value="C">

C

        <input type="radio" name="radio1" id="checkd1" value="D">

D

        <input type="radio" name="radio1" id="checke1" value="E">

None of the above

  <button class="" type="submit" name="testsubmitbutton" id="testsubmitbutton">Submit</button>
  Submitting please do not refresh!
</form>

When I click the submit button it hides the submit button and shows submitting text. But it doesn't change the input property to read-only mode.

A: For radio button use disabled property:

$(document).ready(function() {
  $("#submit_text").hide(); //Hiding submit_text
  $("#testsubmitbutton").click(function() {
    $("#testsubmitbutton").hide(); //Hiding submit button
    $("#submit_text").show(); //Showing submit_text

    $("#testform :input").prop('disabled', true); //Making all inputs to disabled

  });
});
.hiddenFramehideclass {
  position: absolute;
  top: -1px;
  left: -1px;
  width: 1px;
  height: 1px;
}

<form method="post" action="" enctype="multipart/form-data" id="testform" target="hiddenFrame">

  Question 1

Question?

      <input type="hidden" name="qid1" value="22">

        <input type="radio" name="radio1" id="checka1" value="A">

A

        <input type="radio" name="radio1" id="checkb1" value="B">

B

        <input type="radio" name="radio1" id="checkc1" value="C">

C

        <input type="radio" name="radio1" id="checkd1" value="D">

D

        <input type="radio" name="radio1" id="checke1" value="E">

None of the above

  <button class="" type="submit" name="testsubmitbutton" id="testsubmitbutton">Submit</button>
  Submitting please do not refresh!
</form>

If you want send the selected value to the server then probably you can set the pointer-events to none which will indicate that the element is not the target of pointer events:

$(document).ready(function() {
  $("#submit_text").hide(); //Hiding submit_text
  $("#testsubmitbutton").click(function() {
    $("#testsubmitbutton").hide(); //Hiding submit button
    $("#submit_text").show(); //Showing submit_text
    $("#testform :input").css({'pointer-events':'none', 'opacity':'.5'});
    $('.option_div p').css({'opacity':'.5'});
    $('.option_div p').click(false);
    console.log($("form").serialize());
  });
});
.hiddenFramehideclass {
  position: absolute;
  top: -1px;
  left: -1px;
  width: 1px;
  height: 1px;
}

<form method="post" action="" enctype="multipart/form-data" id="testform" target="hiddenFrame">

  Question 1

Question?

      <input type="hidden" name="qid1" value="22">

        <input type="radio" name="radio1" id="checka1" value="A">

A

        <input type="radio" name="radio1" id="checkb1" value="B">

B

        <input type="radio" name="radio1" id="checkc1" value="C">

C

        <input type="radio" name="radio1" id="checkd1" value="D">

D

        <input type="radio" name="radio1" id="checke1" value="E">

None of the above

  <button class="" type="submit" name="testsubmitbutton" id="testsubmitbutton">Submit</button>
  Submitting please do not refresh!
</form>

A: Readonly does not work on radio buttons, you can use disabled: true, however...
See this answer to understand the difference between disabled and readonly: What's the difference between disabled="disabled" and readonly="readonly" for HTML form input fields?

$(document).ready(function() {
  $("#submit_text").hide(); //Hiding submit_text
  $("#testsubmitbutton").click(function() {
    $("#testsubmitbutton").hide(); //Hiding submit button
    $("#submit_text").show(); //Showing submit_text

    $("#testform :input").attr('disabled', true); //Making all inputs to readonly

  });
});
.hiddenFramehideclass {
  position: absolute;
  top: -1px;
  left: -1px;
  width: 1px;
  height: 1px;
}

<form method="post" action="" enctype="multipart/form-data" id="testform" target="hiddenFrame">

  Question 1

Question?

      <input type="hidden" name="qid1" value="22">

        <input type="radio" name="radio1" id="checka1" value="A">

A

        <input type="radio" name="radio1" id="checkb1" value="B">

B

        <input type="radio" name="radio1" id="checkc1" value="C">

C

        <input type="radio" name="radio1" id="checkd1" value="D">

D

        <input type="radio" name="radio1" id="checke1" value="E">

None of the above

  <button class="" type="submit" name="testsubmitbutton" id="testsubmitbutton">Submit</button>
  Submitting please do not refresh!
</form>


text:
Q: Can Firebase work on Genymotion Emulator? hi there I just want to know if my android app constructed using firebase for authentication , can only work on physical devices or there is no problem with genymotion emulator.

A: No problem at all. Just follow this FAQ to install OpenGapps on the device:
https://www.genymotion.com/help/desktop/faq/#google-play-services


text:
Q: Unable to recognize face using Face Recognition lib - face-api.js Im using face-api.js from https://justadudewhohacks.github.io/face-api.js/bbt_face_recognition/..
Besides face detection, I am required to use face recognition, however, i am unable to recognize any faces using the code below. Anyone able to help me?
Below is a running copy that allows user to:
- Detect face & Mark Faces
- Draw Landmark

Objective:
- Able to detect and mark face
- Able to recognize face from a list of images

A: <!DOCTYPE html>

        <link rel="stylesheet" href="styles.css">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.css">

                <video onloadedmetadata="onPlay(this)" id="inputVideo" autoplay muted></video>
                <canvas id="overlay" />

                    <select id="selectFaceDetector">
                        <option value="ssd_mobilenetv1">SSD Mobilenet V1</option>
                        <option value="tiny_face_detector">Tiny Face Detector</option>
                        <option value="mtcnn">MTCNN</option>
                    </select>
                    Select Face Detector

                        Time:
                        <input disabled value="-" id="time" type="text" class="bold">
                        Estimated Fps:
                        <input disabled value="-" id="fps" type="text" class="bold">

                        Min Confidence:
                        <input disabled value="0.5" id="minConfidence" type="text" class="bold">

                    <button
                        class="waves-effect waves-light btn"
                        onclick="onDecreaseMinConfidence()"
                        >
                        -
                    </button>
                    <button
                        class="waves-effect waves-light btn"
                        onclick="onIncreaseMinConfidence()"
                        >
                        +
                    </button>

                        <select id="inputSize">
                            <option value="" disabled selected>Input Size:</option>
                            <option value="128">128 x 128</option>
                            <option value="160">160 x 160</option>
                            <option value="224">224 x 224</option>
                            <option value="320">320 x 320</option>
                            <option value="416">416 x 416</option>
                            <option value="512">512 x 512</option>
                            <option value="608">608 x 608</option>
                        </select>
                        Input Size

                        Score Threshold:
                        <input disabled value="0.5" id="scoreThreshold" type="text" class="bold">

                    <button
                        class="waves-effect waves-light btn"
                        onclick="onDecreaseScoreThreshold()"
                        >
                        -
                    </button>
                    <button
                        class="waves-effect waves-light btn"
                        onclick="onIncreaseScoreThreshold()"
                        >
                        +
                    </button>

                        Minimum Face Size:
                        <input disabled value="20" id="minFaceSize" type="text" class="bold">

                    <button
                        class="waves-effect waves-light btn"
                        onclick="onDecreaseMinFaceSize()"
                        >
                        -
                    </button>
                    <button
                        class="waves-effect waves-light btn"
                        onclick="onIncreaseMinFaceSize()"
                        >
                        +
                    </button>


text:
Q: Websocket connection failed when using socket.io I am using socket.io on both client and server, with the application being served from AWS. I am getting a browser console error:

websocket.js:54 WebSocket connection to
'wss://www.tidee.com/socket.io/?EIO=4&transport=websocket' failed:
doOpen    @   websocket.js:54 open    @   transport.js:44 open    @   socket.js:159

Client code:
socket = io('https://www.tidee.com', {
    transports: ['websocket', 'polling'],
  });
socket.on('reconnect_attempt', () => {
  socket.io.opts.transports = ['polling', 'websocket'];
});

Server code:
const socketIo = require('socket.io');
...
const socketIoServer = https.createServer(app);
const io = socketIo(socketIoServer, {
    transports: ['websocket', 'polling'],
});

In AWS, the security group accepts port 443 and the load balancer listens on 443.
The application works when running locally (status 101) and it uses the ws:// protocol.

A: If using Elastic Beanstalk (EB) to deploy your application. there iss an Nginx proxy server (in the EB configuration) that is deployed to proxy the requests to your load balancer. Remove the Nginx proxy server and the websockets will work. If you want to keep the Nginx proxy, then you will need to configure this to pass through the websocket request.


text:
Q: bluetoothLE universal sample value changed I am currently using the windows-universal-samples-bluetoothle for my final year project. I'm facing one problem. I am connecting this to my rfduino to capture my value. I can manually capture my data whenever I press the "read" button. But how do I press the "read" button one time and it actually auto update the value ?
for example, I have setup my rfduino with mpu6050. so the angles will change will change when I move the mpu6050. I can capture this data everytime I press "read" on my UWP. Now I want to make it update automatically. how do I do that ?

A: Bluetooth LE Advertisements allow your device to constantly beacon out a specific payload, called an advertisement. This advertisement can be seen by any nearby Bluetooth LE capable device, if they are set up to listen for this specific advertisment. If your rfduino supports Bluetooth LE Advertisement. You could create BluetoothLEAdvertisementWatcher to receive Advertisement automatically.
BluetoothLEAdvertisementWatcher watcher = new BluetoothLEAdvertisementWatcher();
watcher.Received += OnAdvertisementReceived;
watcher.Start();

private async void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs eventArgs)
{
    // Do whatever you want with the advertisement
}

For more detail you could refer Bluetooth LE Advertisements official docuemnt and this is code sample.


text:
Q: AndroidMarket - Upload app If I upload an app that I've made in Android's marketplace for selling. How much does google/marketplace take in charge for every penny that I make, and I'm living in Sweden, I've heard they take a percent of the pennty too?
Please can someone explain this to me.
Thanks!

A: See Transaction Fees. Each time you sell your application, Google takes 30% of the application price.


text:
Q: Get Employee Details from the excel sheeet I have a excel sheet containing only "Employee id" in Column A as shown below.
1677
5597
5623
5618

I have one more excel sheet containing "Employee details" of 10000+ Employees. For Eg: The Employee details excel sheet contains contains data of lot of employee here is the example one of employee id shown below.
Empid   Name    Location    JobTitle    Email-id     Department
1677    Umesh     Gadag      ASE      abc@gmail.com    Civil

Here is the Working code
import pandas as pd
df1 = pd.read_excel (r'C:\\Users\\Kiran\\Desktop\\Employee id.xlsx',header=None)# excel sheet containing only ids
df2= pd.read_excel (r'C:\\Users\\Kiran\\Desktop\\Employee details.xlsx)# excel sheet containing all details of 10000+ employees
df3 = df2[df2['Empid'].isin(df1[0])]
df3.to_excel("Output1.xlsx",index=False)#Final output

The code works fine but i get output as Randomly
Empid   Name    Location    JobTitle    Email-id       Department
1677    Umesh     Gadag      ASE      abc@gmail.com      Civil
5623    Kiran     Hubli      SE       123@gmail.com      Civil
5618    Rudra     Bidar      ASE      xyz@gmail.com     Electrical
5597    Suresh    Udupi      ASE       ppp@gmail.com    Mechanical

But i need output in this sequence as follows, since the Employee id are in a particular order. Basically what is the order i gave in Employee id details i need Employee details in same sequence as shown below.
Empid   Name    Location    JobTitle    Email-id      Department
1677    Umesh     Gadag      ASE      abc@gmail.com     Civil
5597    Suresh    Udupi      ASE      ppp@gmail.com     Mechanical
5623    Kiran     Hubli      SE       123@gmail.com     Civil
5618    Rudra     Bidar      ASE      xyz@gmail.com     Electrical

A: Here's a solution:
df1 = df1.reset_index().rename(columns= {"index": "order"})
res = pd.merge(df1, df2, on = "Empid").sort_values("order").drop("order", axis=1)

The output is:
   Empid    Name Location JobTitle       Email-id  Department
0   1677   Umesh    Gadag      ASE  abc@gmail.com       Civil
1   5597  Suresh    Udupi      ASE  ppp@gmail.com  Mechanical
2   5623   Kiran    Hubli       SE  123@gmail.com       Civil
3   5618   Rudra    Bidar      ASE  xyz@gmail.com  Electrical


text:
Q: I try to deploy my process and I have wrong rest endpoint I try to deploy my process and I have wrong rest endpoint,I can't press the deploy button
what is my problem?

A: Well there are two basic problems that come to my mind.

*

*You didn't start camunda. If you are connecting to camunda through an app make sure that it's running. Try deploying again after your app is running successfully.

*You are using the wrong port. Make sure that camunda is running on port 8081 as you stated on your endpoint. You can check whether the port is used or not by entering the netstat -an command to windows cmd. Something with :8081 should show up if it's used.

A: If you using an unmodified recent Camunda version then your REST endpoint URL is:
http://localhost:8080/engine-rest
Of course the server needs to be started / have started without errors.
Please also see:
How to deploy a Camunda modeled diagram into Camunda Tomcat


text:
Q: What is a reasonable alternative when the mean does not exist? Consider a continuous random variable $F''$ following a doubly noncentral $F$ distribution with $8$ and $2$ degrees of freedom, and noncentrality parameters $0$ and $10$; which is to say:
$$
F'' \sim F_{8,2}(0,10) \text{.}
$$
[Actually, $F''$ can be also seen as the reciprocal of $F'$ following a (singly) noncentral $F$ distribution with $2$ and $8$ degrees of freedom and noncentrality parameter $10$.]
The theory (and Mathematica) says that the mean of $F''$ does not exist, or it is not defined. The following chart depicts the average of $F_{8,\nu_2}(0,10)$ when $\nu_2$ varies between $0$ and $8$. It clearly shows a vertical asymptote in $\nu_2=2$, which graphically confirms that the mean of $F''$ does not exist.
IMAGE 1:

Actually, if we plot not the mean itself (which is not defined for $\nu_2 \le 2$) but any of the available analytical expressions for it or, equivalently, for the first raw moment of $F_{8,\nu_2}(0,10)$, the picture is even clearer:
IMAGE 2:

In the chart above, the following expression for the first raw moment of $F_{\nu_1,\nu_2}(\delta_1,\delta_2)$ has been used:
$$
\begin{align}
\mu_1'={}& e^{-(\delta_1+\delta_2)/2} \frac{\nu_2}{\nu_1} \Gamma\!\left(\frac{\nu_1}{2}+1\right) \Gamma\!\left(\frac{\nu_2}{2}-1\right) \times \\
&{}_1\tilde{F}_1\!\left( \frac{\nu_1}{2}+1; \frac{\nu_1}{2} ; \frac{\delta_1}{2}\right){}_1\tilde{F}_1\!\left( \frac{\nu_2}{2}-1; \frac{\nu_2}{2} ; \frac{\delta_2}{2}\right) \text{,}
\end{align}
$$
as seen in http://mathworld.wolfram.com/NoncentralF-Distribution.html.
However, when performing simulations on the mean of $F''$, things seem —I am not sure— to converge to a reasonable value between $0.2$ and $0.4$:
IMAGE 3:

The chart above is the result of calculating the sample average of up to $100\,000$ random observations of $F'' \sim F_{8,2}(0,10)$. The sample average of the $100\,000$ observations happens to be $0.338527$.
Although the theoretical mean of the distribution does not exist, is there a way to give a suitable substitute for it (let us call it pseudomean, for instance)? Clearly, I am not asking for the median, since the distribution is not symmetrical.
For instance, is there a way to calculate a theoretical value for the limit of these sample averages when the sample size tends to infinity (in case such a limit exists)?
To clarify, I want to add another example with $F'' \sim F_{48,\nu_2}(0,50)$:
IMAGE 4:

Despite that, in the above image, there seems not to be any discontinuity, it is there (zoom in):
IMAGE 5:

So, in this example, a suitable substitute for the nonexistent theoretical mean of the distribution $F'' \sim F_{48,2}(0,50)$ would be something between $0.041745$ and $0.041748$, more or less.
Actually, the average of a $200\,000$-element random sample of this distribution was found to be $0.0417525$. This is the associated chart:
IMAGE 6:

So, any suggestions?? My theoretical background tells me that it makes no sense trying to estimate what it does not exist, but simulations and charts suggest that there may be a reasonable theoretical substitute for the unavailable mean.
NOTE: The value should be theoretical in the sense that it should not depend on any sampling process, but only on the parameters of the distribution.

UPDATE
Actually, some related questions are:

*

*What is the average of $\frac{1}{k}(X_1 + \cdots + X_k)$ when $X_i \sim F_{\nu_1,2}(0,\delta_2)$ for all $i$?

*What is the limit of the above expression when $k$ tends to infinity?

*Can the sample average have an average value when the initial distribution does not have one?

UPDATE
Answering the comment by @Glen_b below, a reasonable substitute for the nonexistent mean of $F_{\nu_1,2}(0, \delta_2)$ would be something that fitted the gap that is clearly observed in images 4 and 5; something between $0.041745$ and $0.041748$, in that concrete example, as I already said.
What am I going to use this pseudomean for? I am going to use it as a reference value to calculate a sort of probability intervals (something like $[ \mathrm{mean}-\mathrm{something} \, , \, \mathrm{mean}+\mathrm{something_{~}else}]$). Taking the mean as the reference point for building that interval is a convention that I would like to keep for analogy with other related cases in which the true mean does exist.


text:
Q: Как вывести число строки в django Не могу решить задачу на django.
Есть такая таблица
Ключ   Заголовок
Топ детективов: detective
Топ фантастики:  scifi
Топ нехудожественных: nonfiction
И такая модель
class Book(models.Model):
    title=models.CharField(max_length=30)
    author=models.CharField(max_length=30)
    genre=models.CharField(max_length=30)
    sales=models.IntegerField()

Сама задача: представлена информация, сколько каких книг было продано за последний год. надо составить топ-5(по продажам) по каждому жанру: детектив () нон-фикшн(nonfiction) и фантастика(scifi).
Пример вывода:
Топ детективов:
1 Девушка с татуировкой дракона 3579
2 Исчезнувшая 2205
3 Девушка в поезде 1909
4 Невинная 1740
5 Нож 1620
Вывод самих книг я сделал, но не могу понять, как пронумеровать строки
book = Book.objects.all()
if genre == 'detective':
    books = Book.objects.filter(genre='detective').order_by('-sales')[0:5]
    for detectives in books:
            print(detectives.title, detectives.sales)
elif genre == 'scifi':
    for scifi in Book.objects.filter(genre='scifi').order_by('-sales')[0:5]:
        print(scifi.title, scifi.sales)

elif genre == 'nonfiction':
    for nonfiction in Book.objects.filter(genre='nonfiction').order_by('-sales')[0:5]:
        print(nonfiction.title, nonfiction.sales)

A: Весь Ваш код можно переписать в три строки с учётом поставленной задачи
books = Book.objects.filter(genre=genre).order_by('-sales')
for index, book in enumerate(books[:5], start=1):
    print(index, book.title, book.sales)


text:
Q: Change color conditionally Css I'm using a third party component on my page, It has a class dialog_RechatDialog0D55B000000P6Mv where the Id changes for each post. how do I change color is css if the class contains "dialog_RechatDialog", is that possible?
Any help is much appreciated.
Thanks!

A: This works, assuming your dom element is a div .
div[class^='dialog_RechatDialog'] {
    color: yellow;
}

All (div) with a class that starts (^) with string "diablo_RechatDialog"


text:
Q: How to solve radio button in xamarin I have a Radio buttons in my Xamarin.Forms App. But my App Radio buttons are crashing and overlapping. So in here I want to get 2 Radio buttons in my app, but in my code its not like that. And I would like each element in the grid as shown here:
Sample Preview
    <Grid>
        <ScrollView Orientation="Vertical">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition Height="160" />
                    <RowDefinition Height="*" />
                </Grid.RowDefinitions>
                <Grid Grid.Row="0" Padding="20">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="400" />
                        <ColumnDefinition Width="*" />
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="25" />
                        <RowDefinition Height="25" />
                        <RowDefinition Height="50" />
                        <RowDefinition Height="50" />
                    </Grid.RowDefinitions>
                    <Label Grid.Row="0" Grid.Column="0" Text="Care of User - Address" FontAttributes="Bold" TextColor="Black" />
                    <Label Grid.Row="1" Grid.Column="0" Text="Enter the details of the person that the connection will be in care of." FontSize="Small" TextColor="#757575" />
                    <Label Grid.Row="2" Grid.Column="0" Text="Address Status" FontAttributes="Bold" TextColor="Black" />
                    <input:RadioButtonGroupView Grid.Row="2" Grid.Column="1" Orientation="Horizontal" Margin="20,0,0,30" x:Name="localForeignCustomerType">
                        <input:RadioButton Text="Local customer" TextFontSize="14" x:Name="localCustomerRadioButton" />
                        <input:RadioButton Text="Foreign customer" TextFontSize="14" x:Name="foreignCustomerRadioButton" />
                    </input:RadioButtonGroupView>
                </Grid>

            </Grid>

A: Try this inside your scrollview

<Grid.RowDefinitions>
    <RowDefinition Height="Auto" />
    <RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid Grid.Row="0" Padding="10">
    <Grid.RowDefinitions >
        <RowDefinition Height="35" />
        <RowDefinition Height="35" />
        <RowDefinition Height="35" />
    </Grid.RowDefinitions>
    <Label Grid.Row="0" Text="Care of User - Address" FontAttributes="Bold" TextColor="Black" />
    <Label Grid.Row="1" Text="Enter the details of the person that the connection will be in care of." FontSize="Small" TextColor="#757575" />

    <StackLayout Grid.Row="2"   Orientation="Horizontal"  x:Name="localForeignCustomerType" HorizontalOptions="FillAndExpand">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>

        </Grid>
        <Label Grid.Row="0" Grid.Column="0" Text="Address Status" FontAttributes="Bold" TextColor="Black" HorizontalOptions="StartAndExpand" />
        <input:RadioButtonGroupView Orientation="Horizontal" Grid.Column="1" Grid.Row="0" HorizontalOptions="EndAndExpand">
            <input:RadioButton Text="Local" TextFontSize="14" x:Name="localCustomerRadioButton"  />
            <input:RadioButton Text="Foreign" TextFontSize="14" x:Name="foreignCustomerRadioButton"  />
        </input:RadioButtonGroupView>

    </StackLayout>
</Grid>


text:
Q: graph.facebook get name & link and send to Database with the response_id from a post to the users wall I strip the user_id:
var userid = (response.post_id);
userid = userid.substring(0, userid.indexOf('_'));

Ok. Next I call the facebook graph:
$.getJSON('http://graph.facebook.com/' + userid + '?callback=?',function(data){
var name = data["name"];
var fblink = data["link"];
})

Now I try to save the data in a Database. So I do following:
$.post('<?php echo $siteurl; ?>write.php?fbusr_id=' + userid + '&fb_name=' + name + '&fb_link=' + fblink);

Problem: It works if I only send the fbusr_id but it doesnt work with fb_name & fb_link in the code. Nothing gets written to the database., If I cut fb_name & fb_link out of the $.post it works, the user_id gets written into the databse.
That works:
$.post('<?php echo $siteurl; ?>write.php?fbusr_id=' + userid);

Cant find the reason. Thx for help.
Neil

A: First reason, getJSON is asynchronous method you should use response data in their response function.
Second reason, POST method should send data as object instead of string parameter.
Thrid reason, if you really want to send data as query string parameter (maybe send by GET method) you should use encodeURIComponent(fblink) instead of fblink or something you want to send.
However, you may try this
$.getJSON('http://graph.facebook.com/' + userid + '?callback=?',function(data){
        var name = data["name"];
        var fblink = data["link"];
        $.post('<?php echo $siteurl; ?>write.php', {fbusr_id:userid,fb_name:name,fb_link:fblink},
                 function(response){} );
})


text:
Q: My headerStyle doesn't work. I have tried to assign a background color though it doesn't appear when I run it My headerStyle doesn't work. I have tried to assign a background color though it doesn't appear when I run it. I have given a blue color to backgroundColor in headerStyle. though it isn't working. I have tried everything but it doesn't work. I am fairly new to reactNative so cannot figure out the bug.
import React, { Component } from 'react';
import Menu from './MenuComponent';
import Dishdetail from './DishdetailComponent';
import Home from './HomeComponent.js';
import Contact from './ContactComponent.js';
import About from './AboutComponent.js';
import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
import { createDrawerNavigator } from 'react-navigation-drawer';
import { Icon } from 'react-native-elements';

const MenuNavigator = createStackNavigator({
  Menu:
  { screen: Menu,
    navigationOptions: ({ navigation }) => ({
      headerLeft: <Icon name="menu" size={24}
        color= 'blue'
        onPress={ () => navigation.toggleDrawer() } />
    })
  },
  Dishdetail: { screen: Dishdetail }
},
{
  initialRouteName: 'Menu',
  navigationOptions: {
      headerStyle: {
          backgroundColor: "#512DA8"
      },
      headerTintColor: '#fff',
      headerTitleStyle: {
          color: "#fff"
      }
  }
}
);

const HomeNavigator = createStackNavigator({
  Home: { screen: Home }
}, {
  navigationOptions: ({ navigation }) => ({
    headerStyle: {
      backgroundColor: '#f4511e',
    },
    headerTintColor: '#fff',
    headerTitleStyle: {
      fontWeight: 'bold',
    },
  })
});

const ContactNavigator = createStackNavigator({
  Contact: { screen: Contact }
},
{
  navigationOptions: ({ navigation }) => ({
    headerStyle: {
        backgroundColor: "#512DA8"
    },
    headerTitleStyle: {
        color: "#fff"
    },
    headerLeft: <Icon name = 'menu' size = {24}
        color = 'blue'
        onPress = {() => navigation.toggleDrawer()}
        />,
    headerTintColor: "#fff"
  })
});

const AboutNavigator = createStackNavigator({
  About: { screen: About }
},
{
  navigationOptions: ({ navigation }) => ({
    headerStyle: {
        backgroundColor: "blue"
    },
    headerTitleStyle: {
        color: "#fff"
    },
    headerLeft: <Icon name = 'menu' size = {24}
        color = 'blue'
        onPress = {() => navigation.toggleDrawer()}
        />,
    headerTintColor: "blue"
  })
});

const MainNavigator = createDrawerNavigator({
  Home: {
      screen: HomeNavigator,
      navigationOptions: {
        title: 'Home',
        drawerLabel: 'Home',
        drawerIcon: ({tintColor}) => (
          <Icon
            name='home'
            type='font-awesome'
            size = {24}
            color = {tintColor}
          />
        )
      }
    },
  About: {
      screen: AboutNavigator,
      navigationOptions: {
        title: 'About Us',
        drawerLabel: 'About Us',
        drawerIcon: ({tintColor}) => (
          <Icon
            name='info-circle'
            type='font-awesome'
            size = {24}
            color = {tintColor}
          />
        )
      },
    },
  Menu: {
      screen: MenuNavigator,
      navigationOptions: {
        title: 'Menu',
        drawerLabel: 'Menu',
        drawerIcon: ({tintColor}) => (
          <Icon
            name='list'
            type='font-awesome'
            size = {24}
            color = {tintColor}
          />
        )
      },
    },
  Contact: {
      screen: ContactNavigator,
      navigationOptions: {
        title: 'Contact Us',
        drawerLabel: 'Contact Us',
        drawerIcon: ({tintColor}) => (
          <Icon
            name='address-card'
            type='font-awesome'
            size = {22}
            color = {tintColor}
          />
        )
      },
    }
}, {
drawerBackgroundColor: '#D1C4E9'
});

const Main = createAppContainer(MainNavigator);

export default Main;

A: Depending on what version of React Native you are using the issue could be with navigationOptions. If you are using v3 you need to use defaultNavigationOptions instead.
defaultNavigationOptions: ({ navigation }) => ({
    headerStyle: {
        backgroundColor: "blue"
    },
    ...
}

A: I am currently facing the same issue...
React native v0.70.5 expo managed project created with typescript.
in my case, only background color works every other style property isn't expected to be props of header style, I looked into their package, and here's what I found...
headerStyle?: StyleProp<{
    backgroundColor?: string;
}>;

in this file..
node_modules@react-navigation\native-stack\src\types.tsx
for me the most reasonable solution is to add the properties as defined above.
So I've added the styles I need...
  headerStyle?: StyleProp<{
    backgroundColor?: string;
    borderBottomWidth: number,
    shadowColor: string,
    shadowOpacity: number,
    elevation: number,
    height: number
 }>;

or you could just say:
  headerStyle?: StyleProp<ViewStyle>;

You might need to restart vscode though before the changed reflect...
but this solved it for me.


text:
Q: AMD Radeon r9 Not connecting to HDMI screen? I have a custom built Windows gaming PC, we are using the Sapphire Radeon r9 gfx card and when we attempt to connect to monitor (or rather, HDMI TV) it does not connect, for a second it appears that it will then the "no signal" screen appears on the TV. The TV is a Westinghouse 32" LED TV with HDMI supports pretty high resolution. Could the issue be that the TV is a little old (approx. 3 years old) or is there some other issue we could have missed. We have tried the connection both with VGA and HDMI, when we connect to the motherboard graphics it works fine, we can see everything, hear everything but when we connect it to the graphics card the tv receives no signal. Any suggestions??? On a side note, we are pretty new to the whole computer building thing... So if you have a complicated answer please explain as best you can so I can understand what I should try and do. Thanks, so much, for your time.

A: Have you installed the graphics drivers for your video card yet?  They should install automatically with Windows Update, but if not, you can grab them from here.  They'll generally be required in order to get the video outputs working as intended.
Also, you need to right click on your Windows desktop, and go to where you change the screen resolution.  When you're there, make sure it shows multiple displays available; you might need to change the one that's grayed out to "Extend this display" in order for Windows to output to that monitor.
Have you ensured the TV works with that HDMI port?  Do you have a DVD player, Xbox, something with HDMI-out that you're sure works on the TV?  A dead port is another possibility.  If you have a device that works this way, you can also try using the same cord from your PC->TV, to ensure it's not a bad cord you're using.

A: Solved the issue. In the end, it was my TV that didn't want to work properly. I had a friend bring over his monitor, Dell, and it worked just fine. The graphics card had both pci-e 6-pin connectors plugged up to the graphics card and windows 7 booted right up with the graphics card working. I am going to buy a monitor and not hook up my pc to my TV. Thank you all for your time.


text:
Q: how to manipulate right click context menu using windows API and c# i have work on an app that manipulate some application context menue to extend its functions, i have checked all the common posts here on stackOverFlow on how to manipulate the menu context using Windows api in C# using functions like GetMenu(...), InsertMenuItem(...), ShowOwnedPopups(...) and that comes in vain, here is the scenario, the application i wanna manipulate it context menu has many context menus in many parts but i want to manipulate certain one which belongs to the viewer part. so i have used spy++ to figure the the handle of the viewer and a send a message WM_CONTEXTMENU using SendMessage(...) function. the menu finally appears and i have its handle.

i guess after i get the handle it would be constant for the life time of the program for the single running time, but i figured out that the handle is changing every single time a i have clicked right click. and the parent of the context menu isn't the viewer area itself but the desktop that's was disappointing.

so i have two problems
1- i can't get the handle directly as using GetMenu(...) passing the handle of the viewer returns null, after some search if found that the context menu has a class name of "#32768" so i have filtered all the open windows to get the one that its class name equlas "#32768". and now i can access the handle from my c# code not from the spy. but here is an comming issue: if there is a sub menue.. it also have the same class and unfortunately this is totally logical :/

2- i can't get the context handle before it is shown and if it is shown, i can't manipulate it as i know. The second thing is that the context handle continuously changes every single time i right click the mouse. so i can't pass the first time i click then save the handle for the next clicks to make it work.
any suggestion are very welcomed.

A: First of all you should figure out if you can just send it a WM_COMMAND message to perform your command. A context menu might not use that message but if the application also has a normal menu then it is likely that it will handle the message. Note that the command id might change between program versions.
All Win32 HMENU menus use the same class and MN_GETHMENU is the only related documented message.
The recommended solution is to use UI Automation/MSAA to navigate the UI of other applications.


text:
Q: How do I call a color picker when a button is pressed in android? The button has a predefined color. I need to show a selection of colors on pressing the button. And then give the button the selected background color. I have just started android programming. Any help will be much appreciated.

A: You need to use a color picker for this purpose.
button.setOnClickListener(new OnClickListener() {

 void onClick(View v) {
// create the color picker dialog and display it.
ColorPickerDialog dlg = new ColorPickerDialog(v.getContext(),new OnColorChangedListener()     {
      void colorChanged(int color) {
           mSelectedColor = color;
       }

   }),initialColor);
   dlg.show();
  }
});

initialColor will be replaced by mSelectedColor, the new selected color from the picker.


text:
Q: Changing the root password What are the implications of changing the root password? Is there anything that will be affected? I'm using a private shared SSH key - I assume I do not need to change this as it is not tied to the root account password.

A: I won't say there are no implications on your system, as I have no idea what strange things your might have done, but I've never had any on mine. After all, it's just a password.
Of course, it might be easy to create systems where the root password is stored somewhere for some purpose, but I would consider this bad design to begin with.
And you are right, SSH keys don't need to be touched.

A: If you can't afford to risk it, then consider restoring your server from a backup, or if it's a virtual machine make a clone of it, and test resetting the password.

A: Not many aside from choosing a weak password.
If your system encrypts users home directories it is possible you could be in for a bad time if you then forget the new password.
Standard practice is to not give root access to services like ssh, and instead have users sudo for privilege, this means you can track who logged in with the escalated privileges.

A: If you log in as root by using an ssh key, then you don't need the password. I have multiple servers on which I have changed the root password to be a random string of characters which is not recorded anywhere.
Keys that are already authenticated through ~root/.ssh/authorized_keys will keep working after the root password has been changed. And if you always authenticate using a key, there is no need to know the password.
A couple of things to keep in mind:

*

*Administrating the server locally rather than across the network becomes more troublesome if you don't know the root password, and may require you to reboot the server.

*A random password known to nobody still has to be strong enough to not be possible to brute force.

*You can configure the system such that there is no valid password at all. But if you do that pay close attention to the difference between:

*

*permitting login without password

*asking for a password but never accepting any

*suspending the account


text:
Q: Setup for IntelliJ proxy dont work (win7) I try to setup the proxy configuration on IntelliJ. I follow the help from : https://www.jetbrains.com/help/idea/2016.1/configuring-http-proxy.html
I create an new gradle/Java project. No Dependency from gradle will resolved.
Im working with Win7. There are no fix configurations for proxy setup. The current settings for proxy is:
Setting for Win7

A: You can provide the proxy details in intellij here:
Preferences -> Appearances and Behaviour -> HTTP Proxy.
Click the "check connection" button there to make sure it is ok, and then refresh Gradle dependancies from the gradle tool window.


text:
Q: Index (zero based) must be greater than or equal to zero error im geting the next error:

Index (zero based) must be greater than or equal to zero and less than
  the size of the argument list.

and im not sure what it means, this is my code:
 var gruposA = db_cm.Permisos_Grupo_User.Include("Permisos_Grupo")
                            .Where(g => g.id_user == id && model.grupos.Any(x => int.Parse(x.Value) == g.id_grupo))
                            .ToList();

can someone tell me wath is wrong?
model.grupos is an IEnumerable<SelectListItem>
what i need to do is select a list of cm.Permisos_Grupo_User if the id is on model.grupos

A: well, adding a .ToList() fixed the problem
db_cm.Permisos_Grupo_User.Include("Permisos_Grupo").ToList()
                            .Where(g => g.id_user == id && model.grupos.Any(x => int.Parse(x.Value) == g.id_grupo))
                            .ToList();


text:
Q: PWA app update alert in angular6 I have developed a PWA app in angular6 with @angular/pwa and it is working absolutely great. I am also trying to notify the user to update the PWA app when user opens the app if there is any update in the app. I have gone through different articles and blogs, and find this article, but it is not for angular6. I am unable to add any eventListeners as service workers are automatically created. Please help me in resolving this issue. Thank you!

A: You can do it with SwUpdate service like this:
@Injectable()
export class UpdateService {
    constructor(swUpdate: SwUpdate) {
        swUpdate.available.subscribe(event => {
            // notify user that update is available
        })
    }
}


text:
Q: Merging dataframes in R with duplicated values in rownames im trying to use the rbind function exactly like in this post.
i have 3 dataframes with 2 columns (rownames and "source").
Between the first and second dataframes there are 2 rownames duplicated values and between the first and the third dataframes there's one.
a
TMCS09g1008676 fleshy
TMCS09g1008677  fleshy
TMCS09g1008678  fleshy
TMCS09g1008679  fleshy
TMCS09g1008680  fleshy
TMCS09g1008681  fleshy
TMCS09g1008682  fleshy
TMCS09g1008683  fleshy
b
TMCS09g1008684 rotten
TMCS09g1008685  rotten
TMCS09g1008686  rotten
TMCS09g1008682  rotten
TMCS09g1008688  rotten
TMCS09g1008689  rotten
TMCS09g1008690  rotten
TMCS09g1008691  rotten
TMCS09g1008683  rotten
TMCS09g1008693  rotten
c
TMCS09g1008695 good
TMCS09g1008696  good
TMCS09g1008697  good
TMCS09g1008698  good
TMCS09g1008683  good
TMCS09g1008700  good
TMCS09g1008701  good
TMCS09g1008702  good
TMCS09g1008703  good
TMCS09g1008704  good
TMCS09g1008705  good
after applying the fuction suggested in that post:
duprows <- which(!is.na(match(rownames(a),rownames(b))))
rbind(a, b[-duprows,])
i get this:
> rbind(a, b[-duprows,])
               source
TMCS09g1008677 fleshy
TMCS09g1008678 fleshy
TMCS09g1008679 fleshy
TMCS09g1008680 fleshy
TMCS09g1008681 fleshy
TMCS09g1008682 fleshy
TMCS09g1008683 fleshy
8                <NA>
Warning message:
In[<-.factor(tmp, ri, value = 1L) :
  invalid factor level, NA generated
The main thing is that I would like to retain the 2nd column of the dataframe "a" for the duplicated values. How i was clear.
Thanks in advance

A: What do you think about this.
Sample data (your data - reproducible ;)):
require(tidyverse)

a <- data.frame(ID = c("TMCS09g1008676",
          "TMCS09g1008677",
          "TMCS09g1008678",
          "TMCS09g1008679",
          "TMCS09g1008680" ,
          "TMCS09g1008681",
          "TMCS09g1008682",
          "TMCS09g1008683"), Staus = rep("fleshy"))

b <- data.frame(ID = c( "TMCS09g1008684" ,
                        "TMCS09g1008685" ,
                        "TMCS09g1008686" ,
                        "TMCS09g1008682"  ,
                        "TMCS09g1008688" ,
                        "TMCS09g1008689" ,
                        "TMCS09g1008690" ,
                        "TMCS09g1008691",
                        "TMCS09g1008683" ,
                        "TMCS09g1008693"), Staus = rep("rotten"))

c <- data.frame(ID = c( "TMCS09g1008695" ,
                        "TMCS09g1008696"  ,
                        "TMCS09g1008697" ,
                        "TMCS09g1008698"  ,
                        "TMCS09g1008683"  ,
                        "TMCS09g1008700" ,
                        "TMCS09g1008701"  ,
                        "TMCS09g1008702" ,
                        "TMCS09g1008703"  ,
                        "TMCS09g1008704" ,
                        "TMCS09g1008705" ), Staus = rep("good"))

You can use plyr::join_all to do the matching. Because you have duplicated IDs it will be forced to open new columns to fit the duplicated values.
plyr::join_all(list(a,b,c), by = "ID")

Results:
              ID  Staus  Staus Staus
1 TMCS09g1008676 fleshy   <NA>  <NA>
2 TMCS09g1008677 fleshy   <NA>  <NA>
3 TMCS09g1008678 fleshy   <NA>  <NA>
4 TMCS09g1008679 fleshy   <NA>  <NA>
5 TMCS09g1008680 fleshy   <NA>  <NA>
6 TMCS09g1008681 fleshy   <NA>  <NA>
7 TMCS09g1008682 fleshy rotten  <NA>
8 TMCS09g1008683 fleshy rotten  good


text:
Q: Apache Tiles : change template page at runtime I have a question : suppose that in a spring MVC 3.0 enviroment i manage Views with Tiles : I have a xml file with definitions of all views. Every view extends a specific template. I have two templates : one for rendering a completeDOM () and one for partialDOM (.....).The problem is, there are some views that can be retrieved in fullDOM and also in partialDOM, but i don't want to write two similars definitions.
I was thinking to a dynamic approach : inject the template of a view at runtime, specifying an http parameter which should contains the name of the template. If the request contains the parameter, than Tiles should override the template exteded by the view, with the template detected by http parameter value.
Some suggestions?

A: I know this is an old question but I had needed to do this very thing so I thought I'd share my solution.
Tiles allows what they refer to as "runtime composition", which lets you modify definitions. So you can reuse an existing definition and just swap the template:
<tiles:insertDefinition name="existingDefinition" template="alternateTemplate.jsp" />

A: I think a view preparer might help:
http://tiles.apache.org/framework/tutorial/advanced/preparer.html

A: In spring tilesConfigurer you need to set mutable container:
<property name="useMutableTilesContainer" value="true"/>
<property name="checkRefresh" value="true"/>

And in your Spring Controller:
ModelAndView model = new ModelAndView();
MutableTilesContainer container = (MutableTilesContainer)ServletUtil.getContainer(request.getSession().getServletContext());
Attribute attribute = new Attribute("your template jsp");
HashMap<String, Attribute>  attributes = new HashMap<String, Attribute>();
attributes.put("body", attribute);
Definition definition = new Definition("your definition name", "your jsp", attributes);
definition.setExtends("your definition template name");
definition = PatternUtil.replacePlaceholders(definition, "your definition name", new Object());
container.register(definition, request, response);
model.setViewName("your definition name");


text:
Q: How can I expose React Hook outside of my React Functional Component I have a React Functional Component like this:
export const MyParentComponent = (props: Props) => {
    const [myObjects, setMyObjects = React.useState< MyClass[] | undefined>(undefined);

  //...
}

I have an array of 'MyClass' objects, in myObjects and put that in the 'State' of React since that will affect MyParentComponent rendering.
My question is how can I expose setMyObjects method to class outside of MyParentComponent so that the caller can set a new array of MyObjects and trigger a rendering of MyParentComponent ?

A: If you want the parent component to be able to change the state, you'd either

*

*Make myObjects a state of the parent component or

*Initialize the myObjects state with the props passed from the parent component

Unless having the state inside the component prevents you from making your component a pure component, I'd typically recommend the latter:

const {
  useState
} = React;

const MyComponent = (props) => {
  const [myObjects, setMyObjects] = useState(props.myObjects)

  return (

Rendering from MyComponent

        {myObjects.map(o =>
{o}
)}

  );
};

const MyParentComponent = () => {
  const objects = ['object1 from MyParentComponent', 'object2  from MyParentComponent', 'object3  from MyParentComponent'];
  return (<MyComponent myObjects={objects} />);
}

ReactDOM.render( <MyParentComponent / > ,
  document.getElementById("root")
);

A: since you want to change the state of MyParentComponent in outside of that component, that outside component need to be a child, since you can need to pass the setMyObjects function as a prop.  In other way you can you react feature called Context API to access the state of a component which is not Descendant.
React Context API
This is a simple scenario that elaborates how to change the state of the parent component inside the child component by passing setState function as a prop to child.
const Movie = () => { // This is the Parent component which render movies.
const movies = [
{ id: 1, title: "Batman", ratings: 8 },
{ id: 2, title: "Avengers", ratings: 8 },
{ id: 1, title: "Dune", ratings: 9 }
];
const [myObjects, setMyObjects] = useState(movies);
return (

  {myObjects.map((movie) => (

{movie.title}

  ))}
  <ChangeMovie changeMovieList={setMyObjects}/> // This is the child component which handle changing the state of Movie(Parent). Here pass the state change function as a prop(changeMovieList) to child. Then we can use that to change the state inside that component.

);
};

export default Movie;

const ChangeMovie = (props) => { // This is the child component.
const changeList = () => {
props.changeMovieList([ // here we change the state of Movie(Parent Component) inside child using the function passed.
  { id: 1, title: "Superman", ratings: 8 },
  { id: 2, title: "Titanic", ratings: 8 },
  { id: 1, title: "Fast & Furious 8", ratings: 9 }
]);
};

return (
<>
  <button onClick={changeList}>Change Movie List</button>
</>
);
};

export default ChangeMovie;

Check this demo sandbox I created to elaborate this.


text:
Q: Running Command in a shell script I am trying to execute a opencl program by running the command in a shell script.
When , I run the command on the command line it runs without any errors.
But when I run it in a shell script it throws error -
icpc command not found

Here is my shell script
#!/bin/csh

foreach t (1024 4096 8192 32768 50000 100000 500000 1000000 2000000 3000000 4000000 5000000 6000000 7000000 8000000)
        foreach l (8 16 32 64 128 256 512)
                icpc -o first first.cpp  -no-vec /scratch/cuda-7.0/lib64/libOpenCL.so -lm -openmp -DNMB=$t -DLOCAL_SIZE=$l
                ./first
        end
end

Can anyone please help me fix it

A: Specify full path to icpc in your shell script – algor


text:
Q: Behaviour of | symbol in regex This is my string
String s = "asadsdas357902||190||RUE RACHELLE||ST|||LES CÈDRES|J7T1J9|QC";

I split it as
String a[] = s.split(s, i);

outputs: i=0
        |   |   1   9   0   |   |   R   U   E       R   A   C   H   E   L   L   E   |   |   S   T   |   |   |   L   E   S       C   È   D   R   E   S   |   J   7   T   1   J   9   |   Q   C

First two indexes of array are empty nad then each index has one character.
When i=1, output is the whole original string
asadsdas357902||190||RUE RACHELLE||ST|||LES CÈDRES|J7T1J9|QC

when i=2, output is
    ||190||RUE RACHELLE||ST|||LES CÈDRES|J7T1J9|QC

first index of array is empty and second contains the substring from first | symbol
when i=3, output is
        ||190||RUE RACHELLE||ST|||LES CÈDRES|J7T1J9|QC

first two indexes are empty and last index has the same substring as for i=2
when i=4, output is
        |   |190||RUE RACHELLE||ST|||LES CÈDRES|J7T1J9|QC

first two indexes empty, next contains a pipe and last the rest
when i=5, output is
        |   |   190||RUE RACHELLE||ST|||LES CÈDRES|J7T1J9|QC

first two empty, next two pipe character and last the remaining.
as the i value increases, the output is
first two indexes empty
next all indexes except last contains one character each
last index contains the remaining string

My questions are

*

*Why it is not considering the first word before the first pipe symbol?

*Why it is making he first two indexes empty for every value of i except 1?

*The pattern is the same string here, so what is matched here and how the outputs come?

And another thing is if I replace the pipe symbol with any other symbol such as @ or ! or %, the output is
array length is 2 with both indexes has empty strings. this is for i>=2

for i=0
the array length is also 0

for i=1
the array length is 1 containing the whole string.

Is it taking the pipe symbol as a special regex symbol?
Any help appreciable.

A: split method takes a regex as an input param. Now the regex in your case is
asadsdas357902||190||RUE RACHELLE||ST|||LES CÈDRES|J7T1J9|QC and the second parameter i is the number of times that split operation is applied. This is the explanation of your regex
                         // Match either the regular expression below (attempting the next alternative only if this one fails)
   "asadsdas357902" +       // Match the characters "asadsdas357902" literally
"|" +                    // Or match regular expression number 2 below (attempting the next alternative only if this one fails)
   "|" +                    // Empty alternative effectively truncates the regex at this point because it will always find a zero-width match
                         // Or match regular expression number 3 below (attempting the next alternative only if this one fails)
   "190" +                  // Match the characters "190" literally
"|" +                    // Or match regular expression number 4 below (attempting the next alternative only if this one fails)
   "|" +                    // Empty alternative effectively truncates the regex at this point because it will always find a zero-width match
                         // Or match regular expression number 5 below (attempting the next alternative only if this one fails)
   "RUE\\ RACHELLE" +        // Match the characters "RUE RACHELLE" literally
"|" +                    // Or match regular expression number 6 below (attempting the next alternative only if this one fails)
   "|" +                    // Empty alternative effectively truncates the regex at this point because it will always find a zero-width match
                         // Or match regular expression number 7 below (attempting the next alternative only if this one fails)
   "ST" +                   // Match the characters "ST" literally
"|" +                    // Or match regular expression number 8 below (attempting the next alternative only if this one fails)
   "|" +                    // Empty alternative effectively truncates the regex at this point because it will always find a zero-width match
                         // Or match regular expression number 9 below (attempting the next alternative only if this one fails)
   "|" +                    // Empty alternative effectively truncates the regex at this point because it will always find a zero-width match
                         // Or match regular expression number 10 below (attempting the next alternative only if this one fails)
   "LES\\ CÈDRES" +          // Match the characters "LES CÈDRES" literally
"|" +                    // Or match regular expression number 11 below (attempting the next alternative only if this one fails)
   "J7T1J9" +               // Match the characters "J7T1J9" literally
"|" +                    // Or match regular expression number 12 below (the entire match attempt fails if this one fails to match)
   "QC"                     // Match the characters "QC" literally

So, your regex is effectively equivalent to asadsdas357902| in a way because the regex that comes after it is never tested. See the split method documentation here String#split
This code would give you the same output
private static void splitWithPipe() {
    String s = "asadsdas357902||190||RUE RACHELLE||ST|||LES CÈDRES|J7T1J9|QC";
    for (int i = 0; i < 10; i++) {
        String a[] = s.split("asadsdas357902|", i);
        System.out.println(Arrays.toString(a));
    }
}

A: | is a special character in regular expressions, indeed. It means "Either the stuff to the left of me, or the stuff to the right of me", so ab|cd matches either ab or cd. This can be further constrained by parentheses.
If you want to do a regex split at |, then you need the regex \|, which in Java needs to be written as "\\|" in a string.

A: In regular expressions you don't need a double | symbol - that will just confuse things. You may wish to consider visiting a site with regular expression tutorials and use the web site regular expression tester


text:
Q: What is the origin of the vampire's drudge? I have recently come across the idea of a vampire's drudge: a slave to do a vampire's bidding. However, I have not been able to find the origin of it. In fact, the only references to it I am able to find are unsourced replies to generic questions on sites such as Wikianswers (the questions being of the nature "What is a vampire's slave?" and the answer being "A drudge"), fan-fictions and a series of fiction books called the Chronicles of Vladimir Tod.
What I am looking for is the origin of the term "drudge". I understand the nature of the drudge -- the vampire's servant -- but I am looking for the origin of the actual term: did it come from mythology or is it the creation of an individual author and so on?
EDIT: I had made the connection between drudgery and drudge: it makes sense that a person designated to do hard or menial tasks could, from drudgery, be called a drudge; so I just want to stress I'm after the origin of using the word to mean a vampire's servant.

A: A Drudge, according to the dictionary:

drudge 1  (drŭj)
  n.
  A person who does tedious, menial, or unpleasant work.
  intr.v. drudged, drudg·ing, drudg·es
  To do tedious, unpleasant, or menial work.

Vampires are well known for enjoying the finer side of life. Sipping blood, kidnapping virgins, those kinds of joyous activities. However, somebody has to keep the house clean, drag away the corpses and what not, activities a vampire clearly doesn't care for.
Enter the drudge!
As far as I can tell, the first use of the word 'drudge' for a vampire's servant is in the 'Chronicles of Vladimir Tod'. Other words people sometimes use for the (mostly) human servants of vampires are ghouls and thralls.

A: Drudge is not an invention of a recent author - the word comes from Middle English druggan, which is derived from the Old English dreogan - which is a verb meaning to perform (a service), or to suffer/bear/endure.

A: I have read a lot of vampire books and I have actually never come across that word to describe a vampire's human servant. I think that was just the particular word choice of a few authors, not any kind of shift in nomenclature. I think the choice of the word drudge has more to do with the relationship between the vamp and his person in that world/story than anything else, because some vamps treat their humans really well and some treat them like dirt, and some don't keep people around at all. It just depends on the story.


text:
Q: pthread RWlock quesion I am using a translator because I am not good at English.
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <fcntl.h>
#include <unistd.h>

pthread_rwlock_t R_Lock;
int ac=0;

void* RD_LOCK(void* arg) {
    pthread_rwlock_rdlock(&R_Lock);
    printf("%d\n",ac); // ac is global variable 0
    sleep(1);
    pthread_rwlock_unlock(&R_Lock);
}
void* WR_LOCK(void* arg) {
    pthread_rwlock_wrlock(&R_Lock);
    printf("RW LCOK\n");
    ac++;
    printf("%d\n",ac);
    sleep(1);
    pthread_rwlock_unlock(&R_Lock);
}
void DO_RW_LCOK(){
    pthread_t RW[3];
    pthread_rwlock_init(&R_Lock, NULL);
    pthread_create(&RW[0], NULL, RD_LOCK,NULL); //==0 thread
    pthread_create(&RW[1], NULL, RD_LOCK,NULL); //==1 thread
    pthread_create(&RW[2], NULL, WR_LOCK,NULL); //==2 thread
    pthread_rwlock_destroy(&R_Lock);
    for(int i=0; i<3;i++)
    pthread_join(RW[i],NULL);
}
int main(){
    DO_RW_LCOK();
    return 0;
}

void* RD_LOCK(void* arg) {

  pthread_rwlock_rdlock(&R_Lock);
  printf("%d\n",ac); // ac is global variable 0
  sleep(1);
  pthread_rwlock_unlock(&R_Lock); }

void* WR_LOCK(void* arg) {

  pthread_rwlock_wrlock(&R_Lock);
  ac++;
  printf("%d\n",ac);
  sleep(1);
  pthread_rwlock_unlock(&R_Lock);
}
int main(){
  DO_RW_LOCK();
  return 0;
}

I tried to execute 3 threads.
0,1 thread used readlock and 2 thread used writelcok.
My prediction after the program runs After the 0,1 thread, 2 thread was executed.
However, the run order is 2thread,0thread,1thread
I don't understand this.

A: Threads are always unpredictable. So the order may really change and be unexpected.
In order to guarantee that your threads will be in the order that you want them to be, add a wait option which will make the thread wait if the other threads are not done. Just use wait and notify.
I did not get which thread type you are using but here is a pseudocode.
Lock waitAndNotify;
int rdDone = 0;
void* RD_LOCK(void* arg) {
  pthread_rwlock_rdlock(&R_Lock);
  rdDone++;
  notify(waitAndNotify);
  printf("%d\n",ac); // ac is global variable 0
  sleep(1);
  pthread_rwlock_unlock(&R_Lock); }

void* WR_LOCK(void* arg) {

  pthread_rwlock_wrlock(&R_Lock);
  if(rdDone!=2)
    wait(waitAndNotify);
  ac++;
  printf("%d\n",ac);
  sleep(1);
  pthread_rwlock_unlock(&R_Lock);
}


text:
Q: Extracting JSON from PHP on Android I have tried and tried this and can't seem to get to the bottom of it. Here is the PHP code
$query = "SELECT `title` FROM `c2torsdb`.`pE_vacancies` WHERE active=1 LIMIT 2";
$result = mysql_query($query,$link) or die('Errant query:  '.$query);
/* create one master array of the records */
$posts = array();
if(mysql_num_rows($result)) {
while($post = mysql_fetch_assoc($result)) {
$posts[] = array('post'=>$post);
    }
  }
  /* output in necessary format */
  if($format == 'json') {
    header('Content-type: application/json, charset=utf-8');
    echo json_encode($posts);
  }

And here is my code snippet
    HttpResponse response = httpclient.execute(httppost);
    String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
    JSONObject object = new JSONObject(jsonResult);

    //JSONArray innerobj = object.getJSONArray("post");
    String name = object.getString("title");
    //String name = name1.getString(0);

    Log.v("isurgeon", name);

    //String name = object.getString("posts");
    //String verion = object.getString("version");
    textView.setText(name + " - ");

Here is the JSON output from the PHP script:
[{"post":{"title":"Property Litigation Assistant Solicitor"}},{"post":{"title":"Trusts and Probate Practitioner"}}]

I just want the 'title'.

A: I will be honest, I am not familiar with android but I know JSON.  If I were to take your JSON output and place it into javascript like this:
var abc = [{"post":{"title":"Property Litigation Assistant Solicitor"}},{"post":{"title":"Trusts and Probate Practitioner"}}]

I would get the 1st title by doing this:
abc[0].title

You need to select the nth element of the returned json object THEN get the title.

A: Bill's right - the way your JSON is outputted there, everything is enclosed in an array
Android imo has really good native handling for JSON Objects / arrays so if you simply do
JSONArray jsonArray = new JSONArray(jsonResult);

JSONObject object = jsonArray[0];

everything should work fine