问:
activate button after clicking share button
I am trying to create a share button which will activate download button after share button is clicked. But the function I wrote is not reliable its working with whats app but not with any other share button.</p>

```<code> div class="fb-share-button" data-href="https://youtu.be/1IRh28kJOyA" data-action="activate()" data-layout="button" data-size="small" data-mobile-iframe="true"><a class="fb-xfbml-parse-ignore" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fyoutu.be%2F1IRh28kJOyA&src=sdkpreparse" data-action="activate()">Share</a></div>
    <a href="#">
            <g:plus action="share" data-href="https://youtu.be/1IRh28kJOyA" data-onendinteraction=activate()></g:plus>
    </a>
    <a onclick="activate()" href="https://twitter.com/share" data-text="Kaarunyam | Ps Anoke Praveen Kumar | Tamil christian song 2017 [official] " data-url="https://youtu.be/1IRh28kJOyA" class="twitter-share-button" data-show-count="false">Tweet</a><script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
    <a onclick="activate()" href="whatsapp://send?text=https://youtu.be/1IRh28kJOyA"><i class="fa fa-whatsapp"></i></a>
    <br>
    <input type="submit" id="submit" name="download" value="Download">
</form>
<p id="demo"></p>
<script>
    document.getElementById("submit").setAttribute("disabled", "disbled");
    function activate()
    {
        document.getElementById("submit").removeAttribute("disabled")
    }

</script>
</code>```

答:
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<form>

Share

    <g:plus action="share" data-href="https://youtu.be/1IRh28kJOyA" data-onendinteraction=activate()></g:plus>

  Tweet

  <input style="margin-top:20px;" type="submit" id="submit" name="download" value="Download">
</form>

```

working fine for me.

just put onclick to the fb-share-button div.

and in plnkr => http://plnkr.co/edit/RjH5jjQhO5gn6ZhCAC8P?p=preview

Body:
I am trying to create a share button which will activate download button after share button is clicked. But the function I wrote is not reliable its working with whats app but not with any other share button.

 div class="fb-share-button" data-href="https://youtu.be/1IRh28kJOyA" data-action="activate()" data-layout="button" data-size="small" data-mobile-iframe="true">Share

            <g:plus action="share" data-href="https://youtu.be/1IRh28kJOyA" data-onendinteraction=activate()></g:plus>

    Tweet

    <input type="submit" id="submit" name="download" value="Download">
</form>

Body:
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<form>
  <div onclick="activate()" class="fb-share-button" data-href="https://youtu.be/1IRh28kJOyA" data-action="activate()" data-layout="button" data-size="small" data-mobile-iframe="true"><a class="fb-xfbml-parse-ignore" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fyoutu.be%2F1IRh28kJOyA&amp;src=sdkpreparse" data-action="activate()">Share</a></div>
  <a href="#">
    <g:plus action="share" data-href="https://youtu.be/1IRh28kJOyA" data-onendinteraction=activate()></g:plus>
  </a>
  <a onclick="activate()" href="https://twitter.com/share" data-text="Kaarunyam | Ps Anoke Praveen Kumar | Tamil christian song 2017 [official] " data-url="https://youtu.be/1IRh28kJOyA" class="twitter-share-button" data-show-count="false">Tweet</a>
  <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script><br/>
  <a onclick="activate()" href="whatsapp://send?text=https://youtu.be/1IRh28kJOyA"><i class="fa fa-whatsapp"></i></a>
  <br>
  <input style="margin-top:20px;" type="submit" id="submit" name="download" value="Download">
</form>
<p id="demo"></p>
<script>
  document.getElementById("submit").setAttribute("disabled", "disabled");

  function activate() {
    document.getElementById("submit").removeAttribute("disabled")
  }
</script>

working fine for me.

just put onclick to the fb-share-button div.

and in plnkr => http://plnkr.co/edit/RjH5jjQhO5gn6ZhCAC8P?p=preview


来源: stackexchange

问:
angular-pdfjs-viewer - Message: stream must have data
I am struggling to get angular-pdfjs-viewer working in my angular app that's written in Typescript.

I am always getting a red error message with the text:

PDF.js v1.7.354 (build: 0f7548ba)

Message: stream must have data

The PDF data is coming from an ASP.NET WebAPI controller, and the architecture of our application has the front facing website and the API both deployed as two independent web applications.

Due to this, I am wanting to download the PDF in the angular controller, and set the PDF source to the data attribute of the directive.

The WebAPI returns the PDF like this:

```<code>[HttpGet]
[Route("invoice/{id}/originalpdf")]
public async Task<ActionResult> GetInvoiceSourceImagePdf(string id)
{
    var userId = User.Identity.GetMyId();

    var bytes = await _serviceThatReturnsByteArray(id);

    return File(bytes, System.Net.Mime.MediaTypeNames.Application.Pdf);
}
</code>```

I don't see an issue with the above.  In the browser, if I hit this endpoint, I get the document rendering exactly as expected.

On the front-end side:

We're using the angular-pdfjs-viewer from https://github.com/legalthings/angular-pdfjs-viewer

We're including (via BundleConfig), sources in the order of: pdf.js, then angular.js and then finally angular-pdfjs-viewer.js (with other application required dependencies in between)

I am using the PDF.js dependency that "ships" with angular-pdfjs-viewer.js

The angular controller looks like this:

```<code>module MyApp {
    class PdfDialogController {

        public static $inject = ["$scope", "$window", "$log", "$uibModalInstance", "$http"];

        pdfData: Uint8Array;

        constructor(/*stuff*/){
            this.$http.get(the_url, { responseType: 'arrayBuffer' })
                .then((t) => {
                    this.pdfData = new Uint8Array(<ArrayBuffer>t.data);
            });
        }
    }
}
</code>```

And in the view, we have:

```<code><div class="modal-body">
    <div id="pdf-container">
        <pdfjs-viewer data="vm.pdfData"></pdfjs-viewer>
    </div>
</div>
</code>```

Inspecting the network in the browser, the PDF content is downloaded.

t.data in the controller contains data that starts with

```<code>%PDF-1.3\n%����\n1 0 obj\n[/PDF /Text]
</code>```

However, the views shows this:

And the console outputs an error message:

```<code>Error: An error occurred while loading the PDF.
</code>```

What am I doing wrong, and how can I determine what the issue is with the PDF data (if there is one).

答:
Well, it turns out that I was using

```<code>{ responseType: 'arrayBuffer' } // camel case
</code>```

when I should be using

```<code>{ responseType: 'arraybuffer' } // all lowercase
</code>```

Once changed, the code I posted in the question worked perfectly.

ContentLicense: CC BY-SA 3.0

Body:
I am struggling to get angular-pdfjs-viewer working in my angular app that's written in Typescript.

I am always getting a red error message with the text:

PDF.js v1.7.354 (build: 0f7548ba)

Message: stream must have data

The PDF data is coming from an ASP.NET WebAPI controller, and the architecture of our application has the front facing website and the API both deployed as two independent web applications.

Due to this, I am wanting to download the PDF in the angular controller, and set the PDF source to the data attribute of the directive.

The WebAPI returns the PDF like this:

[HttpGet]
[Route("invoice/{id}/originalpdf")]
public async Task<ActionResult> GetInvoiceSourceImagePdf(string id)
{
    var userId = User.Identity.GetMyId();

    var bytes = await _serviceThatReturnsByteArray(id);

    return File(bytes, System.Net.Mime.MediaTypeNames.Application.Pdf);
}

I don't see an issue with the above.  In the browser, if I hit this endpoint, I get the document rendering exactly as expected.

On the front-end side:

We're using the angular-pdfjs-viewer from https://github.com/legalthings/angular-pdfjs-viewer

We're including (via BundleConfig), sources in the order of: pdf.js, then angular.js and then finally angular-pdfjs-viewer.js (with other application required dependencies in between)

I am using the PDF.js dependency that "ships" with angular-pdfjs-viewer.js

The angular controller looks like this:

module MyApp {
    class PdfDialogController {

        public static $inject = ["$scope", "$window", "$log", "$uibModalInstance", "$http"];

        pdfData: Uint8Array;

        constructor(/*stuff*/){
            this.$http.get(the_url, { responseType: 'arrayBuffer' })
                .then((t) => {
                    this.pdfData = new Uint8Array(<ArrayBuffer>t.data);
            });
        }
    }
}

And in the view, we have:

        <pdfjs-viewer data="vm.pdfData"></pdfjs-viewer>

Inspecting the network in the browser, the PDF content is downloaded.

t.data in the controller contains data that starts with

%PDF-1.3\n%����\n1 0 obj\n[/PDF /Text]

However, the views shows this:

And the console outputs an error message:

Error: An error occurred while loading the PDF.

What am I doing wrong, and how can I determine what the issue is with the PDF data (if there is one).

Body:
Well, it turns out that I was using

{ responseType: 'arrayBuffer' } // camel case

when I should be using

{ responseType: 'arraybuffer' } // all lowercase

Once changed, the code I posted in the question worked perfectly.


问:
Like Case Sensitive in MySQL
I have a MySQL query:

```<code>SELECT concat_ws(title,description) as concatenated HAVING concatenated LIKE '%SearchTerm%';
</code>```

And my table is encoded utf8_general_ci with MyISAM.

Searches seem to be case sensitive.

I can't figure out how to fix it. What's going wrong and/or how do I fix it?

答:
Just for completion, in case it helps:

As stated on https://dev.mysql.com/doc/refman/5.7/en/case-sensitivity.html, for default character sets, nonbinary string comparisons are case insensitive by default.

Therefore, an easy way to perform case-insensitive comparisons is to cast the field to CHAR, VARCHAR or TEXT type.

Here is an example with a check against a single field:

```<code>SELECT * FROM table1 WHERE CAST(`field1` AS CHAR) LIKE '%needle%';
</code>```

Title: Like Case Sensitive in MySQL

Body:
I have a MySQL query:

SELECT concat_ws(title,description) as concatenated HAVING concatenated LIKE '%SearchTerm%';

And my table is encoded utf8_general_ci with MyISAM.

Searches seem to be case sensitive.

I can't figure out how to fix it. What's going wrong and/or how do I fix it?

Body:
Just for completion, in case it helps:

As stated on https://dev.mysql.com/doc/refman/5.7/en/case-sensitivity.html, for default character sets, nonbinary string comparisons are case insensitive by default.

Therefore, an easy way to perform case-insensitive comparisons is to cast the field to CHAR, VARCHAR or TEXT type.

Here is an example with a check against a single field:

SELECT * FROM table1 WHERE CAST(`field1` AS CHAR) LIKE '%needle%';


问:
How can I use a formula in a for loop in java
I am a beginner java programmer, studying off basic youtube videos and overflow forums, and i came across a question on an textbook sheet that asked me to use a for loop program and print this table out as well as fill in each blank

```<code>Number   Square   Cube   (n+1)/(2n-18)
______________________________________
1         #        #          #
2         #        #          #
3         #        #          #
4         #        #          #
5         #        #          #
</code>```

I thought I should try it out to test myself. I came up with the following program that works perfectly for the Number, Square and Cube part of the table, but I don't understand how to generate the numbers using the given formula. The formula I initialized as a variable (double) doesn't print the actual results, and I honestly don't have a clue as to what to do. I'd rather a simple explanation than a complex one and simple changes to the code rather than complex. As I said I am a beginner, and many different methods may go right over my head. Thank you so much in advance (also an extra task asks that I print out the sums of each column. I don't know how to do that at all, and would like an explanation if possible, but wouldn't mind if I don't receive one)

```<code>int number;
int maxValue;

