问:
Plastic SCM. Is it the right solution?
I know there are some questions already regarding Plastic SCM, but they are over a year old.  Has anyone used Plastic SCM lately?  What do you think about it.

I have used git, and I am currently using Hg.  I love the Hg source control, but Visual Studio integration is not great, and related task/project management tools have not been great.  Plastic SCM was recommended, but I like to get a community view on it. - And no, I don't care about grammar on the website.  I prefer well engineered solutions to well marketed websites.

答:
Yes, we use Plastic SCM (small team of 5) for 2 years already and it works great and even gets better every update!

Support is very good (within an hour or at least the same day a response!).

Also branching and merging works very good in practice. Every programmer can work on it's own in his own branch (using branch per task pattern). Such a big relief. When you switch to another branch all changes are automatically shelved/stored on the server. When you switch back, the changes are reloaded, which is a really nice feature! You don't have to worry to loose changes, because Plastic handles everything very good.

Without doubt Plastic SCM is the best Version Control System I've ever seen (used MS Sourcesafe, CVS, SVN, StarTeam). Also heard of other's the branch support is much better than MS Team Foundation.

Title: Plastic SCM. Is it the right solution?


来源: stackexchange

问:
JFrame background color won't change?
So, I'm trying to display a simple JFrame but I'm unable to change the background color? Did a few searches and they all suggest to use useContentPane which I have.

```<code> import java.awt.*;

import javax.swing.*;

public class Login {

     public static void main(String[] args) {

         createWindow();

         }

    private static void createWindow() {
        JFrame frame = new JFrame("Login System");
        frame.getContentPane().setBackground(Color.darkGray);
        frame.setSize(350, 350);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JTextField username = new JTextField();
        frame.add(username);
        frame.setVisible(true);
    }

}
</code>```

The JFrame size works but the background does not and the TextField does not, pretty new to this. Any ideas? All help is appreciated.

答:
The problem with your code is that your text field is covering the full jframe

one of the way is to reduce the text field size in the design view and then in code add this line

getContentPane().setBackground(Color.BLACK);

ContentLicense: CC BY-SA 3.0

Title: JFrame background color won't change?

Body:
So, I'm trying to display a simple JFrame but I'm unable to change the background color? Did a few searches and they all suggest to use useContentPane which I have.

 import java.awt.*;

import javax.swing.*;

public class Login {

     public static void main(String[] args) {

         createWindow();

         }

    private static void createWindow() {
        JFrame frame = new JFrame("Login System");
        frame.getContentPane().setBackground(Color.darkGray);
        frame.setSize(350, 350);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JTextField username = new JTextField();
        frame.add(username);
        frame.setVisible(true);
    }

}

The JFrame size works but the background does not and the TextField does not, pretty new to this. Any ideas? All help is appreciated.


问:
How to include values from files into your code
I have this structure Student Record that I'd like to fill with values from two files NamesIDsDataFile and MarksDataFile temporarily but when I run the loop only values from NamesIDsDataFile go into the structure. I've put the print statement inside the while loop to see what the issue was and when I run the code nothing prints out. Could someone please explain how to print the values from MarksDataFile.   </p>

```<code>struct StudentRecord {

char FirstNames[MAXLENGTH];
char LastNames[MAXLENGTH];
int IDNums;
int Marks;

};

    FILE * NamesIDsDataFile;
    FILE * MarksDataFile;

    while (fscanf(NamesIDsDataFile,"%s%s%d",&(SRecords.FirstNames[0]),
    &(SRecords.LastNames[0]), &(SRecords.IDNums)) != EOF) {

        fscanf(MarksDataFile,"%d",&(SRecords.Marks));

        printf("%d", SRecords.Marks);

    }

    fclose(NamesIDsDataFile);
    fclose(MarksDataFile);
</code>```

答:
Simple way to to so by little change in your code is :

```<code>while (fscanf(NamesIDsDataFile," %s %s %d ",&(SRecords.FirstNames[0]),
    &(SRecords.LastNames[0]), &(SRecords.IDNums)) != EOF)
{
      fscanf(MarksDataFile," %d ",&(SRecords.Marks));

      printf("%d", SRecords.Marks);
}
</code>```

but, if the if the text file is not always same and not structured very well, you should not go with above code, instead use following code.

here is the best way to do it:

```<code>int ret1,ret2;
while (ret =fscanf(NamesIDsDataFile," %s %s %d ",&(SRecords.FirstNames[0]),
&(SRecords.LastNames[0]), &(SRecords.IDNums))) {

    if(ret == EOF)
    {
        break;
    }
    else
    {
        ret2 = fscanf(MarksDataFile," %d ",&(SRecords.Marks));
        if(ret2 == EOF || ret2 == 0)
        {
            break;
        }else
        {
            printf("%d", SRecords.Marks);

        }
    }
}

fclose(NamesIDsDataFile);
fclose(MarksDataFile);
</code>```

ret is an int variable whose value will be :

EOF, if the pointer is reached end of file.

0, if no input matched with the variable

>0, number of matched variables with the file input

Body:
I have this structure Student Record that I'd like to fill with values from two files NamesIDsDataFile and MarksDataFile temporarily but when I run the loop only values from NamesIDsDataFile go into the structure. I've put the print statement inside the while loop to see what the issue was and when I run the code nothing prints out. Could someone please explain how to print the values from MarksDataFile.

struct StudentRecord {

char FirstNames[MAXLENGTH];
char LastNames[MAXLENGTH];
int IDNums;
int Marks;

};

    FILE * NamesIDsDataFile;
    FILE * MarksDataFile;

    while (fscanf(NamesIDsDataFile,"%s%s%d",&(SRecords.FirstNames[0]),
    &(SRecords.LastNames[0]), &(SRecords.IDNums)) != EOF) {

        fscanf(MarksDataFile,"%d",&(SRecords.Marks));

        printf("%d", SRecords.Marks);

    }

    fclose(NamesIDsDataFile);
    fclose(MarksDataFile);

Body:
Simple way to to so by little change in your code is :

while (fscanf(NamesIDsDataFile," %s %s %d ",&(SRecords.FirstNames[0]),
    &(SRecords.LastNames[0]), &(SRecords.IDNums)) != EOF)
{
      fscanf(MarksDataFile," %d ",&(SRecords.Marks));

      printf("%d", SRecords.Marks);
}

but, if the if the text file is not always same and not structured very well, you should not go with above code, instead use following code.

here is the best way to do it:

int ret1,ret2;
while (ret =fscanf(NamesIDsDataFile," %s %s %d ",&(SRecords.FirstNames[0]),
&(SRecords.LastNames[0]), &(SRecords.IDNums))) {

    if(ret == EOF)
    {
        break;
    }
    else
    {
        ret2 = fscanf(MarksDataFile," %d ",&(SRecords.Marks));
        if(ret2 == EOF || ret2 == 0)
        {
            break;
        }else
        {
            printf("%d", SRecords.Marks);

        }
    }
}

fclose(NamesIDsDataFile);
fclose(MarksDataFile);

ret is an int variable whose value will be :

EOF, if the pointer is reached end of file.

0, if no input matched with the variable

>0, number of matched variables with the file input


问:
Improve oracle query performance without indexing
What are some things I can do to improve query performance of an oracle query without creating indexes?

Here is the query I'm trying to run faster:

```<code>SELECT c.ClaimNumber, a.ItemDate, c.DTN, b.FilePath
FROM items a,
itempages b,
keygroupdata c
WHERE a.ItemType IN (112,115,189,241)
AND a.ItemNum = b.ItemNum
AND b.ItemNum = c.ItemNum
ORDER BY a.DateStored DESC
</code>```

None of these columns are indexed and each of the tables contains millions of records. Needless to say, it takes over 3 and half minutes for the query to execute. This is a third party database in a production environment and I'm not allowed to create any indexes so any performance improvements would have to be made to the query itself.

Thanks!

答:
Well, since you can't create indexes, I'd make sure that statistics are all up-to-date then, I'd rewrite the query this way:

with a as (select /*+ MATERIALIZE */ ItemType, ItemNum, DateStored, ItemDate from items where ItemType in (112,115,189,241))
SELECT c.ClaimNumber, a.ItemDate, c.DTN, b.FilePath
FROM a,
itempages b,
keygroupdata c
WHERE a.ItemNum = b.ItemNum
AND b.ItemNum = c.ItemNum
ORDER BY a.DateStored DESC

OwnerDisplayName: Chris Conway

ContentLicense: CC BY-SA 2.5

Body:
What are some things I can do to improve query performance of an oracle query without creating indexes?

Here is the query I'm trying to run faster:

SELECT c.ClaimNumber, a.ItemDate, c.DTN, b.FilePath
FROM items a,
itempages b,
keygroupdata c
WHERE a.ItemType IN (112,115,189,241)
AND a.ItemNum = b.ItemNum
AND b.ItemNum = c.ItemNum
ORDER BY a.DateStored DESC

None of these columns are indexed and each of the tables contains millions of records. Needless to say, it takes over 3 and half minutes for the query to execute. This is a third party database in a production environment and I'm not allowed to create any indexes so any performance improvements would have to be made to the query itself.

Thanks!


问:
How to check that string contains is english only
i have a string which contains values like:

```<code>string str ="Abhigyan Prakash,Primeshow,NewsPoint,NCP,Inflation,सरकार,राहुल,प्राइम शो,न्यूजप्वाइंट,कमजोर,एनसीपी,अभिज्ञान प्रकाश,Rahul";
</code>```

i have used below code to convert it to array list:

```<code>    ArrayList altags = new ArrayList( str.Split(','));
</code>```

now i wants to remove all those strings from arraylist which belongs from non-english language (in my context those words which are written in "hindi" should be removed)

please suggest me how to check that string is written in english (with numeric and symbols) or in other language..

NOTE: i have no issue with generic list. i cant take it also. but please tell me how to check that string contains only alphabets + numeric + symbols
Thanks

答:
According to the ascii tables characters of English words (with numeric) should fall between the ranges 48 - 57 (0-9), 65-90 (A-Z) and 97-122 (a-z)

You might want to add to the ranges punctuation signs and other imported characters like é (from fiancé for example).

Body:
i have a string which contains values like:

string str ="Abhigyan Prakash,Primeshow,NewsPoint,NCP,Inflation,सरकार,राहुल,प्राइम शो,न्यूजप्वाइंट,कमजोर,एनसीपी,अभिज्ञान प्रकाश,Rahul";

i have used below code to convert it to array list:

    ArrayList altags = new ArrayList( str.Split(','));

now i wants to remove all those strings from arraylist which belongs from non-english language (in my context those words which are written in "hindi" should be removed)

please suggest me how to check that string is written in english (with numeric and symbols) or in other language..

NOTE: i have no issue with generic list. i cant take it also. but please tell me how to check that string contains only alphabets + numeric + symbols
Thanks


问:
How to change EditText background color when I enter text?
My EditText has some color, but when I enter some text it should change. Say it's grey, I started to enter and it's yellow. This EditText is also focused, so when this activity starts -- I already can enter the text. How I tried:

```<code><style name="LoginEnterField">
    <item name="android:textColorHint">@color/black</item>
    <item name="android:textColor">@color/black</item>
    <item name="android:background">@drawable/selector_edittext</item>
    <item name="android:textSize">@dimen/general_text_size</item>
    <item name="android:paddingLeft">@dimen/activity_inner_horizontal_margin</item>
    <item name="android:paddingRight">@dimen/activity_inner_horizontal_margin</item>
</style>

<shape xmlns:android="http://schemas.android.com/apk/res/android"

    android:shape="rectangle">
    <solid android:color="@color/grey"/>
    <corners android:radius="5dp" />

</shape>

<shape xmlns:android="http://schemas.android.com/apk/res/android"

  android:shape="rectangle">
  <solid android:color="@color/yellow"/>
  <corners android:radius="5dp" />

</shape>

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_focused="true" android:drawable="@drawable/roundbox_active_style"/>
  <item android:drawable="@drawable/roundbox_inactive_style" />
</selector>
</code>```

