问:
Scala Compiler - How to inspect symbol table?
As far as I know, the state of compiler consists of the AST and the symbol table.  I can inspect the AST with -Xprint or -Ybrowse. How can I inspect the symbol table? </p>

答:
Part of the solution (code snippet included) at
http://www.scala-lang.org/node/5763</p>


来源: stackexchange

问:
How to communicate between two process and two hosts using UDP datagrams on Android
My distributed application, with various hosts need to find local servers within the same LAN.

I had limited success detecting local servers using NsdManager, which is the way to go, but often, servers remain undetected. I am looking for a better solution, something more reliable.

Then I attempted to multicast UDP packets, which I have no problem detecting from within the same process. (My unit test uses both client and servers instances). That works fine. The same classes will not allow my clients to detect my servers running on the same device (client and servers are separate process applications).

Then I varied my approach using broadcast addresses, again, within the same process, unit tests are fine, but in two distinct process, no server found.

As I said, the code works fine within the same process, but they do not work when running in two distinct processes, or on two distinct client / server hosts within the same LAN.

Note: my LAN is a high end WiFi rooter, no special settings.

Anyone has any clue what might be the problem?

Note that my manifest includes these settings for both client and server applications:

```<code><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
</code>```

Note that for my client to detect the server running on the same Host, I am already using TCP sockets, but I need to detect whatever server is in my LAN.

答: UDP communication cannot depend on any kind of processes. The problem is with your code.</p>

ContentLicense: CC BY-SA 3.0

Body:
My distributed application, with various hosts need to find local servers within the same LAN.

I had limited success detecting local servers using NsdManager, which is the way to go, but often, servers remain undetected. I am looking for a better solution, something more reliable.

Then I attempted to multicast UDP packets, which I have no problem detecting from within the same process. (My unit test uses both client and servers instances). That works fine. The same classes will not allow my clients to detect my servers running on the same device (client and servers are separate process applications).

Then I varied my approach using broadcast addresses, again, within the same process, unit tests are fine, but in two distinct process, no server found.

As I said, the code works fine within the same process, but they do not work when running in two distinct processes, or on two distinct client / server hosts within the same LAN.

Note: my LAN is a high end WiFi rooter, no special settings.

Anyone has any clue what might be the problem?

Note that my manifest includes these settings for both client and server applications:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

Note that for my client to detect the server running on the same Host, I am already using TCP sockets, but I need to detect whatever server is in my LAN.


问:
Why Is This CSS Not Being Applied When Live?
I am running the website www.gp2aus.com. When I have updated the foot on the site it shows up perfectly through Dreamweaver when I then click to view in Chrome but when I use Filezilla (FZ) to upload to the server it seems to ignore the pertaining CSS.

So far I have tried:

Updating both the public.html files and another file in FZ

Closing down FZ, reconnecting and resetting FZ to update the CSS file completely

Waiting for half an hour just incase there was some delay in the larger main.css file transferring over (I realise this was just a 'hit & hope'!

Using an online HTML and CSS difference-checker to ensure all of the code created vs uploaded is all the same and these is no difference to any HTML or CSS files

Any ideas what I could consider trying next? I will attach the relevant code below:

HTML

```<code><!-- Footer -->
    <span align="right">
        <ul class="footer">
            <li id="copyright-left">SS Web Designs 2017 All rights reserved.</li>
            <li id="copyright-right"><a href="privacy-policy.html">Privacy Policy</a> | <a href="disclaimer.html">Disclaimer</a> | <a href="termsandconditions.html">Terms & Conditions</a></li>
        </ul>
    </span>
</code>```

CSS

```<code>/* Footer */

ul.footer {
    cursor: default;
    list-style: none;
    padding-left: 0;
    font-size: 0.9em;
    margin-bottom: -3em;
}

ul.footer a {
    color: inherit;
}

    ul.footer li {
        display: inline-block;
        padding: 0 1em 0 0;
        vertical-align: middle;
    }

        ul.footer li:last-child {
            padding-right: 0;
        }

            #copyright-left {
                float: left;
            }

            #copyright-right {
                float: inherit;
            }
</code>```

Even my JSFiddle seems to come out ok.

https://jsfiddle.net/cyum4cw9/

Hmmmmmmmm...

Thanks for the collective wisdom all!

答:
The CSS could possibly be cached in your browser or server side. Try clearing the cache on your browser by pressing CTRL + SHFT + DEL.

edit:
if the image at https://i.stack.imgur.com/PozxO.png is your desired result, this is how your web page is displayed on my browser.

Body:
I am running the website www.gp2aus.com. When I have updated the foot on the site it shows up perfectly through Dreamweaver when I then click to view in Chrome but when I use Filezilla (FZ) to upload to the server it seems to ignore the pertaining CSS.

So far I have tried:

Updating both the public.html files and another file in FZ

Closing down FZ, reconnecting and resetting FZ to update the CSS file completely

Waiting for half an hour just incase there was some delay in the larger main.css file transferring over (I realise this was just a 'hit & hope'!

Using an online HTML and CSS difference-checker to ensure all of the code created vs uploaded is all the same and these is no difference to any HTML or CSS files

Any ideas what I could consider trying next? I will attach the relevant code below:

HTML

SS Web Designs 2017 All rights reserved.

Privacy Policy | Disclaimer | Terms & Conditions

CSS

/* Footer */

ul.footer {
    cursor: default;
    list-style: none;
    padding-left: 0;
    font-size: 0.9em;
    margin-bottom: -3em;
}

ul.footer a {
    color: inherit;
}

    ul.footer li {
        display: inline-block;
        padding: 0 1em 0 0;
        vertical-align: middle;
    }

        ul.footer li:last-child {
            padding-right: 0;
        }

            #copyright-left {
                float: left;
            }

            #copyright-right {
                float: inherit;
            }

Even my JSFiddle seems to come out ok.

https://jsfiddle.net/cyum4cw9/

Hmmmmmmmm...

Thanks for the collective wisdom all!


问:
Pandas add column with formula using value of other column
I have a existing df. I want to extend it with a column RSI.
RSI is calculated using a function rsi_func(close) which returns a number. I've tried the official pandas doc see coding 2) and 3) and Stackoverflow answer, see coding 7) and many other examples, I can't get it to work.
I've tried, without the numbering of course:

```<code>    1)  df['RSI'] = rsi_func(df['close'])
    2)  df.assign(RSI=lambda x: rsi_func(close))
    3a) rsi = rsi_func(df['close'])
    3b) print(rsi)
    3c) df.assign(RSI=rsi)
    4)  df.assign(RSI=rsi_func(df['close']))
    5)  df.assign(RSI=lambda x: rsi_func(close))
    6)  df['RSI'] = df.apply(lambda x: rsi_func(x['close']))
    7)  df['RSI'] = df['close'].apply(rsi_func)
</code>```

When I try 3a+b+c then a python list with RSI values is printed. But 3c doesn't append RSI to df. How can I create RSI with the return of rsi_func(close) and append it to df?

答:
You can use map with the lambda expression

```<code>df['RSI'] = df['close'].map(lambda x: rsi_func(x))
</code>```

Test using basic dataframe:

```<code>def rsi_func(close):
    return close /10
df['RSI'] = df['close'].map(lambda x: rsi_func(x))
df
Out[11]:
    close    RSI
0  20.02  2.002
1  20.04  2.004
2  20.05  2.005
</code>```

Body:
I have a existing df. I want to extend it with a column RSI.
RSI is calculated using a function rsi_func(close) which returns a number. I've tried the official pandas doc see coding 2) and 3) and Stackoverflow answer, see coding 7) and many other examples, I can't get it to work.
I've tried, without the numbering of course:

    1)  df['RSI'] = rsi_func(df['close'])
    2)  df.assign(RSI=lambda x: rsi_func(close))
    3a) rsi = rsi_func(df['close'])
    3b) print(rsi)
    3c) df.assign(RSI=rsi)
    4)  df.assign(RSI=rsi_func(df['close']))
    5)  df.assign(RSI=lambda x: rsi_func(close))
    6)  df['RSI'] = df.apply(lambda x: rsi_func(x['close']))
    7)  df['RSI'] = df['close'].apply(rsi_func)

When I try 3a+b+c then a python list with RSI values is printed. But 3c doesn't append RSI to df. How can I create RSI with the return of rsi_func(close) and append it to df?

Body:
You can use map with the lambda expression

df['RSI'] = df['close'].map(lambda x: rsi_func(x))

Test using basic dataframe:

def rsi_func(close):
    return close /10
df['RSI'] = df['close'].map(lambda x: rsi_func(x))
df
Out[11]:
    close    RSI
0  20.02  2.002
1  20.04  2.004
2  20.05  2.005


问:
Inserting string into specific part of a javascript file
I need to change one specific section of a javascript file by inserting a string, with python. Here is a small sample of the javascript file.

```<code>//----------------------------------------Peter Lighting Priorities-----------------------------------------------------
/*

// Lighting low prios for everything else//
peter_RenderBoy_lighting_lowPrios = {
    "fromProductionGroups" : ["peter_RenderBoy_lighting"],
    "matchFilters" : [
        {"user": "", "name": ""}

    ],
    "toProductionGroup" : "",
    "priority" : 3

};

moveAndPrioritise(peter_RenderBoy_lighting_lowPrios);

// lighting normal and Approved LFL shots (emailed at 8pm) //
peter_RenderBoy_lighting_normalPrios = {
    "fromProductionGroups" : ["peter_RenderBoy_lighting"],
    "matchFilters" : [
        {"user": "", "name": ""}

    ],
    "toProductionGroup" : "",
    "priority" : 2

};

moveAndPrioritise(peter_RenderBoy_lighting_normalPrios);
</code>```

Here is the same sample of javascript showing the string "INSERT_STRING_HERE" in bold where it needs to be inserted:

```<code>//----------------------------------------Peter Lighting Priorities-----------------------------------------------------
/*

// Lighting low prios for everything else//
peter_RenderBoy_lighting_lowPrios = {
    "fromProductionGroups" : ["peter_RenderBoy_lighting"],
    "matchFilters" : [
        {"user": "", "name": ""}

    ],
    "toProductionGroup" : "",
    "priority" : 3

};

moveAndPrioritise(peter_RenderBoy_lighting_lowPrios);

// lighting normal and Approved LFL shots (emailed at 8pm) //
peter_RenderBoy_lighting_normalPrios = {
    "fromProductionGroups" : ["peter_RenderBoy_lighting"],
    "matchFilters" : [
        {"user": "", "name": "***INSERT_STRING_HERE***"}

    ],
    "toProductionGroup" : "",
    "priority" : 2

};

moveAndPrioritise(peter_RenderBoy_lighting_normalPrios);
</code>```