Scanner keyboard = new Scanner(System.in);
System.out.println("how many numbers do you want the max value to be");
maxValue = keyboard.nextInt();

System.out.println("Number\tSquare\tCube (n+1)/(2n-18)");
System.out.println("--------------------------------");
for (number = 1; number <= maxValue; number++) {
    double formula = (number + 1) / (number * 2);
    System.out.println(
        number + "\t\t\t" + number * number + "\t\t\t" +
        number * number * number + "\t\t\t" + formula);
}
</code>```

答:
I'm not sure which outputs are you getting, but it seems to me you're using integer division when trying to get the result of (n+1)/(2n-18).

Try using:

```<code>double decimalNumber = (double) number;
double formula = (decimalNumber + 1) / (decimalNumber * 2 - 18);
</code>```

Body:
I am a beginner java programmer, studying off basic youtube videos and overflow forums, and i came across a question on an textbook sheet that asked me to use a for loop program and print this table out as well as fill in each blank

Number   Square   Cube   (n+1)/(2n-18)
______________________________________
1         #        #          #
2         #        #          #
3         #        #          #
4         #        #          #
5         #        #          #

I thought I should try it out to test myself. I came up with the following program that works perfectly for the Number, Square and Cube part of the table, but I don't understand how to generate the numbers using the given formula. The formula I initialized as a variable (double) doesn't print the actual results, and I honestly don't have a clue as to what to do. I'd rather a simple explanation than a complex one and simple changes to the code rather than complex. As I said I am a beginner, and many different methods may go right over my head. Thank you so much in advance (also an extra task asks that I print out the sums of each column. I don't know how to do that at all, and would like an explanation if possible, but wouldn't mind if I don't receive one)

int number;
int maxValue;

Scanner keyboard = new Scanner(System.in);
System.out.println("how many numbers do you want the max value to be");
maxValue = keyboard.nextInt();

System.out.println("Number\tSquare\tCube (n+1)/(2n-18)");
System.out.println("--------------------------------");
for (number = 1; number <= maxValue; number++) {
    double formula = (number + 1) / (number * 2);
    System.out.println(
        number + "\t\t\t" + number * number + "\t\t\t" +
        number * number * number + "\t\t\t" + formula);
}

Body:
I'm not sure which outputs are you getting, but it seems to me you're using integer division when trying to get the result of (n+1)/(2n-18).

Try using:

double decimalNumber = (double) number;
double formula = (decimalNumber + 1) / (decimalNumber * 2 - 18);


问:
Passing UI Thread method to another thread for calling in C#
I have a Windows Forms project in C#. In this project there is a WaveOut device that's played back in separate thread. This playback thread periodically needs to call a UI thread method and pass it some data (an array holding the audio information that is being passed to the soundcard).
The passAudio method calls the connected EventHandler periodically.

Right now, the waveout device (WaveOutPlayer.cs) has an EventHandler:

```<code>public class WaveOutPlayer : IDisposable
{
    public event EventHandler<AudioEventArgs> BufferSwapped;
    ...
    private void passAudio(byte[] pAudiodata)
    {
        AudioEventArgs args = new AudioEventArgs();
        args.Data = pAudiodata;
        args.WaveFormat = ws.Format;
        if (BufferSwapped != null)
        {
            BufferSwapped.Invoke(this, args);
        }
    }
}
</code>```

And the Windows Form instance connects to this EventHandler:

```<code>private void Start()
{
    WaveStream Audio = new WaveStream("sine440hz_16bit_stereo.wav");
    WaveOutPlayer wp = new WaveOutPlayer(audio, 0);
    wp.BufferSize = 8192; // testing
    wp.Repeat = false; // 'true' not implemented yet
    wp.BufferSwapped += Wp_BufferSwapped;
}

private void Wp_BufferSwapped(object sender, AudioEventArgs e)
{
    // The audio buffer data can be found in the event args.
    // So analyze this Audio and manipulate some of the forms' controls
    // accordingly.

    this.labelForAmplitude.Text = "some value";
}
</code>```

However, this results in an exception because the Wp_BufferSwapped-Method actually belongs to the playback thread and thus may not manipulate the label's text.

Now:
How can I solve this problem without making the Windows Form's code more difficult? The reason for this is that I want to let my students (high school) do some cool stuff with arrays and simple user interfaces. But at this point they only have a very basic understanding of user interfaces work. They do not know anything about stuff like BeginInvoke or MethodInvoker, yet.
So I want to give them the WaveOutPlayer in form of a DLL - and they only need to deal with the Windows Form.
Is there a solution for this particular Kind of problem?

答:
You can capture current SynchronizationContext in constructor and then Post your event handler invocation to it, like this:

```<code>public class WaveOutPlayer {
    private readonly SynchronizationContext _context;
    public WaveOutPlayer() {
        // capture
        _context = SynchronizationContext.Current;
    }

    public event EventHandler<AudioEventArgs> BufferSwapped;

    private void passAudio(byte[] pAudioData) {
        var args = new AudioEventArgs();
        args.Data = pAudioData;
        var handler = BufferSwapped;
        if (handler != null) {
            if (_context != null)
                // post
                _context.Post(_ => handler(this, args), null);
            else
                handler(this, args);
        }
    }
}
</code>```

By doing this you do not introduce dependency on winforms to your WaveOutPlayer while at the same time no compilcated actions are required from WinForms part, event handlers are just invoked on UI thread. Note that Post here will be analog to Control.BeginInvoke. If you want analog of Control.Invoke - use Send instead.

Body:
I have a Windows Forms project in C#. In this project there is a WaveOut device that's played back in separate thread. This playback thread periodically needs to call a UI thread method and pass it some data (an array holding the audio information that is being passed to the soundcard).
The passAudio method calls the connected EventHandler periodically.

Right now, the waveout device (WaveOutPlayer.cs) has an EventHandler:

public class WaveOutPlayer : IDisposable
{
    public event EventHandler<AudioEventArgs> BufferSwapped;
    ...
    private void passAudio(byte[] pAudiodata)
    {
        AudioEventArgs args = new AudioEventArgs();
        args.Data = pAudiodata;
        args.WaveFormat = ws.Format;
        if (BufferSwapped != null)
        {
            BufferSwapped.Invoke(this, args);
        }
    }
}

And the Windows Form instance connects to this EventHandler:

private void Start()
{
    WaveStream Audio = new WaveStream("sine440hz_16bit_stereo.wav");
    WaveOutPlayer wp = new WaveOutPlayer(audio, 0);
    wp.BufferSize = 8192; // testing
    wp.Repeat = false; // 'true' not implemented yet
    wp.BufferSwapped += Wp_BufferSwapped;
}

private void Wp_BufferSwapped(object sender, AudioEventArgs e)
{
    // The audio buffer data can be found in the event args.
    // So analyze this Audio and manipulate some of the forms' controls
    // accordingly.

    this.labelForAmplitude.Text = "some value";
}

However, this results in an exception because the Wp_BufferSwapped-Method actually belongs to the playback thread and thus may not manipulate the label's text.

Now:
How can I solve this problem without making the Windows Form's code more difficult? The reason for this is that I want to let my students (high school) do some cool stuff with arrays and simple user interfaces. But at this point they only have a very basic understanding of user interfaces work. They do not know anything about stuff like BeginInvoke or MethodInvoker, yet.
So I want to give them the WaveOutPlayer in form of a DLL - and they only need to deal with the Windows Form.
Is there a solution for this particular Kind of problem?

Body:
You can capture current SynchronizationContext in constructor and then Post your event handler invocation to it, like this:

public class WaveOutPlayer {
    private readonly SynchronizationContext _context;
    public WaveOutPlayer() {
        // capture
        _context = SynchronizationContext.Current;
    }

    public event EventHandler<AudioEventArgs> BufferSwapped;

    private void passAudio(byte[] pAudioData) {
        var args = new AudioEventArgs();
        args.Data = pAudioData;
        var handler = BufferSwapped;
        if (handler != null) {
            if (_context != null)
                // post
                _context.Post(_ => handler(this, args), null);
            else
                handler(this, args);
        }
    }
}

By doing this you do not introduce dependency on winforms to your WaveOutPlayer while at the same time no compilcated actions are required from WinForms part, event handlers are just invoked on UI thread. Note that Post here will be analog to Control.BeginInvoke. If you want analog of Control.Invoke - use Send instead.


问:
Logging Facebook using selenium
I know this is a not a proper technical question, but i am facing problem while using selenium to make a facebook post bot.
This is my code so far

```<code>    from selenium import webdriver

browser = webdriver.Firefox(executable_path='D:\\soft\\geckodriver-v0.18.0-win64\\geckodriver.exe')
browser.get('http://www.facebook.com')
emailElem = browser.find_element_by_id('email')
passElem = browser.find_element_by_id('pass')
submitIt = browser.find_element_by_id('u_0_r')
email_id = 'xxxxxxxxxxxxxx'
password = 'xxxxxxx'
status = 'Hie all'
emailElem.send_keys(email_id)
passElem.send_keys(password)
submitIt.click()
statusBox = browser.find_element_by_xpath(
   "//*[@id='js_kk']/div[1]/div/div[1]/div[2]/div/div/div/div/div/div[2]/div/div/div/div/span/br")