I think the point is in this selector. My EditText changes color, but it always yellow. How to make it became yellow only if I enter some text? I can't make any code changes! It's very important. I can't add or change only xml files.

EDIT: It's impossible to do from xml only, so make code changes.

答:
Use TextWatcher

```<code>editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
</code>```

You can add your desired code in any of the method that suits you. For further reference visit:

https://developer.android.com/reference/android/text/TextWatcher.html

ContentLicense: CC BY-SA 4.0

Body:
My EditText has some color, but when I enter some text it should change. Say it's grey, I started to enter and it's yellow. This EditText is also focused, so when this activity starts -- I already can enter the text. How I tried:

<shape xmlns:android="http://schemas.android.com/apk/res/android"

    android:shape="rectangle">
    <solid android:color="@color/grey"/>
    <corners android:radius="5dp" />

</shape>

<shape xmlns:android="http://schemas.android.com/apk/res/android"

  android:shape="rectangle">
  <solid android:color="@color/yellow"/>
  <corners android:radius="5dp" />

</shape>

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_focused="true" android:drawable="@drawable/roundbox_active_style"/>
  <item android:drawable="@drawable/roundbox_inactive_style" />
</selector>

I think the point is in this selector. My EditText changes color, but it always yellow. How to make it became yellow only if I enter some text? I can't make any code changes! It's very important. I can't add or change only xml files.

EDIT: It's impossible to do from xml only, so make code changes.

Body:
Use TextWatcher

editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

You can add your desired code in any of the method that suits you. For further reference visit:

https://developer.android.com/reference/android/text/TextWatcher.html


问:
Use from "php - $_GET[]" and "RewriteRule" in "htaccess" for "d.com" and "d.com/p/1"

Mode 1 :

URL: domain.com/?sv=g

.htaccess: RewriteRule ^page/([0-9]+)/$ fa/?page=$1

When I use from $_GET['sv'] return to me g.

Mode 2 :

URL: domain.com/page/1/?sv=g

.htaccess:  RewriteRule ^page/([0-9]+)/$ fa/?page=$1

When I use from $_GET['sv'] return to me null.

答:
You need to add the QSA flag to your RewriteRule, or it won't add in any existing query string paramters from the request:

When the replacement URI contains a query string, the default behavior of RewriteRule is to discard the existing query string, and replace it with the newly generated one. Using the [QSA] flag causes the query strings to be combined.

Try this:

```<code>RewriteRule ^page/([0-9]+)/$ fa/?page=$1 [QSA]
</code>```

Body:
You need to add the QSA flag to your RewriteRule, or it won't add in any existing query string paramters from the request:

When the replacement URI contains a query string, the default behavior of RewriteRule is to discard the existing query string, and replace it with the newly generated one. Using the [QSA] flag causes the query strings to be combined.

Try this:

RewriteRule ^page/([0-9]+)/$ fa/?page=$1 [QSA]


问:
Getting file name out of a string
I need to get the filename 'HomeModel' out of a string app\model\common\HomeModel. This is what I tried

First, replace '\' with '/' using the str_replace.

```<code>$model = 'app\model\common\HomeModel';
$file = str_replace("\\", '/', $model) . ".php";
echo $file;
</code>```

the result

```<code>app/model/common/HomeModel.php
</code>```

then I explode the result like so

```<code>$model = 'app\model\common\HomeModel';
$file = str_replace("\\", '/', $model) . ".php";
echo $file;

$result = explode("/", $file);
echo '<br>';
var_dump($result);
</code>```

and then this is what I have

```<code>array (size=4)
  0 => string 'app' (length=3)
  1 => string 'model' (length=5)
  2 => string 'common' (length=6)
  3 => string 'HomeModel.php' (length=18)
</code>```

Now, how do I get the last value 'HomeModel' out of this array for further use?, I need to assign the value 'HomeModel' to $class.

答:
You can try this approach:</p>

```<code><?php

$model = 'app\model\common\HomeModel';

$fileName = substr(str_replace("\\", '/',$model), strrpos(str_replace("\\", '/',$model),'/') + 1).'.php';

echo $fileName;
</code>```

Title: Getting file name out of a string

Body:
I need to get the filename 'HomeModel' out of a string app\model\common\HomeModel. This is what I tried

First, replace '\' with '/' using the str_replace.

$model = 'app\model\common\HomeModel';
$file = str_replace("\\", '/', $model) . ".php";
echo $file;

the result

app/model/common/HomeModel.php

then I explode the result like so

$model = 'app\model\common\HomeModel';
$file = str_replace("\\", '/', $model) . ".php";
echo $file;

$result = explode("/", $file);
echo '
';
var_dump($result);

and then this is what I have

array (size=4)
  0 => string 'app' (length=3)
  1 => string 'model' (length=5)
  2 => string 'common' (length=6)
  3 => string 'HomeModel.php' (length=18)

Now, how do I get the last value 'HomeModel' out of this array for further use?, I need to assign the value 'HomeModel' to $class.

Body:
You can try this approach:

<?php

$model = 'app\model\common\HomeModel';

$fileName = substr(str_replace("\\", '/',$model), strrpos(str_replace("\\", '/',$model),'/') + 1).'.php';

echo $fileName;


问:
How to access pixels data from ID3D11Texture2D?
I'm using Windows Desktop Duplication API to make my own mirroring protocol.
I have this piece of code :

```<code>// Get new frame
HRESULT hr = m_DeskDupl->AcquireNextFrame(500, &FrameInfo, &DesktopResource);
if (hr == DXGI_ERROR_WAIT_TIMEOUT)
{
    *Timeout = true;
    return DUPL_RETURN_SUCCESS;
}
</code>```

Here is the FrameInfo structure :

```<code>`typedef struct _FRAME_DATA {
ID3D11Texture2D* Frame;
DXGI_OUTDUPL_FRAME_INFO FrameInfo;
_Field_size_bytes_((MoveCount * sizeof(DXGI_OUTDUPL_MOVE_RECT)) +    (DirtyCount * sizeof(RECT))) BYTE* MetaData;
UINT DirtyCount;
UINT MoveCount;
 } FRAME_DATA;`
</code>```

I would like to extract the pixel buffer from ID3D11Texture2D* Frame;
How can I extract on a BYTE * or unsigned char * and have a RGB sequence ?
Thank you !

答:
Hi here is the code which helps for your requirement. output will be in UCHAR buffer g_iMageBuffer

```<code>//Variable Declaration
IDXGIOutputDuplication* IDeskDupl;
IDXGIResource*          lDesktopResource = nullptr;
DXGI_OUTDUPL_FRAME_INFO IFrameInfo;
ID3D11Texture2D*        IAcquiredDesktopImage;
ID3D11Texture2D*        lDestImage;
ID3D11DeviceContext*    lImmediateContext;
UCHAR*                  g_iMageBuffer=nullptr;

//Screen capture start here
hr = lDeskDupl->AcquireNextFrame(20, &lFrameInfo, &lDesktopResource);

// >QueryInterface for ID3D11Texture2D
hr = lDesktopResource->QueryInterface(IID_PPV_ARGS(&lAcquiredDesktopImage));
lDesktopResource.Release();

// Copy image into GDI drawing texture
lImmediateContext->CopyResource(lDestImage,lAcquiredDesktopImage);
lAcquiredDesktopImage.Release();
lDeskDupl->ReleaseFrame();

// Copy GPU Resource to CPU
D3D11_TEXTURE2D_DESC desc;
lDestImage->GetDesc(&desc);
D3D11_MAPPED_SUBRESOURCE resource;
UINT subresource = D3D11CalcSubresource(0, 0, 0);
lImmediateContext->Map(lDestImage, subresource, D3D11_MAP_READ_WRITE, 0, &resource);

std::unique_ptr<BYTE> pBuf(new BYTE[resource.RowPitch*desc.Height]);
UINT lBmpRowPitch = lOutputDuplDesc.ModeDesc.Width * 4;
BYTE* sptr = reinterpret_cast<BYTE*>(resource.pData);
BYTE* dptr = pBuf.get() + resource.RowPitch*desc.Height - lBmpRowPitch;
UINT lRowPitch = std::min<UINT>(lBmpRowPitch, resource.RowPitch);

for (size_t h = 0; h < lOutputDuplDesc.ModeDesc.Height; ++h)
{
    memcpy_s(dptr, lBmpRowPitch, sptr, lRowPitch);
    sptr += resource.RowPitch;
    dptr -= lBmpRowPitch;
}

lImmediateContext->Unmap(lDestImage, subresource);
long g_captureSize=lRowPitch*desc.Height;
g_iMageBuffer= new UCHAR[g_captureSize];
g_iMageBuffer = (UCHAR*)malloc(g_captureSize);

//Copying to UCHAR buffer
memcpy(g_iMageBuffer,pBuf,g_captureSize);
</code>```

Body:
I'm using Windows Desktop Duplication API to make my own mirroring protocol.
I have this piece of code :

// Get new frame
HRESULT hr = m_DeskDupl->AcquireNextFrame(500, &FrameInfo, &DesktopResource);
if (hr == DXGI_ERROR_WAIT_TIMEOUT)
{
    *Timeout = true;
    return DUPL_RETURN_SUCCESS;
}

Here is the FrameInfo structure :

`typedef struct _FRAME_DATA {
ID3D11Texture2D* Frame;
DXGI_OUTDUPL_FRAME_INFO FrameInfo;
_Field_size_bytes_((MoveCount * sizeof(DXGI_OUTDUPL_MOVE_RECT)) +    (DirtyCount * sizeof(RECT))) BYTE* MetaData;
UINT DirtyCount;
UINT MoveCount;
 } FRAME_DATA;`

I would like to extract the pixel buffer from ID3D11Texture2D* Frame;
How can I extract on a BYTE * or unsigned char * and have a RGB sequence ?
Thank you !

Body:
Hi here is the code which helps for your requirement. output will be in UCHAR buffer g_iMageBuffer

//Variable Declaration
IDXGIOutputDuplication* IDeskDupl;
IDXGIResource*          lDesktopResource = nullptr;
DXGI_OUTDUPL_FRAME_INFO IFrameInfo;
ID3D11Texture2D*        IAcquiredDesktopImage;
ID3D11Texture2D*        lDestImage;
ID3D11DeviceContext*    lImmediateContext;
UCHAR*                  g_iMageBuffer=nullptr;

//Screen capture start here
hr = lDeskDupl->AcquireNextFrame(20, &lFrameInfo, &lDesktopResource);

// >QueryInterface for ID3D11Texture2D
hr = lDesktopResource->QueryInterface(IID_PPV_ARGS(&lAcquiredDesktopImage));
lDesktopResource.Release();

// Copy image into GDI drawing texture
lImmediateContext->CopyResource(lDestImage,lAcquiredDesktopImage);
lAcquiredDesktopImage.Release();
lDeskDupl->ReleaseFrame();

// Copy GPU Resource to CPU
D3D11_TEXTURE2D_DESC desc;
lDestImage->GetDesc(&desc);
D3D11_MAPPED_SUBRESOURCE resource;
UINT subresource = D3D11CalcSubresource(0, 0, 0);
lImmediateContext->Map(lDestImage, subresource, D3D11_MAP_READ_WRITE, 0, &resource);