This was my attempt so far, which merely shows that I've imported regex, but since gave up on my efforts with that, and am trying to loop through the  javascript file, but don't know how to proceed to achieve what I need:

```<code>import re
javascript_file = open('/depts/wranglers/frankie/farmtools/priorities/autoHook.js')
for line in javascript_file:
    if '// lighting normal and Approved LFL shots (emailed at 8pm) //' in line:
</code>```

答:
When you see that comment line, set a variable. Then when you see the line with the pattern you want to replace, check whether the variable is set, and do the replacement.</p>

```<code>with open('/depts/wranglers/frankie/farmtools/priorities/autoHook.js') as javascript_file, \
     open('/depts/wranglers/frankie/farmtools/priorities/autoHook.new.js') as new_file
    section_found = False
    for line in javascript_file:
        if '// lighting normal and Approved LFL shots (emailed at 8pm) //' in line:
            section_found = True
        elif '{"user": "", "name": ""}' and section_found:
            line = line.replace('"name": ""', '"name": "INSERT_STRING_HERE"')
            section_found = False
        new_file.write(line + "\n")
</code>```

Body:
I need to change one specific section of a javascript file by inserting a string, with python. Here is a small sample of the javascript file.

//----------------------------------------Peter Lighting Priorities-----------------------------------------------------
/*

// Lighting low prios for everything else//
peter_RenderBoy_lighting_lowPrios = {
    "fromProductionGroups" : ["peter_RenderBoy_lighting"],
    "matchFilters" : [
        {"user": "", "name": ""}

    ],
    "toProductionGroup" : "",
    "priority" : 3

};

moveAndPrioritise(peter_RenderBoy_lighting_lowPrios);

// lighting normal and Approved LFL shots (emailed at 8pm) //
peter_RenderBoy_lighting_normalPrios = {
    "fromProductionGroups" : ["peter_RenderBoy_lighting"],
    "matchFilters" : [
        {"user": "", "name": ""}

    ],
    "toProductionGroup" : "",
    "priority" : 2

};

moveAndPrioritise(peter_RenderBoy_lighting_normalPrios);

Here is the same sample of javascript showing the string "INSERT_STRING_HERE" in bold where it needs to be inserted:

//----------------------------------------Peter Lighting Priorities-----------------------------------------------------
/*

// Lighting low prios for everything else//
peter_RenderBoy_lighting_lowPrios = {
    "fromProductionGroups" : ["peter_RenderBoy_lighting"],
    "matchFilters" : [
        {"user": "", "name": ""}

    ],
    "toProductionGroup" : "",
    "priority" : 3

};

moveAndPrioritise(peter_RenderBoy_lighting_lowPrios);

// lighting normal and Approved LFL shots (emailed at 8pm) //
peter_RenderBoy_lighting_normalPrios = {
    "fromProductionGroups" : ["peter_RenderBoy_lighting"],
    "matchFilters" : [
        {"user": "", "name": "***INSERT_STRING_HERE***"}

    ],
    "toProductionGroup" : "",
    "priority" : 2

};

moveAndPrioritise(peter_RenderBoy_lighting_normalPrios);

This was my attempt so far, which merely shows that I've imported regex, but since gave up on my efforts with that, and am trying to loop through the  javascript file, but don't know how to proceed to achieve what I need:

import re
javascript_file = open('/depts/wranglers/frankie/farmtools/priorities/autoHook.js')
for line in javascript_file:
    if '// lighting normal and Approved LFL shots (emailed at 8pm) //' in line:

Body:
When you see that comment line, set a variable. Then when you see the line with the pattern you want to replace, check whether the variable is set, and do the replacement.

with open('/depts/wranglers/frankie/farmtools/priorities/autoHook.js') as javascript_file, \
     open('/depts/wranglers/frankie/farmtools/priorities/autoHook.new.js') as new_file
    section_found = False
    for line in javascript_file:
        if '// lighting normal and Approved LFL shots (emailed at 8pm) //' in line:
            section_found = True
        elif '{"user": "", "name": ""}' and section_found:
            line = line.replace('"name": ""', '"name": "INSERT_STRING_HERE"')
            section_found = False
        new_file.write(line + "\n")


问:
AdMob Interstitial stopped working
The Interstitial ad was working properly and after two days of testing it stopped working. I have the error: Possible Unhandled Promise Rejection (id: 0): Error: Request Error: No ad to show from all configured ad networks. This error is only for the Interstitial ad. I have AdMobBanner but it's working perfectly fine. For both I use the test ids from https://developers.google.com/admob/ios/test-ads. I have tried to create different app but it's the same. Also have tried with real ad but again not working. It's not working on both platform - iOS & Android. My AdMob account is not banned or showing any warning messages. I am using https://github.com/sbugert/react-native-admob with the following code:

```<code>AdMobInterstitial.setAdUnitID('ca-app-pub-3940256099942544/4411468910');
AdMobInterstitial.setTestDevices([AdMobInterstitial.simulatorId]);
AdMobInterstitial.requestAd().then(() => AdMobInterstitial.showAd());
</code>```

As I said it was working for two days.

答:
There appears to be an issue with the interstitial ad server that is causing this problem that appears to be cross-platform. It relates to a no ads fill issue, even with test ads. I’m on Android and experiencing the same problem. Like many others, I have flagged this up with Google and they’ve responded and appear to be working on it as we speak, we hope!

Stay tuned to this thread and hopefully we’ll get an update shortly: Google AdMob Forum

Title: AdMob Interstitial stopped working

Body:
The Interstitial ad was working properly and after two days of testing it stopped working. I have the error: Possible Unhandled Promise Rejection (id: 0): Error: Request Error: No ad to show from all configured ad networks. This error is only for the Interstitial ad. I have AdMobBanner but it's working perfectly fine. For both I use the test ids from https://developers.google.com/admob/ios/test-ads. I have tried to create different app but it's the same. Also have tried with real ad but again not working. It's not working on both platform - iOS & Android. My AdMob account is not banned or showing any warning messages. I am using https://github.com/sbugert/react-native-admob with the following code:

AdMobInterstitial.setAdUnitID('ca-app-pub-3940256099942544/4411468910');
AdMobInterstitial.setTestDevices([AdMobInterstitial.simulatorId]);
AdMobInterstitial.requestAd().then(() => AdMobInterstitial.showAd());

As I said it was working for two days.


问:
Android studio error: An error occurred while trying to compute required packages
I'm trying to install the latest Android Studio on a MacBook pro 2015

Unfortunately I get this error:

An error occurred while trying to compute required packages.

Here a screenshot of the error:

which is not very informative. What's causing the problem?

EDIT

This is the exception I get when I run the application from the terminal:

```<code>[  33666]   WARN - e.wizard.InstallComponentsPath - Dependant package with key emulator not found!
com.android.tools.idea.sdk.wizard.SdkQuickfixUtils$PackageResolutionException: Dependant package with key emulator not found!
    at com.android.tools.idea.sdk.wizard.SdkQuickfixUtils.resolve(SdkQuickfixUtils.java:261)
    at com.android.tools.idea.welcome.install.ComponentInstaller.getPackagesToInstall(ComponentInstaller.java:51)
    at com.android.tools.idea.welcome.wizard.InstallComponentsPath.lambda$init$0(InstallComponentsPath.java:195)
    at com.android.tools.idea.welcome.wizard.InstallSummaryStep.generateSummary(InstallSummaryStep.java:115)
    at com.android.tools.idea.welcome.wizard.InstallSummaryStep.onEnterStep(InstallSummaryStep.java:106)
    at com.android.tools.idea.wizard.dynamic.DynamicWizardPath.next(DynamicWizardPath.java:311)
    at com.android.tools.idea.wizard.dynamic.DynamicWizardPath.next(DynamicWizardPath.java:58)
    at com.android.tools.idea.wizard.dynamic.DynamicWizard.showNextStep(DynamicWizard.java:346)
    at com.android.tools.idea.wizard.dynamic.DynamicWizard.doNextAction(DynamicWizard.java:336)
    at com.android.tools.idea.welcome.wizard.FirstRunWizardHost$NextAction.actionPerformed(FirstRunWizardHost.java:385)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6533)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
    at java.awt.Component.processEvent(Component.java:6298)
    at java.awt.Container.processEvent(Container.java:2236)
    at java.awt.Component.dispatchEventImpl(Component.java:4889)
    at java.awt.Container.dispatchEventImpl(Container.java:2294)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
    at java.awt.Container.dispatchEventImpl(Container.java:2280)
    at java.awt.Window.dispatchEventImpl(Window.java:2746)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
    at java.awt.EventQueue$4.run(EventQueue.java:731)
    at java.awt.EventQueue$4.run(EventQueue.java:729)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
    at com.intellij.ide.IdeEventQueue.defaultDispatchEvent(IdeEventQueue.java:795)
    at com.intellij.ide.IdeEventQueue._dispatchEvent(IdeEventQueue.java:627)
    at com.intellij.ide.IdeEventQueue.dispatchEvent(IdeEventQueue.java:387)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
</code>```

EDIT

Google has fixed the bug. Just download the new installer and everything should be fine

答:
I was getting this error on Arch Linux because the SDK setup wizard ran out of space on /tmp, which is a tmpfs.

Another question with a similar error and same possible cause: Android studio- “SDK tools directory is missing”

Body:
I'm trying to install the latest Android Studio on a MacBook pro 2015

Unfortunately I get this error:

An error occurred while trying to compute required packages.

Here a screenshot of the error:

which is not very informative. What's causing the problem?

EDIT

This is the exception I get when I run the application from the terminal:

[  33666]   WARN - e.wizard.InstallComponentsPath - Dependant package with key emulator not found!
com.android.tools.idea.sdk.wizard.SdkQuickfixUtils$PackageResolutionException: Dependant package with key emulator not found!
    at com.android.tools.idea.sdk.wizard.SdkQuickfixUtils.resolve(SdkQuickfixUtils.java:261)
    at com.android.tools.idea.welcome.install.ComponentInstaller.getPackagesToInstall(ComponentInstaller.java:51)
    at com.android.tools.idea.welcome.wizard.InstallComponentsPath.lambda$init$0(InstallComponentsPath.java:195)
    at com.android.tools.idea.welcome.wizard.InstallSummaryStep.generateSummary(InstallSummaryStep.java:115)
    at com.android.tools.idea.welcome.wizard.InstallSummaryStep.onEnterStep(InstallSummaryStep.java:106)
    at com.android.tools.idea.wizard.dynamic.DynamicWizardPath.next(DynamicWizardPath.java:311)
    at com.android.tools.idea.wizard.dynamic.DynamicWizardPath.next(DynamicWizardPath.java:58)
    at com.android.tools.idea.wizard.dynamic.DynamicWizard.showNextStep(DynamicWizard.java:346)
    at com.android.tools.idea.wizard.dynamic.DynamicWizard.doNextAction(DynamicWizard.java:336)
    at com.android.tools.idea.welcome.wizard.FirstRunWizardHost$NextAction.actionPerformed(FirstRunWizardHost.java:385)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6533)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
    at java.awt.Component.processEvent(Component.java:6298)
    at java.awt.Container.processEvent(Container.java:2236)
    at java.awt.Component.dispatchEventImpl(Component.java:4889)
    at java.awt.Container.dispatchEventImpl(Container.java:2294)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
    at java.awt.Container.dispatchEventImpl(Container.java:2280)
    at java.awt.Window.dispatchEventImpl(Window.java:2746)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
    at java.awt.EventQueue$4.run(EventQueue.java:731)
    at java.awt.EventQueue$4.run(EventQueue.java:729)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
    at com.intellij.ide.IdeEventQueue.defaultDispatchEvent(IdeEventQueue.java:795)
    at com.intellij.ide.IdeEventQueue._dispatchEvent(IdeEventQueue.java:627)
    at com.intellij.ide.IdeEventQueue.dispatchEvent(IdeEventQueue.java:387)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

EDIT

Google has fixed the bug. Just download the new installer and everything should be fine


问:
How do "invisible" function parameters in Haskell work?
An example of what I am talking about is takeWhile

```<code>takeWhile :: (a -> Bool) -> [a] -> [a]
</code>```

Example usage

```<code>takeWhile (< 3) [1,2,3,4,1,2,3,4] == [1,2]
</code>```

From what I can tell (< 3) becomes (a < 3) where a is the current item in the list being checked.

How is this done in Haskell and how would I be able to move where a goes so I could do something like

```<code>takeWhile ((length a) < 4) ["aaa", "aaaaa"]
</code>```

答:
There go nowhere, you have to remember that every function in Haskell is currified, so, think in the (+) function, you can do the next, think in the type first:

```<code>(+) :: Num a => a -> a -> a
</code>```

now I can do my custom plusOne, plusTwo, etc, so fast thanks to the curryfication, because

```<code>(+) :: Num a => a -> a -> a
</code>```

has "implicit paranthesis" and really looks like:

```<code>(+) :: Num a => a -> (a -> a)
</code>```

meaning give me a number a give you a function back, so:

```<code>plusOne :: Num a => a -> a
plusOne = (+1)

plusTwo :: Num a => a -> a
plusTwo = (+2)
</code>```

Can you see? you transform the (+) in a new function by giving to it just one of the two parameters, same happens with < and  >  functions, you can create the function greaterThanTen like this:

```<code>greaterThanTen :: (Num a, Ord a) => a -> a
greaterThanTen = (>10)
</code>```

So in your example of takeWhile (< 3) your (< 3) is the function "less than 3", and if you "read" all the function would be "take while n is less than 3"

you can play around with it in the console by asking the types with :t command

```<code>  :t (< 3)
(< 3) :: (Num a, Ord a) => a -> Bool
</code>```

Body:
An example of what I am talking about is takeWhile

takeWhile :: (a -> Bool) -> [a] -> [a]

Example usage

takeWhile (< 3) [1,2,3,4,1,2,3,4] == [1,2]

From what I can tell (< 3) becomes (a < 3) where a is the current item in the list being checked.

How is this done in Haskell and how would I be able to move where a goes so I could do something like

takeWhile ((length a) < 4) ["aaa", "aaaaa"]

Body:
There go nowhere, you have to remember that every function in Haskell is currified, so, think in the (+) function, you can do the next, think in the type first:

(+) :: Num a => a -> a -> a

now I can do my custom plusOne, plusTwo, etc, so fast thanks to the curryfication, because

(+) :: Num a => a -> a -> a

has "implicit paranthesis" and really looks like:

(+) :: Num a => a -> (a -> a)

meaning give me a number a give you a function back, so:

plusOne :: Num a => a -> a
plusOne = (+1)

plusTwo :: Num a => a -> a
plusTwo = (+2)

Can you see? you transform the (+) in a new function by giving to it just one of the two parameters, same happens with < and  >  functions, you can create the function greaterThanTen like this:

greaterThanTen :: (Num a, Ord a) => a -> a
greaterThanTen = (>10)

So in your example of takeWhile (< 3) your (< 3) is the function "less than 3", and if you "read" all the function would be "take while n is less than 3"

you can play around with it in the console by asking the types with :t command

  :t (< 3)
(< 3) :: (Num a, Ord a) => a -> Bool


问:
Can we call a number in middle of a conference call in Twilio?
I am new in this field. coming to question. I want to call a number during the conference call and add that participant to the current conference.
I have tried a sample code for the conference given here in Java. Is there any way to gather the input then call the number and add the participant to the same conference.

here is what I tried. I have created a conference and which will return the following response

```<code><Response>
<Dial hangupOnStar="true">
<Conference startConferenceOnEnter="true" endConferenceOnExit="true">My Conference</Conference>
</Dial>
<Gather timeout="10" action="/twilio-tut/add/participant?confName=My%20Conference" finishOnKey="#">
<Say>Please enter the number you want to connect followed by hash key.</Say></Gather>
</Response>
</code>```

Now One of the participants in conference say A press * and dialed a number of another person to whom he wants to add to the conference.

Now on action of Gather verb, I am dialing a number the code as shown below

```<code>Number number =
                    new Number.Builder(some_valid_phone_number)
                    .statusCallback("https://xxxxxxx.ngrok.io/twilio-tut/to/conference")
                    .statusCallbackMethod(Method.POST)
                    .statusCallbackEvents(Arrays.asList(Event.ANSWERED))
                    .build();

            Dial dial = new Dial.Builder()
                    .number(number)
                    .conference(new Conference.Builder(conferenceName).build())
                    .build();

            twiml = new VoiceResponse.Builder().dial(dial)
                    .build();
</code>```

On statusCallback, I am updating the call to redirect to conference for both caller and callee where caller is the one who left the conference by pressing * i.e. A and callee is some_valid_phone_number. Code is as shown below

```<code>Call callee = Call.updater(callSid)
                    .setUrl("https://xxxxx.ngrok.io/twilio-tut/voice").setMethod(HttpMethod.POST).update();
            Call caller = Call.updater(parentCallSid)
                    .setUrl("https://xxxxx.ngrok.io/twilio-tut/voice").setMethod(HttpMethod.POST).update();
</code>```

above code transfer the callee and disconnect the caller with Exception

```<code>com.twilio.exception.ApiException: Call is not in-progress. Cannot redirect.
</code>```

What I want to do is A call some other number and finally they will connect to same conference. And A should be capable of calling other numbers and add them in same conference. I am using mobile phone to connect the numbers.

Thanks in advance.

答:
Twilio employee here.

You can! What you can do is make an outbound call using the REST API, and have that call return TwiML with the Conference verb, and the same conference name - e.g, if you've created a conference call named conference1 you'll want to respond with TwiML that looks something like:

```<code><Response>
    <Dial>
        <Conference>conference1</Conference>
    </Dial>
</Response>
</code>```

That will connect the outbound call to the existing conference, or create it.

If you're using the <Gather> verb for input on an existing call, then you can use this solution as well. You want to redirect the call flow, not create a whole new call, so just return this TwiML in the Gather callback.

If you've kept track of the Conference SID, you could also programmatically add them by creating an outbound conference call (sample code here). Similarly to the TwiML, if the conference call doesn't exist, Twilio will create it; if it does exist, Twilio will add the person to it.

Body:
I am new in this field. coming to question. I want to call a number during the conference call and add that participant to the current conference.
I have tried a sample code for the conference given here in Java. Is there any way to gather the input then call the number and add the participant to the same conference.

here is what I tried. I have created a conference and which will return the following response

<Response>
<Dial hangupOnStar="true">
<Conference startConferenceOnEnter="true" endConferenceOnExit="true">My Conference</Conference>
</Dial>
<Gather timeout="10" action="/twilio-tut/add/participant?confName=My%20Conference" finishOnKey="#">
<Say>Please enter the number you want to connect followed by hash key.</Say></Gather>
</Response>

Now One of the participants in conference say A press * and dialed a number of another person to whom he wants to add to the conference.

Now on action of Gather verb, I am dialing a number the code as shown below

Number number =
                    new Number.Builder(some_valid_phone_number)
                    .statusCallback("https://xxxxxxx.ngrok.io/twilio-tut/to/conference")
                    .statusCallbackMethod(Method.POST)
                    .statusCallbackEvents(Arrays.asList(Event.ANSWERED))
                    .build();

            Dial dial = new Dial.Builder()
                    .number(number)
                    .conference(new Conference.Builder(conferenceName).build())
                    .build();

            twiml = new VoiceResponse.Builder().dial(dial)
                    .build();

On statusCallback, I am updating the call to redirect to conference for both caller and callee where caller is the one who left the conference by pressing * i.e. A and callee is some_valid_phone_number. Code is as shown below

Call callee = Call.updater(callSid)
                    .setUrl("https://xxxxx.ngrok.io/twilio-tut/voice").setMethod(HttpMethod.POST).update();
            Call caller = Call.updater(parentCallSid)
                    .setUrl("https://xxxxx.ngrok.io/twilio-tut/voice").setMethod(HttpMethod.POST).update();

above code transfer the callee and disconnect the caller with Exception

com.twilio.exception.ApiException: Call is not in-progress. Cannot redirect.

What I want to do is A call some other number and finally they will connect to same conference. And A should be capable of calling other numbers and add them in same conference. I am using mobile phone to connect the numbers.

Thanks in advance.

Body:
Twilio employee here.

You can! What you can do is make an outbound call using the REST API, and have that call return TwiML with the Conference verb, and the same conference name - e.g, if you've created a conference call named conference1 you'll want to respond with TwiML that looks something like:

<Response>
    <Dial>
        <Conference>conference1</Conference>
    </Dial>
</Response>

That will connect the outbound call to the existing conference, or create it.

If you're using the <Gather> verb for input on an existing call, then you can use this solution as well. You want to redirect the call flow, not create a whole new call, so just return this TwiML in the Gather callback.

If you've kept track of the Conference SID, you could also programmatically add them by creating an outbound conference call (sample code here). Similarly to the TwiML, if the conference call doesn't exist, Twilio will create it; if it does exist, Twilio will add the person to it.


问:
C# Console application grid calculation
I am trying to write a console application in C# that counts the number of unique blocks a robot is moving through in a grid on a floor. The input takes instructions for movement using the four compass points such as : N ,E ,S W.

The application processes the amount of blocks the robot travels through once, if the X co-ordinate and Y co-ordinate of the robot's path cross at any time, that block is counted once and not twice. For instance if the robot travels N4, 2E , 2S and 4W, there will be an intersection of x and y on the 2nd block the robot travelled at the beginning of it's movement.

This is what I have so far:

```<code>static void Main(string[] args)
    {

        //List<string> movements = new List<string>();

        int x1 = 0;
        int y1 = 0;

        int x2 = 0;
        int y2 = 0;

        int x3 = 0;
        int y3 = 0;

        int x4 = 0;
        int y4 = 0;

        int N, S, E, W, Total;
        string coordinate1, coordinate2, coordinate3, coordinate4;

        Console.Write("Enter North : ");
        N = int.Parse(Console.ReadLine());

        if(N != 0)
        {
            x1 += 0;
            y1 += N;

        }
        coordinate1 = "(" + x1 + "," + y1 + ")";

        Console.Write("Enter East: ");
        E = int.Parse(Console.ReadLine());

        if (E != 0)
        {
            y3 += 0;
            x3 += E;

        }
        coordinate3 = "(" + x3 + "," + y3 + ")";

        Console.Write("Enter South: ");
        S = int.Parse(Console.ReadLine());

        if (S != 0)
        {
            x2 += 0;
            y2 -= S;

        }

        coordinate2 = "(" + x2 + "," + y2 + ")";

        Console.Write("Enter West: ");
        W = int.Parse(Console.ReadLine());

        if (W != 0)
        {
            y4 += 0;
            x4 -= W;

        }
        coordinate4 = "(" + x4 + "," + y4 + ")";

        if (coordinate1 == coordinate2|| coordinate1== coordinate3 || coordinate1 == coordinate4 || coordinate2 == coordinate3 || coordinate2 == coordinate4 || coordinate3 ==coordinate4 )
        {
            Total = (N + S + E + W) - 1 ;
            Console.WriteLine("The total Blocks travelled are " + Total);
        }

        else
        {
            Total = N + S + E + W;
            Console.WriteLine("The total Blocks travelled are " + Total);
        }

    }
</code>```

答:
You can do it with simple math. And this is simple way if you want more complex i can write it too.</p>

```<code>    int N,S,E,W,Total;
    Console.Write("Enter North : ");
    N=int.Parse(Console.Readline());

    Console.Write("Enter South: ");
    S=int.Parse(Console.Readline());

    Console.Write("Enter East: ");

    E=int.Parse(Console.Readline());

    Console.Write("Enter West: ");
    W=int.Parse(Console.Readline());

    if(N > S)
       Total = N-S;
    else
       Total = S-N;

    if(E > W)
       Total += (E-W)
    else
       Total += (W-E)

    Console.Write("Final Total Step are : "+Total);
</code>```

Title: C# Console application grid calculation

Body:
I am trying to write a console application in C# that counts the number of unique blocks a robot is moving through in a grid on a floor. The input takes instructions for movement using the four compass points such as : N ,E ,S W.

The application processes the amount of blocks the robot travels through once, if the X co-ordinate and Y co-ordinate of the robot's path cross at any time, that block is counted once and not twice. For instance if the robot travels N4, 2E , 2S and 4W, there will be an intersection of x and y on the 2nd block the robot travelled at the beginning of it's movement.

This is what I have so far:

static void Main(string[] args)
    {

        //List<string> movements = new List<string>();

        int x1 = 0;
        int y1 = 0;

        int x2 = 0;
        int y2 = 0;

        int x3 = 0;
        int y3 = 0;

        int x4 = 0;
        int y4 = 0;

        int N, S, E, W, Total;
        string coordinate1, coordinate2, coordinate3, coordinate4;

        Console.Write("Enter North : ");
        N = int.Parse(Console.ReadLine());

        if(N != 0)
        {
            x1 += 0;
            y1 += N;

        }
        coordinate1 = "(" + x1 + "," + y1 + ")";

        Console.Write("Enter East: ");
        E = int.Parse(Console.ReadLine());

        if (E != 0)
        {
            y3 += 0;
            x3 += E;

        }
        coordinate3 = "(" + x3 + "," + y3 + ")";

        Console.Write("Enter South: ");
        S = int.Parse(Console.ReadLine());

        if (S != 0)
        {
            x2 += 0;
            y2 -= S;

        }

        coordinate2 = "(" + x2 + "," + y2 + ")";

        Console.Write("Enter West: ");
        W = int.Parse(Console.ReadLine());

        if (W != 0)
        {
            y4 += 0;
            x4 -= W;

        }
        coordinate4 = "(" + x4 + "," + y4 + ")";

        if (coordinate1 == coordinate2|| coordinate1== coordinate3 || coordinate1 == coordinate4 || coordinate2 == coordinate3 || coordinate2 == coordinate4 || coordinate3 ==coordinate4 )
        {
            Total = (N + S + E + W) - 1 ;
            Console.WriteLine("The total Blocks travelled are " + Total);
        }

        else
        {
            Total = N + S + E + W;
            Console.WriteLine("The total Blocks travelled are " + Total);
        }

    }

Body:
You can do it with simple math. And this is simple way if you want more complex i can write it too.

    int N,S,E,W,Total;
    Console.Write("Enter North : ");
    N=int.Parse(Console.Readline());

    Console.Write("Enter South: ");
    S=int.Parse(Console.Readline());

    Console.Write("Enter East: ");

    E=int.Parse(Console.Readline());

    Console.Write("Enter West: ");
    W=int.Parse(Console.Readline());

    if(N > S)
       Total = N-S;
    else
       Total = S-N;

    if(E > W)
       Total += (E-W)
    else
       Total += (W-E)

    Console.Write("Final Total Step are : "+Total);


问:
PHP count of occurrences of characters of a string within another string
Let's say I have two strings.

```<code>$needle = 'AGUXYZ';
$haystack = 'Agriculture ID XYZ-A';
</code>```

I want to count how often characters that are in $needle occur in $haystack. In $haystack, there are the characters 'A' (twice), 'X', 'Y' and 'Z', all of which are in the needle, thus the result is supposed to be 5 (case-sensitive).

Is there any function for that in PHP or do I have to program it myself?

Thanks in advance!

答:
There is a PHP function substr_count to count the number of instances of a character in a string. It would be trivial to extend it for multiple characters:

```<code>function substr_multi_count ($haystack, $needle, $offset = 0, $length = null) {
    $ret = 0;

    if ($length === null) {
        $length = strlen($haystack) - $offset;
    }

    for ($i = strlen($needle); $i--; ) {
        $ret += substr_count($haystack, $needle, $offset, $length);
    }

    return $ret;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Let's say I have two strings.

$needle = 'AGUXYZ';
$haystack = 'Agriculture ID XYZ-A';

I want to count how often characters that are in $needle occur in $haystack. In $haystack, there are the characters 'A' (twice), 'X', 'Y' and 'Z', all of which are in the needle, thus the result is supposed to be 5 (case-sensitive).

Is there any function for that in PHP or do I have to program it myself?

Thanks in advance!

Body:
There is a PHP function substr_count to count the number of instances of a character in a string. It would be trivial to extend it for multiple characters:

function substr_multi_count ($haystack, $needle, $offset = 0, $length = null) {
    $ret = 0;

    if ($length === null) {
        $length = strlen($haystack) - $offset;
    }

    for ($i = strlen($needle); $i--; ) {
        $ret += substr_count($haystack, $needle, $offset, $length);
    }

    return $ret;
}


答:
The first argument to takeWhile is a predicate; this is your unary function (< 3), which is true, when the argument has numeric semantics and is less than 3. This option is applied to each list member, making up a new list and terminating, when the predicate is not true the first time. The elements, which have passed, make up the result list.

Your example is almost correct, you must only convert it into predicate form, i.e. create an unary function, which is true, when the parameter (a string) has a length less than 4. This can for example done by

```<code>(\a -> (length a) < 4)
</code>```

then

```<code>takeWhile (\a -> (length a) < 4) ["aaa", "aaaaa"]
</code>```

should     do what you expect.

Title: How do "invisible" function parameters in Haskell work?

Body:
The first argument to takeWhile is a predicate; this is your unary function (< 3), which is true, when the argument has numeric semantics and is less than 3. This option is applied to each list member, making up a new list and terminating, when the predicate is not true the first time. The elements, which have passed, make up the result list.

Your example is almost correct, you must only convert it into predicate form, i.e. create an unary function, which is true, when the parameter (a string) has a length less than 4. This can for example done by

(\a -> (length a) < 4)

then

takeWhile (\a -> (length a) < 4) ["aaa", "aaaaa"]

should     do what you expect.


问:
TSQL Conditional Where or Group By?
I have a table like the following:

```<code>id | type        | duedate
-------------------------
 1 | original    | 01/01/2017
 1 | revised     | 02/01/2017
 2 | original    | 03/01/2017
 3 | original    | 10/01/2017
 3 | revised     | 09/01/2017
</code>```

Where there may be either one or two rows for each id.  If there are two rows with same id, there would be one with type='original' and one with type='revised'.  If there is one row for the id, type will always be 'original'.

What I want as a result are all the rows where type='revised', but if there is only one row for a particular id (thus type='original') then I want to include that row too.  So desired output for the above would be:

```<code>id | type        | duedate
 1 | revised     | 02/01/2017
 2 | original    | 03/01/2017
 3 | revised     | 09/01/2017
</code>```

I do not know how to construct a WHERE clause that conditionally checks whether there are 1 or 2 rows for a given id, nor am I sure how to use GROUP BY because the revised date could be greater than or less than than the original date so use of aggregate functions MAX or MIN don't work.  I thought about using CASE somehow, but also do not know how to construct a conditional that chooses between two different rows of data (if there are two rows) and display one of them rather than the other.

Any suggested approaches would be appreciated.

Thanks!

答:
You could use a subquery to take the MAX([type]).  In this case it works for [type] since alphabetically we want revised first, then original and "r" comes after "o" in the alphabet.  We can then INNER JOIN back on the same table with the matching conditions.

```<code>SELECT T2.*
  FROM (
         SELECT id, MAX([type]) AS [MAXtype]
           FROM myTABLE
         GROUP BY id
       ) AS dT INNER JOIN myTable T2 ON dT.id = T2.id AND dT.[MAXtype] = T2.[type]
ORDER BY T2.[id]
</code>```

Gives output:

```<code>id  type      duedate
1   revised   2017-02-01
2   original  2017-03-01
3   revised   2017-09-01
</code>```

Here is the sqlfiddle: http://sqlfiddle.com/#!6/14121f/6/0

Title: TSQL Conditional Where or Group By?

Body:
I have a table like the following:

id | type        | duedate
-------------------------
 1 | original    | 01/01/2017
 1 | revised     | 02/01/2017
 2 | original    | 03/01/2017
 3 | original    | 10/01/2017
 3 | revised     | 09/01/2017

Where there may be either one or two rows for each id.  If there are two rows with same id, there would be one with type='original' and one with type='revised'.  If there is one row for the id, type will always be 'original'.

What I want as a result are all the rows where type='revised', but if there is only one row for a particular id (thus type='original') then I want to include that row too.  So desired output for the above would be:

id | type        | duedate
 1 | revised     | 02/01/2017
 2 | original    | 03/01/2017
 3 | revised     | 09/01/2017

I do not know how to construct a WHERE clause that conditionally checks whether there are 1 or 2 rows for a given id, nor am I sure how to use GROUP BY because the revised date could be greater than or less than than the original date so use of aggregate functions MAX or MIN don't work.  I thought about using CASE somehow, but also do not know how to construct a conditional that chooses between two different rows of data (if there are two rows) and display one of them rather than the other.

Any suggested approaches would be appreciated.

Thanks!

Body:
You could use a subquery to take the MAX([type]).  In this case it works for [type] since alphabetically we want revised first, then original and "r" comes after "o" in the alphabet.  We can then INNER JOIN back on the same table with the matching conditions.

SELECT T2.*
  FROM (
         SELECT id, MAX([type]) AS [MAXtype]
           FROM myTABLE
         GROUP BY id
       ) AS dT INNER JOIN myTable T2 ON dT.id = T2.id AND dT.[MAXtype] = T2.[type]
ORDER BY T2.[id]

Gives output:

id  type      duedate
1   revised   2017-02-01
2   original  2017-03-01
3   revised   2017-09-01

Here is the sqlfiddle: http://sqlfiddle.com/#!6/14121f/6/0


问:
Paste string values from df column into a function
I have a dataset in R organized like so:

```<code>             x freq
1 PRODUCT10000    6
2 PRODUCT10001   20
3 PRODUCT10002   11
4 PRODUCT10003    4
5 PRODUCT10004    1
6 PRODUCT10005    2
</code>```

Then, I have a function like

```<code>fun <- function(number, df1, string, df2){NormC <- as.numeric(df1[string, "normc"])
    df2$NormC <- rep(NormC)}
</code>```

How can I iterate through my df and insert each value of "x" into the function?

I think the problem is that this part of the function (which has 4 input variables) is structured like so- NormC <- as.numeric(df[string, "normc"])

答:
As explained by @duckmayr, you don't need to iterate through column x. Here is an example creating new variable.

```<code>df <- read.table(text = "             x freq
1 PRODUCT10000    6
2 PRODUCT10001   20
3 PRODUCT10002   11
4 PRODUCT10003    4
5 PRODUCT10004    1
6 PRODUCT10005    2", header = TRUE)
fun <- function(string){paste0(string, "X")} # example
# option 1
df$new.col1 <- fun(df$x) # see duckmayr's comment
# option 2
library(data.table)
setDT(df)[, new.col2 := fun(x)]
</code>```

Body:
I have a dataset in R organized like so:

             x freq
1 PRODUCT10000    6
2 PRODUCT10001   20
3 PRODUCT10002   11
4 PRODUCT10003    4
5 PRODUCT10004    1
6 PRODUCT10005    2

Then, I have a function like

fun <- function(number, df1, string, df2){NormC <- as.numeric(df1[string, "normc"])
    df2$NormC <- rep(NormC)}

How can I iterate through my df and insert each value of "x" into the function?

I think the problem is that this part of the function (which has 4 input variables) is structured like so- NormC <- as.numeric(df[string, "normc"])

Body:
As explained by @duckmayr, you don't need to iterate through column x. Here is an example creating new variable.

df <- read.table(text = "             x freq
1 PRODUCT10000    6
2 PRODUCT10001   20
3 PRODUCT10002   11
4 PRODUCT10003    4
5 PRODUCT10004    1
6 PRODUCT10005    2", header = TRUE)
fun <- function(string){paste0(string, "X")} # example
# option 1
df$new.col1 <- fun(df$x) # see duckmayr's comment
# option 2
library(data.table)
setDT(df)[, new.col2 := fun(x)]


问:
Non-void Coroutine Without Return Statement
I am trying to wrap my head around the C++ coroutine feature. I read Kenny's article (C++ - Introducing C++/WinRT) and also tried watching this presentation, CppCon 2016: James McNellis “Introduction to C++ Coroutines". I keep seeing non-void "functions" without some form of return statement. As an example, see the following code sample from Kenny's article. The PrintFeedAsync function/coroutine has an IAsyncAction return type but there is no return statement in the definition. could someone explain how this works?

```<code>IAsyncAction PrintFeedAsync()
{
    Uri uri(L"http://kennykerr.ca/feed");
    SyndicationClient client;
    SyndicationFeed feed = co_await client.RetrieveFeedAsync(uri);
    for (SyndicationItem item : feed.Items())
    {
        hstring title = item.Title().Text();
        printf("%ls\n", title.c_str());
    }
}

int main()
{
    initialize();
    PrintFeedAsync().get();
}
</code>```

答:
For a function to be a coroutine, its return type has to have certain traits defined that describes how the coroutine will work. C++/WinRT defines those traits for their version of IAsyncAction or IAsyncOperation<TResult>. Specifically, there are two methods that handle returning from a coroutine: return_value(...) or return_void(). IAsyncOperation uses the former, and IAsyncAction uses the latter.

Looking at the latest coroutine spec at the time of this answer, we find what happens if there is no co_return statement in the body of a coroutine function:

If p.return_void() is a valid expression, flowing off the end of a coroutine is equivalent to a co_return with no operand; otherwise flowing off the end of a coroutine results in undefined behavior.

–"Programming Languages – C++ Extensions for Coroutines" (N4680) § 6.6.3.1/3

Since C++/WinRT defines a return_void for IAsyncAction's traits then the compiler will follow the above rule. At the end where execution flows off the end of the coroutine, the return_void method is used, the same as if you ended the function with co_return;. If we look at the definition of return_void, we see it's equivalent to setting the status as Completed and calling the completion handler if there is one.

Body:
I am trying to wrap my head around the C++ coroutine feature. I read Kenny's article (C++ - Introducing C++/WinRT) and also tried watching this presentation, CppCon 2016: James McNellis “Introduction to C++ Coroutines". I keep seeing non-void "functions" without some form of return statement. As an example, see the following code sample from Kenny's article. The PrintFeedAsync function/coroutine has an IAsyncAction return type but there is no return statement in the definition. could someone explain how this works?

IAsyncAction PrintFeedAsync()
{
    Uri uri(L"http://kennykerr.ca/feed");
    SyndicationClient client;
    SyndicationFeed feed = co_await client.RetrieveFeedAsync(uri);
    for (SyndicationItem item : feed.Items())
    {
        hstring title = item.Title().Text();
        printf("%ls\n", title.c_str());
    }
}

int main()
{
    initialize();
    PrintFeedAsync().get();
}


问:
Don't allow use of non existent keys on a given flow type
given this simple object: { id: 'x', value: 1 }, in TypeScript if you try to do:

```<code>type foo = {
    id: string,
    v: number,
};

const bar: foo = { id: 'something', v: 1111 };

// refrencing non existent key
if (bar.xyz) {
    console.log('xyz');
}
</code>```

you would get an error saying xyz does not exist on foo. How do you get the same result on Flowjs?

I've tried the following but flowjs isn't throwing any errors:

```<code>type foo = {|
    id: string,
    v: number,
|};

const bar: foo = { id: 'something', v: 1111 };

if (bar.xyz) { // no errors
    console.log('xyz');
}
</code>```

答:
Flow always allows for property checks in ifs. You can use this as a workaround:

```<code>if (!!bar.xyz == true) {
</code>```

Body:
given this simple object: { id: 'x', value: 1 }, in TypeScript if you try to do:

type foo = {
    id: string,
    v: number,
};

const bar: foo = { id: 'something', v: 1111 };

// refrencing non existent key
if (bar.xyz) {
    console.log('xyz');
}

you would get an error saying xyz does not exist on foo. How do you get the same result on Flowjs?

I've tried the following but flowjs isn't throwing any errors:

type foo = {|
    id: string,
    v: number,
|};

const bar: foo = { id: 'something', v: 1111 };

if (bar.xyz) { // no errors
    console.log('xyz');
}

Body:
Flow always allows for property checks in ifs. You can use this as a workaround:

if (!!bar.xyz == true) {


问:
Java: jumbled word program
My program loads two text files: one with a list of English words, another with jumbled words (more just random strings but most make words), then determines what words can be made of the jumbled ones and prints (at least supposed to) the word with its jumbled version next to it. My program effectively finds what words the jumbled words can make up. The problem is not all the words with jumbled equivalents print jumbled word next to them. Also I need the jumbled words on the right unscrambled on the right. Example here's some output (commas separate lines ie if two words in comma they were printed next to each other ;
addej,
ahicryrhe hierarchy,
alvan naval,
annaab banana,
baltoc,
braney nearby,</p>

```<code>   public class Lab4{

    public static void main(String [] args) throws Exception{
        if(args.length<2) {
            Error(); }
        BufferedReader jumbledW = new BufferedReader(new FileReader(args[1]));
        BufferedReader words = new BufferedReader(new FileReader(args[0]));
        List<String> jumbledWList = new ArrayList<>();
        List<String> wList = new ArrayList<>();

        long initialTime = System.currentTimeMillis();

        while(jumbledW.ready()){
            String jumble = jumbledW.readLine();
            jumbledWList.add(jumble);
        }

        Collections.sort(jumbledWList);
        while (words.ready()){
            String word = words.readLine();
            wList.add(word);
        }
        Collections.sort(wList);
        for (String jumble : jumbledWList ) {
            System.out.print(jumble + " ");
            for (String word : wList) {
                if(toConnical(jumble).equals(toConnical(word)))
                    System.out.print(word);

        }
        System.out.println();
        }
        long finalTime = System.currentTimeMillis();
        long time = finalTime - initialTime;
        System.out.println("The time taken for this program to run is " + time/1000.0 + " seconds" );

        }

    private static void Error(){
        System.out.println("\nError:You have to pass the name of the input files on the command line" );
        System.exit(0);
        }

    private static String toConnical(String word){
        char [] arr = word.toCharArray();
        Arrays.sort(arr);
        String connical = new String(arr);
        return connical;
    }
}
</code>```

答:
While skipping through old unanswered posts I had come across this particular question which quite frankly is somewhat unclear as to what the actual problem may be. The way I read the post is this:

A file name is passed to this application through the command line which consists of several jumbled character words. Not certain however whether each line within the file consists of single jumbled words OR each line within the file consists of multiple jumbled words separated with one or more white-spaces (or perhaps even tabs). With this in mind we need to cover either scenario.

Yet another file name is also passed to this application through the command line which consists of several valid language type words. This file is to be considered the Word List to whereas any single jumbled word could pertain to one (or more) of those words within the list if it were unscrambled or not (the word within the Jumbled String list might not be jumbled).

As the Jumbled String list is processed each Word List word that is found to be capable of matching via sorted character to character comparison to the sorted Jumbled word characters is printed to console window.

Console output required is to be a comma delimited string consisting of each jumbled word followed by space delimited matching words from the Word List:

addej jaded, ahicryrhe hierarchy, alvan alvan naval, annaab banana,...etc

This is however appears to now be contradictory to your comment:

"the program is given a txt file of a great deal of english words youd
  find in a dictionary and another txt file with jumbled words such as
  cra which could make car or rat. The output i desire is the in
  reference to the example of cra would be "car cra" (on one line)."

Whereas space delimited Word List words are to come first then the jumbled word processed each consuming a single console window line. Which format is desired? By the way rat can not be achieved from cra.

In reality your code works as expected however since you are using a BufferedReader object and a FileReader object your code will need to be in a try/catch block to handle any exceptions such as the FileNotFoundException and the IOException. This is a requiremnt and can not be excluded.

Below is your code slightly modified to accommodate your first desired output format:

```<code>try {
    BufferedReader jumbledW = new BufferedReader(new FileReader(args[1]));
    BufferedReader words = new BufferedReader(new FileReader(args[0]));
    List<String> jumbledWList = new ArrayList<>();
    List<String> wList = new ArrayList<>();

    long initialTime = System.currentTimeMillis();

    while (jumbledW.ready()) {
        String jumble = jumbledW.readLine();
        jumbledWList.add(jumble);
    }

    Collections.sort(jumbledWList);
    while (words.ready()) {
        String word = words.readLine();
        wList.add(word);
    }
    Collections.sort(wList);

    String resultString = "";
    for (int i = 0; i < jumbledWList.size(); i++){
        String jumble = jumbledWList.get(i);
        resultString+= jumble + ":";
        for (String word : wList) {
            if (toConnical(jumble).equals(toConnical(word))) {
                resultString+= " " + word;
            }
        }
        if (i != (jumbledWList.size()-1)) { resultString+= ", "; }
    }
    System.out.println(resultString);

    long finalTime = System.currentTimeMillis();
    long time = finalTime - initialTime;
    System.out.println("The time taken for this program to run is " + time / 1000.0 + " seconds");
}
catch (FileNotFoundException ex) { ex.printStackTrace(); }
catch (IOException ex) { ex.printStackTrace(); }
</code>```

The jumbled word list file contained the following jumbled strings:

```<code>addej
ahicryrhe
alvan
annaab
baltoc
braney
cra
htis
</code>```

the console output looked like this after running the above list of jumbled words across my 370,101 word Word List file. It took 0.740 seconds to process on my system:

```<code>addej: jaded, ahicryrhe: hierarchy, alvan: alvan naval, annaab: banana, baltoc: cobalt, braney: barney nearby, cra: arc car, htis: hist hits isth shit sith this tshi
</code>```

All words shown above were in my Word List file.

Title: Java: jumbled word program

Body:
My program loads two text files: one with a list of English words, another with jumbled words (more just random strings but most make words), then determines what words can be made of the jumbled ones and prints (at least supposed to) the word with its jumbled version next to it. My program effectively finds what words the jumbled words can make up. The problem is not all the words with jumbled equivalents print jumbled word next to them. Also I need the jumbled words on the right unscrambled on the right. Example here's some output (commas separate lines ie if two words in comma they were printed next to each other ;
addej,
ahicryrhe hierarchy,
alvan naval,
annaab banana,
baltoc,
braney nearby,

   public class Lab4{

    public static void main(String [] args) throws Exception{
        if(args.length<2) {
            Error(); }
        BufferedReader jumbledW = new BufferedReader(new FileReader(args[1]));
        BufferedReader words = new BufferedReader(new FileReader(args[0]));
        List<String> jumbledWList = new ArrayList<>();
        List<String> wList = new ArrayList<>();

        long initialTime = System.currentTimeMillis();

        while(jumbledW.ready()){
            String jumble = jumbledW.readLine();
            jumbledWList.add(jumble);
        }

        Collections.sort(jumbledWList);
        while (words.ready()){
            String word = words.readLine();
            wList.add(word);
        }
        Collections.sort(wList);
        for (String jumble : jumbledWList ) {
            System.out.print(jumble + " ");
            for (String word : wList) {
                if(toConnical(jumble).equals(toConnical(word)))
                    System.out.print(word);

        }
        System.out.println();
        }
        long finalTime = System.currentTimeMillis();
        long time = finalTime - initialTime;
        System.out.println("The time taken for this program to run is " + time/1000.0 + " seconds" );

        }

    private static void Error(){
        System.out.println("\nError:You have to pass the name of the input files on the command line" );
        System.exit(0);
        }

    private static String toConnical(String word){
        char [] arr = word.toCharArray();
        Arrays.sort(arr);
        String connical = new String(arr);
        return connical;
    }
}

Body:
While skipping through old unanswered posts I had come across this particular question which quite frankly is somewhat unclear as to what the actual problem may be. The way I read the post is this:

A file name is passed to this application through the command line which consists of several jumbled character words. Not certain however whether each line within the file consists of single jumbled words OR each line within the file consists of multiple jumbled words separated with one or more white-spaces (or perhaps even tabs). With this in mind we need to cover either scenario.

Yet another file name is also passed to this application through the command line which consists of several valid language type words. This file is to be considered the Word List to whereas any single jumbled word could pertain to one (or more) of those words within the list if it were unscrambled or not (the word within the Jumbled String list might not be jumbled).

As the Jumbled String list is processed each Word List word that is found to be capable of matching via sorted character to character comparison to the sorted Jumbled word characters is printed to console window.

Console output required is to be a comma delimited string consisting of each jumbled word followed by space delimited matching words from the Word List:

addej jaded, ahicryrhe hierarchy, alvan alvan naval, annaab banana,...etc

This is however appears to now be contradictory to your comment:

"the program is given a txt file of a great deal of english words youd
  find in a dictionary and another txt file with jumbled words such as
  cra which could make car or rat. The output i desire is the in
  reference to the example of cra would be "car cra" (on one line)."

Whereas space delimited Word List words are to come first then the jumbled word processed each consuming a single console window line. Which format is desired? By the way rat can not be achieved from cra.

In reality your code works as expected however since you are using a BufferedReader object and a FileReader object your code will need to be in a try/catch block to handle any exceptions such as the FileNotFoundException and the IOException. This is a requiremnt and can not be excluded.

Below is your code slightly modified to accommodate your first desired output format:

try {
    BufferedReader jumbledW = new BufferedReader(new FileReader(args[1]));
    BufferedReader words = new BufferedReader(new FileReader(args[0]));
    List<String> jumbledWList = new ArrayList<>();
    List<String> wList = new ArrayList<>();

    long initialTime = System.currentTimeMillis();

    while (jumbledW.ready()) {
        String jumble = jumbledW.readLine();
        jumbledWList.add(jumble);
    }

    Collections.sort(jumbledWList);
    while (words.ready()) {
        String word = words.readLine();
        wList.add(word);
    }
    Collections.sort(wList);

    String resultString = "";
    for (int i = 0; i < jumbledWList.size(); i++){
        String jumble = jumbledWList.get(i);
        resultString+= jumble + ":";
        for (String word : wList) {
            if (toConnical(jumble).equals(toConnical(word))) {
                resultString+= " " + word;
            }
        }
        if (i != (jumbledWList.size()-1)) { resultString+= ", "; }
    }
    System.out.println(resultString);

    long finalTime = System.currentTimeMillis();
    long time = finalTime - initialTime;
    System.out.println("The time taken for this program to run is " + time / 1000.0 + " seconds");
}
catch (FileNotFoundException ex) { ex.printStackTrace(); }
catch (IOException ex) { ex.printStackTrace(); }

The jumbled word list file contained the following jumbled strings:

addej
ahicryrhe
alvan
annaab
baltoc
braney
cra
htis

the console output looked like this after running the above list of jumbled words across my 370,101 word Word List file. It took 0.740 seconds to process on my system:

addej: jaded, ahicryrhe: hierarchy, alvan: alvan naval, annaab: banana, baltoc: cobalt, braney: barney nearby, cra: arc car, htis: hist hits isth shit sith this tshi

All words shown above were in my Word List file.


问:
Route not defined react router and spring boot server
I want to add react-route to my app, i have the code below:

import React from 'react';
import ReactDOM from 'react-dom';

```<code>import { Router, browserHistory } from 'react-router';

import App from './App.js';

ReactDOM.render(
    <Router history={browserHistory}>
        <Route exact path="/" component={App} />
    </Router>,
    document.getElementById('root')
);
</code>```

app:

```<code>import React from 'react';

class App extends React.Component {
    render() {
        return (
            <div className="container">
                Hello
            </div>
        );
    }
}

export default App;
</code>```

I have a spring boot server which listens on 8080, in browser i get error when checking localhost:8080 (debug mozilla):

```<code>ReferenceError: Route is not defined
</code>```

I have  "react-router": "^4.1.1".

EDIT:
imported route but i get now:

```<code>TypeError: i.props.history is undefined
</code>```

UPDATE:
Installed react-router 3.0.2 and worked.

答:
You need to use BrowserRouter or HashRouter from react-router-dom package, not Router from react-router package, if you are using react router in a webbrowser.

You should never need to import react-router yourself, react-router-dom will do this for you.

ContentLicense: CC BY-SA 4.0

Body:
I want to add react-route to my app, i have the code below:

import React from 'react';
import ReactDOM from 'react-dom';

import { Router, browserHistory } from 'react-router';

import App from './App.js';

ReactDOM.render(
    <Router history={browserHistory}>
        <Route exact path="/" component={App} />
    </Router>,
    document.getElementById('root')
);

app:

import React from 'react';

class App extends React.Component {
    render() {
        return (

                Hello

        );
    }
}

export default App;

I have a spring boot server which listens on 8080, in browser i get error when checking localhost:8080 (debug mozilla):

ReferenceError: Route is not defined

I have  "react-router": "^4.1.1".

EDIT:
imported route but i get now:

TypeError: i.props.history is undefined

UPDATE:
Installed react-router 3.0.2 and worked.


问:
virtualenvwrapper mkproject and shell startup in windows issue?
Why is the virtualenvwrapper mkproject command is not working in Windows 10?  And what file do you edit for shell startup in Windows 10 to setup virtualenvwrapper?</p>

答:
mkproject is included in v1.2.4 of virtualenvwrapper-win.

There is no need to call a setup script like you would do in linux. The linux version implements virtualenvwrapper as shell functions, while virtualenvwrapper-win implements them as .bat files located in your python's Scripts directory.


问:
ImageView not changing with setImageResource()?
Here's the code:

```<code>public class MainActivity extends AppCompatActivity implements View.OnClickListener{

  ImageView button;

 @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    button = (ImageView)findViewById(R.id.startButton);
    button.setOnClickListener(this);
    button.setImageResource(R.drawable.play);
}
    public void onClick(View v) {
        button.setImageResource(R.drawable.pause);
    }
}
</code>```

Apparently if I put the button.setImageResource(R.drawable.pause);in the onCreate it works and changes images but not in the onClick? I tried debugging it and it ran the onClick code but didn't change the button image. I'm probably making a very stupid mistake but I can't figure it out.

xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.larry.app.MainActivity"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
   <ImageView
        android:id="@+id/startButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clickable="true" />
</LinearLayout>
</code>```

答: you had better set ImageView self OnClickListener</p>

Body:
Here's the code:

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

  ImageView button;

 @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    button = (ImageView)findViewById(R.id.startButton);
    button.setOnClickListener(this);
    button.setImageResource(R.drawable.play);
}
    public void onClick(View v) {
        button.setImageResource(R.drawable.pause);
    }
}

Apparently if I put the button.setImageResource(R.drawable.pause);in the onCreate it works and changes images but not in the onClick? I tried debugging it and it ran the onClick code but didn't change the button image. I'm probably making a very stupid mistake but I can't figure it out.

xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.larry.app.MainActivity"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
   <ImageView
        android:id="@+id/startButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clickable="true" />
</LinearLayout>


问:
Creating a Morse Code translator for my programming class,having troubles with the output
this is my first post on this platform ,im kinda new to this java programing and also not that good at english :p

My teacher asked for a morse code translator that does morse to letters and vice versa

Here's the code i came up with:

```<code>import java.util.Scanner;
public class Morse2 {
    public static void main(String[] args){
 String[] letras = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l",
                  "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x",
                  "y", "z"};
 String[] MORSE = {
 ".-" ,"-...","-.-.","-.." ,"." ,
 "..-.","--." ,"....",".." ,".---",
 "-.-" ,".-..","--" ,"-." ,"---" ,
 ".--.","--.-",".-." ,"..." ,"-" ,
 "..-" ,"...-",".--", "-..-","-.--",
 "--.."};
System.out.println("Insira uma frase em codigo morse para uma traducao para texto ou vice-versa");
Scanner in=new Scanner(System.in);
String frase =in.nextLine();
String resp="";

frase=frase.toLowerCase();
String[] paraletras=frase.split("");
String[]paraMorse=frase.split(" ");
for(int i=0;i< paraletras.length;i++){
    for(int j=0;j< letras.length ;j++){
     if (paraletras[i].equals(letras[j])){
    resp=resp+ MORSE[j]+" ";}
    }
}
for(int k=0;k<paraMorse.length;k++){
     for (int l=0;l<MORSE.length;l++){
          if(paraMorse[k].equals(MORSE[l])){
    resp=resp+letras[l]+ " ";}}
    }

System.out.print(resp);}

    }
</code>```

The class compiles fine but im having some issues with my output,more specifically the order of the output:

e.g My input " a b -.- c "
    What i wanted ".- -... k -.-."
    What i got ".- -... -.-. k"
I believe that's because i used 2 for cycles instead of 1 but i cant really tell how to do it.Would apreciate some help
Also when the user writes an impossible character like "*" im suppossed to put an "?" in that position and im also strugling on that i dont know if i should use a if else cycle or what

Please help me and thank you everybody ^^

答:
Sorry to be such a noob,but probably is also because ive been here since 8 hours ago but why is this code giving me only the morse code to the letter 'a' a couple times? </p>

```<code>import java.util.Scanner;
public class Morse2 {
    public static void main(String[] args){
 String[] abecedario = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l",
                  "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x",
                  "y", "z"};
 String[] MORSE = {
 ".-" ,"-...","-.-.","-.." ,"." ,
 "..-.","--." ,"....",".." ,".---",
 "-.-" ,".-..","--" ,"-." ,"---" ,
 ".--.","--.-",".-." ,"..." ,"-" ,
 "..-" ,"...-",".--", "-..-","-.--",
 "--.."};
System.out.println("Insira uma frase em codigo morse para uma traducao para texto ou vice-versa");
Scanner in=new Scanner(System.in);
String frase =in.nextLine();
String resp="";
frase=frase.toLowerCase();
String[] palavra=frase.split(" ");
for(int i=0;i< palavra.length;i++){
    String letra=palavra[i];
    String novochar="";

    for (int j=0;j<abecedario.length;j++){
        if (abecedario[j].equals(letra));
        novochar=MORSE[j];
        break;

    }
    if(novochar==""){
        for (int j=0;j<MORSE.length;j++){
        if (MORSE[j].equals(letra));
        novochar=abecedario[j];
        break;
    }
    }

    if(novochar==""){
        novochar="?";
        continue;

    }
    resp=resp+novochar+" ";
    }
    System.out.println(resp);
    }
}
</code>```

Body:
this is my first post on this platform ,im kinda new to this java programing and also not that good at english :p

My teacher asked for a morse code translator that does morse to letters and vice versa

Here's the code i came up with:

import java.util.Scanner;
public class Morse2 {
    public static void main(String[] args){
 String[] letras = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l",
                  "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x",
                  "y", "z"};
 String[] MORSE = {
 ".-" ,"-...","-.-.","-.." ,"." ,
 "..-.","--." ,"....",".." ,".---",
 "-.-" ,".-..","--" ,"-." ,"---" ,
 ".--.","--.-",".-." ,"..." ,"-" ,
 "..-" ,"...-",".--", "-..-","-.--",
 "--.."};
System.out.println("Insira uma frase em codigo morse para uma traducao para texto ou vice-versa");
Scanner in=new Scanner(System.in);
String frase =in.nextLine();
String resp="";

frase=frase.toLowerCase();
String[] paraletras=frase.split("");
String[]paraMorse=frase.split(" ");
for(int i=0;i< paraletras.length;i++){
    for(int j=0;j< letras.length ;j++){
     if (paraletras[i].equals(letras[j])){
    resp=resp+ MORSE[j]+" ";}
    }
}
for(int k=0;k<paraMorse.length;k++){
     for (int l=0;l<MORSE.length;l++){
          if(paraMorse[k].equals(MORSE[l])){
    resp=resp+letras[l]+ " ";}}
    }

System.out.print(resp);}

    }

The class compiles fine but im having some issues with my output,more specifically the order of the output:

e.g My input " a b -.- c "
    What i wanted ".- -... k -.-."
    What i got ".- -... -.-. k"
I believe that's because i used 2 for cycles instead of 1 but i cant really tell how to do it.Would apreciate some help
Also when the user writes an impossible character like "*" im suppossed to put an "?" in that position and im also strugling on that i dont know if i should use a if else cycle or what

Please help me and thank you everybody ^^

Body:
Sorry to be such a noob,but probably is also because ive been here since 8 hours ago but why is this code giving me only the morse code to the letter 'a' a couple times?

import java.util.Scanner;
public class Morse2 {
    public static void main(String[] args){
 String[] abecedario = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l",
                  "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x",
                  "y", "z"};
 String[] MORSE = {
 ".-" ,"-...","-.-.","-.." ,"." ,
 "..-.","--." ,"....",".." ,".---",
 "-.-" ,".-..","--" ,"-." ,"---" ,
 ".--.","--.-",".-." ,"..." ,"-" ,
 "..-" ,"...-",".--", "-..-","-.--",
 "--.."};
System.out.println("Insira uma frase em codigo morse para uma traducao para texto ou vice-versa");
Scanner in=new Scanner(System.in);
String frase =in.nextLine();
String resp="";
frase=frase.toLowerCase();
String[] palavra=frase.split(" ");
for(int i=0;i< palavra.length;i++){
    String letra=palavra[i];
    String novochar="";

    for (int j=0;j<abecedario.length;j++){
        if (abecedario[j].equals(letra));
        novochar=MORSE[j];
        break;

    }
    if(novochar==""){
        for (int j=0;j<MORSE.length;j++){
        if (MORSE[j].equals(letra));
        novochar=abecedario[j];
        break;
    }
    }

    if(novochar==""){
        novochar="?";
        continue;

    }
    resp=resp+novochar+" ";
    }
    System.out.println(resp);
    }
}


问:
C++ Wait x secound inside a loop
I am trying to figure out how to wait inside a loop.
What I want to do is to click a button on a program and if a error happened it is going to show a error message for 3 seconds than disappear. All this is inside a loop that runs all the time.
I have tried ctime, sleep etc. But all of them freeze the program to the time has ended. And that isn't what I am looking for.

I have thought about getting the PC clock and + 3 seconds than make a if() to check if the clock == clock + 3. But i didn't find a way to get the clock time and do what i was thinking. And i know that their is a good way of doing what i want for this, but i just haven't figured out how. I just end up freezing the threads to the clock is done.

So it had been nice if someone can lead me in the right direction or/and maybe show me some examples on how to do this.

答:
Pausing main thread for some amount of time will freeze the whole program regardless of the way you are using to pause.
I am not really familiar with event-loop mentioned in the comments above. However I would achieve the task using std::thread (c++11), if you're not familiar with c++11, there are many other non-standarised ways of of creating threads, namely pthread in linux and in windows you can use windows.h as in the link.
So let's talk some C++:
For example you can write a function to show the error message, wait a number of seconds and return;
The function would have the following signature

```<code>void myFunction(char errMsg[], unsigned int durationSeconds);
</code>```

then you can call it from the main thread (the function you were showing the message in), using:

```<code>std::thread(myFunction("error message", 3));
</code>```

Now back to your question, C++11 also offers a convenient way for pausing a thread for some amount of time without a while loop, you can use the code below for it:

```<code>std::chrono::seconds interval(durationSeconds);
std::this_thread::sleep_for(interval);
</code>```

just write them after showing the message and that should help.

Title: C++ Wait x secound inside a loop

Body:
Pausing main thread for some amount of time will freeze the whole program regardless of the way you are using to pause.
I am not really familiar with event-loop mentioned in the comments above. However I would achieve the task using std::thread (c++11), if you're not familiar with c++11, there are many other non-standarised ways of of creating threads, namely pthread in linux and in windows you can use windows.h as in the link.
So let's talk some C++:
For example you can write a function to show the error message, wait a number of seconds and return;
The function would have the following signature

void myFunction(char errMsg[], unsigned int durationSeconds);

then you can call it from the main thread (the function you were showing the message in), using:

std::thread(myFunction("error message", 3));

Now back to your question, C++11 also offers a convenient way for pausing a thread for some amount of time without a while loop, you can use the code below for it:

std::chrono::seconds interval(durationSeconds);
std::this_thread::sleep_for(interval);

just write them after showing the message and that should help.


问:
Mongoose/MongoDB: Get second to last document
How would I be able to get the 2nd to latest or previous day's document collection using Mongoose?

my code to get the latest data goes as follows:

```<code>data.findOne()
        .sort({"_id": -1})
        .exec(function(err, data) {
            if (err) {
                console.log('Error getting data..');
            }
            if (data) {
                res.json(data);
            }
            else {
                console.log('No data found!');
            }
        });
</code>```

This only returns the LATEST document in the collection. I instead need the one prior to the latest one, so one from a day before this one, how would I be able to do this?

答:
Then you'd have to use aggregation:

```<code>db.getCollection('data').aggregate([
  { $sort: {"date": -1}}, // sort by latest date (descending)
  { $limit: 2}, // limit to the first two results
  { $sort: {"date": 1}}, // sort these two ascending
  { $limit: 1} // get first document
])
</code>```

This pipeline is translated in mongoose like that (I think):

```<code>data.aggregate([
      { $sort: {"date": -1}},
      { $limit: 2},
      { $sort: {"date": 1}},
      { $limit: 1}
    ], function (err, result) {
        if (err) {
            next(err);
        } else {
            res.json(result);
        }
    });
</code>```

Also by sorting without adding a $match pipeline, your first $sort would sort all the documents in your collection. So if your collection is big you might want to restrict them with some query parameters that you can add to the $match pipeline. You could add the match before the first $sort

E.g.

```<code>db.getCollection('data').aggregate([
  { $match: {...}},
  { $sort: {"date": -1}},
  { $limit: 2},
  { $sort: {"date": 1}},
  { $limit: 1}
])
</code>```

Body:
How would I be able to get the 2nd to latest or previous day's document collection using Mongoose?

my code to get the latest data goes as follows:

data.findOne()
        .sort({"_id": -1})
        .exec(function(err, data) {
            if (err) {
                console.log('Error getting data..');
            }
            if (data) {
                res.json(data);
            }
            else {
                console.log('No data found!');
            }
        });

This only returns the LATEST document in the collection. I instead need the one prior to the latest one, so one from a day before this one, how would I be able to do this?

Body:
Then you'd have to use aggregation:

db.getCollection('data').aggregate([
  { $sort: {"date": -1}}, // sort by latest date (descending)
  { $limit: 2}, // limit to the first two results
  { $sort: {"date": 1}}, // sort these two ascending
  { $limit: 1} // get first document
])

This pipeline is translated in mongoose like that (I think):

data.aggregate([
      { $sort: {"date": -1}},
      { $limit: 2},
      { $sort: {"date": 1}},
      { $limit: 1}
    ], function (err, result) {
        if (err) {
            next(err);
        } else {
            res.json(result);
        }
    });

Also by sorting without adding a $match pipeline, your first $sort would sort all the documents in your collection. So if your collection is big you might want to restrict them with some query parameters that you can add to the $match pipeline. You could add the match before the first $sort

E.g.

db.getCollection('data').aggregate([
  { $match: {...}},
  { $sort: {"date": -1}},
  { $limit: 2},
  { $sort: {"date": 1}},
  { $limit: 1}
])


问:
Showing Div via CSS selector within a UL
I want to build CSS drop down menus.

I want to solve the problem of too long drop down items in UL. So I want to use DIV within a UL.

If you run this example, heading 3 will show you drop down UL items. I want the same for Heading 2 link. Because I put that UL in a DIV. So how can I do it?

CSS Code:

```<code>li{
    list-style: none;
    float: left;
}

li ul {
    display: none;
    background-color: #69f;
}

li:hover > div#mDiv {
    display: block;
}

.menuDiv{
    display: none;
}

li:hover > ul {
    display: block;
}
</code>```

Markup:

```<code><ul>
  <li><a href="#">Heading 1</a></li>
  <li><a href="#">Heading 2</a>
    <div class = "menuDiv" id = "mDiv">
        <ul>
          <li><a href="#">Subitem 1</a></li>
          <li><a href="#">Subitem 2</a></li>
          <li><a href="#">Subitem 3</a></li>
        </ul>
    </div>
  </li>
  <li><a href="#">Heading 3</a>
    <ul>
      <li><a href="#">Subitem 4</a></li>
      <li><a href="#">Subitem 5</a></li>
      <li><a href="#">Subitem 6</a></li>
    </ul>
  </li>
  </ul>
</code>```

答:
If the > in your rules is required change this rule:

```<code>li:hover > div ul, li:hover > ul {
display: block;
</code>```

}

Body:
I want to build CSS drop down menus.

I want to solve the problem of too long drop down items in UL. So I want to use DIV within a UL.

If you run this example, heading 3 will show you drop down UL items. I want the same for Heading 2 link. Because I put that UL in a DIV. So how can I do it?

CSS Code:

li{
    list-style: none;
    float: left;
}

li ul {
    display: none;
    background-color: #69f;
}

li:hover > div#mDiv {
    display: block;
}

.menuDiv{
    display: none;
}

li:hover > ul {
    display: block;
}

Markup:

Heading 1

Heading 2

Subitem 1

Subitem 2

Subitem 3

Heading 3

Subitem 4

Subitem 5

Subitem 6

Body:
If the > in your rules is required change this rule:

li:hover > div ul, li:hover > ul {
display: block;

}


答:
Make sure you use

```<code>android:src
</code>```

to set the initial image in the xml.

Title: ImageView not changing with setImageResource()?

Body:
Make sure you use

android:src

to set the initial image in the xml.


问:
How do I write a function that prints counts of values in an array, taking the array as a parameter?
Starting with the below program that creates an array of coin flips, I have to add a function that prints out the total number of heads and total number of tails flipped.  The function must take the array of flips as a parameter.

This is the given program:

```<code>var NUM_FLIPS = 100;

function start(){
    var flips = flipCoins();
    printArray(flips);
    countHeadsAndTails();
}

// This function should flip a coin NUM_FLIPS
// times, and add the result to an array. We
// return the result to the caller.
function flipCoins(){
    var flips = [];
    for(var i = 0; i < NUM_FLIPS; i++){
        if(Randomizer.nextBoolean()){
            flips.push("Heads");
        }else{
            flips.push("Tails");
        }
    }
    return flips;
}

function printArray(arr){
    for(var i = 0; i < arr.length; i++){
        println(i + ": " + arr[i]);
    }
}
</code>```

And I need to write this function:

```<code>function countHeadsAndTails(flips) {
    //Write the program here
}
</code>```

This is what I have so far, but the function does not work as expected. I am stuck on what to put in the if statement.

```<code>function countHeadsAndTails(flips) {
    var headCount = 0;
    var tailCount = 0;
    for (var i = 0; i < NUM_FLIPS; i++) {
        if (i == "Heads") {
            headCount += 1;
        }else {
            tailCount += 1;
        }
    }

    println("Total Heads: " + headCount);
    println("Total Tails: " + tailCount);
}
</code>```

The program randomly flips heads or tails 100 times and prints out the results, but the counter does not work and I get this:

```<code>Total Heads: 100
Total Tails: 0
</code>```

答:
The reason if (i == "Heads") { doesn't work is because i is the current index (a number) and you're comparing it to a string "Heads". I suspect what you want is if (flips[i] == "Heads") {. Basically using the index i to grab the ith element in the array and comparing that with "Heads".

Also the parameter flips is not being passed to countHeadsAndTails() in the start() function. Looks like that might be a problem with the provided problem itself. I assume the countHeadsAndTails stub function they provided already had the flips parameter?

Body:
Starting with the below program that creates an array of coin flips, I have to add a function that prints out the total number of heads and total number of tails flipped.  The function must take the array of flips as a parameter.

This is the given program:

var NUM_FLIPS = 100;

function start(){
    var flips = flipCoins();
    printArray(flips);
    countHeadsAndTails();
}

// This function should flip a coin NUM_FLIPS
// times, and add the result to an array. We
// return the result to the caller.
function flipCoins(){
    var flips = [];
    for(var i = 0; i < NUM_FLIPS; i++){
        if(Randomizer.nextBoolean()){
            flips.push("Heads");
        }else{
            flips.push("Tails");
        }
    }
    return flips;
}

function printArray(arr){
    for(var i = 0; i < arr.length; i++){
        println(i + ": " + arr[i]);
    }
}

And I need to write this function:

function countHeadsAndTails(flips) {
    //Write the program here
}

This is what I have so far, but the function does not work as expected. I am stuck on what to put in the if statement.

function countHeadsAndTails(flips) {
    var headCount = 0;
    var tailCount = 0;
    for (var i = 0; i < NUM_FLIPS; i++) {
        if (i == "Heads") {
            headCount += 1;
        }else {
            tailCount += 1;
        }
    }

    println("Total Heads: " + headCount);
    println("Total Tails: " + tailCount);
}

The program randomly flips heads or tails 100 times and prints out the results, but the counter does not work and I get this:

Total Heads: 100
Total Tails: 0


问:
Can't get a telephone keyboard for input in iPad

I'm trying to set the input tag with type that will cause the virtual keyboard to be opened in telephone mode, like this example:
Telephone keyboard

I've tried using type="tel" but it's opens the full numeric keyboard (with the symbols), the same while using type="number" along with pattern="[0-9]*" or [/d]*

I'm afraid that iPad doesn't have this type of keyboard...

Is there anyway to do it on iPad?

答: the telephone keyboard is not supported by ipad.</p>


问:
How do I run a bash script and set variables?
I am trying to run a bash script and set the variables in one command. Is this possible?

```<code>bash wp.sh dbname="hello",dbuser="admin"
</code>```

It's not working for me, and I can't seem to find any guidance on this. Thanks in advance for your help!

答:
To set environment variables that will be inherited by the script process, put the assignments at the beginning:</p>

```<code>dbname="hello" dbuser="admin" bash wp.sh
</code>```

Body:
I am trying to run a bash script and set the variables in one command. Is this possible?

bash wp.sh dbname="hello",dbuser="admin"

It's not working for me, and I can't seem to find any guidance on this. Thanks in advance for your help!

Body:
To set environment variables that will be inherited by the script process, put the assignments at the beginning:

dbname="hello" dbuser="admin" bash wp.sh