statusBox.send_keys("Hie")
</code>```

Now, the problem is my code is not able to locate the status box in Fb page, I am quite new to selenium. Any help would be nice.It is coded in python.

答:
This Code is to log in to Facebook and Post "Hello World" text in status   </p>

```<code>public void facebookLogin() throws InterruptedException {

 //1. Set gecko driver path

System.setProperty("webdriver.gecko.driver","C:\\Selenium\\selenium-java-3.0.1\\geckodriver.exe");

WebDriver d= new FirefoxDriver();

  //2. Enter URL

  d.get("https://www.facebook.com/");

  //3. maximize window

  d.manage().window().maximize();
  Thread.sleep(2000);

   //4. Login Into Fcaebook
  d.findElement(By.id("email")).sendKeys("email");
  d.findElement(By.id("pass")).sendKeys("password");
  d.findElement(By.id("loginbutton")).click();
   Thread.sleep(3000);

    //5. Post "Hello World" into status

   d.get("https://www.facebook.com/");
   WebElement post= d.findElement(By.xpath("//*[@name='xhpc_message']"));
   post.click();
   post.sendKeys("Hello World");
   d.findElement(By.xpath("(//button[@value='1'])[5]")).click();

   Thread.sleep(2000);

  }
</code>```

Title: Logging Facebook using selenium

Body:
I know this is a not a proper technical question, but i am facing problem while using selenium to make a facebook post bot.
This is my code so far

    from selenium import webdriver

browser = webdriver.Firefox(executable_path='D:\\soft\\geckodriver-v0.18.0-win64\\geckodriver.exe')
browser.get('http://www.facebook.com')
emailElem = browser.find_element_by_id('email')
passElem = browser.find_element_by_id('pass')
submitIt = browser.find_element_by_id('u_0_r')
email_id = 'xxxxxxxxxxxxxx'
password = 'xxxxxxx'
status = 'Hie all'
emailElem.send_keys(email_id)
passElem.send_keys(password)
submitIt.click()
statusBox = browser.find_element_by_xpath(
   "//*[@id='js_kk']/div[1]/div/div[1]/div[2]/div/div/div/div/div/div[2]/div/div/div/div/span/br")
statusBox.send_keys("Hie")

Now, the problem is my code is not able to locate the status box in Fb page, I am quite new to selenium. Any help would be nice.It is coded in python.

Body:
This Code is to log in to Facebook and Post "Hello World" text in status

public void facebookLogin() throws InterruptedException {

 //1. Set gecko driver path

System.setProperty("webdriver.gecko.driver","C:\\Selenium\\selenium-java-3.0.1\\geckodriver.exe");

WebDriver d= new FirefoxDriver();

  //2. Enter URL

  d.get("https://www.facebook.com/");

  //3. maximize window

  d.manage().window().maximize();
  Thread.sleep(2000);

   //4. Login Into Fcaebook
  d.findElement(By.id("email")).sendKeys("email");
  d.findElement(By.id("pass")).sendKeys("password");
  d.findElement(By.id("loginbutton")).click();
   Thread.sleep(3000);

    //5. Post "Hello World" into status

   d.get("https://www.facebook.com/");
   WebElement post= d.findElement(By.xpath("//*[@name='xhpc_message']"));
   post.click();
   post.sendKeys("Hello World");
   d.findElement(By.xpath("(//button[@value='1'])[5]")).click();

   Thread.sleep(2000);

  }


问:
Disable print screen option in IE,but the code works fine with google chrome
Print screen option has been disabled in Google Chrome with the below js code.

```<code>document.onkeydown = keydown;
document.onkeyup = keyup;