std::unique_ptr<BYTE> pBuf(new BYTE[resource.RowPitch*desc.Height]);
UINT lBmpRowPitch = lOutputDuplDesc.ModeDesc.Width * 4;
BYTE* sptr = reinterpret_cast<BYTE*>(resource.pData);
BYTE* dptr = pBuf.get() + resource.RowPitch*desc.Height - lBmpRowPitch;
UINT lRowPitch = std::min<UINT>(lBmpRowPitch, resource.RowPitch);

for (size_t h = 0; h < lOutputDuplDesc.ModeDesc.Height; ++h)
{
    memcpy_s(dptr, lBmpRowPitch, sptr, lRowPitch);
    sptr += resource.RowPitch;
    dptr -= lBmpRowPitch;
}

lImmediateContext->Unmap(lDestImage, subresource);
long g_captureSize=lRowPitch*desc.Height;
g_iMageBuffer= new UCHAR[g_captureSize];
g_iMageBuffer = (UCHAR*)malloc(g_captureSize);

//Copying to UCHAR buffer
memcpy(g_iMageBuffer,pBuf,g_captureSize);


问:
Firefox does not render <input> element inside JQuery modal dialog
I have tried to search for any clues but have not discovered any. Take a look at the following page:

http://jqtest.encorephoenix.com/withinput.aspx (JQuery modal popup with <input>)

Popup is renders correctly in IE, Chrome, Safari and Opera. Firefox 3.6.13 does not render the popup with  correctly. You can view withoutinput.aspx at the same URL to see that Firefox renders it correctly, since this page does not have <input> element. I have tried the following with no resolution to this peculiar problem:

Changed doctype

Used  to enclose <input>

Used  to enclose <input>

Used all possible CSS display attributes for <input>

Any suggestions would be greatly appreciated.

答:
The problem may have something to do with the function that runs when the ready event is called.

If I paste this function into Firebug console and run it, the modal window is displayed:

```<code>$(function () {
    var dlg = jQuery("#divPopup").dialog({
        modal: true,
        draggable: true,
        resizable: false,
        show: 'Transfer',
        hide: 'Transfer',
        height: 400,
        width: 480,
        minHeight: 400,
        minWidth: 480,
        autoOpen: false
    });
    dlg.parent().appendTo(jQuery("#form1:first"));
});
</code>```

This suggests that when this is called the first time, it's not being properly bound to the DOM elements.  An HTML Validation error could be related, or the doctype.

I'm seeing warnings in my HTML Validator whereby the system thinks it's a different doctype.  Additionally, any use of elements in a nonstandard manner could contribute to such behavior.

The solution to this problem is a step by step reduction of elements on the page until the problem disappears, then to slowly add elements back in until you've found the one that throws off the parser.

Alternatively, fix the doctype so it matches the standard of HTML coding used.

Body:
The problem may have something to do with the function that runs when the ready event is called.

If I paste this function into Firebug console and run it, the modal window is displayed:

$(function () {
    var dlg = jQuery("#divPopup").dialog({
        modal: true,
        draggable: true,
        resizable: false,
        show: 'Transfer',
        hide: 'Transfer',
        height: 400,
        width: 480,
        minHeight: 400,
        minWidth: 480,
        autoOpen: false
    });
    dlg.parent().appendTo(jQuery("#form1:first"));
});

This suggests that when this is called the first time, it's not being properly bound to the DOM elements.  An HTML Validation error could be related, or the doctype.

I'm seeing warnings in my HTML Validator whereby the system thinks it's a different doctype.  Additionally, any use of elements in a nonstandard manner could contribute to such behavior.

The solution to this problem is a step by step reduction of elements on the page until the problem disappears, then to slowly add elements back in until you've found the one that throws off the parser.

Alternatively, fix the doctype so it matches the standard of HTML coding used.


问:
Will I get the entire VM machine with all installation?
If I created a VM Azure machine and setup/installed all required nodejs, npm modules, IIS, mongoDb. on basis on my usages I shut down the VM machine. After start the VM machine, Will I get the entire machine with all installation.</p>

答:
Yes, you will. VMs are stateful. The only thing that might change (depending on the setup) is the internal\external IP addresses.

Azure even provides auto shutdown feature, to save you some clicking.


问:
Xcode Swift: How to stop variables from changing back after each viewDidLoad, how to save and update data from different ViewControllers?
I have some vars in my Main VC and when user clicks a button in another VC the prepareForSegue passes along a new value to the Main VC and updates a label.

But when the user clicks again it's back to initial value, so it doesn't increment since the value is set back in the viewDidLoad?

MainVC:

```<code>var statsHealth:Int = 0

override func viewDidLoad() {
    super.viewDidLoad()

    healthLabel.text = String("Health: \(statsHealth)/10")

}
</code>```

Another VC:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

```<code>    if (segue.identifier == "startSegue") {

        let startVC = segue.destinationViewController as ViewController

        startVC.statsHealth += 1

    }
</code>```

It's displayed as 0, then 1 but then 0 again and then 1 instead of 2,3,4 etc.

Any ideas?

BR

Nils

答:
Perhaps not the most 'Swift' way to do it, but certainly works well....

Create a file called Variables.swift which will hold all your 'universal' variables (if these are going to be on every page, I see no reason this isn't the 'best' way to do it - certainly it is the most simple to understand!)

in Variables.swift, hold all your universal variables

```<code>struct Variables {
    static var statsHealth = 0
.....
}
</code>```

Then, in each other page, access them at any time

```<code> healthLabel.text = String("Health: \(Variables.statsHealth)/10")
</code>```

or set them

```<code>Variables.statsHealth += 1
</code>```

Body:
I have some vars in my Main VC and when user clicks a button in another VC the prepareForSegue passes along a new value to the Main VC and updates a label.

But when the user clicks again it's back to initial value, so it doesn't increment since the value is set back in the viewDidLoad?

MainVC:

var statsHealth:Int = 0

override func viewDidLoad() {
    super.viewDidLoad()

    healthLabel.text = String("Health: \(statsHealth)/10")

}

Another VC:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if (segue.identifier == "startSegue") {

        let startVC = segue.destinationViewController as ViewController

        startVC.statsHealth += 1

    }

It's displayed as 0, then 1 but then 0 again and then 1 instead of 2,3,4 etc.

Any ideas?

BR

Nils

Body:
Perhaps not the most 'Swift' way to do it, but certainly works well....

Create a file called Variables.swift which will hold all your 'universal' variables (if these are going to be on every page, I see no reason this isn't the 'best' way to do it - certainly it is the most simple to understand!)

in Variables.swift, hold all your universal variables

struct Variables {
    static var statsHealth = 0
.....
}

Then, in each other page, access them at any time

 healthLabel.text = String("Health: \(Variables.statsHealth)/10")

or set them

Variables.statsHealth += 1


问:
Configure dependency injection from middleware in dot net core
I have a class that calls an external service which requires a token, and this is injected using the Settings class.

Now, depending on the request, I need to use one of two tokens.

I would like to use middleware to look at the incoming request to then configure what is injected into my service, but not sure this is possible?

Can I configure the DI from middleware?

答:
I'm not sure that you can configure Dependency Injection from within middleware because DI is done (if you're using the DI system supplied with .NET Core) during the Container setup faze (take a look at your startup.cs class).

I have a class that calls an external service which requires a token, and this is injected using the Settings class.

Now, depending on the request, I need to use one of two tokens

Could you not get both tokens and pass them into your middleware's constructor? I did something similar (passing a configuration object into the middleware constructor) when I was creating my OWASP secure headers middleware (it's part two in a now finished multipart series).

Could you take in the config and switch on something found within the request during your middleware's Invoke task?


问:
how to access dataTable variable outside ajax
I have this datatable that is created inside a function call. But if I want to create new rows based on event listeners like this, it gives an error that the table variable is undefined, which is understandable because it is inside a function call and not global. So how do I create a workaround for this and add event listeners under $(document).ready() section?

The structure of my JS file is very shabby, but it's intended to be in that way.

```<code>$(document).ready(function()
{
     var table=null;
     $('#button').click(function()
     {
         callfunction1();
     }
     callfunction1()
     {
         $.ajax({
              'success': function(response) //response contains the plain table
                         {
                             createDatatable(response)
                         }
         })
     }
     createDatatable(response)
     {
            $('#division').html(response); //creating the plain table
            table=$('#tableId').Datatable({}); //converting it to datatable
     }
     //I want to add event listeners here, because if I add
     //it anywhere else, it doesn't work, because basically
     //it's a function call.
}
</code>```

答:
The following should work if you choose one var table declaration and delete the other

```<code>var table; //accessible everywhere
$(document).ready(function()
{
     var table; //accessible anywhere in this function
     $('#button').click(function() {
         callfunction1();
     }); //); were missing

     function callfunction1 ()
     {
         $.ajax({
              'success': createDatatable //no () here, you want to pass a function, not the result of a function call
         });
     }

     function createDatatable()
     {
            table=$('#tableId').Datatable({});
     }

}
</code>```

This should give no errors, but i'm not sure if this is what you want to do.

Body:
I have this datatable that is created inside a function call. But if I want to create new rows based on event listeners like this, it gives an error that the table variable is undefined, which is understandable because it is inside a function call and not global. So how do I create a workaround for this and add event listeners under $(document).ready() section?

The structure of my JS file is very shabby, but it's intended to be in that way.