function keydown(e) {
console.log("key down triggered");
var keystroke = String.fromCharCode(event.keyCode).toLowerCase();

if (e.keyCode == 44 || e.keyCode == "44" || e.which == 44 || e.which == "44") {
e.cancelBubble = true;
e.preventDefault();
e.stopImmediatePropagation();
}

if (e.ctrlKey && (e.key == "P" || e.key == "C" || e.key == "A" || e.key == "p"||e.key == "c" || e.key == "a" || e.charCode == 16 || e.charCode == 112 ||e.keyCode == 80) || (e.keyCode == 44) || (e.keyCode == 123)) {
//alert("Inspect element & Print &cut/copy option is restricted");
e.cancelBubble = true;
e.preventDefault();
e.stopImmediatePropagation();
}

if (e.keyCode > 111 && e.keyCode < 124) {
//alert("Function option is restricted");
e.cancelBubble = true;
e.preventDefault();
e.stopImmediatePropagation();
}

if (e.key == "F11" || e.key == "f11") {
//alert("Function option is restricted");
e.cancelBubble = true;
e.preventDefault();
e.stopImmediatePropagation();
}
}
function keyup(e) {
debugger;
console.log("key up triggered");
if (e.keyCode == 44 || e.keyCode == "44" || e.which == 44 || e.which =="44") {
e.cancelBubble = true;
e.preventDefault();
e.stopImmediatePropagation();
}

if (e.keyCode > 111 && e.keyCode < 124) {
e.cancelBubble = true;
e.preventDefault();
e.stopImmediatePropagation();
}
if (e.key == "F11" || e.key == "f11") {
//alert("Function option is restricted");
e.cancelBubble = true;
e.preventDefault();
e.stopImmediatePropagation();
}
</code>```

The above code works fine in Google Chrome.key code 44 for Print screen option is used.In IE all the function keys have been restricted,but the keyup and keydown function is not getting triggered,when in IE browser alone.

What is the alternate way to handle print screen option in IE Browser using jquery.?

And additionally the above code fails to prevent print screen when the user opens a bootbox alert pop up inside a web application.

Suggest a solution for the above 2 scenarios.

答:
Don't.

No matter how clever your code, you can't stop me from focussing a different window on my second monitor and hitting Print Screen there to get a copy of whatever's on-screen that you're trying to stop me from screenshotting.

Or I could just open the browser console (even if you block F12 / Ctrl+Shift+I, I can still get there via the browser's menus) and type document.onkeydown = document.onkeyup = null; and break your entire guard.

It's not often that I "answer" a question by completely shutting it down, but you are wasting your time.

Body:
Print screen option has been disabled in Google Chrome with the below js code.

document.onkeydown = keydown;
document.onkeyup = keyup;

function keydown(e) {
console.log("key down triggered");
var keystroke = String.fromCharCode(event.keyCode).toLowerCase();

if (e.keyCode == 44 || e.keyCode == "44" || e.which == 44 || e.which == "44") {
e.cancelBubble = true;
e.preventDefault();
e.stopImmediatePropagation();
}

if (e.ctrlKey && (e.key == "P" || e.key == "C" || e.key == "A" || e.key == "p"||e.key == "c" || e.key == "a" || e.charCode == 16 || e.charCode == 112 ||e.keyCode == 80) || (e.keyCode == 44) || (e.keyCode == 123)) {
//alert("Inspect element & Print &cut/copy option is restricted");
e.cancelBubble = true;
e.preventDefault();
e.stopImmediatePropagation();
}

if (e.keyCode > 111 && e.keyCode < 124) {
//alert("Function option is restricted");
e.cancelBubble = true;
e.preventDefault();
e.stopImmediatePropagation();
}

if (e.key == "F11" || e.key == "f11") {
//alert("Function option is restricted");
e.cancelBubble = true;
e.preventDefault();
e.stopImmediatePropagation();
}
}
function keyup(e) {
debugger;
console.log("key up triggered");
if (e.keyCode == 44 || e.keyCode == "44" || e.which == 44 || e.which =="44") {
e.cancelBubble = true;
e.preventDefault();
e.stopImmediatePropagation();
}

if (e.keyCode > 111 && e.keyCode < 124) {
e.cancelBubble = true;
e.preventDefault();
e.stopImmediatePropagation();
}
if (e.key == "F11" || e.key == "f11") {
//alert("Function option is restricted");
e.cancelBubble = true;
e.preventDefault();
e.stopImmediatePropagation();
}

The above code works fine in Google Chrome.key code 44 for Print screen option is used.In IE all the function keys have been restricted,but the keyup and keydown function is not getting triggered,when in IE browser alone.

What is the alternate way to handle print screen option in IE Browser using jquery.?

And additionally the above code fails to prevent print screen when the user opens a bootbox alert pop up inside a web application.

Suggest a solution for the above 2 scenarios.


问:
Setting IKImageBrowserView to one long row
I've got a IKImageBrowserView in an NSScrollView and I want to lay it out so it only scrolls from left to right.

By default the IKImageBrowserView lays out the images in a grid and the width is being correctly constrained but it's always increasing the height to fit the number of rows of images it's containing.

My naive approach to this has been to try setting the IKImageBrowserView's and NSScrollView's frames so the height is the equivalent of 1 row of images, but this had no effect.

Can anyone recommend the correct way to approach to this?

答:
No sooner do I ask the question and I find the answer:</p>

```<code>[imageBrowser setContentResizingMask:NSViewWidthSizable];
</code>```

ContentLicense: CC BY-SA 2.5

Body:
No sooner do I ask the question and I find the answer:

[imageBrowser setContentResizingMask:NSViewWidthSizable];


问:
PHP class: Global variable as property in class
I have a global variable outside my class = $MyNumber;

How do I declare this as a property in myClass?

For every method in my class, this is what I do:

```<code>class myClass() {

    private function foo() {
         $privateNumber = $GLOBALS['MyNumber'];
    }

}
</code>```

I want this

```<code>class myClass() {

    //What goes here?
    var $classNumber = ???//the global $MyNumber;

    private function foo() {
         $privateNumber = $this->classNumber;
    }

}
</code>```

EDIT: I want to create a variable based on the global $MyNumber but

 modified before using it in the methods

something like: var $classNumber = global $MyNumber + 100;

答:
```<code>class myClass
{
protected $foo;

public function __construct(&$var)
{
    $this->foo = &$var;
}

public function foo()
{
    return ++$this->foo;
}
}
</code>```

Body:
I have a global variable outside my class = $MyNumber;

How do I declare this as a property in myClass?

For every method in my class, this is what I do:

class myClass() {

    private function foo() {
         $privateNumber = $GLOBALS['MyNumber'];
    }

}

I want this

class myClass() {

    //What goes here?
    var $classNumber = ???//the global $MyNumber;

    private function foo() {
         $privateNumber = $this->classNumber;
    }

}

EDIT: I want to create a variable based on the global $MyNumber but

 modified before using it in the methods

something like: var $classNumber = global $MyNumber + 100;

ContentLicense: CC BY-SA 4.0


问:
Mongodb terminates when it runs out of memory
I have the following configuration:

a host machine that runs three docker containers:

Mongodb

Redis

A program using the previous two containers to store data

Both Redis and Mongodb are used to store huge amounts of data. I know Redis needs to keep all its data in RAM and I am fine with this. Unfortunately, what happens is that Mongo starts taking up a lot of RAM and as soon as the host RAM is full (we're talking about 32GB here), either Mongo or Redis crashes.

I have read the following previous questions about this:

Limit MongoDB RAM Usage: apparently most RAM is used up by the WiredTiger cache

MongoDB limit memory: here apparently the problem was log data

Limit the RAM memory usage in MongoDB: here they suggest to limit mongo's memory so that it uses a smaller amount of memory for its cache/logs/data

MongoDB using too much memory: here they say it's WiredTiger caching system which tends to use as much RAM as possible to provide faster access. They also state it's completely okay to limit the WiredTiger cache size, since it handles I/O operations pretty efficiently

Is there any option to limit mongodb memory usage?: caching again, they also add MongoDB uses the LRU (Least Recently Used) cache algorithm to determine which "pages" to release, you will find some more information in these two questions

MongoDB index/RAM relationship: quote: MongoDB keeps what it can of the indexes in RAM. They'll be swaped out on an LRU basis. You'll often see documentation that suggests you should keep your "working set" in memory: if the portions of index you're actually accessing fit in memory, you'll be fine.

how to release the caching which is used by Mongodb?: same answer as in 5.

Now what I appear to understand from all these answers is that:

For faster access it would be better for Mongo to fit all indices in RAM. However, in my case, I am fine with indices partially residing on disk as I have a quite fast SSD.

RAM is mostly used for caching by Mongo.

Considering this, I was expecting Mongo to try and use as much RAM space as possible but being able to function also with few RAM space and fetching most things from disk. However, I limited Mongo Docker container's memory (to 8GB for instance), by using --memory and --memory-swap, but instead of fetching stuff from disk, Mongo just crashed as soon as it ran out of memory.

How can I force Mongo to use only the available memory and to fetch from disk everything that does not fit into memory?

答:
Thanks to @AlexBlex's comment I solved my issue. Apparently the problem was that Docker limited the container's RAM to 8GB but the wiredTiger storage engine was still trying to use up 50% - 1GB of the total system RAM for it's cache (which in my case would have been 15 GB).

Capping wiredTiger's cache size by using this configuration option to a value less than what Docker was allocating solved the problem.


问:
How to use choice in try catch block using apache Camel in a Route with Java DSL
How to use choice in try catch block using Apache Camel in a Route with Java DSL?

I have a situation in which, I need the following structure:

route-->from--> doTry-->choice-->when-->simple-->to-->otherwise-->to-->enddoTry-->docatch-->to-->enddocatch-->endroute

As of now I tried below lines:

```<code>    .doTry()
    .choice()
    .when(header("CamelFileName").contains("xxxxx"))
    .to()
    .otherwise().to("controlbus:route?routeId=XXXX&action=stop")
    .doCatch(java.lang.Exception.class)
    .log("STOPPING ROUTE")
    .to("controlbus:route?routeId=XXXX&action=stop&async=true")
</code>```

But I am getting "cannot find symbol" error at docatch()

Could you please suggest way to use "choice" in try catch block with Java DSL?

答:
Try this. This should work  </p>

```<code>.doTry()
    .choice()
      .when(header("CamelFileName").contains("xxxxx"))
        .to()
      .otherwise()
        .to("controlbus:route?routeId=XXXX&action=stop")
.endDoTry()
.doCatch(java.lang.Exception.class)
.log("STOPPING ROUTE")
.to("controlbus:route?routeId=XXXX&action=stop&async=true")
</code>```

Body:
How to use choice in try catch block using Apache Camel in a Route with Java DSL?

I have a situation in which, I need the following structure:

route-->from--> doTry-->choice-->when-->simple-->to-->otherwise-->to-->enddoTry-->docatch-->to-->enddocatch-->endroute

As of now I tried below lines:

    .doTry()
    .choice()
    .when(header("CamelFileName").contains("xxxxx"))
    .to()
    .otherwise().to("controlbus:route?routeId=XXXX&action=stop")
    .doCatch(java.lang.Exception.class)
    .log("STOPPING ROUTE")
    .to("controlbus:route?routeId=XXXX&action=stop&async=true")

But I am getting "cannot find symbol" error at docatch()

Could you please suggest way to use "choice" in try catch block with Java DSL?

Body:
Try this. This should work

.doTry()
    .choice()
      .when(header("CamelFileName").contains("xxxxx"))
        .to()
      .otherwise()
        .to("controlbus:route?routeId=XXXX&action=stop")
.endDoTry()
.doCatch(java.lang.Exception.class)
.log("STOPPING ROUTE")
.to("controlbus:route?routeId=XXXX&action=stop&async=true")


问:
How to save NLTK concordance results in a list?
I'm using the NLTK to find word in a text. I need to save result of concordance function into a list. The question is already asked  here
but i cannot see the changes. I try to find the type of returnde value of the function by :

```<code>type(text.concordance('myword'))
</code>```

the result was :

```<code><class 'NoneType'>
</code>```

答:
To use text concordance, you need to instantiate a NLTK Text() object and then use concordance() method on that object :

```<code>import nltk.corpus
from nltk.text import Text
moby = Text(nltk.corpus.gutenberg.words('melville-moby_dick.txt'))
</code>```

Here we instantiate a Text object on the text file melville-moby_dick.txt and then we are able to use the method :

```<code>moby.concordance("monster")
</code>```

If you have a NonType here, it seeems to be because you did not created any Text object and so your variable text is None.

Body:
I'm using the NLTK to find word in a text. I need to save result of concordance function into a list. The question is already asked  here
but i cannot see the changes. I try to find the type of returnde value of the function by :

type(text.concordance('myword'))

the result was :

<class 'NoneType'>

Body:
To use text concordance, you need to instantiate a NLTK Text() object and then use concordance() method on that object :

import nltk.corpus
from nltk.text import Text
moby = Text(nltk.corpus.gutenberg.words('melville-moby_dick.txt'))

Here we instantiate a Text object on the text file melville-moby_dick.txt and then we are able to use the method :

moby.concordance("monster")

If you have a NonType here, it seeems to be because you did not created any Text object and so your variable text is None.


问:
how to convert list<enum> to string. I need save string in database not number(enum) in C#
its my enum

```<code>public enum Employee_roles
{
    admin,
    controller,
    planner,
    stockkeeper,
    client,
    bpengineer,
    superintendent,
    seniorengineer,
    procurementmanager,
    hseadmin,
    hseclient,
    rawadmin,
}
</code>```

this model class

```<code>public class access_right
{

    public string id { get; set; }
    public string model { get; set; }
    [JsonConverter(typeof(StringEnumConverter))]
    public method method { get; set; }
    [JsonConverter(typeof(StringEnumConverter))]
    public List<Employee_roles> roles { get; set; }
    public List<string> email { get; set; }
    [JsonConverter(typeof(StringEnumConverter))]
    public access_type access { get; set; }

}
</code>```

**roles property is List. if it's not list no problem [JsonConverter(typeof(StringEnumConverter))] this method working. But List how to convert please help me **

答:
```<code>var list = Enum.GetNames(typeof(Employee_roles)).ToList();
</code>```

Body:
its my enum

public enum Employee_roles
{
    admin,
    controller,
    planner,
    stockkeeper,
    client,
    bpengineer,
    superintendent,
    seniorengineer,
    procurementmanager,
    hseadmin,
    hseclient,
    rawadmin,
}

this model class

public class access_right
{

    public string id { get; set; }
    public string model { get; set; }
    [JsonConverter(typeof(StringEnumConverter))]
    public method method { get; set; }
    [JsonConverter(typeof(StringEnumConverter))]
    public List<Employee_roles> roles { get; set; }
    public List<string> email { get; set; }
    [JsonConverter(typeof(StringEnumConverter))]
    public access_type access { get; set; }

}

**roles property is List. if it's not list no problem [JsonConverter(typeof(StringEnumConverter))] this method working. But List how to convert please help me **


问:
Ultimate Member login Shortcodes for dropdown login form not working
I create a drop down button for Wordpress plugin ultimate member login form. It's working correctly inside the content page, but when i paste these codes outside i mean in header.php it's not show login form.I'm also using restricted content code of ultimate member.Please any one help me.
Thanks in Advance.
Problem

Inside content page of wordpress working 100% correct

```<code>    <div style="width:120px; background:lightgrey;" class="ld-en">
<div class="col-md-1"><h4>Hello</h4></div>
<div class="col-md-2">[um_loggedin show_lock=no] <h4 style="color:red;padding-left:15px;">{first_name} </h4>
    [/um_loggedin]</div>

<div class="col-md-2">[um_loggedout]  <div class="dropdown"> <button class="login-drop dropdown-toggle" id="menu1" type="button" data-toggle="dropdown"> Log In<span class="caret"></span></button>

     <div class="dropdown-menu login-dropdown"  role="menu" aria-labelledby="menu1"> [ultimatemember form_id=287]
<ul class="login-dropdown">
      <li role="presentation" class="divider"></li>
      <li role="presentation"><a role="menuitem" tabindex="-1" href="">Register</a></li>
    </ul></div>
  </div>  [/um_loggedout]</div>
 </div>
</code>```

答:
You have to use do_short_code() for each short code you have used in your file
check this out check how to use it
for example</p>

```<code> <div style="width:120px; background:lightgrey;" class="ld-en">
<div class="col-md-1"><h4>Hello</h4></div>
<div class="col-md-2"><?php echo do_shortcode( '[um_loggedin show_lock=no]' ); ?> <h4 style="color:red;padding-left:15px;">{first_name} </h4>
    <?php echo do_shortcode( '[/um_loggedin]') ?></div>
</code>```

Body:
I create a drop down button for Wordpress plugin ultimate member login form. It's working correctly inside the content page, but when i paste these codes outside i mean in header.php it's not show login form.I'm also using restricted content code of ultimate member.Please any one help me.
Thanks in Advance.
Problem

Inside content page of wordpress working 100% correct

Hello

[um_loggedin show_lock=no]
{first_name}

    [/um_loggedin]

[um_loggedout]
 <button class="login-drop dropdown-toggle" id="menu1" type="button" data-toggle="dropdown"> Log In</button>

 [ultimatemember form_id=287]

Register

  [/um_loggedout]

Body:
You have to use do_short_code() for each short code you have used in your file
check this out check how to use it
for example

 <div style="width:120px; background:lightgrey;" class="ld-en">
<div class="col-md-1"><h4>Hello</h4></div>
<div class="col-md-2"><?php echo do_shortcode( '[um_loggedin show_lock=no]' ); ?> <h4 style="color:red;padding-left:15px;">{first_name} </h4>
    <?php echo do_shortcode( '[/um_loggedin]') ?></div>


问:
Add child with automatically incremented custom ID - Firebase
I want to add a new user to firebase database with auto increment id as shown below screenshots:

I have tried:

```<code>    var rootRef = firebase.database().ref();
    var storesRef = rootRef.child("/users");
    storesRef.set({
      "name": "user1",
      "pageId": "user1"
    });
</code>```

答:
I do not recommend this, but you can try the following:

```<code>storesRef.limitToLast(1).once('value', (snapshot) => {
    const nextID = parseInt(snapshot.key) + 1;
    let updates = {};
    updates['/users/' + nextID] = // your user;
    rootRef.update(updates);
});
</code>```

However, I would strongly suggest you use Firebases automatically generated IDs instead, since this approach is very error prone.

You should also have a look at this answer.

Body:
I want to add a new user to firebase database with auto increment id as shown below screenshots:

I have tried:

    var rootRef = firebase.database().ref();
    var storesRef = rootRef.child("/users");
    storesRef.set({
      "name": "user1",
      "pageId": "user1"
    });

Body:
I do not recommend this, but you can try the following:

storesRef.limitToLast(1).once('value', (snapshot) => {
    const nextID = parseInt(snapshot.key) + 1;
    let updates = {};
    updates['/users/' + nextID] = // your user;
    rootRef.update(updates);
});

However, I would strongly suggest you use Firebases automatically generated IDs instead, since this approach is very error prone.

You should also have a look at this answer.


问:
Change mysql query to laravel 5.4
I have a mysql query

```<code>SELECT * FROM Appraisal_skills WHERE INSTR(`assigned_to`, 6);
</code>```

Which working well.I want to change this to laravel

I tried

```<code>$getskillset=Db::table('Appraisal_skills')->where(`assigned_to`, 6)->instr()->get();
</code>```

But got an error like BadMethodCallException in Builder.php line 2508:
  Call to undefined method Illuminate\Database\Query\Builder::instr()

Please correct me.Any help would be appreciated.

答:
Laravels database query builder doesn't have instr method. But you can use whereRaw method.

So your code will be like this

```<code>$getskillset=Db::table('Appraisal_skills')->whereRaw('INSTR(`assigned_to`, ?)', [6])->get();
</code>```

You can read more about raw expressions in Laravel docs

and here is api documentation

Title: Change mysql query to laravel 5.4

Body:
I have a mysql query

SELECT * FROM Appraisal_skills WHERE INSTR(`assigned_to`, 6);

Which working well.I want to change this to laravel

I tried

$getskillset=Db::table('Appraisal_skills')->where(`assigned_to`, 6)->instr()->get();

But got an error like BadMethodCallException in Builder.php line 2508:
  Call to undefined method Illuminate\Database\Query\Builder::instr()

Please correct me.Any help would be appreciated.

Body:
Laravels database query builder doesn't have instr method. But you can use whereRaw method.

So your code will be like this

$getskillset=Db::table('Appraisal_skills')->whereRaw('INSTR(`assigned_to`, ?)', [6])->get();

You can read more about raw expressions in Laravel docs

and here is api documentation


问:
Creating a Docx file using Officegen with html
I'm using officegen to create a docx file with Node.js. I'm adding images, lines, paragraphs, the issue that I have is that I have html with simple style like bold texxt, lists, and so on.

I've tried to use Textversion.js and it removes all the styling.

How can I convert that to be able to add it to the word doc without loosing the style? Any other tool that I can use?

答:
I was able to resolve my problem using https://github.com/evidenceprime/html-docx-js. Using this package I was able to use html from server side and generate a docx file keeping the html styling. It is not compatible with google docs, but once you open the file with Microsoft Word and sabe it, you can upload it to google docs or use with any other free tool like OpenOffice.
Thanks. </p>


问:
C# static vs instance methods
I'm risking it this might be a newb question but here goes. I'm tempted to add a method to a class that could possible have thousands and thousands of instances in memory at a given time. Now, the other option is creating a static class with a static method, and just create the [static] method there, instead of an instance method in the class. Something like so:

This:

```<code>public static class PetOwner
{
    public static void RenamePet(Pet pet, string newName)
    {
        pet.Name = newName;
    }
}
</code>```

Instead of this:

```<code>public class Pet
{
    public string Name { get; set; }

    public void Rename(string newName)
    {
        this.Name = newName;
    }
}
</code>```

I'm just wondering if the static class alternative would take considerably less memory.

Thanks!

答: The amount of instances of a class, does not effect how much memory the method uses.</p>

Title: C# static vs instance methods

Body:
I'm risking it this might be a newb question but here goes. I'm tempted to add a method to a class that could possible have thousands and thousands of instances in memory at a given time. Now, the other option is creating a static class with a static method, and just create the [static] method there, instead of an instance method in the class. Something like so:

This:

public static class PetOwner
{
    public static void RenamePet(Pet pet, string newName)
    {
        pet.Name = newName;
    }
}

Instead of this:

public class Pet
{
    public string Name { get; set; }

    public void Rename(string newName)
    {
        this.Name = newName;
    }
}

I'm just wondering if the static class alternative would take considerably less memory.

Thanks!


问:
Using usb-serial set rts to high
I am trying to implement this:
https://github.com/mik3y/usb-serial-for-android/blob/master/usbSerialExamples/src/main/java/src/com/hoho/android/usbserial/examples/SerialConsoleActivity.java

I have an LED connected to rts and 5v pin through CH340g. I have tested it on UsbTerminal app on android and it works fine but my app does not detect any usb serial device and it crashes when i try to check the RTS checkbox.

I am new to programming and android and its my very first experience using such components so any help would be appreciated.

Here is my code:

```<code>package com.example.dell.cashregister;

import android.content.Context;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialPort;
import com.hoho.android.usbserial.driver.UsbSerialProber;
import com.hoho.android.usbserial.driver.UsbSerialPort;
import com.hoho.android.usbserial.util.HexDump;
import com.hoho.android.usbserial.util.SerialInputOutputManager;

import java.io.IOException;
import java.util.List;
import java.io.*;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ScrollView;
import android.widget.TextView;

import com.hoho.android.usbserial.driver.UsbSerialPort;
import com.hoho.android.usbserial.util.HexDump;
import com.hoho.android.usbserial.util.SerialInputOutputManager;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MainActivity extends Activity {

private final String TAG = MainActivity.class.getSimpleName();

private static UsbSerialPort sPort = null;

private TextView mTitleTextView;
private TextView mDumpTextView;
private ScrollView mScrollView;
private CheckBox chkDTR;
private CheckBox chkRTS;

private final ExecutorService mExecutor = Executors.newSingleThreadExecutor();

private SerialInputOutputManager mSerialIoManager;

private final SerialInputOutputManager.Listener mListener =
        new SerialInputOutputManager.Listener() {

            @Override
            public void onRunError(Exception e) {
                Log.d(TAG, "Runner stopped.");
            }

            @Override
            public void onNewData(final byte[] data) {
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        MainActivity.this.updateReceivedData(data);
                    }
                });
            }
        };

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mTitleTextView = (TextView) findViewById(R.id.demoTitle);
    mDumpTextView = (TextView) findViewById(R.id.consoleText);
    mScrollView = (ScrollView) findViewById(R.id.demoScroller);
    chkDTR = (CheckBox) findViewById(R.id.checkBoxDTR);
    chkRTS = (CheckBox) findViewById(R.id.checkBoxRTS);

    chkDTR.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            try {
                sPort.setDTR(isChecked);
            }catch (IOException x){}
        }
    });

    chkRTS.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            try {
                sPort.setRTS(isChecked);
            }catch (IOException x){}
        }
    });

}

@Override
protected void onPause() {
    super.onPause();
    stopIoManager();
    if (sPort != null) {
        try {
            sPort.close();
        } catch (IOException e) {
            // Ignore.
        }
        sPort = null;
    }
    finish();
}

void showStatus(TextView theTextView, String theLabel, boolean theValue){
    String msg = theLabel + ": " + (theValue ? "enabled" : "disabled") + "\n";
    theTextView.append(msg);
}

@Override
protected void onResume() {
    super.onResume();
    Log.d(TAG, "Resumed, port=" + sPort);
    if (sPort == null) {
        mTitleTextView.setText("No serial device.");
    } else {
        final UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);

        UsbDeviceConnection connection = usbManager.openDevice(sPort.getDriver().getDevice());
        if (connection == null) {
            mTitleTextView.setText("Opening device failed");
            return;
        }

        try {
            sPort.open(connection);
            sPort.setParameters(115200, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);

            showStatus(mDumpTextView, "CD  - Carrier Detect", sPort.getCD());
            showStatus(mDumpTextView, "CTS - Clear To Send", sPort.getCTS());
            showStatus(mDumpTextView, "DSR - Data Set Ready", sPort.getDSR());
            showStatus(mDumpTextView, "DTR - Data Terminal Ready", sPort.getDTR());
            showStatus(mDumpTextView, "DSR - Data Set Ready", sPort.getDSR());
            showStatus(mDumpTextView, "RI  - Ring Indicator", sPort.getRI());
            showStatus(mDumpTextView, "RTS - Request To Send", sPort.getRTS());

        } catch (IOException e) {
            Log.e(TAG, "Error setting up device: " + e.getMessage(), e);
            mTitleTextView.setText("Error opening device: " + e.getMessage());
            try {
                sPort.close();
            } catch (IOException e2) {
                // Ignore.
            }
            sPort = null;
            return;
        }
        mTitleTextView.setText("Serial device: " + sPort.getClass().getSimpleName());
    }
    onDeviceStateChange();
}

private void stopIoManager() {
    if (mSerialIoManager != null) {
        Log.i(TAG, "Stopping io manager ..");
        mSerialIoManager.stop();
        mSerialIoManager = null;
    }
}

private void startIoManager() {
    if (sPort != null) {
        Log.i(TAG, "Starting io manager ..");
        mSerialIoManager = new SerialInputOutputManager(sPort, mListener);
        mExecutor.submit(mSerialIoManager);
    }
}