$(document).ready(function()
{
     var table=null;
     $('#button').click(function()
     {
         callfunction1();
     }
     callfunction1()
     {
         $.ajax({
              'success': function(response) //response contains the plain table
                         {
                             createDatatable(response)
                         }
         })
     }
     createDatatable(response)
     {
            $('#division').html(response); //creating the plain table
            table=$('#tableId').Datatable({}); //converting it to datatable
     }
     //I want to add event listeners here, because if I add
     //it anywhere else, it doesn't work, because basically
     //it's a function call.
}

Body:
The following should work if you choose one var table declaration and delete the other

var table; //accessible everywhere
$(document).ready(function()
{
     var table; //accessible anywhere in this function
     $('#button').click(function() {
         callfunction1();
     }); //); were missing

     function callfunction1 ()
     {
         $.ajax({
              'success': createDatatable //no () here, you want to pass a function, not the result of a function call
         });
     }

     function createDatatable()
     {
            table=$('#tableId').Datatable({});
     }

}

This should give no errors, but i'm not sure if this is what you want to do.


问:
What exactly is it Xamarin.android.support.v7.appcompat
I'm working with Xamarin.Android.
Appcompat is actually necessary for use material design because the nougat package (Android.support.design) requires it.
But why, for example, if I work only with API 27, I must add the AppCompat package? In my toolBox i've not the floatingActionButton, NavigationDrawer etc.. so I must add this packet to unlock them.
What is exactly this package? I've read on the web that this package works with backward compatibility but I only work with new APIs, so why I must install it?
Thanks.

答:
AppCompat should add the functionality of the latest API to older APIs when needed. For instance, lollipop added the CardView class, which can be used in older Android APIs when AppCompat is used, with some minor differences (some of the Android L animations may not apply on older versions of Android for example). It is recommended to use AppCompat in most cases since more users will be able to run your app when you do (depending on your MinSdkVersion). If you want to know what classes you can access in AppCompat, you can take a look at the features here:

https://developer.android.com/topic/libraries/support-library/features.html


问:
Regex [4 characters, one letter, Cannot be all the same character]
Requirements:
Must be more than 4 characters
Must contain at least one letter a-zA-Z
Cannot be all the same character (regardless of length)

based on a previous answer I came up with:

```<code>(?!.*([A-Za-z0-9])\1{2})(?=.*[a-z]).{5,}
</code>```

and it works fine not matching values like "aaaaa".

(?!.*([A-Za-z0-9])\1{2}) makes sure that none of the chars repeat more than twice in a row.

(?=.*[a-z]) requires at least one lowercase letter

The problem is I need the "row" to be valid (I use the regex for validation purposes) if the word with repeated characters is part of a sentence (not on his own) e.g. "includes AAA batteries".

答:
You could try to remove the ".*" expression from the first negative look-ahead:

```<code>(?!([A-Za-z0-9])\1{2})(?=.*[a-z]).{5,}
</code>```

This now matches: hello AAAAA test or includes AAA batteries

But it still does not match: AAAAA

Edit:

If you want to support also expressions like AAAAA batteries, you should actually use:

```<code>(?!([A-Za-z0-9])\1{2}$)(?=.*[a-z]).{5,}
</code>```

Credits go to @Brian Stephens on this correction.

Body:
Requirements:
Must be more than 4 characters
Must contain at least one letter a-zA-Z
Cannot be all the same character (regardless of length)

based on a previous answer I came up with:

(?!.*([A-Za-z0-9])\1{2})(?=.*[a-z]).{5,}

and it works fine not matching values like "aaaaa".

(?!.*([A-Za-z0-9])\1{2}) makes sure that none of the chars repeat more than twice in a row.

(?=.*[a-z]) requires at least one lowercase letter

The problem is I need the "row" to be valid (I use the regex for validation purposes) if the word with repeated characters is part of a sentence (not on his own) e.g. "includes AAA batteries".

Body:
You could try to remove the ".*" expression from the first negative look-ahead:

(?!([A-Za-z0-9])\1{2})(?=.*[a-z]).{5,}

This now matches: hello AAAAA test or includes AAA batteries

But it still does not match: AAAAA

Edit:

If you want to support also expressions like AAAAA batteries, you should actually use:

(?!([A-Za-z0-9])\1{2}$)(?=.*[a-z]).{5,}

Credits go to @Brian Stephens on this correction.


问:
angular 5 material MatTableDataSource
I updated from angular 4.4.6 and material beta 19 to angular 5 and material 5.0.0-rc0

The application compiles correctly, but executing on Chrome I get

"Uncaught Error: Unexpected value 'MatTable DataSource' imported by the module 'Material Modules'. Please add a @NgModule annotation."

Other material components work correctly, mat-icon, mat-card-content, mat-tab-group, mat-dialog-xxx ...

Could you help me?

答:
MatTableDataSource is in the master branch but it isn't added to the current version.

I hope this link can help you to make your own data source with the Abstract class "DataSource" in the module "@angular/cdk/collections"

https://github.com/angular/material2/issues/6036

Title: angular 5 material MatTableDataSource


问:
Can table in psql be named with 'references'
I'm wondering can I rename a table to "references"? I want to name a table back to "references" but there is a syntax error. Is there anyway to fix it?</p>

```<code>alter table referencesc rename to references;
ERROR:  syntax error at or near "references"
LINE 1: alter table referencesc rename to references;
</code>```

答:
The issue is probably being caused by that references is a keyword in Postgres.  To get around this, you can try escaping the table name in double quotes:

```<code>alter table referencesc rename to "references";
</code>```

But in general you should avoid naming columns, tables, etc. using reserved keywords, because you will likely have to escape such names everywhere.

Body:
I'm wondering can I rename a table to "references"? I want to name a table back to "references" but there is a syntax error. Is there anyway to fix it?

alter table referencesc rename to references;
ERROR:  syntax error at or near "references"
LINE 1: alter table referencesc rename to references;

Body:
The issue is probably being caused by that references is a keyword in Postgres.  To get around this, you can try escaping the table name in double quotes:

alter table referencesc rename to "references";

But in general you should avoid naming columns, tables, etc. using reserved keywords, because you will likely have to escape such names everywhere.


问:
how to pass single quote to applescript by zsh alias
i am use applescript to login ssh by gateway。

```<code>alias  sshtoxxxx="osascript  ~/workspace/script/applescript/fox/ssh_xxxx.applescript  root@10.10.1.199  hFVDa4d\'vLe"
</code>```

when password contains ' , it will  can not login.

and the applescript is below  also it is no use

```<code>on run argv
    set arg1 to (item 1 of argv)
    set arg2 to (item 2 of argv)
    testFunc(arg1,arg2)
    sshxxx(arg1,arg2)
end run

on sshxxx(target,password)
    tell application "iTerm"
        reopen
        activate
        tell the current window
            create tab with default profile
            tell the current tab
                tell the current session
                    write text "clear"
                    write text "logfin the gate way host"
                    delay 0.2
                    repeat until "xxxxx" is in contents
                    end repeat
                    write text "clear"
                    set targetText to "ssh " & target
                    write text   targetText
                    repeat until "password" is in contents
                    end repeat
                    write text password
                end  tell
            end tell
        end tell
    end tell
end sshxxx
</code>```

答:
The question is not related to Applescript. Zsh doesn't care, what programming language the called executable is written in.

If you want to use an alias, your approach is correct. Applescript will see the password parameter as hFVDa4d'vL. However, for ease of debugging, I recommend using a Zsh function instead of an alias; here you have to drop the backslash:

```<code>function sshtoxxxx {
  osascript  ~/workspace/script/applescript/fox/ssh_xxxx.applescript  root@10.10.1.199  "hFVDa4d'vLe"
}
</code>```

Body:
i am use applescript to login ssh by gateway。

alias  sshtoxxxx="osascript  ~/workspace/script/applescript/fox/ssh_xxxx.applescript  root@10.10.1.199  hFVDa4d\'vLe"

when password contains ' , it will  can not login.

and the applescript is below  also it is no use

on run argv
    set arg1 to (item 1 of argv)
    set arg2 to (item 2 of argv)
    testFunc(arg1,arg2)
    sshxxx(arg1,arg2)
end run

on sshxxx(target,password)
    tell application "iTerm"
        reopen
        activate
        tell the current window
            create tab with default profile
            tell the current tab
                tell the current session
                    write text "clear"
                    write text "logfin the gate way host"
                    delay 0.2
                    repeat until "xxxxx" is in contents
                    end repeat
                    write text "clear"
                    set targetText to "ssh " & target
                    write text   targetText
                    repeat until "password" is in contents
                    end repeat
                    write text password
                end  tell
            end tell
        end tell
    end tell
end sshxxx

Body:
The question is not related to Applescript. Zsh doesn't care, what programming language the called executable is written in.

If you want to use an alias, your approach is correct. Applescript will see the password parameter as hFVDa4d'vL. However, for ease of debugging, I recommend using a Zsh function instead of an alias; here you have to drop the backslash:

function sshtoxxxx {
  osascript  ~/workspace/script/applescript/fox/ssh_xxxx.applescript  root@10.10.1.199  "hFVDa4d'vLe"
}


问:
How to remove the white space before a word in a sentance in JS
I have a sentence like below,

```<code>var text  = 'My       name         is           Ran';
</code>```

I wnat this text to print like below,

```<code>'My       name is              Ran';
</code>```

I want to remove the space before 'is'.Can anyone please suggest help.Thanks.

答:
You can use the replace method with second parameter one space.

var text  = 'My name      is  Ran';
var newString = text.replace(/\s+/g,' ');
console.log(newString);```

Hope this will help you.

Body:
I have a sentence like below,

var text  = 'My       name         is           Ran';

I wnat this text to print like below,

'My       name is              Ran';

I want to remove the space before 'is'.Can anyone please suggest help.Thanks.

Body:
You can use the replace method with second parameter one space.

var text  = 'My name      is  Ran';
var newString = text.replace(/\s+/g,' ');
console.log(newString);

Hope this will help you.


问:
JS code popping up error
I got this below code from Google for E-mail validation in my js file.

```<code>function validateEmail(thefield)
{
   alert ('This is the 1st step');
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   alert ('This is the 2nd step');  **after this i am getting error in explorer**
   var address = document.elements[thefield].value;
   alert ('going into if loop' + address.value);
   if(reg.test(address) == false)
   {
    alert('Invalid Email Address');
      return false;
   }
}
</code>```

Please let me know what modifications are required in this to make it work??

HTML code:

```<code><form action="pageserver" method="post" id="inputForm" target="_parent" onsubmit="return(onSubmit());">
 <input type="text" value=" " name="MIR-CLI-CNTCT-ID-TXT-T[1]" stype="Text" maxlength="50" onfocus="enterField(this)" onblur="validateEmail(this)" size="50" />
</code>```

答:
Thansk sdleihssirhc.

I could find out the error.... and fix it...

the line was having erros, var address = document.elements[thefield].value;

I removed the vairable which was passed in the function and just placed the same variable directly in the required field....

var address = document.all[email].value;

Title: JS code popping up error

Body:
I got this below code from Google for E-mail validation in my js file.

function validateEmail(thefield)
{
   alert ('This is the 1st step');
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   alert ('This is the 2nd step');  **after this i am getting error in explorer**
   var address = document.elements[thefield].value;
   alert ('going into if loop' + address.value);
   if(reg.test(address) == false)
   {
    alert('Invalid Email Address');
      return false;
   }
}

Please let me know what modifications are required in this to make it work??

HTML code:

<form action="pageserver" method="post" id="inputForm" target="_parent" onsubmit="return(onSubmit());">
 <input type="text" value=" " name="MIR-CLI-CNTCT-ID-TXT-T[1]" stype="Text" maxlength="50" onfocus="enterField(this)" onblur="validateEmail(this)" size="50" />


问:
Warning messages during the training of my classification model using Caret and xgboost
I am using Caret in R to run the xgboost algorithm for a machine learning classification problem.

After running the following R codes, I am getting the warning messages (shown below):

```<code>cl <- makeCluster(10, type = "SOCK")

registerDoSNOW(cl)

caret.cv <- train(market ~ .,
                  data = mydata.train,
                  method = "xgbTree",
                  tuneGrid = tune.grid,
                  trControl = train.control)

Warning messages:
1: closing unused connection 12 (<-John-laptop.mycompany.local:11916)
2: closing unused connection 11 (<-John-laptop.mycompany.local:11916)
3: closing unused connection 10 (<-John-laptop.mycompany.local:11916)
4: closing unused connection 9 (<-John-laptop.mycompany.local:11916)
5: closing unused connection 8 (<-John-laptop.mycompany.local:11916)
6: closing unused connection 7 (<-John-laptop.mycompany.local:11916)
7: closing unused connection 6 (<-John-laptop.mycompany.local:11916)
8: closing unused connection 5 (<-John-laptop.mycompany.local:11916)
9: closing unused connection 4 (<-John-laptop.mycompany.local:11916)
10: closing unused connection 3 (<-John-laptop.mycompany.local:11916)
</code>```

Can I ignore them and proceed on with the analysis or is something wrong behind the scenes?

答:
This is too long for a comment...

When you started your cluster, R made a connection to each process. The warning messages are simply the connections being automatically closed.

It would be more elegant to stop your cluster and close them explicitly, but if you are not having any problems you could realistically ignore it.

Something like stopCluster(cl) (depends on which libraries you have loaded) will stop the cluster but you will sometimes still get errors about unused connections - this is unlikely to be a real issue as you are not close to the connections limit.

Note that 10 threads is probably excessive on a laptop - try detectCores() from the parallel package, to get the number of processors, and use that.

Body:
I am using Caret in R to run the xgboost algorithm for a machine learning classification problem.

After running the following R codes, I am getting the warning messages (shown below):

cl <- makeCluster(10, type = "SOCK")

registerDoSNOW(cl)

caret.cv <- train(market ~ .,
                  data = mydata.train,
                  method = "xgbTree",
                  tuneGrid = tune.grid,
                  trControl = train.control)

Warning messages:
1: closing unused connection 12 (<-John-laptop.mycompany.local:11916)
2: closing unused connection 11 (<-John-laptop.mycompany.local:11916)
3: closing unused connection 10 (<-John-laptop.mycompany.local:11916)
4: closing unused connection 9 (<-John-laptop.mycompany.local:11916)
5: closing unused connection 8 (<-John-laptop.mycompany.local:11916)
6: closing unused connection 7 (<-John-laptop.mycompany.local:11916)
7: closing unused connection 6 (<-John-laptop.mycompany.local:11916)
8: closing unused connection 5 (<-John-laptop.mycompany.local:11916)
9: closing unused connection 4 (<-John-laptop.mycompany.local:11916)
10: closing unused connection 3 (<-John-laptop.mycompany.local:11916)

Can I ignore them and proceed on with the analysis or is something wrong behind the scenes?


问:
Failed to upload WordPress media files using XML-RPC
This is my code.

```<code>    public void fileUpload() throws Exception {
         byte fileByte[] =org.apache.commons.io.FileUtils.readFileToByteArray(new File(path+realName));
                String wpUpFile=fileToString(new File(path+realName));
                XmlRpcClient blog  = new XmlRpcClient();
                XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
                Hashtable<String, String> post = new Hashtable<>();
                Vector<Serializable> params = new Vector<Serializable>();
                config.setServerURL(url);
                config.setBasicUserName(user);
                config.setBasicPassword(pw);
                params.addElement(id);
                params.addElement(user);
                params.addElement(pw);
                post.put("name", realName);
                post.put("type", "image/jpeg");
                post.put("bits", wpUpFile);
                post.put("overwrite", "false");
                params.addElement(post);
                params.addElement(true);
                Object blogPostID = blog.execute(config, "wp.uploadFile", params);
    }
</code>```

file base64 change code

```<code> public String fileToString(File file) throws IOException {
                String fileString = new String();
                FileInputStream inputStream =  null;
                ByteArrayOutputStream byteOutStream = null;
                try {
                    inputStream = new FileInputStream(file);
                    byteOutStream = new ByteArrayOutputStream();
                    int len = 0;
                    byte[] buf = new byte[1024];
                        while ((len = inputStream.read(buf)) != -1) {
                             byteOutStream.write(buf, 0, len);
                    }
                    byte[] fileArray = byteOutStream.toByteArray();
                    fileString = new String(Base64.encodeBase64(fileArray));
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    inputStream.close();
                    byteOutStream.close();
                }
               return fileString;
    }
</code>```

result

The image file was not displayed properly. What is the problem?

答:
It expects binary data of the raw image. Shouldn't be base64 encoded. bits parameter should be byte[] only. Don't convert to String.

```<code>inputStream = new FileInputStream(file);
byte[] bits = IOUtils.toByteArray(inputStream);
</code>```

Hope you are already using org.apache.commons.io.IOUtils - in your code wpUpFile should just be byte[] bits.

Body:
This is my code.

    public void fileUpload() throws Exception {
         byte fileByte[] =org.apache.commons.io.FileUtils.readFileToByteArray(new File(path+realName));
                String wpUpFile=fileToString(new File(path+realName));
                XmlRpcClient blog  = new XmlRpcClient();
                XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
                Hashtable<String, String> post = new Hashtable<>();
                Vector<Serializable> params = new Vector<Serializable>();
                config.setServerURL(url);
                config.setBasicUserName(user);
                config.setBasicPassword(pw);
                params.addElement(id);
                params.addElement(user);
                params.addElement(pw);
                post.put("name", realName);
                post.put("type", "image/jpeg");
                post.put("bits", wpUpFile);
                post.put("overwrite", "false");
                params.addElement(post);
                params.addElement(true);
                Object blogPostID = blog.execute(config, "wp.uploadFile", params);
    }

file base64 change code

 public String fileToString(File file) throws IOException {
                String fileString = new String();
                FileInputStream inputStream =  null;
                ByteArrayOutputStream byteOutStream = null;
                try {
                    inputStream = new FileInputStream(file);
                    byteOutStream = new ByteArrayOutputStream();
                    int len = 0;
                    byte[] buf = new byte[1024];
                        while ((len = inputStream.read(buf)) != -1) {
                             byteOutStream.write(buf, 0, len);
                    }
                    byte[] fileArray = byteOutStream.toByteArray();
                    fileString = new String(Base64.encodeBase64(fileArray));
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    inputStream.close();
                    byteOutStream.close();
                }
               return fileString;
    }

result

The image file was not displayed properly. What is the problem?

Body:
It expects binary data of the raw image. Shouldn't be base64 encoded. bits parameter should be byte[] only. Don't convert to String.

inputStream = new FileInputStream(file);
byte[] bits = IOUtils.toByteArray(inputStream);

Hope you are already using org.apache.commons.io.IOUtils - in your code wpUpFile should just be byte[] bits.


问:
Powershell - Retrieve List of Groups, Use List To Find Specific Group Member
Good afternoon.  So I have the below line of code that retrieves any AD group with the suffix of -blah1 and blah2.

```<code>import-module activedirectory

$group = Get-ADGroup -Filter { (name -like "*-blah1") -or (name -like "*-blah2") } | Select Name
</code>```

The above code shows groups:

abc-blah1

  abc-blah2

I want to be able to query these groups for a specific user (for example: blahuser).  If the user does not exist in the group, I want to script to tell me.  Any ideas?  Thanks.

答:
Function Connect-Mstsc {
<#

.SYNOPSIS

Function to connect an RDP session without the password prompt

.DESCRIPTION
This function provides the functionality to start an RDP session without having to type in the password

.PARAMETER ComputerName
This can be a single computername or an array of computers to which RDP session will be opened

.PARAMETER User
The user name that will be used to authenticate

.PARAMETER Password
The password that will be used to authenticate

.PARAMETER Credential
The PowerShell credential object that will be used to authenticate against the remote system

.PARAMETER Admin
Sets the /admin switch on the mstsc command: Connects you to the session for administering a server

.PARAMETER MultiMon
Sets the /multimon switch on the mstsc command: Configures the Remote Desktop Services session monitor layout to be identical to the current client-side configuration

.PARAMETER FullScreen
Sets the /f switch on the mstsc command: Starts Remote Desktop in full-screen mode

.PARAMETER Public
Sets the /public switch on the mstsc command: Runs Remote Desktop in public mode

.PARAMETER Width
Sets the /w: parameter on the mstsc command: Specifies the width of the Remote Desktop window

.PARAMETER Height
Sets the /h: parameter on the mstsc command: Specifies the height of the Remote Desktop window

.NOTES

Name:        Connect-Mstsc
Author:      Jaap Brasser
DateUpdated: 2016-10-28
Version:     1.2.5
Blog:        http://www.jaapbrasser.com

.LINK
http://www.jaapbrasser.com

.EXAMPLE

. .\Connect-Mstsc.ps1

Description

This command dot sources the script to ensure the Connect-Mstsc function is available in your current PowerShell session

.EXAMPLE

Connect-Mstsc -ComputerName server01 -User contoso\jaapbrasser -Password (ConvertTo-SecureString 'supersecretpw' -AsPlainText -Force)

Description

A remote desktop session to server01 will be created using the credentials of contoso\jaapbrasser

.EXAMPLE

Connect-Mstsc server01,server02 contoso\jaapbrasser (ConvertTo-SecureString 'supersecretpw' -AsPlainText -Force)

Description

Two RDP sessions to server01 and server02 will be created using the credentials of contoso\jaapbrasser

.EXAMPLE

server01,server02 | Connect-Mstsc -User contoso\jaapbrasser -Password (ConvertTo-SecureString 'supersecretpw' -AsPlainText -Force) -Width 1280 -Height 720

Description

Two RDP sessions to server01 and server02 will be created using the credentials of contoso\jaapbrasser and both session will be at a resolution of 1280x720.

.EXAMPLE

server01,server02 | Connect-Mstsc -User contoso\jaapbrasser -Password (ConvertTo-SecureString 'supersecretpw' -AsPlainText -Force) -Wait

Description

RDP sessions to server01 will be created, once the mstsc process is closed the session next session is opened to server02. Using the credentials of contoso\jaapbrasser and both session will be at a resolution of 1280x720.

.EXAMPLE

Connect-Mstsc -ComputerName server01:3389 -User contoso\jaapbrasser -Password (ConvertTo-SecureString 'supersecretpw' -AsPlainText -Force) -Admin -MultiMon

Description

A RDP session to server01 at port 3389 will be created using the credentials of contoso\jaapbrasser and the /admin and /multimon switches will be set for mstsc

.EXAMPLE

Connect-Mstsc -ComputerName server01:3389 -User contoso\jaapbrasser -Password (ConvertTo-SecureString 'supersecretpw' -AsPlainText -Force) -Public

Description

A RDP session to server01 at port 3389 will be created using the credentials of contoso\jaapbrasser and the /public switches will be set for mstsc

.EXAMPLE
Connect-Mstsc -ComputerName 192.168.1.10 -Credential $Cred

Description

A RDP session to the system at 192.168.1.10 will be created using the credentials stored in the $cred variable.

.EXAMPLE

Get-AzureVM | Get-AzureEndPoint -Name 'Remote Desktop' | ForEach-Object { Connect-Mstsc -ComputerName ($.Vip,$.Port -join ':') -User contoso\jaapbrasser -Password (ConvertTo-SecureString 'supersecretpw' -AsPlainText -Force) }

Description

A RDP session is started for each Azure Virtual Machine with the user contoso\jaapbrasser and password supersecretpw

.EXAMPLE
PowerShell.exe -Command "& {. .\Connect-Mstsc.ps1; Connect-Mstsc server01 contoso\jaapbrasser (ConvertTo-SecureString 'supersecretpw' -AsPlainText -Force) -Admin}"

Description

An remote desktop session to server01 will be created using the credentials of contoso\jaapbrasser connecting to the administrative session, this example can be used when scheduling tasks or for batch files.

>

```<code>[cmdletbinding(SupportsShouldProcess,DefaultParametersetName='UserPassword')]
param (
    [Parameter(Mandatory=$true,
        ValueFromPipeline=$true,
        ValueFromPipelineByPropertyName=$true,
        Position=0)]
    [Alias('CN')]
        [string[]]     $ComputerName,
    [Parameter(ParameterSetName='UserPassword',Mandatory=$true,Position=1)]
    [Alias('U')]
        [string]       $User,
    [Parameter(ParameterSetName='UserPassword',Mandatory=$true,Position=2)]
    [Alias('P')]
        [string]       $Password,
    [Parameter(ParameterSetName='Credential',Mandatory=$true,Position=1)]
    [Alias('C')]
        [PSCredential] $Credential,
    [Alias('A')]
        [switch]       $Admin,
    [Alias('MM')]
        [switch]       $MultiMon,
    [Alias('F')]
        [switch]       $FullScreen,
    [Alias('Pu')]
        [switch]       $Public,
    [Alias('W')]
        [int]          $Width,
    [Alias('H')]
        [int]          $Height,
    [Alias('WT')]
        [switch]       $Wait
)

begin {
    [string]$MstscArguments = ''
    switch ($true) {
        {$Admin}      {$MstscArguments += '/admin '}
        {$MultiMon}   {$MstscArguments += '/multimon '}
        {$FullScreen} {$MstscArguments += '/f '}
        {$Public}     {$MstscArguments += '/public '}
        {$Width}      {$MstscArguments += "/w:$Width "}
        {$Height}     {$MstscArguments += "/h:$Height "}
    }

    if ($Credential) {
        $User     = $Credential.UserName
        $Password = $Credential.GetNetworkCredential().Password
    }
}
process {
    foreach ($Computer in $ComputerName) {
        $ProcessInfo = New-Object System.Diagnostics.ProcessStartInfo
        $Process = New-Object System.Diagnostics.Process

        # Remove the port number for CmdKey otherwise credentials are not entered correctly
        if ($Computer.Contains(':')) {
            $ComputerCmdkey = ($Computer -split ':')[0]
        } else {
            $ComputerCmdkey = $Computer
        }

        $ProcessInfo.FileName    = "$($env:SystemRoot)\system32\cmdkey.exe"
        $ProcessInfo.Arguments   = "/generic:TERMSRV/$ComputerCmdkey /user:$User /pass:$($Password)"
        $ProcessInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Hidden
        $Process.StartInfo = $ProcessInfo
        if ($PSCmdlet.ShouldProcess($ComputerCmdkey,'Adding credentials to store')) {
            [void]$Process.Start()
        }

        $ProcessInfo.FileName    = "$($env:SystemRoot)\system32\mstsc.exe"
        $ProcessInfo.Arguments   = "$MstscArguments /v $Computer"
        $ProcessInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Normal
        $Process.StartInfo       = $ProcessInfo
        if ($PSCmdlet.ShouldProcess($Computer,'Connecting mstsc')) {
            [void]$Process.Start()
            if ($Wait) {
                $null = $Process.WaitForExit()
            }
        }
    }
}
</code>```

}

Body:
Good afternoon.  So I have the below line of code that retrieves any AD group with the suffix of -blah1 and blah2.

import-module activedirectory

$group = Get-ADGroup -Filter { (name -like "*-blah1") -or (name -like "*-blah2") } | Select Name

The above code shows groups:

abc-blah1

  abc-blah2

I want to be able to query these groups for a specific user (for example: blahuser).  If the user does not exist in the group, I want to script to tell me.  Any ideas?  Thanks.

Body:
Function Connect-Mstsc {
<#

.SYNOPSIS

Function to connect an RDP session without the password prompt

.DESCRIPTION
This function provides the functionality to start an RDP session without having to type in the password

.PARAMETER ComputerName
This can be a single computername or an array of computers to which RDP session will be opened

.PARAMETER User
The user name that will be used to authenticate

.PARAMETER Password
The password that will be used to authenticate

.PARAMETER Credential
The PowerShell credential object that will be used to authenticate against the remote system

.PARAMETER Admin
Sets the /admin switch on the mstsc command: Connects you to the session for administering a server

.PARAMETER MultiMon
Sets the /multimon switch on the mstsc command: Configures the Remote Desktop Services session monitor layout to be identical to the current client-side configuration

.PARAMETER FullScreen
Sets the /f switch on the mstsc command: Starts Remote Desktop in full-screen mode

.PARAMETER Public
Sets the /public switch on the mstsc command: Runs Remote Desktop in public mode

.PARAMETER Width
Sets the /w: parameter on the mstsc command: Specifies the width of the Remote Desktop window

.PARAMETER Height
Sets the /h: parameter on the mstsc command: Specifies the height of the Remote Desktop window

.NOTES

Name:        Connect-Mstsc
Author:      Jaap Brasser
DateUpdated: 2016-10-28
Version:     1.2.5
Blog:        http://www.jaapbrasser.com

.LINK
http://www.jaapbrasser.com

.EXAMPLE

. .\Connect-Mstsc.ps1

Description

This command dot sources the script to ensure the Connect-Mstsc function is available in your current PowerShell session

.EXAMPLE

Connect-Mstsc -ComputerName server01 -User contoso\jaapbrasser -Password (ConvertTo-SecureString 'supersecretpw' -AsPlainText -Force)

Description

A remote desktop session to server01 will be created using the credentials of contoso\jaapbrasser

.EXAMPLE

Connect-Mstsc server01,server02 contoso\jaapbrasser (ConvertTo-SecureString 'supersecretpw' -AsPlainText -Force)

Description

Two RDP sessions to server01 and server02 will be created using the credentials of contoso\jaapbrasser

.EXAMPLE

server01,server02 | Connect-Mstsc -User contoso\jaapbrasser -Password (ConvertTo-SecureString 'supersecretpw' -AsPlainText -Force) -Width 1280 -Height 720

Description

Two RDP sessions to server01 and server02 will be created using the credentials of contoso\jaapbrasser and both session will be at a resolution of 1280x720.

.EXAMPLE

server01,server02 | Connect-Mstsc -User contoso\jaapbrasser -Password (ConvertTo-SecureString 'supersecretpw' -AsPlainText -Force) -Wait

Description

RDP sessions to server01 will be created, once the mstsc process is closed the session next session is opened to server02. Using the credentials of contoso\jaapbrasser and both session will be at a resolution of 1280x720.

.EXAMPLE

Connect-Mstsc -ComputerName server01:3389 -User contoso\jaapbrasser -Password (ConvertTo-SecureString 'supersecretpw' -AsPlainText -Force) -Admin -MultiMon

Description

A RDP session to server01 at port 3389 will be created using the credentials of contoso\jaapbrasser and the /admin and /multimon switches will be set for mstsc

.EXAMPLE

Connect-Mstsc -ComputerName server01:3389 -User contoso\jaapbrasser -Password (ConvertTo-SecureString 'supersecretpw' -AsPlainText -Force) -Public

Description

A RDP session to server01 at port 3389 will be created using the credentials of contoso\jaapbrasser and the /public switches will be set for mstsc

.EXAMPLE
Connect-Mstsc -ComputerName 192.168.1.10 -Credential $Cred

Description

A RDP session to the system at 192.168.1.10 will be created using the credentials stored in the $cred variable.

.EXAMPLE

Get-AzureVM | Get-AzureEndPoint -Name 'Remote Desktop' | ForEach-Object { Connect-Mstsc -ComputerName ($.Vip,$.Port -join ':') -User contoso\jaapbrasser -Password (ConvertTo-SecureString 'supersecretpw' -AsPlainText -Force) }

Description

A RDP session is started for each Azure Virtual Machine with the user contoso\jaapbrasser and password supersecretpw

.EXAMPLE
PowerShell.exe -Command "& {. .\Connect-Mstsc.ps1; Connect-Mstsc server01 contoso\jaapbrasser (ConvertTo-SecureString 'supersecretpw' -AsPlainText -Force) -Admin}"

Description

An remote desktop session to server01 will be created using the credentials of contoso\jaapbrasser connecting to the administrative session, this example can be used when scheduling tasks or for batch files.

>

[cmdletbinding(SupportsShouldProcess,DefaultParametersetName='UserPassword')]
param (
    [Parameter(Mandatory=$true,
        ValueFromPipeline=$true,
        ValueFromPipelineByPropertyName=$true,
        Position=0)]
    [Alias('CN')]
        [string[]]     $ComputerName,
    [Parameter(ParameterSetName='UserPassword',Mandatory=$true,Position=1)]
    [Alias('U')]
        [string]       $User,
    [Parameter(ParameterSetName='UserPassword',Mandatory=$true,Position=2)]
    [Alias('P')]
        [string]       $Password,
    [Parameter(ParameterSetName='Credential',Mandatory=$true,Position=1)]
    [Alias('C')]
        [PSCredential] $Credential,
    [Alias('A')]
        [switch]       $Admin,
    [Alias('MM')]
        [switch]       $MultiMon,
    [Alias('F')]
        [switch]       $FullScreen,
    [Alias('Pu')]
        [switch]       $Public,
    [Alias('W')]
        [int]          $Width,
    [Alias('H')]
        [int]          $Height,
    [Alias('WT')]
        [switch]       $Wait
)

begin {
    [string]$MstscArguments = ''
    switch ($true) {
        {$Admin}      {$MstscArguments += '/admin '}
        {$MultiMon}   {$MstscArguments += '/multimon '}
        {$FullScreen} {$MstscArguments += '/f '}
        {$Public}     {$MstscArguments += '/public '}
        {$Width}      {$MstscArguments += "/w:$Width "}
        {$Height}     {$MstscArguments += "/h:$Height "}
    }

    if ($Credential) {
        $User     = $Credential.UserName
        $Password = $Credential.GetNetworkCredential().Password
    }
}
process {
    foreach ($Computer in $ComputerName) {
        $ProcessInfo = New-Object System.Diagnostics.ProcessStartInfo
        $Process = New-Object System.Diagnostics.Process

        # Remove the port number for CmdKey otherwise credentials are not entered correctly
        if ($Computer.Contains(':')) {
            $ComputerCmdkey = ($Computer -split ':')[0]
        } else {
            $ComputerCmdkey = $Computer
        }

        $ProcessInfo.FileName    = "$($env:SystemRoot)\system32\cmdkey.exe"
        $ProcessInfo.Arguments   = "/generic:TERMSRV/$ComputerCmdkey /user:$User /pass:$($Password)"
        $ProcessInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Hidden
        $Process.StartInfo = $ProcessInfo
        if ($PSCmdlet.ShouldProcess($ComputerCmdkey,'Adding credentials to store')) {
            [void]$Process.Start()
        }

        $ProcessInfo.FileName    = "$($env:SystemRoot)\system32\mstsc.exe"
        $ProcessInfo.Arguments   = "$MstscArguments /v $Computer"
        $ProcessInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Normal
        $Process.StartInfo       = $ProcessInfo
        if ($PSCmdlet.ShouldProcess($Computer,'Connecting mstsc')) {
            [void]$Process.Start()
            if ($Wait) {
                $null = $Process.WaitForExit()
            }
        }
    }
}

}


问:
How to improve speed sorting by datetime field from another table?
I have a table of Products which contains hundreds of thousands of records. The basic table structure is like so:

```<code>ProductID (int pk) | ObjectID (int fk) | ProductTitle | Price
101                | 5005              | Toothbrush   | 1.50
</code>```

I have another table for Objects which stores information about different objects, but mainly who they were created by and when.

```<code>ObjectID (int pk) | DateCreated (datetime)  | UserID
5005              |  2017-11-16 13:00:00    | 50
</code>```

The following query selecting Products runs in half a second:

```<code>SELECT
  p.*
FROM
  dbo.Products p
ORDER BY
  ProductID DESC
</code>```

This following query takes almost 3.5 seconds

```<code>SELECT
  p.*
FROM
  dbo.Products p
INNER JOIN
  dbo.Objects o ON
  o.ObjectID = p.ObjectID
ORDER BY
  o.DateCreated DESC
</code>```

ObjectID in the Products table has been setup as a foreign key to the Objects table. It also has a unique index on it.

The DateCreated field in Objects has also been indexed.

Why is the second query running 5 times slower just because I'm ordering by a DateTime field from another table? I know that ordering by an int is meant to be faster, especially as its clustered, but I didn't expect the difference to be this huge.

Any suggestions please? I am using SQL Server 2016.

答:
To really understand what is happening, you need to look at the execution plans.  However, the results are not surprising.

The first query is faster because -- presumably -- the query can use an index on the table for the order by.  I wouldn't be surprised if the id were a primary key, making the ordering even more efficient.

The second query is slower because the order by is probably doing an actual sort.  This is often needed when joining tables together.

It is possible that an index on Objects(DateCreated, ObjectId) would be a bit more efficient.  Whether SQL Server decides to use it depends on the statistics of the tables.

Body:
I have a table of Products which contains hundreds of thousands of records. The basic table structure is like so:

ProductID (int pk) | ObjectID (int fk) | ProductTitle | Price
101                | 5005              | Toothbrush   | 1.50

I have another table for Objects which stores information about different objects, but mainly who they were created by and when.

ObjectID (int pk) | DateCreated (datetime)  | UserID
5005              |  2017-11-16 13:00:00    | 50

The following query selecting Products runs in half a second:

SELECT
  p.*
FROM
  dbo.Products p
ORDER BY
  ProductID DESC

This following query takes almost 3.5 seconds

SELECT
  p.*
FROM
  dbo.Products p
INNER JOIN
  dbo.Objects o ON
  o.ObjectID = p.ObjectID
ORDER BY
  o.DateCreated DESC

ObjectID in the Products table has been setup as a foreign key to the Objects table. It also has a unique index on it.

The DateCreated field in Objects has also been indexed.

Why is the second query running 5 times slower just because I'm ordering by a DateTime field from another table? I know that ordering by an int is meant to be faster, especially as its clustered, but I didn't expect the difference to be this huge.

Any suggestions please? I am using SQL Server 2016.


问:
Sharepoint CSOM - Timeout downloading files
I'm trying to download files from a large document library (5k+ files) in SharePoint Online. I have a txt file containing the urls for all the files in said library (to avoid the view limits) and download each one using OpenBinaryDirect. The problem is that after a certain number of files (seems to be always the same, around 300 or so), OpenBinaryDirect throws a timeout exception. I'm getting a new instance of ClientContext for each file, and the files are small (less than 100kb). Not sure what's going on, any ideas? I tried changing the file's order to rule out an issue with a particular file but got the same results.

Thanks,

Gonzalo

答:
If the exception is timeout then you should increase the timeout of the clientcontext that you are creating, maybe one file is larger and taking more time to download which exceeds the default timeout.
The below code will set the timeout to 20 minutes.

you can do it by

```<code>using(ClientContext context=new ClinetContext("http://aboc.come/sites/test"))
{
   context..RequestTimeout= 20 * 60 * 1000;
}
</code>```

https://msdn.microsoft.com/en-us/library/ee541007.aspx

Body:
If the exception is timeout then you should increase the timeout of the clientcontext that you are creating, maybe one file is larger and taking more time to download which exceeds the default timeout.
The below code will set the timeout to 20 minutes.

you can do it by

using(ClientContext context=new ClinetContext("http://aboc.come/sites/test"))
{
   context..RequestTimeout= 20 * 60 * 1000;
}

https://msdn.microsoft.com/en-us/library/ee541007.aspx


问:
execute linux command in java
i want to execute the command crontab file.txt in java.

What is the procedure...?

答: Take a look at Runtime.getRuntime().exec("contrab file.txt")

Title: execute linux command in java


问:
How to calculate recency in R
I have the following data:

```<code>set.seed(20)
round<-rep(1:10,2)
part<-rep(1:2, c(10,10))
game<-rep(rep(1:2,c(5,5)),2)
pay1<-sample(1:10,20,replace=TRUE)
pay2<-sample(1:10,20,replace=TRUE)
pay3<-sample(1:10,20,replace=TRUE)
decs<-sample(1:3,20,replace=TRUE)
previous_max<-c(0,1,0,0,0,0,0,1,0,0,0,0,1,1,1,0,0,1,1,0)
gamematrix<-cbind(part,game,round,pay1,pay2,pay3,decs,previous_max )
gamematrix<-data.frame(gamematrix)
</code>```

Here is the output:

```<code>       part game round pay1 pay2 pay3 decs previous_max
1        1    1     1    9    5    6    2            0
2        1    1     2    8    1    1    1            1
3        1    1     3    3    5    5    3            0
4        1    1     4    6    1    5    1            0
5        1    1     5   10    3    8    3            0
6        1    2     6   10    1    5    1            0
7        1    2     7    1   10    7    3            0
8        1    2     8    1   10    8    2            1
9        1    2     9    4    1    5    1            0
10       1    2    10    4    7    7    2            0
11       2    1     1    8    4    1    1            0
12       2    1     2    8    5    5    2            0
13       2    1     3    1    9    3    1            1
14       2    1     4    8    2   10    2            1
15       2    1     5    2    6    2    3            1
16       2    2     6    5    5    6    2            0
17       2    2     7    4    5    1    2            0
18       2    2     8    2   10    5    2            1
19       2    2     9    3    7    3    2            1
20       2    2    10    9    3    1    1            0
</code>```

How can I calculate a new indicator variable "previous_max",which returns  whether in the next round of the same game, the same participant choose the maximal payoff from the previous round.
So I want something like follows:

Participant (part) 1:

In the first round of each game, previous_max is "0" (no previous round), in round 2, previous_max ="1", because in round 1, the maximal pay was max(pay1,pay2,pay3)=max(9,5,6)=9, and in round 2, the participant's decisions (decs) was 1 (which was the maximal value in previous round).

In round 3, previous_max=0, because the maximal value in round 2 was 8 (which is "pay1"), but the participant choose "3" (which is pay3).

答:
Here's a solution using dplyr and purr::map.
I would have preferred to use group_by than split but max.col ignores groups and I don't know of a dplyr equivalent`.

the output is slightly different but I think it's because of your mistakes, please explain if not and I'll update my answer.

```<code>library(purrr)
library(dplyr)

  gamematrix       %>%
    split(.$part)  %>%
    map(~ .x %>% mutate(
      prev_max = as.integer(
        decs ==
        c(0,max.col(.[c("pay1","pay2","pay3")])[-n()]) # the number of the max columns, offset by one
      ))) %>%
    bind_rows

  # `  part game round pay1 pay2 pay3 decs prev_max
  # 1     1    1     1    9    5    6    2        0
  # 2     1    1     2    8    1    1    1        1
  # 3     1    1     3    3    5    5    3        0
  # 4     1    1     4    6    1    5    1        0
  # 5     1    1     5   10    3    8    3        0
  # 6     1    2     6   10    1    5    1        1
  # 7     1    2     7    1   10    7    3        0
  # 8     1    2     8    1   10    8    2        1
  # 9     1    2     9    4    1    5    1        0
  # 10    1    2    10    4    7    7    2        0
  # 11    2    1     1    8    4    1    1        0
  # 12    2    1     2    8    5    5    2        0
  # 13    2    1     3    1    9    3    1        1
  # 14    2    1     4    8    2   10    2        1
  # 15    2    1     5    2    6    2    3        1
  # 16    2    2     6    5    5    6    2        1
  # 17    2    2     7    4    5    1    2        0
  # 18    2    2     8    2   10    5    2        1
  # 19    2    2     9    3    7    3    2        1
  # 20    2    2    10    9    3    1    1        0
</code>```

Title: How to calculate recency in R

Body:
I have the following data:

set.seed(20)
round<-rep(1:10,2)
part<-rep(1:2, c(10,10))
game<-rep(rep(1:2,c(5,5)),2)
pay1<-sample(1:10,20,replace=TRUE)
pay2<-sample(1:10,20,replace=TRUE)
pay3<-sample(1:10,20,replace=TRUE)
decs<-sample(1:3,20,replace=TRUE)
previous_max<-c(0,1,0,0,0,0,0,1,0,0,0,0,1,1,1,0,0,1,1,0)
gamematrix<-cbind(part,game,round,pay1,pay2,pay3,decs,previous_max )
gamematrix<-data.frame(gamematrix)

Here is the output:

       part game round pay1 pay2 pay3 decs previous_max
1        1    1     1    9    5    6    2            0
2        1    1     2    8    1    1    1            1
3        1    1     3    3    5    5    3            0
4        1    1     4    6    1    5    1            0
5        1    1     5   10    3    8    3            0
6        1    2     6   10    1    5    1            0
7        1    2     7    1   10    7    3            0
8        1    2     8    1   10    8    2            1
9        1    2     9    4    1    5    1            0
10       1    2    10    4    7    7    2            0
11       2    1     1    8    4    1    1            0
12       2    1     2    8    5    5    2            0
13       2    1     3    1    9    3    1            1
14       2    1     4    8    2   10    2            1
15       2    1     5    2    6    2    3            1
16       2    2     6    5    5    6    2            0
17       2    2     7    4    5    1    2            0
18       2    2     8    2   10    5    2            1
19       2    2     9    3    7    3    2            1
20       2    2    10    9    3    1    1            0

How can I calculate a new indicator variable "previous_max",which returns  whether in the next round of the same game, the same participant choose the maximal payoff from the previous round.
So I want something like follows:

Participant (part) 1:

In the first round of each game, previous_max is "0" (no previous round), in round 2, previous_max ="1", because in round 1, the maximal pay was max(pay1,pay2,pay3)=max(9,5,6)=9, and in round 2, the participant's decisions (decs) was 1 (which was the maximal value in previous round).

In round 3, previous_max=0, because the maximal value in round 2 was 8 (which is "pay1"), but the participant choose "3" (which is pay3).

Body:
Here's a solution using dplyr and purr::map.
I would have preferred to use group_by than split but max.col ignores groups and I don't know of a dplyr equivalent`.

the output is slightly different but I think it's because of your mistakes, please explain if not and I'll update my answer.

library(purrr)
library(dplyr)

  gamematrix       %>%
    split(.$part)  %>%
    map(~ .x %>% mutate(
      prev_max = as.integer(
        decs ==
        c(0,max.col(.[c("pay1","pay2","pay3")])[-n()]) # the number of the max columns, offset by one
      ))) %>%
    bind_rows

  # `  part game round pay1 pay2 pay3 decs prev_max
  # 1     1    1     1    9    5    6    2        0
  # 2     1    1     2    8    1    1    1        1
  # 3     1    1     3    3    5    5    3        0
  # 4     1    1     4    6    1    5    1        0
  # 5     1    1     5   10    3    8    3        0
  # 6     1    2     6   10    1    5    1        1
  # 7     1    2     7    1   10    7    3        0
  # 8     1    2     8    1   10    8    2        1
  # 9     1    2     9    4    1    5    1        0
  # 10    1    2    10    4    7    7    2        0
  # 11    2    1     1    8    4    1    1        0
  # 12    2    1     2    8    5    5    2        0
  # 13    2    1     3    1    9    3    1        1
  # 14    2    1     4    8    2   10    2        1
  # 15    2    1     5    2    6    2    3        1
  # 16    2    2     6    5    5    6    2        1
  # 17    2    2     7    4    5    1    2        0
  # 18    2    2     8    2   10    5    2        1
  # 19    2    2     9    3    7    3    2        1
  # 20    2    2    10    9    3    1    1        0


问:
Explode to array and print each element as list item
I have a set of numbers in a table field in database, the numbers are separated by comma ','.
I am trying to do the following:

Step 1. : SELECT set of numbers from database and explode it to array :

```<code>$array =  explode(',', $set_of_numbers);
</code>```

Step 2. : Print each element of the array as list item by using foreach loop :

```<code>foreach ($array as $list_item => $set_of_numbers){
    echo "<li>";
    print_r(array_list_items($set_of_numbers));
    echo "</li>";}
</code>```

Please anybody tell me what is wrong. Thank you.

答:
This can easily be achieved by the following code snippet:

```<code><?php
$my_numbers = '1,12,3.2,853.3,4545,221';
echo '<ul>';
foreach(explode(',', $my_numbers) AS $my_number){
    echo '<li>'.$my_number.'</li>';
}
echo '</ul>';
</code>```

The above code will output the following HTML:

```<code><ul><li>1</li><li>12</li><li>3.2</li><li>853.3</li><li>4545</li><li>221</li></ul>
</code>```

Credits: http://dwellupper.io/post/49/understanding-php-explode-function-with-examples

Body:
I have a set of numbers in a table field in database, the numbers are separated by comma ','.
I am trying to do the following:

Step 1. : SELECT set of numbers from database and explode it to array :

$array =  explode(',', $set_of_numbers);

Step 2. : Print each element of the array as list item by using foreach loop :

foreach ($array as $list_item => $set_of_numbers){
    echo "
";
    print_r(array_list_items($set_of_numbers));
    echo "
";}

Please anybody tell me what is wrong. Thank you.

Body:
This can easily be achieved by the following code snippet:

<?php
$my_numbers = '1,12,3.2,853.3,4545,221';
echo '<ul>';
foreach(explode(',', $my_numbers) AS $my_number){
    echo '<li>'.$my_number.'</li>';
}
echo '</ul>';

The above code will output the following HTML:

<ul><li>1</li><li>12</li><li>3.2</li><li>853.3</li><li>4545</li><li>221</li></ul>

Credits: http://dwellupper.io/post/49/understanding-php-explode-function-with-examples


问:
With Java Spark how do I send a html file as a repsonse
How do I use spark to return an existing page

I have the example working where I just return some text

```<code>import static spark.Spark.*;

public class HelloWorld {
    public static void main(String[] args) {
        get("/hello", (req, res) -> "Hello World");
    }
}
</code>```

I have changed to

```<code>import spark.Service;
import static spark.Spark.*;

public class HelloWorld {
    public static void main(String[] args) {
        staticFiles.externalLocation("C:\\HtmlFolder\\"); // Static files
        init();
        get("/hello", (req, res) -> "Report00001.html");
    }
}
</code>```

and I want it to display the contents of HtmlFolder\Report00001.hml but it just displays Report0001.html

I cannot see any examples showing how to do this

So if I place a index.html within C:\HtmlFolder\ then that is now displayed when open browser at http://localhost:4567/ but I cannnot see how do a mapping for get requests to display other files

答:
It seems that

```<code>get("/hello", (req, res) -> "Report00001.html");
</code>```

returns a single string. If that string is supposed to be a file - you probably have to open the file, collect its content, and return that content as string.

Body:
How do I use spark to return an existing page

I have the example working where I just return some text

import static spark.Spark.*;

public class HelloWorld {
    public static void main(String[] args) {
        get("/hello", (req, res) -> "Hello World");
    }
}

I have changed to

import spark.Service;
import static spark.Spark.*;

public class HelloWorld {
    public static void main(String[] args) {
        staticFiles.externalLocation("C:\\HtmlFolder\\"); // Static files
        init();
        get("/hello", (req, res) -> "Report00001.html");
    }
}

and I want it to display the contents of HtmlFolder\Report00001.hml but it just displays Report0001.html

I cannot see any examples showing how to do this

So if I place a index.html within C:\HtmlFolder\ then that is now displayed when open browser at http://localhost:4567/ but I cannnot see how do a mapping for get requests to display other files

Body:
It seems that

get("/hello", (req, res) -> "Report00001.html");

returns a single string. If that string is supposed to be a file - you probably have to open the file, collect its content, and return that content as string.


问:
WinAPI timed mutex lock
How to lock mutex (critical section) for some amount of time? Is there any API function for that? As far as I see there is nothing like that in windows. If so, is it possible to implement it manualy?

Thanks.

答: The equivalent of pthread_mutex_timedlock() in Win32 is using a Mutex and specifying a timeout (other than INFINITE) in one of the wait-functions.

Title: WinAPI timed mutex lock


问:
Nested queries in SQL
I am trying to combine 2 queries using a nested query.
The first one is this:

```<code>SELECT DISTINCT( de.MCH_CODE) AS Mach, md.MAT_CODE as ShortenCode, de.TIME as start_time
FROM table1 AS de
JOIN table1table2 AS md
ON de.subcode= md.subcode
WHERE de.ev = '123' AND de.time > '2017-11-14 07:00' and de.side = 'R' AND de.end IS NULL AND de.Subcat = 'STOP'
ORDER BY de.time
</code>```

Which generates the result

```<code>Mach  ShortenCode  Tme
Mach1   451         2017-12-25 08:25
Mach2   854         2017-12-25 08:25
</code>```

So 451 is on Mach1. The tricky part is that for ShortenCode  i would like to show the previous Mach that it was on.
It would be something like:

```<code>SELECT distinct de.MCH_CODE FROM table1 AS de
join table2 as md
ON de.subcode = md.subcode
WHERE de.ShortenCode = 'the ones displayed in the first query'
</code>```

How can I subquery to get:

```<code>Mach  ShortenCode  Tme                 Mach(Previous)
Mach1   451         2017-12-25 08:25   Mach4
Mach2   854         2017-12-25 08:25   Mach5
</code>```

Basily Mach column has Mach1, Mach2 and also Mach4 and Mach5.
I've tried this but with no success:

```<code>SELECT t1.Mach, t1.ShortenCode, t1.start_time, t2.PreviousMach
    FROM( SELECT DISTINCT( de.MCH_CODE) AS Mach, md.MAT_CODE as ShortenCode, de.TIME as start_time, mch_
            FROM table1 AS de
            JOIN table1table2 AS md
            ON de.subcode= md.subcode
            WHERE de.ev = '123' AND de.time > '2017-11-14 07:00' and de.side = 'R' AND de.end IS NULL AND de.Subcat = 'STOP'
            ORDER BY de.time
    ) t1
    join
        ( SELECT distinct de.MCH_CODE FROM table1 AS de
                join table2 as md
                ON de.subcode = md.subcode
                WHERE de.ShortenCode = t1.ShortenCode
        ) t2
</code>```

If you have any suggestions I would appreciate very much

答:
you can use the below query to get your answer.</p>

```<code>SELECT distinct de.MCH_CODE
FROM table1 AS de
join table2 as md ON de.subcode = md.subcode WHERE de.ShortenCode
in
(
    select Table2.ShortenCode from
    (
       SELECT DISTINCT de.MCH_CODE AS Mach,
                       md.MAT_CODE as ShortenCode,
                       de.TIME as start_time
       FROM table1 AS de
       JOIN table1table2 AS md ON de.subcode= md.subcode
       WHERE de.ev = '123' AND de.time > '2017-11-14 07:00' and de.side = 'R' AND de.end IS NULL AND de.Subcat = 'STOP'
       ORDER BY de.time
    ) Table2
)
</code>```

Title: Nested queries in SQL

Body:
I am trying to combine 2 queries using a nested query.
The first one is this:

SELECT DISTINCT( de.MCH_CODE) AS Mach, md.MAT_CODE as ShortenCode, de.TIME as start_time
FROM table1 AS de
JOIN table1table2 AS md
ON de.subcode= md.subcode
WHERE de.ev = '123' AND de.time > '2017-11-14 07:00' and de.side = 'R' AND de.end IS NULL AND de.Subcat = 'STOP'
ORDER BY de.time

Which generates the result

Mach  ShortenCode  Tme
Mach1   451         2017-12-25 08:25
Mach2   854         2017-12-25 08:25

So 451 is on Mach1. The tricky part is that for ShortenCode  i would like to show the previous Mach that it was on.
It would be something like:

SELECT distinct de.MCH_CODE FROM table1 AS de
join table2 as md
ON de.subcode = md.subcode
WHERE de.ShortenCode = 'the ones displayed in the first query'

How can I subquery to get:

Mach  ShortenCode  Tme                 Mach(Previous)
Mach1   451         2017-12-25 08:25   Mach4
Mach2   854         2017-12-25 08:25   Mach5

Basily Mach column has Mach1, Mach2 and also Mach4 and Mach5.
I've tried this but with no success:

SELECT t1.Mach, t1.ShortenCode, t1.start_time, t2.PreviousMach
    FROM( SELECT DISTINCT( de.MCH_CODE) AS Mach, md.MAT_CODE as ShortenCode, de.TIME as start_time, mch_
            FROM table1 AS de
            JOIN table1table2 AS md
            ON de.subcode= md.subcode
            WHERE de.ev = '123' AND de.time > '2017-11-14 07:00' and de.side = 'R' AND de.end IS NULL AND de.Subcat = 'STOP'
            ORDER BY de.time
    ) t1
    join
        ( SELECT distinct de.MCH_CODE FROM table1 AS de
                join table2 as md
                ON de.subcode = md.subcode
                WHERE de.ShortenCode = t1.ShortenCode
        ) t2

If you have any suggestions I would appreciate very much

Body:
you can use the below query to get your answer.

SELECT distinct de.MCH_CODE
FROM table1 AS de
join table2 as md ON de.subcode = md.subcode WHERE de.ShortenCode
in
(
    select Table2.ShortenCode from
    (
       SELECT DISTINCT de.MCH_CODE AS Mach,
                       md.MAT_CODE as ShortenCode,
                       de.TIME as start_time
       FROM table1 AS de
       JOIN table1table2 AS md ON de.subcode= md.subcode
       WHERE de.ev = '123' AND de.time > '2017-11-14 07:00' and de.side = 'R' AND de.end IS NULL AND de.Subcat = 'STOP'
       ORDER BY de.time
    ) Table2
)


问:
compare two arrays for common Items and return another array with the common items
So the problem is I have two array and have to check them for common items.Usual stuff, very easy.But the tricky thing for me is that I have to return another array with the elements that have been found to be common.I cannot not use any Collections.Thanks in advance.This is my code so far!</p>

```<code>public class checkArrayItems {
    static int[] array1 = { 4, 5, 6, 7, 8 };
    static int[] array2 = { 1, 2, 3, 4, 5 };

    public static void main(String[] args) {
        checkArrayItems obj = new checkArrayItems();
        System.out.println(obj.checkArr(array1, array2));

    }

    int[] checkArr(int[] arr1, int[] arr2) {
        int[] arr = new int[array1.length];
        for (int i = 0; i < arr1.length; i++) {
            for (int j = 0; j < arr2.length; j++) {
                if (arr1[i] == arr2[j]) {
                    arr[i] = arr1[i];
                }

            }
        }
        return arr;

    }

}
</code>```

答:
I'm lazy to type the code, but here is the algorithm.
1. sort both array
2. iterate over array comparing items and increasing the indexes.

Hope this helps.

Body:
So the problem is I have two array and have to check them for common items.Usual stuff, very easy.But the tricky thing for me is that I have to return another array with the elements that have been found to be common.I cannot not use any Collections.Thanks in advance.This is my code so far!

public class checkArrayItems {
    static int[] array1 = { 4, 5, 6, 7, 8 };
    static int[] array2 = { 1, 2, 3, 4, 5 };

    public static void main(String[] args) {
        checkArrayItems obj = new checkArrayItems();
        System.out.println(obj.checkArr(array1, array2));

    }

    int[] checkArr(int[] arr1, int[] arr2) {
        int[] arr = new int[array1.length];
        for (int i = 0; i < arr1.length; i++) {
            for (int j = 0; j < arr2.length; j++) {
                if (arr1[i] == arr2[j]) {
                    arr[i] = arr1[i];
                }

            }
        }
        return arr;

    }

}