private void onDeviceStateChange() {
    stopIoManager();
    startIoManager();
}

private void updateReceivedData(byte[] data) {
    final String message = "Read " + data.length + " bytes: \n"
            + HexDump.dumpHexString(data) + "\n\n";
    mDumpTextView.append(message);
    mScrollView.smoothScrollTo(0, mDumpTextView.getBottom());
}

/**
 * Starts the activity, using the supplied driver instance.
 *
 * @param context
 * @param driver
 */
static void show(Context context, UsbSerialPort port) {
    sPort = port;
    final Intent intent = new Intent(context, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY);
    context.startActivity(intent);
}
</code>```

}

Please let me know if anything needs to be changed in order to detect my device or if there is any other problem.

Here is the logcat:

```<code>12-05 16:32:34.677 17322-17322/com.example.dell.cashregister
E/AndroidRuntime: FATAL EXCEPTION: main
                                                                           Process: com.example.dell.cashregister, PID: 17322
                                                                           java.lang.NullPointerException: Attempt to invoke interface method 'void com.hoho.android.usbserial.driver.UsbSerialPort.setRTS(boolean)' on a null object reference
                                                                               at com.example.dell.cashregister.MainActivity$3.onCheckedChanged(MainActivity.java:101)
                                                                               at android.widget.CompoundButton.setChecked(CompoundButton.java:161)
                                                                               at android.widget.CompoundButton.toggle(CompoundButton.java:115)
                                                                               at android.widget.CompoundButton.performClick(CompoundButton.java:127)
                                                                               at android.view.View$PerformClick.run(View.java:20755)
                                                                               at android.os.Handler.handleCallback(Handler.java:739)
                                                                               at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                               at android.os.Looper.loop(Looper.java:145)
                                                                               at android.app.ActivityThread.main(ActivityThread.java:5835)
                                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                                               at java.lang.reflect.Method.invoke(Method.java:372)
                                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
</code>```

答:
Are you sure you have initialised the activity using the static void show(Context context, UsbSerialPort port) method and passed a NonNull value for UsbSerialPort port? From the logs, it seems like the mPort variable has not been initialised. And from looking at your code the only way it gets initialised when you call this method.

My guess is that you are trying to initialise the Activity without calling this method. For the purpose of this example, the activity should only be initialised (at least for the first time) using the show method.

I did also take a look at the example you are trying to recreate, and it is stated there that using a static variable for the port reference is a hacky way of implementing this. For a quick example it should be ok, but it may crash in some scenarios and it would be a good idea to find a different way of initialising it if you plan to use it further.

Title: Using usb-serial set rts to high

Body:
I am trying to implement this:
https://github.com/mik3y/usb-serial-for-android/blob/master/usbSerialExamples/src/main/java/src/com/hoho/android/usbserial/examples/SerialConsoleActivity.java

I have an LED connected to rts and 5v pin through CH340g. I have tested it on UsbTerminal app on android and it works fine but my app does not detect any usb serial device and it crashes when i try to check the RTS checkbox.

I am new to programming and android and its my very first experience using such components so any help would be appreciated.

Here is my code:

package com.example.dell.cashregister;

import android.content.Context;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialPort;
import com.hoho.android.usbserial.driver.UsbSerialProber;
import com.hoho.android.usbserial.driver.UsbSerialPort;
import com.hoho.android.usbserial.util.HexDump;
import com.hoho.android.usbserial.util.SerialInputOutputManager;

import java.io.IOException;
import java.util.List;
import java.io.*;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ScrollView;
import android.widget.TextView;

import com.hoho.android.usbserial.driver.UsbSerialPort;
import com.hoho.android.usbserial.util.HexDump;
import com.hoho.android.usbserial.util.SerialInputOutputManager;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MainActivity extends Activity {

private final String TAG = MainActivity.class.getSimpleName();

private static UsbSerialPort sPort = null;

private TextView mTitleTextView;
private TextView mDumpTextView;
private ScrollView mScrollView;
private CheckBox chkDTR;
private CheckBox chkRTS;

private final ExecutorService mExecutor = Executors.newSingleThreadExecutor();

private SerialInputOutputManager mSerialIoManager;

private final SerialInputOutputManager.Listener mListener =
        new SerialInputOutputManager.Listener() {

            @Override
            public void onRunError(Exception e) {
                Log.d(TAG, "Runner stopped.");
            }

            @Override
            public void onNewData(final byte[] data) {
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        MainActivity.this.updateReceivedData(data);
                    }
                });
            }
        };

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mTitleTextView = (TextView) findViewById(R.id.demoTitle);
    mDumpTextView = (TextView) findViewById(R.id.consoleText);
    mScrollView = (ScrollView) findViewById(R.id.demoScroller);
    chkDTR = (CheckBox) findViewById(R.id.checkBoxDTR);
    chkRTS = (CheckBox) findViewById(R.id.checkBoxRTS);

    chkDTR.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            try {
                sPort.setDTR(isChecked);
            }catch (IOException x){}
        }
    });

    chkRTS.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            try {
                sPort.setRTS(isChecked);
            }catch (IOException x){}
        }
    });

}

@Override
protected void onPause() {
    super.onPause();
    stopIoManager();
    if (sPort != null) {
        try {
            sPort.close();
        } catch (IOException e) {
            // Ignore.
        }
        sPort = null;
    }
    finish();
}

void showStatus(TextView theTextView, String theLabel, boolean theValue){
    String msg = theLabel + ": " + (theValue ? "enabled" : "disabled") + "\n";
    theTextView.append(msg);
}

@Override
protected void onResume() {
    super.onResume();
    Log.d(TAG, "Resumed, port=" + sPort);
    if (sPort == null) {
        mTitleTextView.setText("No serial device.");
    } else {
        final UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);

        UsbDeviceConnection connection = usbManager.openDevice(sPort.getDriver().getDevice());
        if (connection == null) {
            mTitleTextView.setText("Opening device failed");
            return;
        }

        try {
            sPort.open(connection);
            sPort.setParameters(115200, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);

            showStatus(mDumpTextView, "CD  - Carrier Detect", sPort.getCD());
            showStatus(mDumpTextView, "CTS - Clear To Send", sPort.getCTS());
            showStatus(mDumpTextView, "DSR - Data Set Ready", sPort.getDSR());
            showStatus(mDumpTextView, "DTR - Data Terminal Ready", sPort.getDTR());
            showStatus(mDumpTextView, "DSR - Data Set Ready", sPort.getDSR());
            showStatus(mDumpTextView, "RI  - Ring Indicator", sPort.getRI());
            showStatus(mDumpTextView, "RTS - Request To Send", sPort.getRTS());

        } catch (IOException e) {
            Log.e(TAG, "Error setting up device: " + e.getMessage(), e);
            mTitleTextView.setText("Error opening device: " + e.getMessage());
            try {
                sPort.close();
            } catch (IOException e2) {
                // Ignore.
            }
            sPort = null;
            return;
        }
        mTitleTextView.setText("Serial device: " + sPort.getClass().getSimpleName());
    }
    onDeviceStateChange();
}

private void stopIoManager() {
    if (mSerialIoManager != null) {
        Log.i(TAG, "Stopping io manager ..");
        mSerialIoManager.stop();
        mSerialIoManager = null;
    }
}

private void startIoManager() {
    if (sPort != null) {
        Log.i(TAG, "Starting io manager ..");
        mSerialIoManager = new SerialInputOutputManager(sPort, mListener);
        mExecutor.submit(mSerialIoManager);
    }
}

private void onDeviceStateChange() {
    stopIoManager();
    startIoManager();
}

private void updateReceivedData(byte[] data) {
    final String message = "Read " + data.length + " bytes: \n"
            + HexDump.dumpHexString(data) + "\n\n";
    mDumpTextView.append(message);
    mScrollView.smoothScrollTo(0, mDumpTextView.getBottom());
}

/**
 * Starts the activity, using the supplied driver instance.
 *
 * @param context
 * @param driver
 */
static void show(Context context, UsbSerialPort port) {
    sPort = port;
    final Intent intent = new Intent(context, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY);
    context.startActivity(intent);
}

}

Please let me know if anything needs to be changed in order to detect my device or if there is any other problem.

Here is the logcat:

12-05 16:32:34.677 17322-17322/com.example.dell.cashregister
E/AndroidRuntime: FATAL EXCEPTION: main
                                                                           Process: com.example.dell.cashregister, PID: 17322
                                                                           java.lang.NullPointerException: Attempt to invoke interface method 'void com.hoho.android.usbserial.driver.UsbSerialPort.setRTS(boolean)' on a null object reference
                                                                               at com.example.dell.cashregister.MainActivity$3.onCheckedChanged(MainActivity.java:101)
                                                                               at android.widget.CompoundButton.setChecked(CompoundButton.java:161)
                                                                               at android.widget.CompoundButton.toggle(CompoundButton.java:115)
                                                                               at android.widget.CompoundButton.performClick(CompoundButton.java:127)
                                                                               at android.view.View$PerformClick.run(View.java:20755)
                                                                               at android.os.Handler.handleCallback(Handler.java:739)
                                                                               at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                               at android.os.Looper.loop(Looper.java:145)
                                                                               at android.app.ActivityThread.main(ActivityThread.java:5835)
                                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                                               at java.lang.reflect.Method.invoke(Method.java:372)
                                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)


问:
How to make static library modular in Swift 4?
As after release of Swift 4, Swift is supporting Static library. But when I am trying to make use of Static binary inside application, it showing error with undefined module.

We are creating SDK with modular structure with 15 framework one for each module, but as Apple suggest it is not good to add more than 6 dynamic framework(As dynamic linking slow down app launch time.).
So after support of static lib in Swift, we decided to convert it to static library and then create one dynamic framework which provide facade interface for all 15 frameworks.

I created one Static lib named StaticA an try to add it in Dynamic Framework, but it shows below error.

No such module 'StaticA'

I also set Defines Modules to Yes but it does not helping.
Is it possible to make Static library modular using Swift ?
If Yes, then suggest way.
Thanks

答:
Go to your Project's Build Phases

and

Click on the "+" under "Link Binary With Libraries" to add a new library. Then click on the "Add Other" button.

and pls also ensure you have the lib path to Library Search Paths under Build Settings


问:
Stop Wordpress on Subdomain
I have a website (http://alvarezpatrick.com) that uses wordpress. I have set up a subdomain (portfolio.alvarezpatrick.com) which I want to use to show example projects, etc. and which I would like not to be part of wordpress. However, if you go to http://portfolio.alvarezpatrick.com it seems to redirect you to http://alvarezpatrick.com, and if you go to http://alvarezpatrick.com/portfolio_html/index.php it seems to say it isn't found.

From looking around I've seen that it should work if I do the following, but unfortunately it does not:

Edit the .htaccess in the main public folder by adding:

RewriteCond %{http_host} ^(www\.)?alvarezpatrick\.com$ [nc]

Create a .htaccess in the portfolio.alvarezpatrick.com domain root folder "portfolio_html" with the following single line of code: RewriteEngine Off

答:
Your main website is on public_html. To avoid using the wordpress on your sub-domain you can point the sub-domain outside the public_html.

For example:

```<code>/portfolio/   --- portfolio.example.com
/public_html/ --- example.com
</code>```

Title: Stop Wordpress on Subdomain

Body:
Your main website is on public_html. To avoid using the wordpress on your sub-domain you can point the sub-domain outside the public_html.

For example:

/portfolio/   --- portfolio.example.com
/public_html/ --- example.com


问:
Android Callback failure does not work
I want to know how to prevent the android application from crushing while an execution error happens.

I'm using this project here.

the error occurs when the requests does not find any result or when it takes to much time.

```<code> FetchExpression fetchExpression = new FetchExpression(
                Utils.getEscapedContactSearchTermFetch(query));
        mOrgService.RetrieveMultiple(fetchExpression, new Callback<EntityCollection>() {
            @Override
            public void success(EntityCollection entityCollection) {
                mMainList.setAdapter(new SearchResultsAdapter(getApplicationContext(), entityCollection));
                mSwipeRefresh.setRefreshing(false);
            }

            @Override
            public void failure(Throwable error) {
                displayError(error.getMessage());
            }
        });
</code>```

the method failure does not work in some cases.

How can I prevent this application from crushing.

Thanks,

答:
You should put that block of code in a try catch block and add the error you want to get in the catch block.</p>

```<code>try {
    some code here
    ....
} catch(Exception yourException) {
}
</code>```

Title: Android Callback failure does not work

Body:
I want to know how to prevent the android application from crushing while an execution error happens.

I'm using this project here.

the error occurs when the requests does not find any result or when it takes to much time.

 FetchExpression fetchExpression = new FetchExpression(
                Utils.getEscapedContactSearchTermFetch(query));
        mOrgService.RetrieveMultiple(fetchExpression, new Callback<EntityCollection>() {
            @Override
            public void success(EntityCollection entityCollection) {
                mMainList.setAdapter(new SearchResultsAdapter(getApplicationContext(), entityCollection));
                mSwipeRefresh.setRefreshing(false);
            }

            @Override
            public void failure(Throwable error) {
                displayError(error.getMessage());
            }
        });

the method failure does not work in some cases.

How can I prevent this application from crushing.

Thanks,

Body:
You should put that block of code in a try catch block and add the error you want to get in the catch block.

try {
    some code here
    ....
} catch(Exception yourException) {
}


问:
Implement ripple effects on imageButton
I'm trying to implement the ripple effect in an Imagebutton.

activty_main.xml

```<code>        <ImageButton
        android:id="@+id/idbuttonsix"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/iconagift"
        android:background="@drawable/ripple_effect"
</code>```

I have try to implementing this code, I don't get the ripple effect on the ImageButton on touch:

```<code>android:foreground="?android:attr/selectableItemBackground"
</code>```

and this

```<code>android:background="?attr/selectableItemBackgroundBorderless"
</code>```

I am looking for someone who can help me step by step.

ripple_effect.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<ripple
xmlns:android="http://schemas.android.com/apk/res/android"
android:color="@color/colorAccent">
<item>
    <shape
        android:shape="rectangle">
        <solid android:color="#4CAF50" />
    </shape>
</item>
</code>```

答:
<ImageButton
    android:id="@+id/idbuttonsix"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="?android:attr/selectableItemBackground"/>```

Note that i have removed the "src" tag here and have just used "background" attribute. This would definitely work for you to give ripple effect to this button.

Title: Implement ripple effects on imageButton

Body:
I'm trying to implement the ripple effect in an Imagebutton.

activty_main.xml

        <ImageButton
        android:id="@+id/idbuttonsix"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/iconagift"
        android:background="@drawable/ripple_effect"

I have try to implementing this code, I don't get the ripple effect on the ImageButton on touch:

android:foreground="?android:attr/selectableItemBackground"

and this

android:background="?attr/selectableItemBackgroundBorderless"

I am looking for someone who can help me step by step.

ripple_effect.xml

<?xml version="1.0" encoding="utf-8"?>
<ripple
xmlns:android="http://schemas.android.com/apk/res/android"
android:color="@color/colorAccent">
<item>
    <shape
        android:shape="rectangle">
        <solid android:color="#4CAF50" />
    </shape>
</item>

Body:
<ImageButton
    android:id="@+id/idbuttonsix"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="?android:attr/selectableItemBackground"/>

Note that i have removed the "src" tag here and have just used "background" attribute. This would definitely work for you to give ripple effect to this button.


答: Methods only exist once in memory, regardless if they are static or not, so there is no difference at all in memory usage.</p>

Title: C# static vs instance methods


问:
when user turn On location show marker on current location
i create one map in this i show one marker on current location its working fine
when location turn on already but when Activity is on and i turn On location it does not show any marker i want to show marker when location is on
any help?..</p>

```<code>public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
         getCurrentLocation();
       // latLngCurrentLocation is my current location which is update using getCurrentLocation() method.

    if(latLngCurrentLocation != null) {

    // add marker on current location
            markerCurrent = mMap.addMarker(new MarkerOptions()
                    .position(latLngCurrentLocation)
                    .draggable(true)
                    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
                    .title("Current Location"));

            mMap.moveCamera(CameraUpdateFactory.newLatLng(latLngCurrentLocation));
            mMap.animateCamera(CameraUpdateFactory.zoomTo(8));
            mMap.getUiSettings().setZoomControlsEnabled(true);
            mMap.setOnMarkerDragListener(this);

        }

    }
</code>```

答:
You will get location in onLocationChanged(Location location) once your position is changed. You will get Latitude and Longitude in location object, so you can set your marker into onLocationChanged(Location location) method

```<code>@Override
public void onLocationChanged(Location location)
{
    mLastLocation = location;
    if (mCurrLocationMarker != null)
    {
        mCurrLocationMarker.remove();
    }

    //Place current location marker
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latLng);
    markerOptions.title("Current Position");
    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
    mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);

    //move map camera
    mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(11));

}
</code>```

OR if you want to refresh your marker once GPS turns on then you can use BroadcastReceiver. BroadcastReciever triggers when GPS turns/off so you can check whether GPS is turned on or off, You can find example in following link, Broadcast receiver for GPS

Body:
i create one map in this i show one marker on current location its working fine
when location turn on already but when Activity is on and i turn On location it does not show any marker i want to show marker when location is on
any help?..

public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
         getCurrentLocation();
       // latLngCurrentLocation is my current location which is update using getCurrentLocation() method.

    if(latLngCurrentLocation != null) {

    // add marker on current location
            markerCurrent = mMap.addMarker(new MarkerOptions()
                    .position(latLngCurrentLocation)
                    .draggable(true)
                    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
                    .title("Current Location"));

            mMap.moveCamera(CameraUpdateFactory.newLatLng(latLngCurrentLocation));
            mMap.animateCamera(CameraUpdateFactory.zoomTo(8));
            mMap.getUiSettings().setZoomControlsEnabled(true);
            mMap.setOnMarkerDragListener(this);

        }

    }

Body:
You will get location in onLocationChanged(Location location) once your position is changed. You will get Latitude and Longitude in location object, so you can set your marker into onLocationChanged(Location location) method

@Override
public void onLocationChanged(Location location)
{
    mLastLocation = location;
    if (mCurrLocationMarker != null)
    {
        mCurrLocationMarker.remove();
    }

    //Place current location marker
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latLng);
    markerOptions.title("Current Position");
    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
    mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);

    //move map camera
    mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(11));

}

OR if you want to refresh your marker once GPS turns on then you can use BroadcastReceiver. BroadcastReciever triggers when GPS turns/off so you can check whether GPS is turned on or off, You can find example in following link, Broadcast receiver for GPS


问:
upgrade android.arch.persistence.room version error on build
I'm trying to upgrade android.arch.persistence.room in my android project.

Now I'm using the alpha-9 and all is working correctly.
If I try to use the "released" version 1.0.0 I'll recive the error reported below on the line compile 'com.android.support:appcompat-v7:26.0.2'.

Error:Execution failed for task ':app:processDebugManifest'.
  Manifest merger failed : Attribute meta-data#android.support.VERSION@value value=(26.0.2) from [com.android.support:design:26.0.2] AndroidManifest.xml:28:13-35
      is also present at [com.android.support:support-core-utils:26.1.0] AndroidManifest.xml:28:13-35 value=(26.1.0).
      Suggestion: add 'tools:replace="android:value"' to  element at AndroidManifest.xml:26:9-28:38 to override.

The gradle file is

apply plugin: 'com.android.application'
android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    defaultConfig {
        minSdkVersion 18
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            useLibrary 'org.apache.http.legacy'
        }
    }
}
dependencies {
    debugCompile 'com.amitshekhar.android:debug-db:1.0.1'
    compile 'com.android.support:appcompat-v7:26.0.2'
    compile 'com.android.support:design:26.0.2'
    compile 'com.google.code.gson:gson:2.2.4'
    compile 'com.android.support:support-v4:26.0.2'
    compile 'com.journeyapps:zxing-android-embedded:3.5.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'android.arch.persistence.room:runtime:1.0.0'
    annotationProcessor 'android.arch.persistence.room:compiler:1.0.0'
}```

Does someone kwnow how I can fix it?

Thanks

答:
Change:

```<code>compile 'com.android.support:appcompat-v7:26.0.2'
compile 'com.android.support:design:26.0.2'
compile 'com.android.support:support-v4:26.0.2'
</code>```

to:

```<code>compile 'com.android.support:appcompat-v7:26.1.0'
compile 'com.android.support:design:26.1.0'
compile 'com.android.support:support-v4:26.1.0'
</code>```

Body:
I'm trying to upgrade android.arch.persistence.room in my android project.

Now I'm using the alpha-9 and all is working correctly.
If I try to use the "released" version 1.0.0 I'll recive the error reported below on the line compile 'com.android.support:appcompat-v7:26.0.2'.

Error:Execution failed for task ':app:processDebugManifest'.
  Manifest merger failed : Attribute meta-data#android.support.VERSION@value value=(26.0.2) from [com.android.support:design:26.0.2] AndroidManifest.xml:28:13-35
      is also present at [com.android.support:support-core-utils:26.1.0] AndroidManifest.xml:28:13-35 value=(26.1.0).
      Suggestion: add 'tools:replace="android:value"' to  element at AndroidManifest.xml:26:9-28:38 to override.

The gradle file is

apply plugin: 'com.android.application'
android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    defaultConfig {
        minSdkVersion 18
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            useLibrary 'org.apache.http.legacy'
        }
    }
}
dependencies {
    debugCompile 'com.amitshekhar.android:debug-db:1.0.1'
    compile 'com.android.support:appcompat-v7:26.0.2'
    compile 'com.android.support:design:26.0.2'
    compile 'com.google.code.gson:gson:2.2.4'
    compile 'com.android.support:support-v4:26.0.2'
    compile 'com.journeyapps:zxing-android-embedded:3.5.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'android.arch.persistence.room:runtime:1.0.0'
    annotationProcessor 'android.arch.persistence.room:compiler:1.0.0'
}

Does someone kwnow how I can fix it?

Thanks

Body:
Change:

compile 'com.android.support:appcompat-v7:26.0.2'
compile 'com.android.support:design:26.0.2'
compile 'com.android.support:support-v4:26.0.2'

to:

compile 'com.android.support:appcompat-v7:26.1.0'
compile 'com.android.support:design:26.1.0'
compile 'com.android.support:support-v4:26.1.0'


问:
angular4:ng-content nested class based selection
As we all know in Angular4 we have support for ng-content.

In this, we can select based upon class, element-name, attributes.

I am trying to select element based upon class :
Here is my consumer component html :

```<code> <my-component>
      <div class = "item">
        <div class = "item-small">small-item content</div>
     <div class = "item-large">large-item content</div>
    </div>

</my-component>
</code>```

Now in my my-component template, I am trying to access div with class item-small.

My my-component template looks as follows:

```<code><div class="my-component">
   <ng-content select = ".item>.item-small"></ng-content>
</div>
</code>```

But it is not returning me anything.
Here is the plunk for this issue:

https://plnkr.co/edit/2hlL2GezNXRoLCD1FAPD?p=preview

What is the best option to handle such cases?

Kindly give right approach to solve this problem.

答:
I'm pretty sure only selectors are supported that directly match elements

This should work

```<code>".item-small"
</code>```

but this not

```<code>".item>.item-small"
</code>```

like with element or directive selectors.

Body:
As we all know in Angular4 we have support for ng-content.

In this, we can select based upon class, element-name, attributes.

I am trying to select element based upon class :
Here is my consumer component html :

 <my-component>

small-item content

large-item content

</my-component>

Now in my my-component template, I am trying to access div with class item-small.

My my-component template looks as follows:

   <ng-content select = ".item>.item-small"></ng-content>

But it is not returning me anything.
Here is the plunk for this issue:

https://plnkr.co/edit/2hlL2GezNXRoLCD1FAPD?p=preview

What is the best option to handle such cases?

Kindly give right approach to solve this problem.

Body:
I'm pretty sure only selectors are supported that directly match elements

This should work

".item-small"

but this not

".item>.item-small"

like with element or directive selectors.


问:
updating enabled-status of QAction
When Delphi introduced actions some years ago now, one of the great advantages was that the status (enabled/disabled) of the action was handled in the event loop, rather than that the programmer had to think about updating these states concommittant to all status changes of the application. For example:

procedure TMyForm.SaveActionUpdate(Sender: TObject)
begin
    (sender as TAction).enabled := self.contentHasChanged();
end;

instead of

procedure TMyForm.onContentChanging(sender: TObject)
begin
    SaveAction.enabled := True;
    SaveAsAction.enabled := True;
    RevertAction ... etc.
end;

Now I am trying to rebuild some of these old Delphi programs in Python using Qt, but so far I have failed to figure out how to enable QActions without resorting to explicitly setting it enabled whenever my content changes. What would be a fruitful approach to do this?

答:
I dived into the VCL to see how it's implemented there. I hesitated whether it would be a good idea to do so, for the concept op this framework may be well different from Qt and put me on the wrong track rather than being helpful. However, the lack of response to this question suggests to me that Qt actions just may not work this way. Which is a pity.

Delphi's VCL actions register themselves on construction in a central list that gets evaluated in the application's idle time in the event loop. This at least I found can be emulated in Qt by using a timer started with timeout 0. Thus I come to this work-around:

```<code>class HFClient(QMainWindow):

    def updateAction(self, action):
        action.setEnabled(False)

class ActionUpdater(QTimer):

    def __init__(self):
        super(ActionUpdater, self).__init__()
        self.members = {}
        self.timeout.connect(self.timerEvent)

    def add(self, action, updateProc):
        self.members[action] = updateProc

    def remove(self, action):
        del self.members[action]

    def timerEvent(self, unused):
        # prevent being the last one to keep the object alive:
        done = [action for action in self.members if sys.getrefcount(action) < 5]
        for action in done:
            self.remove(action)

        # call registered method:
        for action, updateProc in self.members.items():
                updateProc(action)

if __name__ == '__main__':

    app = QApplication(sys.argv)
    w   = HFClient()
    w.show()

    updater = ActionUpdater()
    updater.start()

    a = QAction("save as", app)
    updater.add(a, w.updateAction)
#     del a
    app.exec()
</code>```

Memory managed programming languages are a bit hard to have the objects unregistered again when the registered object is done for. All too easily the object is kept alive because it still has a reference in the register. I tried to circumvent this by checking the refcount vs. the number of references within the updater instance. I would value a better method for this, though.

One could make a QAction descendant that would register itself (and maybe a signal slot combination for updating).

UPDATE

To use the conventional signal-slot mechanism, descend from Action like

```<code>class UpdatedAction(QAction):
    update = pyqtSignal(QAction)

    def getUpdated(self):
        self.update.emit(self)
</code>```

Weakrefs solve the reference counting issue in the code above:

```<code>class ActionUpdater(QTimer):

    def __init__(self):
        super(ActionUpdater, self).__init__()
        self.members = []
        self.timeout.connect(self.timerEvent)

    def add(self, action):
        self.members.append(weakref.ref(action, self.remove))

    def remove(self, action):
        self.members.remove(action)

    def timerEvent(self, unused):
        # call registered method:
        for action in self.members:
            action().getUpdated()
</code>```

Title: updating enabled-status of QAction

Body:
I dived into the VCL to see how it's implemented there. I hesitated whether it would be a good idea to do so, for the concept op this framework may be well different from Qt and put me on the wrong track rather than being helpful. However, the lack of response to this question suggests to me that Qt actions just may not work this way. Which is a pity.

Delphi's VCL actions register themselves on construction in a central list that gets evaluated in the application's idle time in the event loop. This at least I found can be emulated in Qt by using a timer started with timeout 0. Thus I come to this work-around:

class HFClient(QMainWindow):

    def updateAction(self, action):
        action.setEnabled(False)

class ActionUpdater(QTimer):

    def __init__(self):
        super(ActionUpdater, self).__init__()
        self.members = {}
        self.timeout.connect(self.timerEvent)

    def add(self, action, updateProc):
        self.members[action] = updateProc

    def remove(self, action):
        del self.members[action]

    def timerEvent(self, unused):
        # prevent being the last one to keep the object alive:
        done = [action for action in self.members if sys.getrefcount(action) < 5]
        for action in done:
            self.remove(action)

        # call registered method:
        for action, updateProc in self.members.items():
                updateProc(action)

if __name__ == '__main__':

    app = QApplication(sys.argv)
    w   = HFClient()
    w.show()

    updater = ActionUpdater()
    updater.start()

    a = QAction("save as", app)
    updater.add(a, w.updateAction)
#     del a
    app.exec()

Memory managed programming languages are a bit hard to have the objects unregistered again when the registered object is done for. All too easily the object is kept alive because it still has a reference in the register. I tried to circumvent this by checking the refcount vs. the number of references within the updater instance. I would value a better method for this, though.

One could make a QAction descendant that would register itself (and maybe a signal slot combination for updating).

UPDATE

To use the conventional signal-slot mechanism, descend from Action like

class UpdatedAction(QAction):
    update = pyqtSignal(QAction)

    def getUpdated(self):
        self.update.emit(self)

Weakrefs solve the reference counting issue in the code above:

class ActionUpdater(QTimer):

    def __init__(self):
        super(ActionUpdater, self).__init__()
        self.members = []
        self.timeout.connect(self.timerEvent)

    def add(self, action):
        self.members.append(weakref.ref(action, self.remove))

    def remove(self, action):
        self.members.remove(action)

    def timerEvent(self, unused):
        # call registered method:
        for action in self.members:
            action().getUpdated()


问:
iOS App isn't able to find framework header files
I have a Cocoa Touch framework created in Obj-C, I have built it for simulator as well as for arm7, 7s, 64 and it is a fat framework.

After adding this framework to the test project by dragging, when I try to add header file through import it autocompletes, yet Xcode is unable to locate those files and returns an error.

I have tried adding search paths as well but to no avail, Xcode just doesn't find those files.

I have made all those headers public while creating framework, have tested with an embedded test app it works

Here are Xcode images

答:
I used to get this issue when I was using the library provided by a third party.And you should have noticed that the related .framework file was marked with a question mark, which might not be recognized by the XCode and appeared to be the same issue as I met.

My solution was right clicked the .framework file and deleted it, and then added the original file again until the question mark was disappeared.

Good luck.


问:
How to automatically scale graph to fit it on Y axis?
I have almost finished Line graph, and I want to fit screen it on Y axis. MIN\MAX Peak values should touch top and bottom corner of the graph. How to do this?</p>

答:
Find minimum and maximum in your DataSet and use

```<code>chart.getAxisLeft().setAxisMinimum(0f);
chart.getAxisLeft().setAxisMaximum(100f);
</code>```

to set the boundaries accordingly.

Body:
Find minimum and maximum in your DataSet and use

chart.getAxisLeft().setAxisMinimum(0f);
chart.getAxisLeft().setAxisMaximum(100f);

to set the boundaries accordingly.