问:
2sxc general exception errors in admin log
We are encountering lot of "General Exception" errors related to DNN search and 2sxc, sometimes the site even stops loading.

I'm attaching one of the errors from the admin log, but there are plenty can anyone help?

We're using Evoq 8.5, 2sxc 8.5.4.

```<code><log LogGUID="e8a0d5ca-12f6-4865-a184-f440611ad3d5" LogFileID="" LogTypeKey="GENERAL_EXCEPTION" LogUserID="-1" LogEventID="212842" LogUserName="" LogPortalID="-1" LogPortalName="" LogCreateDate="3/5/2017 2:02:57 AM" LogCreateDateNum="0" BypassBuffering="False" LogServerName="RD0003FF6E964E" LogConfigID="4">
    <LogProperties>
      <LogProperty>
        <PropertyName>AbsoluteURL</PropertyName>
        <PropertyValue />
      </LogProperty>
      <LogProperty>
        <PropertyName>DefaultDataProvider</PropertyName>
        <PropertyValue>DotNetNuke.Data.SqlDataProvider, DotNetNuke</PropertyValue>
      </LogProperty>
      <LogProperty>
        <PropertyName>ExceptionGUID</PropertyName>
        <PropertyValue>d5db1b63-65bb-424e-9284-d6bdeb597078</PropertyValue>
      </LogProperty>
    </LogProperties>
    <Exception>
      <AssemblyVersion />
      <PortalId>-1</PortalId>
      <UserId>-1</UserId>
      <TabId>-1</TabId>
      <RawUrl />
      <Referrer />
      <UserAgent />
      <ExceptionHash>h7DfzrR5N2NZPGujVU3A9A==</ExceptionHash>
      <Message>Search: Error while indexing module 3429 on tab 1311, portal 14</Message>
      <StackTrace>   at ToSic.SexyContent.Environment.Dnn7.DnnBusinessController.GetModifiedSearchDocuments(ModuleInfo moduleInfo, DateTime beginDate) in C:\Projects\2SexyContent\Web\DesktopModules\ToSIC_SexyContent\Environment\Dnn7\DnnBusinessController.cs:line 32
   at DotNetNuke.Services.Search.ModuleIndexer.IndexSearchDocuments(Int32 portalId, ScheduleHistoryItem schedule, DateTime startDateLocal, Action`1 indexer)</StackTrace>
      <InnerMessage>The underlying provider failed on Open.</InnerMessage>
      <InnerStackTrace>   at System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure)
   at System.Data.EntityClient.EntityConnection.Open()
   at System.Data.Objects.ObjectContext.EnsureConnection()
   at System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
   at System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator()
   at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source)
   at ToSic.Eav.BLL.EavDataController.InitZoneApp(Nullable`1 zoneId, Nullable`1 appId) in C:\Projects\eav-server\ToSic.Eav\BLL\EavDataController.cs:line 145
   at ToSic.SexyContent.Internal.AppManagement.EnsureAppIsConfigured(Int32 zoneId, Int32 appId, String appName) in C:\Projects\2SexyContent\Web\DesktopModules\ToSIC_SexyContent\SexyContent\Internal\AppManagement.cs:line 106
   at ToSic.SexyContent.App.InitializeResourcesSettingsAndMetadata(Boolean allowSideEffects) in C:\Projects\2SexyContent\Web\DesktopModules\ToSIC_SexyContent\SexyContent\App.cs:line 110
   at ToSic.SexyContent.App..ctor(Int32 zoneId, Int32 appId, PortalSettings ownerPortalSettings, Boolean allowSideEffects) in C:\Projects\2SexyContent\Web\DesktopModules\ToSIC_SexyContent\SexyContent\App.cs:line 103
   at ToSic.SexyContent.ContentBlock.ModuleContentBlock..ctor(ModuleInfo moduleInfo, IEnumerable`1 overrideParams) in C:\Projects\2SexyContent\Web\DesktopModules\ToSIC_SexyContent\SexyContent\ContentBlock\ModuleContentBlock.cs:line 55
   at ToSic.SexyContent.Search.SearchController.GetModifiedSearchDocuments(ModuleInfo moduleInfo, DateTime beginDate) in C:\Projects\2SexyContent\Web\DesktopModules\ToSIC_SexyContent\SexyContent\Search\SearchController.cs:line 48
   at ToSic.SexyContent.Environment.Dnn7.DnnBusinessController.GetModifiedSearchDocuments(ModuleInfo moduleInfo, DateTime beginDate) in C:\Projects\2SexyContent\Web\DesktopModules\ToSIC_SexyContent\Environment\Dnn7\DnnBusinessController.cs:line 28</InnerStackTrace>
      <Source>ToSic.SexyContent</Source>
      <FileName />
      <FileLineNumber>0</FileLineNumber>
      <FileColumnNumber>0</FileColumnNumber>
      <Method />
    </Exception>
  </log>
</code>```

答:
Denis updated 2sxc and I've investigated the log files and found this error that might help narrow it down:

2017-11-14 12:35:46,608 [H10][Thread:76][ERROR] DotNetNuke.Services.Exceptions.Exceptions - System.Exception: [Indexing: Behavior SiteSearch (#1)] Error reading content source DNN Modules Indexer ---> ToSic.SexyContent.Search.SearchIndexException: Search: Error while indexing module 5242 on tab 1901, portal 0 ---> System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.
   at System.ThrowHelper.ThrowKeyNotFoundException()
   at System.Collections.Generic.Dictionary2.get_Item(TKey key)
   at ASP._Page_Portals_0_2sxc_Documents__Environment_Filter_App_cshtml.CustomizeData() in \Portals\0\2sxc\Documents\_Environment Filter App.cshtml:line 11
   at ToSic.SexyContent.Engines.RazorEngine.CustomizeData() in C:\Projects\2SexyContent\Web\DesktopModules\ToSIC_SexyContent\2Sexy Content Razor\RazorEngine.cs:line 109
   at ToSic.SexyContent.Engines.EngineBase.Init(Template template, App app, ModuleInfo hostingModule, IDataSource dataSource, InstancePurposes instancePurposes, SxcInstance sxcInstance, Log parentLog) in C:\Projects\2SexyContent\Web\DesktopModules\ToSIC_SexyContent\SexyContent\Engines\EngineBase.cs:line 64
   at ToSic.SexyContent.Search.SearchController.GetModifiedSearchDocuments(ModuleInfo moduleInfo, DateTime beginDate) in C:\Projects\2SexyContent\Web\DesktopModules\ToSIC_SexyContent\SexyContent\Search\SearchController.cs:line 143
   at ToSic.SexyContent.Environment.Dnn7.DnnBusinessController.GetModifiedSearchDocuments(ModuleInfo moduleInfo, DateTime beginDate) in C:\Projects\2SexyContent\Web\DesktopModules\ToSIC_SexyContent\Environment\Dnn7\DnnBusinessController.cs:line 85
   --- End of inner exception stack trace ---
   at ToSic.SexyContent.Environment.Dnn7.DnnBusinessController.GetModifiedSearchDocuments(ModuleInfo moduleInfo, DateTime beginDate) in C:\Projects\2SexyContent\Web\DesktopModules\ToSIC_SexyContent\Environment\Dnn7\DnnBusinessController.cs:line 89
   at DnnSharp.Common2.Services.Dnn.ModuleService.<GetSearchItems>d__4.MoveNext()
   at DnnSharp.SearchBoost.Core.ContentSource.DnnModules.<GetIndexingJobsForTabModules>d__26.MoveNext()
   at DnnSharp.SearchBoost.Core.ContentSource.DnnModules.<GetIndexingJobs>d__25.MoveNext()
   at DnnSharp.SearchBoost.Core.ContentSource.DnnModules.<Query>d__20.MoveNext()
   at DnnSharp.SearchBoost.Core.Services.QueryContentSourcesService.QueryAllContentSourcesToCache(SearchBehavior behavior, List1 cache, CancellationTokenSource cancellationToken)
   --- End of inner exception stack trace ---

Body:
We are encountering lot of "General Exception" errors related to DNN search and 2sxc, sometimes the site even stops loading.

I'm attaching one of the errors from the admin log, but there are plenty can anyone help?

We're using Evoq 8.5, 2sxc 8.5.4.

<log LogGUID="e8a0d5ca-12f6-4865-a184-f440611ad3d5" LogFileID="" LogTypeKey="GENERAL_EXCEPTION" LogUserID="-1" LogEventID="212842" LogUserName="" LogPortalID="-1" LogPortalName="" LogCreateDate="3/5/2017 2:02:57 AM" LogCreateDateNum="0" BypassBuffering="False" LogServerName="RD0003FF6E964E" LogConfigID="4">
    <LogProperties>
      <LogProperty>
        <PropertyName>AbsoluteURL</PropertyName>
        <PropertyValue />
      </LogProperty>
      <LogProperty>
        <PropertyName>DefaultDataProvider</PropertyName>
        <PropertyValue>DotNetNuke.Data.SqlDataProvider, DotNetNuke</PropertyValue>
      </LogProperty>
      <LogProperty>
        <PropertyName>ExceptionGUID</PropertyName>
        <PropertyValue>d5db1b63-65bb-424e-9284-d6bdeb597078</PropertyValue>
      </LogProperty>
    </LogProperties>
    <Exception>
      <AssemblyVersion />
      <PortalId>-1</PortalId>
      <UserId>-1</UserId>
      <TabId>-1</TabId>
      <RawUrl />
      <Referrer />
      <UserAgent />
      <ExceptionHash>h7DfzrR5N2NZPGujVU3A9A==</ExceptionHash>
      <Message>Search: Error while indexing module 3429 on tab 1311, portal 14</Message>
      <StackTrace>   at ToSic.SexyContent.Environment.Dnn7.DnnBusinessController.GetModifiedSearchDocuments(ModuleInfo moduleInfo, DateTime beginDate) in C:\Projects\2SexyContent\Web\DesktopModules\ToSIC_SexyContent\Environment\Dnn7\DnnBusinessController.cs:line 32
   at DotNetNuke.Services.Search.ModuleIndexer.IndexSearchDocuments(Int32 portalId, ScheduleHistoryItem schedule, DateTime startDateLocal, Action`1 indexer)</StackTrace>
      <InnerMessage>The underlying provider failed on Open.</InnerMessage>
      <InnerStackTrace>   at System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure)
   at System.Data.EntityClient.EntityConnection.Open()
   at System.Data.Objects.ObjectContext.EnsureConnection()
   at System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
   at System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator()
   at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source)
   at ToSic.Eav.BLL.EavDataController.InitZoneApp(Nullable`1 zoneId, Nullable`1 appId) in C:\Projects\eav-server\ToSic.Eav\BLL\EavDataController.cs:line 145
   at ToSic.SexyContent.Internal.AppManagement.EnsureAppIsConfigured(Int32 zoneId, Int32 appId, String appName) in C:\Projects\2SexyContent\Web\DesktopModules\ToSIC_SexyContent\SexyContent\Internal\AppManagement.cs:line 106
   at ToSic.SexyContent.App.InitializeResourcesSettingsAndMetadata(Boolean allowSideEffects) in C:\Projects\2SexyContent\Web\DesktopModules\ToSIC_SexyContent\SexyContent\App.cs:line 110
   at ToSic.SexyContent.App..ctor(Int32 zoneId, Int32 appId, PortalSettings ownerPortalSettings, Boolean allowSideEffects) in C:\Projects\2SexyContent\Web\DesktopModules\ToSIC_SexyContent\SexyContent\App.cs:line 103
   at ToSic.SexyContent.ContentBlock.ModuleContentBlock..ctor(ModuleInfo moduleInfo, IEnumerable`1 overrideParams) in C:\Projects\2SexyContent\Web\DesktopModules\ToSIC_SexyContent\SexyContent\ContentBlock\ModuleContentBlock.cs:line 55
   at ToSic.SexyContent.Search.SearchController.GetModifiedSearchDocuments(ModuleInfo moduleInfo, DateTime beginDate) in C:\Projects\2SexyContent\Web\DesktopModules\ToSIC_SexyContent\SexyContent\Search\SearchController.cs:line 48
   at ToSic.SexyContent.Environment.Dnn7.DnnBusinessController.GetModifiedSearchDocuments(ModuleInfo moduleInfo, DateTime beginDate) in C:\Projects\2SexyContent\Web\DesktopModules\ToSIC_SexyContent\Environment\Dnn7\DnnBusinessController.cs:line 28</InnerStackTrace>
      <Source>ToSic.SexyContent</Source>
      <FileName />
      <FileLineNumber>0</FileLineNumber>
      <FileColumnNumber>0</FileColumnNumber>
      <Method />
    </Exception>
  </log>


来源: stackexchange

问:
C++ conditional statement to test if variable is a string
I have a C++ method findID that uses templates, and I want to be able to run a condition in this method based on the input type. The template parameter U will either be of type int or type string. I want to run a different condition based on the type of ID.

The code I have is follows:

```<code>template <typename S>
template <typename U>
S * findID(U ID){
    for (typename vector<S*>::collectionsIter element = collection.begin() ; element != collection.end(); ++element)
        if((*element)->getID() == ID) return *element;
    return NULL;
}
</code>```

I want my code to do the following:

```<code>template <typename S>
    template <typename U>
    S * findID(U ID){

      ***if ID is an int:
        for (typename vector<S*>::collectionsIter element = collection.begin() ; element != collection.end(); ++element)
            if((*element)->getID() == ID) return *element;

      ***if ID is a string:

         for (typename vector<S*>::collectionsIter element = collection.begin() ; element != collection.end(); ++element)
            if((*element)->getStringID() == ID) return *element;

       ***else

        return NULL;

    }
</code>```

The reason that I want to do this is because I want to be able to compare string variables of ID to the string method of getStringID(), and the int variables of ID to the int method of getID(). In addition I do not want to break these up into separate methods, so I am trying to use templates and these conditions to refactor it into 1 method.

答:
Just use 2 overloads:</p>

```<code>template <typename S>
S* findID(int ID){
    for (auto* element : collection)
        if (element->getID() == ID) return element;
    return nullptr;
}

template <typename S>
S* findID(const std::string& ID){
    for (auto* element : collection)
        if (element->getStringID() == ID) return element;
    return nullptr;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a C++ method findID that uses templates, and I want to be able to run a condition in this method based on the input type. The template parameter U will either be of type int or type string. I want to run a different condition based on the type of ID.

The code I have is follows:

template <typename S>
template <typename U>
S * findID(U ID){
    for (typename vector<S*>::collectionsIter element = collection.begin() ; element != collection.end(); ++element)
        if((*element)->getID() == ID) return *element;
    return NULL;
}

I want my code to do the following:

template <typename S>
    template <typename U>
    S * findID(U ID){

      ***if ID is an int:
        for (typename vector<S*>::collectionsIter element = collection.begin() ; element != collection.end(); ++element)
            if((*element)->getID() == ID) return *element;

      ***if ID is a string:

         for (typename vector<S*>::collectionsIter element = collection.begin() ; element != collection.end(); ++element)
            if((*element)->getStringID() == ID) return *element;

       ***else

        return NULL;

    }

The reason that I want to do this is because I want to be able to compare string variables of ID to the string method of getStringID(), and the int variables of ID to the int method of getID(). In addition I do not want to break these up into separate methods, so I am trying to use templates and these conditions to refactor it into 1 method.

Body:
Just use 2 overloads:

template <typename S>
S* findID(int ID){
    for (auto* element : collection)
        if (element->getID() == ID) return element;
    return nullptr;
}

template <typename S>
S* findID(const std::string& ID){
    for (auto* element : collection)
        if (element->getStringID() == ID) return element;
    return nullptr;
}


问:
NPM packages: Deliver assets/images package
I created an (angular2) npm package and uploaded it to my (private) registry.

The component itself is pretty easy and should show an icon. Please see the template here:

```<code><span
  [class]="'icon icon-' + key"
  [inlineSVG]="'./assets/icons.svg#' + key"
  aria-hidden="true"
></span>
</code>```

As the path in [inlineSVG] shows, I would like to deliver the icons with the package. So I've put them into ./assets folder.

But everytime I publish the package and import it into my application, I get a 404 that the file cannot be found:

I'm building my packages with gulp. I can post my gulpfile as well if needed.

Now my question: Is it generally possible to deliver assets (images) in an npm package?

Any help is greatly appreciated :)

答:
Well technically no you can't because you might be able to upload the assets but the actual path changes. Your assets are not even served in the server to be honest since they are in the node_modules folder.

What you might be able to do is import the svgs inline in the css.
https://github.com/davidkpiano/sass-svg

Or otherwise include base64 uri of the image.

Body:
I created an (angular2) npm package and uploaded it to my (private) registry.

The component itself is pretty easy and should show an icon. Please see the template here:

As the path in [inlineSVG] shows, I would like to deliver the icons with the package. So I've put them into ./assets folder.

But everytime I publish the package and import it into my application, I get a 404 that the file cannot be found:

I'm building my packages with gulp. I can post my gulpfile as well if needed.

Now my question: Is it generally possible to deliver assets (images) in an npm package?

Any help is greatly appreciated :)


问:
WebClient works, wget doesn't (when run under SYSTEM account)
I'm using a powershell script to get information from a URL using basic authentication. This works well using all the common techniques: wget, Invoke-WebRequest and System.Net.WebClient.

When that same script is running using Task Scheduler as SYSTEM account, only System.Net.WebClient works.

Any suggestions as to why that is the case?

答:
Probably because SYSTEM not has the same path and no initialized Powershell Profile.

For Invoke-WebRequest you need the Module Microsoft.PowerShell.Utility, so either use Import-Module or #requires in the script.

For wget it might be the path, try using full paths to file? Either that or set working directory in scheduled task.


问:
Appium iOS Error Domain=NSCocoaErrorDomain Code=260 "The file “WebDriverAgentRunner-Runner.app” couldn’t be opened because there is no such file
When I am running appium on real iPhone, appium gives below error. I did not found any solution for that. </p>

```<code>[XCUITest] Using WDA path: '/Applications/Appium.app/Contents/Resources/app/node_modules/appium/node_modules/appium-xcuitest-driver/WebDriverAgent'
[XCUITest] Using WDA agent: '/Applications/Appium.app/Contents/Resources/app/node_modules/appium/node_modules/appium-xcuitest-driver/WebDriverAgent/WebDriverAgent.xcodeproj'

[XCUITest] Beginning test with command 'xcodebuild build-for-testing test-without-building -project /Applications/Appium.app/Contents/Resources/app/node_modules/appium/node_modules/appium-xcuitest-driver/WebDriverAgent/WebDriverAgent.xcodeproj -scheme WebDriverAgentRunner -destination id=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX -configuration Debug IPHONEOS_DEPLOYMENT_TARGET=11.0' in directory '/Applications/Appium.app/Contents/Resources/app/node_modules/appium/node_modules/appium-xcuitest-driver/WebDriverAgent'

[Xcode] 2017-11-04 17:13:55.690 xcodebuild[3522:289240] Error Domain=NSCocoaErrorDomain Code=260 "The file “WebDriverAgentRunner-Runner.app” couldn’t be opened because there is no such file." UserInfo={NSFilePath=/Users/tcs/Library/Developer/Xcode/DerivedData/WebDriverAgent-dikkwtrisltbeobjmfvpthwwekvs/Build/Products/Debug-iphoneos/WebDriverAgentRunner-Runner.app, NSUnderlyingError=0x7fdc48f69390 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}

[XCUITest] Error: Unable to launch WebDriverAgent because of xcodebuild failure: xcodebuild failed with code 65
    at XCUITestDriver.quitAndUninstall$ (/Applications/Appium.app/Contents/Resources/app/node_modules/appium/node_modules/appium-xcuitest-driver/lib/driver.js:374:15)
[MJSONWP] Encountered internal error running command: Error: Unable to launch WebDriverAgent because of xcodebuild failure: xcodebuild failed with code 65
    at XCUITestDriver.quitAndUninstall$ (/Applications/Appium.app/Contents/Resources/app/node_modules/appium/node_modules/appium-xcuitest-driver/lib/driver.js:374:15)
</code>```

<p>I found that xcode not able to make the build. </p>

```<code>[XCUITest] Error: Unable to launch WebDriverAgent because of xcodebuild failure: xcodebuild failed with code 65
    at XCUITestDriver.quitAndUninstall$ (/Applications/Appium.app/Contents/Resources/app/node_modules/appium/node_modules/appium-xcuitest-driver/lib/driver.js:374:15)
</code>```

答:
WebdriverAgent is not opened in your real device before starting execution on the device. I faced similar issue and resolved by following the below steps.

Sign the WebDriverAgent project in Xcode

Build the project and then click Product-> Test. This will launch the WebdriverAgent in your real device.

Start the appium.

Body:
When I am running appium on real iPhone, appium gives below error. I did not found any solution for that.

[XCUITest] Using WDA path: '/Applications/Appium.app/Contents/Resources/app/node_modules/appium/node_modules/appium-xcuitest-driver/WebDriverAgent'
[XCUITest] Using WDA agent: '/Applications/Appium.app/Contents/Resources/app/node_modules/appium/node_modules/appium-xcuitest-driver/WebDriverAgent/WebDriverAgent.xcodeproj'

[XCUITest] Beginning test with command 'xcodebuild build-for-testing test-without-building -project /Applications/Appium.app/Contents/Resources/app/node_modules/appium/node_modules/appium-xcuitest-driver/WebDriverAgent/WebDriverAgent.xcodeproj -scheme WebDriverAgentRunner -destination id=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX -configuration Debug IPHONEOS_DEPLOYMENT_TARGET=11.0' in directory '/Applications/Appium.app/Contents/Resources/app/node_modules/appium/node_modules/appium-xcuitest-driver/WebDriverAgent'

[Xcode] 2017-11-04 17:13:55.690 xcodebuild[3522:289240] Error Domain=NSCocoaErrorDomain Code=260 "The file “WebDriverAgentRunner-Runner.app” couldn’t be opened because there is no such file." UserInfo={NSFilePath=/Users/tcs/Library/Developer/Xcode/DerivedData/WebDriverAgent-dikkwtrisltbeobjmfvpthwwekvs/Build/Products/Debug-iphoneos/WebDriverAgentRunner-Runner.app, NSUnderlyingError=0x7fdc48f69390 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}

[XCUITest] Error: Unable to launch WebDriverAgent because of xcodebuild failure: xcodebuild failed with code 65
    at XCUITestDriver.quitAndUninstall$ (/Applications/Appium.app/Contents/Resources/app/node_modules/appium/node_modules/appium-xcuitest-driver/lib/driver.js:374:15)
[MJSONWP] Encountered internal error running command: Error: Unable to launch WebDriverAgent because of xcodebuild failure: xcodebuild failed with code 65
    at XCUITestDriver.quitAndUninstall$ (/Applications/Appium.app/Contents/Resources/app/node_modules/appium/node_modules/appium-xcuitest-driver/lib/driver.js:374:15)

I found that xcode not able to make the build.

[XCUITest] Error: Unable to launch WebDriverAgent because of xcodebuild failure: xcodebuild failed with code 65
    at XCUITestDriver.quitAndUninstall$ (/Applications/Appium.app/Contents/Resources/app/node_modules/appium/node_modules/appium-xcuitest-driver/lib/driver.js:374:15)


问:
Magento category view next and previous page toolbar
Whomever worked on the site previous me has somehow turned off the toolbar on the category view page. They had wanted to get rid of the filter by, and other options.

Now we have too many products to display them all on one page, so I went ahead and limited it to show 12 products, which it does. But now navigation shows up. I assume this is because of how they turned off the toolbar. Where do I find the code (using a theme) to control this toolbar? I am hoping they just commented out the code.

Magento 1.9.3.3

答:
there is also a possibility to remove toolbar in layout xml.

most common place for this would be local.xml of the Theme
app/design/frontend/[theme]/layout/local.xml

can also be done in any other xml (like catalog.xml) in
app/design/frontend/[theme]/layout/

simply search for product_list_toolbar block and actions like remove or unsetChild


问:
UDP port 1433 (ms-sql-s service): NOT LISTENING
Screenshot of cmd console

Image of Main Error:

Image of Configuration manager where no server found:

I have try to search all solution for error 26 of sql server but no solution work for me.

I have check that server is running by going to services.msc and I have also checked through management configuration tool, but all get fail in my case.
I have reinstall it to check any missing file in installation process.
So at the end I have used PortQryUI.exe to find main reason where I get this message on my console

UDP port 1433 (ms-sql-s service): NOT LISTENING

I am attaching some screen shot for more clarification. And I have also follow all the steps given at stackoverflow.com for solving error 26 but no solution work for me so please don't close this question, may it have some other problem but sowing error 26.

答:
UDP 1434 is the SQL Server Browser Service port. This service is disabled by default. This service is only needed when connecting to named SQL Server instances (or default instances listening on non-default ports) from the network. Local connections are able to discover named instances using the registry.

TCP port 1433 is the SQL Server listenning port for default instances. Named instances (like SQLEXPRESS) use a dynamic port by default.

The SQL Server Protocols team has some good practical troubleshooting articles for connectivity issues:

Steps to troubleshoot SQL connectivity issues

How to Troubleshoot Connecting to the SQL Server Database Engine

Solving Connectivity errors to SQL Server


问:
Overriding !important with css or jquery
(This is using content scripts in a chrome extension)

I need to overwrite some css properties that the webpage has labeled as !important. Is this possible?

For instance, if I want to get rid of the border that is labeled important:

```<code>$(".someclass").css('border','none'); //does not work
</code>```

答:
This should help.

```<code>$(".someclass").attr("style","border:none!important");
</code>```

Updated, so as not to overwrite all styles:

```<code>var existingStyles = $(".someclass").attr("style");
$(".someclass").attr("style", existingStyles+"border:none!important");
</code>```

Body:
(This is using content scripts in a chrome extension)

I need to overwrite some css properties that the webpage has labeled as !important. Is this possible?

For instance, if I want to get rid of the border that is labeled important:

$(".someclass").css('border','none'); //does not work

Body:
This should help.

$(".someclass").attr("style","border:none!important");

Updated, so as not to overwrite all styles:

var existingStyles = $(".someclass").attr("style");
$(".someclass").attr("style", existingStyles+"border:none!important");

ContentLicense: CC BY-SA 4.0


问:
Error: Could not find or load main class - Spring Boot Application jar
I built a Spring Boot application and deployed it as a jar to Ubuntu 16.04 LTS.

When I try to run the application by using

java -jar myapp.jar

it works fine.

However, after I created a systemd file to run it as a service, I get the following error:

```<code>myapp.service - myapp
   Loaded: loaded (/etc/systemd/system/myapp.service; disabled; vendor preset: enabled)
   Active: failed (Result: exit-code) since Wed 2017-11-15 08:38:01 UTC; 18s ago
  Process: 5138 ExecStart=/usr/bin/java /var/myapp/myapp.jar (code=exited, status=1/FAILURE)
 Main PID: 5138 (code=exited, status=1/FAILURE)

Nov 15 08:38:01 ip-xxx-xx-xx-xx systemd[1]: Started myapp.
Nov 15 08:38:01 ip-xxx-xx-xx-xx java[5138]: Error: Could not find or load main class .var.myapp.myapp.jar
Nov 15 08:38:01 ip-xxx-xx-xx-xx systemd[1]: myapp.service: Main process exited, code=exited, status=1/FAILURE
Nov 15 08:38:01 ip-xxx-xx-xx-xx systemd[1]: myapp.service: Unit entered failed state.
Nov 15 08:38:01 ip-xxx-xx-xx-xx systemd[1]: myapp.service: Failed with result 'exit-code'.
</code>```

Can someone please help? Thanks.

答:
```<code>ExecStart=/usr/bin/java /var/myapp/myapp.jar
</code>```

You are missing -jar parameter comparing to Your working command. It should be

```<code>ExecStart=/usr/bin/java -jar /var/myapp/myapp.jar
</code>```

Body:
I built a Spring Boot application and deployed it as a jar to Ubuntu 16.04 LTS.

When I try to run the application by using

java -jar myapp.jar

it works fine.

However, after I created a systemd file to run it as a service, I get the following error:

myapp.service - myapp
   Loaded: loaded (/etc/systemd/system/myapp.service; disabled; vendor preset: enabled)
   Active: failed (Result: exit-code) since Wed 2017-11-15 08:38:01 UTC; 18s ago
  Process: 5138 ExecStart=/usr/bin/java /var/myapp/myapp.jar (code=exited, status=1/FAILURE)
 Main PID: 5138 (code=exited, status=1/FAILURE)

Nov 15 08:38:01 ip-xxx-xx-xx-xx systemd[1]: Started myapp.
Nov 15 08:38:01 ip-xxx-xx-xx-xx java[5138]: Error: Could not find or load main class .var.myapp.myapp.jar
Nov 15 08:38:01 ip-xxx-xx-xx-xx systemd[1]: myapp.service: Main process exited, code=exited, status=1/FAILURE
Nov 15 08:38:01 ip-xxx-xx-xx-xx systemd[1]: myapp.service: Unit entered failed state.
Nov 15 08:38:01 ip-xxx-xx-xx-xx systemd[1]: myapp.service: Failed with result 'exit-code'.

Can someone please help? Thanks.

Body:
ExecStart=/usr/bin/java /var/myapp/myapp.jar

You are missing -jar parameter comparing to Your working command. It should be

ExecStart=/usr/bin/java -jar /var/myapp/myapp.jar


问:
Rails controller testing: Testing in isolation or integration?
I'm a bit confused when testing Rails controller, whether to test them in isolation(mocking, less DB hits: faster), or in an integration way(no mocking, a lot of DB hits: slower).

Say we have this example:

```<code>class ProductsController

  def create
    product = Product.new(product_params)
    if product.save
      redirect_to root_path
    else
      render :new
    end
  end

  private

  def product_params
    require(:product).permit(:name, :price)
  end

end

RSpec.describe ProductsController do

  describe '#create in isolation' do
    it "pass" do
      params = { name: "name", price: 100}
      mocked_product = double(save: true)
      expect(Product).to receive(:new).with(params).and_return(mocked_product)

      post :create, params: { product: params }

      expect(response).to be_redirect
    end
  end

  describe '#create in integration' do
    it "pass" do
      params = { name: "name", price: 100}

      post :create, params: { product: params }

      expect(response).to be_redirect
    end
  end

end
</code>```

Testing in isolation doesn't hit the DB which makes it faster, however what if in Product model
we added a description field that is required, where we forget to add it to product_params method, which will
result in Product record not receiving description, and it won't be valid when saved.

Then the first test will pass with no problems, making a false positive that our controller code is okay, where actually
it is not because we have to change product_params method for it to work

The second test will fail because we didn't mock creating the product.

I think this is an open question/topic any way, so I wonder if there is best practices when doing controller tests.

EDIT(generalizing the idea)

I think this can be generalized as it is not limited to controllers but the concept of testing in isolation, the basic idea is the following:

Assume we have a function func(x,y), this function has its own units tests. Then when we have another servive(S) calling func, we will just stub func call as it is tested elsewhere, in order to save time from executing func (especially when it consumes time, like DB hits!)

expect(func).to receive(some_x, some_y).and_return(some_value)

This is the basic idea of testing in isolation.

The problem with this, what if the method signature of func didn't change, however the arguments passed to func from S now will make func throw some exception, due to some implementation changes in func itself, where S is still calling func with the old arguments values, which will result in exception now. And since we mocked calls to func, S test won't catch this error and the code will be deployed successfully.

I believe this is the general pattern

答:
I would go with the integration mode.

Mocking is useful only for long-running operations. You don't need to mock everything.

Database objects creation should not take a long time as long as you are using transactional database cleaners.

If your ActiveRecord object is doing some other long operations like calling some other third party service, you can mock this long-running operation.

If you still think the isolation mode is more suitable for your case, you can set only one test case using the real object. And the other test cases can do mocking. In this case, the false positive case you have mentioned will be covered.

Body:
I'm a bit confused when testing Rails controller, whether to test them in isolation(mocking, less DB hits: faster), or in an integration way(no mocking, a lot of DB hits: slower).

Say we have this example:

class ProductsController

  def create
    product = Product.new(product_params)
    if product.save
      redirect_to root_path
    else
      render :new
    end
  end

  private

  def product_params
    require(:product).permit(:name, :price)
  end

end

RSpec.describe ProductsController do

  describe '#create in isolation' do
    it "pass" do
      params = { name: "name", price: 100}
      mocked_product = double(save: true)
      expect(Product).to receive(:new).with(params).and_return(mocked_product)

      post :create, params: { product: params }

      expect(response).to be_redirect
    end
  end

  describe '#create in integration' do
    it "pass" do
      params = { name: "name", price: 100}

      post :create, params: { product: params }

      expect(response).to be_redirect
    end
  end

end

Testing in isolation doesn't hit the DB which makes it faster, however what if in Product model
we added a description field that is required, where we forget to add it to product_params method, which will
result in Product record not receiving description, and it won't be valid when saved.

Then the first test will pass with no problems, making a false positive that our controller code is okay, where actually
it is not because we have to change product_params method for it to work

The second test will fail because we didn't mock creating the product.

I think this is an open question/topic any way, so I wonder if there is best practices when doing controller tests.

EDIT(generalizing the idea)

I think this can be generalized as it is not limited to controllers but the concept of testing in isolation, the basic idea is the following:

Assume we have a function func(x,y), this function has its own units tests. Then when we have another servive(S) calling func, we will just stub func call as it is tested elsewhere, in order to save time from executing func (especially when it consumes time, like DB hits!)

expect(func).to receive(some_x, some_y).and_return(some_value)

This is the basic idea of testing in isolation.

The problem with this, what if the method signature of func didn't change, however the arguments passed to func from S now will make func throw some exception, due to some implementation changes in func itself, where S is still calling func with the old arguments values, which will result in exception now. And since we mocked calls to func, S test won't catch this error and the code will be deployed successfully.

I believe this is the general pattern


问:
How to fetch data without duplicating products after adding price and stocks
I have a problem in adding price, size and stocks. How can I add price, stocks and size without duplicating?

Here is my database structure:

tblproduct

tblextension

PS: tblproduct product_id and tblproduct_extension product_id are the same.

Here is the result after I add price, stocks and price. As you can see there are two 'Nike Lebron 15 Ghost'.

query

```<code>SELECT * FROM tblproduct LEFT JOIN tblproduct_extension ON tblproduct_extension.product_id = tblproduct.product_id;
</code>```

ajax

```<code>//Show modal for adding size, price and stocks
function add_product_extension() {
    $('#product_add_extension').click(function(e){
        var product_id = $('#product_id').val();
        var product_price = $('#product_price').val();
        var product_stocks = $('#product_stocks').val();
        var product_size = $('#product_size').val();
        $.ajax({
            type: 'POST',
            url: '../admin/class.php',
            data: {product_id:product_id,product_price:product_price,product_stocks:product_stocks,product_size:product_size},
            success:function(data) {
                $('#addSize').modal('hide');
            }
        });
    });
}
</code>```

class.php

```<code>    //Add size, price, stocks
    if(isset($_POST['product_id'])) {
        $product_price = $_POST['product_price'];
        $product_stocks = $_POST['product_stocks'];
        $product_size = $_POST['product_size'];
        $product_id = $_POST['product_id'];

        $insert_query = "INSERT INTO tblproduct_extension (product_stocks, product_price, product_size, product_id)VALUES('$product_stocks', '$product_price', '$product_size', '$product_id')";
        $query = mysqli_query($db_conn, $insert_query);
    }
</code>```

Code to display products

```<code>    //Get Products by ID
    function get_products() {
        GLOBAL $db_conn;
        $id = $_GET['id'];
        $search_query= "SELECT * FROM tblproduct LEFT JOIN tblproduct_extension ON tblproduct_extension.product_id = tblproduct.product_id WHERE tblproduct.segment_id='$id'";
        $query = mysqli_query($db_conn, $search_query);

        while ($row = mysqli_fetch_array($query)) {
            ?>
                <div class="products">
                    <a href="details.php?view_product=<?=$row['product_id']?>&id=<?=$row['segment_id']?>"><img class="img_product" src="../admin/<?=$row['product_image']?>" alt="<?=$row['product_name']?>"></a>
                    <?php if($row['product_stocks'] == 0) {?>
                        <span class="stock-label">SOLD OUT</span>
                    <?php } ?>
                    <h4><?=$row['product_name']?></h4>
                    <h3>₱<?=number_format($row['product_price'], 2)?></h3>
                </div>
            <?php
        }
        return $row;
    }
</code>```

答:
As you can have multiple product_size, you can display also this information with  product name

```<code>...
<h4><?=$row['product_name']?> - Size <?=$row['product_size']?></h4>
...
</code>```

You can do a bit more complex query for achieve what you want (function get_products).

First Select only unique couple of product/extension, with smallest key of extension. From this, you do a second select who fetch data to display.

Those queries were not tested, but that give an idea.

With GROUP BY

```<code>-- 2. After you select your data with unique id get from sub query
SELECT      p.*, pe.*
FROM        tblproduct p
JOIN        (
            -- 1. First select your product_id and smallest product_extension_id
            SELECT      p.product_id,
                        MIN(pe.product_extension_id) as product_extension_id
            FROM        tblproduct p
            LEFT JOIN   tblproduct_extension pe
            ON          pe.product_id = p.product_id
            WHERE       p.segment_id='$id'
            GROUP BY    p.product_id
) product_unique
JOIN        tblproduct_extension pe
ON          pe.product_extension_id = product_unique.product_extension_id
WHERE       p.product_id = product_unique.product_id
</code>```

With DISTINCT

```<code>-- 2. After you select your data with unique id get from sub query
SELECT      p.*, pe.*
FROM        tblproduct p
JOIN        (
            -- 1. First select your product_id and smallest product_extension_id
            SELECT      DISTINCT
                        p.product_id,
                        MIN(pe.product_extension_id) as product_extension_id
            FROM        tblproduct p
            LEFT JOIN   tblproduct_extension pe
            ON          pe.product_id = p.product_id
            WHERE       p.segment_id='$id'
) product_unique
JOIN        tblproduct_extension pe
ON          pe.product_extension_id = product_unique.product_extension_id
WHERE       p.product_id = product_unique.product_id
</code>```

Body:
I have a problem in adding price, size and stocks. How can I add price, stocks and size without duplicating?

Here is my database structure:

tblproduct

tblextension

PS: tblproduct product_id and tblproduct_extension product_id are the same.

Here is the result after I add price, stocks and price. As you can see there are two 'Nike Lebron 15 Ghost'.

query

SELECT * FROM tblproduct LEFT JOIN tblproduct_extension ON tblproduct_extension.product_id = tblproduct.product_id;

ajax

//Show modal for adding size, price and stocks
function add_product_extension() {
    $('#product_add_extension').click(function(e){
        var product_id = $('#product_id').val();
        var product_price = $('#product_price').val();
        var product_stocks = $('#product_stocks').val();
        var product_size = $('#product_size').val();
        $.ajax({
            type: 'POST',
            url: '../admin/class.php',
            data: {product_id:product_id,product_price:product_price,product_stocks:product_stocks,product_size:product_size},
            success:function(data) {
                $('#addSize').modal('hide');
            }
        });
    });
}

class.php

    //Add size, price, stocks
    if(isset($_POST['product_id'])) {
        $product_price = $_POST['product_price'];
        $product_stocks = $_POST['product_stocks'];
        $product_size = $_POST['product_size'];
        $product_id = $_POST['product_id'];

        $insert_query = "INSERT INTO tblproduct_extension (product_stocks, product_price, product_size, product_id)VALUES('$product_stocks', '$product_price', '$product_size', '$product_id')";
        $query = mysqli_query($db_conn, $insert_query);
    }

Code to display products

    //Get Products by ID
    function get_products() {
        GLOBAL $db_conn;
        $id = $_GET['id'];
        $search_query= "SELECT * FROM tblproduct LEFT JOIN tblproduct_extension ON tblproduct_extension.product_id = tblproduct.product_id WHERE tblproduct.segment_id='$id'";
        $query = mysqli_query($db_conn, $search_query);

        while ($row = mysqli_fetch_array($query)) {
            ?>

                    <a href="details.php?view_product=<?=$row['product_id']?>&id=<?=$row['segment_id']?>"><img class="img_product" src="../admin/<?=$row['product_image']?>" alt="<?=$row['product_name']?>">
                    <?php if($row['product_stocks'] == 0) {?>
                        SOLD OUT
                    <?php } ?>

<?=$row['product_name']?>

₱<?=number_format($row['product_price'], 2)?>

            <?php
        }
        return $row;
    }

Body:
As you can have multiple product_size, you can display also this information with  product name

...
<h4><?=$row['product_name']?> - Size <?=$row['product_size']?></h4>
...

You can do a bit more complex query for achieve what you want (function get_products).

First Select only unique couple of product/extension, with smallest key of extension. From this, you do a second select who fetch data to display.

Those queries were not tested, but that give an idea.

With GROUP BY

-- 2. After you select your data with unique id get from sub query
SELECT      p.*, pe.*
FROM        tblproduct p
JOIN        (
            -- 1. First select your product_id and smallest product_extension_id
            SELECT      p.product_id,
                        MIN(pe.product_extension_id) as product_extension_id
            FROM        tblproduct p
            LEFT JOIN   tblproduct_extension pe
            ON          pe.product_id = p.product_id
            WHERE       p.segment_id='$id'
            GROUP BY    p.product_id
) product_unique
JOIN        tblproduct_extension pe
ON          pe.product_extension_id = product_unique.product_extension_id
WHERE       p.product_id = product_unique.product_id

With DISTINCT

-- 2. After you select your data with unique id get from sub query
SELECT      p.*, pe.*
FROM        tblproduct p
JOIN        (
            -- 1. First select your product_id and smallest product_extension_id
            SELECT      DISTINCT
                        p.product_id,
                        MIN(pe.product_extension_id) as product_extension_id
            FROM        tblproduct p
            LEFT JOIN   tblproduct_extension pe
            ON          pe.product_id = p.product_id
            WHERE       p.segment_id='$id'
) product_unique
JOIN        tblproduct_extension pe
ON          pe.product_extension_id = product_unique.product_extension_id
WHERE       p.product_id = product_unique.product_id


问:
Can my chrome extension open a link in a different profile?
I use two different Chrome profiles (users) on my laptop: one for my work stuff and one for my personal browsing.

Sometimes I click a link from HipChat and it opens it in the personal profile even though it's for work (e.g. login.work.com).  (This is because I happen to have been in my personal chrome window most recently.)

I'd like to make a chrome extension I can install in my personal profile to match the URLs of *.work.com and send these over to the work profile window.

I haven't found a way to open a url into a different profile.  Anyone know of a way?

(A hacky idea I got from reading https://superuser.com/a/289618 is maybe I could shell out to something along the lines of google-chrome --user-data-dir=$work_profile, but I'd be happier if there was a JS API and I didn't have to ask permission to run programs on the user's computer.)

答:
There is no solution for this. It would need a handler, a separate program, that captures the URL before it reaches Chrome, parses your preferences for which URLs go to which profile and then starts the specified Chrome installation with specified profile flags.

However, afaik, such a program does not exist (at least on Windows).

Further, Chrome cannot even select which profile out of many is selected, when Chrome is started from the OS "call URL to be opened" function and NOT started by user-activated clicking on a Chrome application shortcut (with specific profile selection instructions).

Naturally, the latter works 100% wonderfully on Firefox, which has built-in profile selector after the browser has been started, and regardless of which method was used to start Firefox (user click on Firefox icon or OS pipe of "open URL" to Firefox).

So; no solution in Chrome.


问:
How to do an action when tab bar item is pressed every time Swift
I am making an application with TabBar. In the Tab Bar there are 2 tabs. One of those tabs is history which is linked with a table view which shows history. I want to refresh that view every time when i click that so that i can get updated tableview. How can i do that? Thanks in advance.</p>

答:
Hi easiest solution for swift 4, to reload view by tapping again on tab bar icon.
</p>

```<code> @objc
 func tabBarController(_ tabBarController: UITabBarController,
                 didSelect viewController: UIViewController) {

    if tabBarController.selectedIndex == 0  {
       viewController.viewDidLoad()
    }
 }
</code>```

Body:
Hi easiest solution for swift 4, to reload view by tapping again on tab bar icon.

 @objc
 func tabBarController(_ tabBarController: UITabBarController,
                 didSelect viewController: UIViewController) {

    if tabBarController.selectedIndex == 0  {
       viewController.viewDidLoad()
    }
 }


问:
Nested Case Statement for multiple condition
I have a data set like bellow image.
I need in the data set

Grade Red is present then in OpenSegment=yes if not but
Grade Amber is present then in OpenSegment=yes if not but
Grade Blue is present then in OpenSegment=yes

for that I write

```<code> COALESCE(
                  CASE WHEN airag.FK_MasterRAGRatingID=1 THEN 'yes' ELSE '' END,
                  CASE WHEN airag.FK_MasterRAGRatingID=2 THEN 'yes' ELSE '' END,
                 CASE WHEN airag.FK_MasterRAGRatingID=4 THEN 'yes' ELSE '' END
                )
</code>```

but not working.

Result after putting  ELSE NULL

答:
I don't even think you need three separate CASE expressions here:

```<code>SELECT
    CASE WHEN airag.FK_MasterRAGRatingID IN (1, 2, 4) THEN 'yes' END AS OpenSegment
    -- other columns
FROM yourTable
</code>```

The above logic should work whether or not the table you showed us is derived.

The default ELSE condition for a CASE expression is NULL.  Hence the above would label open segments of non matching rows as NULL.  If you want to use a different value, then provide an explicit ELSE:

```<code>CASE WHEN airag.FK_MasterRAGRatingID IN (1, 2, 4) THEN 'yes' ELSE '' END
</code>```

This would assume you want to use empty string, but it could be any value.

Body:
I have a data set like bellow image.
I need in the data set

Grade Red is present then in OpenSegment=yes if not but
Grade Amber is present then in OpenSegment=yes if not but
Grade Blue is present then in OpenSegment=yes

for that I write

 COALESCE(
                  CASE WHEN airag.FK_MasterRAGRatingID=1 THEN 'yes' ELSE '' END,
                  CASE WHEN airag.FK_MasterRAGRatingID=2 THEN 'yes' ELSE '' END,
                 CASE WHEN airag.FK_MasterRAGRatingID=4 THEN 'yes' ELSE '' END
                )

but not working.

Result after putting  ELSE NULL

Body:
I don't even think you need three separate CASE expressions here:

SELECT
    CASE WHEN airag.FK_MasterRAGRatingID IN (1, 2, 4) THEN 'yes' END AS OpenSegment
    -- other columns
FROM yourTable

The above logic should work whether or not the table you showed us is derived.

The default ELSE condition for a CASE expression is NULL.  Hence the above would label open segments of non matching rows as NULL.  If you want to use a different value, then provide an explicit ELSE:

CASE WHEN airag.FK_MasterRAGRatingID IN (1, 2, 4) THEN 'yes' ELSE '' END

This would assume you want to use empty string, but it could be any value.


问:
how to take input in a 2D char array using C?
I am getting weird results when I try to take input of a 2D char array for some reason. I have always taken integer 2D arrays in the past this way but somehow this method doesn't work for char arrays.

```<code>#include <stdio.h>

int main()
{
    int i,j,n;
    scanf("%d",&n);
    char a[n][n];
    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
            scanf("%c",&a[i][j]);
    }

    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
            printf("%c",a[i][j]);
    }
    return 0;
}
</code>```

Excepted Input:

3

a b c

d e f

g h i

Expected Output:

a b c

d e f

g h i

What happens:

3

a b c

d e f

(Input abruptly stops)

Output:

a b c

d

答:
Assuming you insert the input like this:

a

whitespace

b

whitespace

c

enter...

then your program has too many chars in the input buffer. You want to read 9 char with scanf("%c") and indeed 9 chars enter the buffer, but they include things you don't want (whitespaces and newlines).

Fix: add whitespace before %c like this - scanf(" %c",&a[i][j]);. This would ignore any sort of whitespace between chars read ('\n' '\t'" ' ').

Body:
I am getting weird results when I try to take input of a 2D char array for some reason. I have always taken integer 2D arrays in the past this way but somehow this method doesn't work for char arrays.

#include <stdio.h>

int main()
{
    int i,j,n;
    scanf("%d",&n);
    char a[n][n];
    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
            scanf("%c",&a[i][j]);
    }

    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
            printf("%c",a[i][j]);
    }
    return 0;
}

Excepted Input:

3

a b c

d e f

g h i

Expected Output:

a b c

d e f

g h i

What happens:

3

a b c

d e f

(Input abruptly stops)

Output:

a b c

d


问:
Bulk inserting new model instances using an hmt relation
I have two models with a "has_many, through" relationship as defined by these definitions:

```<code>class TabAccount < ApplicationRecord
  has_many :tab_community_accounts
  has_many :tab_communities, through: :tab_community_accounts
end

class TabCommunity < ApplicationRecord
  has_many :tab_community_accounts
  has_many :tab_accounts, through: :tab_community_accounts
end

class TabCommunityAccount < ApplicationRecord
  belongs_to :tab_community
  belongs_to :tab_account
end
</code>```

I want to bulk add new accounts from a CSV file after I create a new community. This does not generate an error:

```<code>_upload_dir = <string>
_import_filename = <string>
_community_name = <string>
_this_community = TabCommunity.find_by_name(_community_name)

File.foreach("#{_upload_dir}/#{_import_filename}") do |csv_row_raw|
  csv_row = csv_row_raw.split(",")
  _screen_name = csv_row[0].strip
  _this_community.tab_accounts.first_or_create!({screen_name: _screen_name, ref_platform_id: RefPlatform.find_by_name("Twitter").id})
end
</code>```

But it only inserts a new account and hmt relation for the first row from the CSV file. I want to use .first_or_create() because the account might already exist in the database. I added put statements inside the foreach before and after .first_or_create() and they do print for each row, but only the 1st row and its relation is saved in my database. Can anyone clue me in as to how I can dump the rest of the rows? I suspect I'm close.

答:
You can make sure if an account already exists or create otherwise by using find_or_create_by! on TabAccount model itself and assign it back to the TabCommunity relation like so:

```<code>acc = TabAccount.find_or_create_by!(
  screen_name: _screen_name,
  ref_platform_id: RefPlatform.find_by_name("Twitter").id
)
_this_community.tab_accounts << acc unless _this_community.tab_accounts.include?(acc)
</code>```

Body:
I have two models with a "has_many, through" relationship as defined by these definitions:

class TabAccount < ApplicationRecord
  has_many :tab_community_accounts
  has_many :tab_communities, through: :tab_community_accounts
end

class TabCommunity < ApplicationRecord
  has_many :tab_community_accounts
  has_many :tab_accounts, through: :tab_community_accounts
end

class TabCommunityAccount < ApplicationRecord
  belongs_to :tab_community
  belongs_to :tab_account
end

I want to bulk add new accounts from a CSV file after I create a new community. This does not generate an error:

_upload_dir = <string>
_import_filename = <string>
_community_name = <string>
_this_community = TabCommunity.find_by_name(_community_name)

File.foreach("#{_upload_dir}/#{_import_filename}") do |csv_row_raw|
  csv_row = csv_row_raw.split(",")
  _screen_name = csv_row[0].strip
  _this_community.tab_accounts.first_or_create!({screen_name: _screen_name, ref_platform_id: RefPlatform.find_by_name("Twitter").id})
end

But it only inserts a new account and hmt relation for the first row from the CSV file. I want to use .first_or_create() because the account might already exist in the database. I added put statements inside the foreach before and after .first_or_create() and they do print for each row, but only the 1st row and its relation is saved in my database. Can anyone clue me in as to how I can dump the rest of the rows? I suspect I'm close.

Body:
You can make sure if an account already exists or create otherwise by using find_or_create_by! on TabAccount model itself and assign it back to the TabCommunity relation like so:

acc = TabAccount.find_or_create_by!(
  screen_name: _screen_name,
  ref_platform_id: RefPlatform.find_by_name("Twitter").id
)
_this_community.tab_accounts << acc unless _this_community.tab_accounts.include?(acc)


问:
you missing a using directive or an assembly reference?
'Microsoft.Reporting.WinForms.ReportViewer' does not contain a definition for 'ReportSource' and no extension method 'ReportSource' accepting a first argument of type 'Microsoft.Reporting.WinFord (are you missing a using directive or an assembly reference?

Please help

答: "are you missing a using directive or an assembly reference" means that you have lost some assemblies . you need to add.</p>


问:
Administrate Gem does not yet support namespaced models
Am working on a Modular Rails Application by following TutsPlus Modular Rails App training here.

However, after install Administrate Gem and running rails generate administrate:install to install my dashboard, I get the error as is in the image below:

In short Administrated Gem doesn't work with a Modular Rails App. How do I solve this problem or how do I make Administrate Gem support Namespaced Models???

What I have done:

I have tried to hard code a dashboard, but wont just work with Administrate (Rails just cant fine Administrate Gem in a Modular Rails App because of that error, but works with a Monolithic Rails App).

答:
Read and follow carefully the instruction, then update me

What Is Administrate?

Administrate is a library for Rails apps that automatically generates admin dashboards. Administrate's admin dashboards give non-technical users clean interfaces that allow them to create, edit, search, and delete records for any model in the application.

Administrate solves the same problem as Rails Admin and ActiveAdmin, but aims to provide a better user experience for site admins, and to be easier for developers to customize.

To accomplish these goals, Administrate follows a few guiding principles:

No DSLs (domain-specific languages)

Support the simplest use cases,
and let the user override defaults with standard tools such as plain
Rails controllers and views.

Break up the library into core components and plugins, so each component stays small and easy to maintain.

Getting Started

Administrate supports Rails from 4.2, up to 5.0 and beyond.

Add Administrate to your Gemfile and re-bundle:

```<code>gem "administrate"
</code>```

Then RUN bundle install in your terminal!!!

The included installer will create dashboards for each model in your app, complete with routes:

```<code>$ rails generate administrate:install
</code>```

Restart your server, and visit http://localhost:3000/admin to see your new dashboard in action.

For more detailed instructions or to make it work with Rails API-only applications, please go through the 'Getting Started` guide.

Body:
Read and follow carefully the instruction, then update me

What Is Administrate?

Administrate is a library for Rails apps that automatically generates admin dashboards. Administrate's admin dashboards give non-technical users clean interfaces that allow them to create, edit, search, and delete records for any model in the application.

Administrate solves the same problem as Rails Admin and ActiveAdmin, but aims to provide a better user experience for site admins, and to be easier for developers to customize.

To accomplish these goals, Administrate follows a few guiding principles:

No DSLs (domain-specific languages)

Support the simplest use cases,
and let the user override defaults with standard tools such as plain
Rails controllers and views.

Break up the library into core components and plugins, so each component stays small and easy to maintain.

Getting Started

Administrate supports Rails from 4.2, up to 5.0 and beyond.

Add Administrate to your Gemfile and re-bundle:

gem "administrate"

Then RUN bundle install in your terminal!!!

The included installer will create dashboards for each model in your app, complete with routes:

$ rails generate administrate:install

Restart your server, and visit http://localhost:3000/admin to see your new dashboard in action.

For more detailed instructions or to make it work with Rails API-only applications, please go through the 'Getting Started` guide.


问:
Get spinner selected item inside RecyclerView
I have added Spinner inside RecyclerView , when i am trying to get spinner selected item data, its getting another/wrong position data, any one suggest me to get correct selected item and position from Spinner onItemSelected

Here is my code

```<code>@Override
public void onBindViewHolder(final QuestionHolder holder, final int position) {
        if (position % 2 == 1)
            holder.itemView.setBackgroundColor(Color.parseColor("#F8F8F8"));
        adapter = new ArrayAdapter<Option>(binding.getRoot().getContext(),
                        R.layout.item_spinner, questionList.get(position).getOptions());
        adapter.setDropDownViewResource(R.layout.item_spinner);
        binding.optionSpinner.setAdapter(adapter);

        binding.serialNo.setText((position + 1) + ".");
        binding.setQuestion(questionList.get(position));
        binding.executePendingBindings();
        binding.optionSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(holder.itemView.getContext(), position+" : "+binding.optionSpinner.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
                spinnerData.setSelectedData(position, binding.optionSpinner.getSelectedItem().toString());
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }
</code>```

答:
Check this, can be helpful and may fix your problem. If this won't fix your problem at least you get rid of Lint error. Lint error “Do not treat position as fixed; only use immediately…”. So everywhere you are using final int position** change it to getAdapterPosition();

The documentation of RecyclerView.Adapter.onBindViewHolder()
  states:

Note that unlike ListView, RecyclerView will not call this method
    again if the position of the item changes in the data set unless the
    item itself is invalidated or the new position cannot be determined.
    For this reason, you should only use the position parameter while
    acquiring the related data item inside this method and should not keep
    a copy of it. If you need the position of an item later on (e.g. in a
    click listener), use getAdapterPosition() which will have the updated
    adapter position

So, technically items may be re-arranged and binding will not be
    necessary because items are not invalidated yet. The position
    variable received holds true only for the scope of bind function and
    will not always point to correct position in the data set. That's why
    the function getAdapterPosition() must be called everytime updated
    position is needed.

IMHO, mLastPosition = holder.getAdapterPosition(); is still
    potentially wrong. Because item may be re-arranged and mLastPosition
    still points to old position.

About why lint is silent, perhaps Lint rule is not that thorough. Its
    only checking whether position parameter is being copied or not.

Body:
I have added Spinner inside RecyclerView , when i am trying to get spinner selected item data, its getting another/wrong position data, any one suggest me to get correct selected item and position from Spinner onItemSelected

Here is my code

@Override
public void onBindViewHolder(final QuestionHolder holder, final int position) {
        if (position % 2 == 1)
            holder.itemView.setBackgroundColor(Color.parseColor("#F8F8F8"));
        adapter = new ArrayAdapter<Option>(binding.getRoot().getContext(),
                        R.layout.item_spinner, questionList.get(position).getOptions());
        adapter.setDropDownViewResource(R.layout.item_spinner);
        binding.optionSpinner.setAdapter(adapter);

        binding.serialNo.setText((position + 1) + ".");
        binding.setQuestion(questionList.get(position));
        binding.executePendingBindings();
        binding.optionSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(holder.itemView.getContext(), position+" : "+binding.optionSpinner.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
                spinnerData.setSelectedData(position, binding.optionSpinner.getSelectedItem().toString());
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }


问:
Guaranteed file deletion upon program termination (C/C++)
Win32's CreateFile has FILE_FLAG_DELETE_ON_CLOSE, but I'm on Linux.

I want to open a temporary file which will always be deleted upon program termination.  I could understand that in the case of a program crash it may not be practical to guarantee this, but in any other case I'd like it to work.

I know about RAII.  I know about signals.  I know about atexit(3).  I know I can open the file and delete it immediately and the file will remain accessible until the file descriptor is closed (which even handles a crash).  None of these seem like a complete and straightforward solution:

RAII: been there, done that: I have an object whose destructor deletes the file, but the destructor is not called if the program is terminated by a signal.

signals: I'm writing a low-level library which makes registering a signal handler a tricky proposition.  For example, what if the application uses signals itself?  I don't want to step on any toes.  I might consider some clever use of sigaction(2) to cope...but haven't put enough thought into this possibility yet.

atexit(3): apparently useless, since it isn't called during abnormal termination (e.g. via a signal).

preemptive unlink(2): this is pretty good except that I need the file to remain visible in the filesystem (otherwise the system is harder to monitor/troubleshoot).

What would you do here?

Further Explanation

I elided one detail in my original post which I now realize I should have included.  The "file" in this case is not strictly a normal file, but rather is a POSIX Message Queue.  I create it via mq_open().  It can be closed via mq_close() or close() (the former is an alias for the latter on my system).  It can be removed from the system via mq_unlink().  All of this makes it analogous to a regular file, except that I cannot choose the directory in which the file resides.  This makes the current most popular answer (placing the file in /tmp) unworkable, because the "file" is created by the system in a virtual filesystem with very limited capacity.  (I've mounted the virtual filesystem in /dev/mqueue, following the example in man mq_overview) .

This also explains why I need the name to remain visible (making the immediate-unlink approach unworkable): the "file" must be shared between two or more processes.

答: You could have the process fork after creating the file, and then wait on the child to close, and then the parent can unlink the file and exit.</p>

OwnerDisplayName: John Zwinck

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: John Zwinck

OwnerDisplayName: Nikron


问:
Processing a Django UploadedFile as UTF-8 with universal newlines
In my django application, I provide a form that allows users to upload a file. The file can be in a variety of formats (Excel, CSV), come from a variety of platforms (Mac, Linux, Windows), and be encoded in a variety of encodings (ASCII, UTF-8).

For the purpose of this question, let's assume that I have a view which is receiving request.FILES['file'], which is an instance of InMemoryUploadedFile, called file. My problem is that InMemoryUploadedFile objects (like file):

Do not support UTF-8 encoding (I see a \xef\xbb\xbf at the beginning of the file, which as I understand is a flag meaning 'this file is UTF-8').

Do not support universal newlines (which probably the majority of the files uploaded to this system will need).

Complicating the issue is that I wish to pass the file in to the python csv module, which does not natively support Unicode. I will happily accept answers that avoid this issue - once I get django playing nice with UTF-8 I'm sure I can bludgeon csv into doing the same. (Similarly, please ignore the requirement to support Excel - I am waiting until CSV works before I tackle parsing Excel files.)

I have tried using StringIO,mmap,codec, and any of a wide variety of ways of accessing the data in an InMemoryUploadedFile object. Each approach has yielded differing errors, none so far have been perfect. This shows some of the code that I feel came the closest:

```<code>import csv
import codecs

class CSVParser:
    def __init__(self,file):
        # 'file' is assumed to be an InMemoryUploadedFile object.
        dialect = csv.Sniffer().sniff(codecs.EncodedFile(file,"utf-8").read(1024))
        file.open() # seek to 0
        self.reader = csv.reader(codecs.EncodedFile(file,"utf-8"),
                                 dialect=dialect)
        try:
            self.field_names = self.reader.next()
        except StopIteration:
            # The file was empty - this is not allowed.
            raise ValueError('Unrecognized format (empty file)')

        if len(self.field_names) <= 1:
            # This probably isn't a CSV file at all.
            # Note that the csv module will (incorrectly) parse ALL files, even
            # binary data. This will catch most such files.
            raise ValueError('Unrecognized format (too few columns)')

        # Additional methods snipped, unrelated to issue
</code>```

Please note that I haven't spent too much time on the actual parsing algorithm so it may be wildly inefficient, right now I'm more concerned with getting encoding to work as expected.

The problem is that the results are also not encoded, despite being wrapped in the Unicode codecs.EncodedFile file wrapper.

EDIT: It turns out, the above code does in fact work. codecs.EncodedFile(file,"utf-8") is the ticket. It turns out the reason I thought it didn't work was that the terminal I was using does not support UTF-8. Live and learn!

答: For CSV and Excel upload to django, this site may help.</p>

Body:
In my django application, I provide a form that allows users to upload a file. The file can be in a variety of formats (Excel, CSV), come from a variety of platforms (Mac, Linux, Windows), and be encoded in a variety of encodings (ASCII, UTF-8).

For the purpose of this question, let's assume that I have a view which is receiving request.FILES['file'], which is an instance of InMemoryUploadedFile, called file. My problem is that InMemoryUploadedFile objects (like file):

Do not support UTF-8 encoding (I see a \xef\xbb\xbf at the beginning of the file, which as I understand is a flag meaning 'this file is UTF-8').

Do not support universal newlines (which probably the majority of the files uploaded to this system will need).

Complicating the issue is that I wish to pass the file in to the python csv module, which does not natively support Unicode. I will happily accept answers that avoid this issue - once I get django playing nice with UTF-8 I'm sure I can bludgeon csv into doing the same. (Similarly, please ignore the requirement to support Excel - I am waiting until CSV works before I tackle parsing Excel files.)

I have tried using StringIO,mmap,codec, and any of a wide variety of ways of accessing the data in an InMemoryUploadedFile object. Each approach has yielded differing errors, none so far have been perfect. This shows some of the code that I feel came the closest:

import csv
import codecs

class CSVParser:
    def __init__(self,file):
        # 'file' is assumed to be an InMemoryUploadedFile object.
        dialect = csv.Sniffer().sniff(codecs.EncodedFile(file,"utf-8").read(1024))
        file.open() # seek to 0
        self.reader = csv.reader(codecs.EncodedFile(file,"utf-8"),
                                 dialect=dialect)
        try:
            self.field_names = self.reader.next()
        except StopIteration:
            # The file was empty - this is not allowed.
            raise ValueError('Unrecognized format (empty file)')

        if len(self.field_names) <= 1:
            # This probably isn't a CSV file at all.
            # Note that the csv module will (incorrectly) parse ALL files, even
            # binary data. This will catch most such files.
            raise ValueError('Unrecognized format (too few columns)')

        # Additional methods snipped, unrelated to issue

Please note that I haven't spent too much time on the actual parsing algorithm so it may be wildly inefficient, right now I'm more concerned with getting encoding to work as expected.

The problem is that the results are also not encoded, despite being wrapped in the Unicode codecs.EncodedFile file wrapper.

EDIT: It turns out, the above code does in fact work. codecs.EncodedFile(file,"utf-8") is the ticket. It turns out the reason I thought it didn't work was that the terminal I was using does not support UTF-8. Live and learn!


问:
Gradle task ordering issue in Android Studio
I am using Android Studio 2.2 Beta 3 and my test project uses CMake to build a hybrid C++ and Java app. The JNI interface is generated by SWIG. This means that I would want to generate the SWIG wrappers before the externalNativeBuild and JavaCompile gradle tasks; ie my CMakeLists.txt specifies the cpp wrapper file generated by SWIG and my java code imports the java wrapper files generated by SWIG.

To ensure SWIG is run and generates the necessary wrapper files before any tasks, I specifies the following in my app/build.gradle file

```<code>project.afterEvaluate {
    preBuild.dependsOn("runSwig")
}
</code>```

When I run from the commandline using the command

```<code>./gradlew assembleDebug
</code>```

I do not face any issues and as expected my task "runSwig" runs before any of the other tasks

```<code>:app:runSwig
:app:preBuild
:app:preDebugBuild
<blah blah more tasks>
:app:externalNativeBuildDebug
</code>```

But issue is when the project is first opened in Android Studio, it looks like the external native build gets invoked before runSwig and I get the error

```<code>CMake Error at CMakeLists.txt:79 (add_library):
  Cannot find source file:

    ../../../wrap.cxx

  Tried extensions .c .C .c++ .cc .cpp .cxx .m .M .mm .h .hh .h++ .hm .hpp
  .hxx .in .txx

FAILURE: Build failed with an exception.
</code>```

The error does not go away till I either assemble using command line OR, remove the wrap.cxx file from my CMakeLists.txt and re-add it after swig gets run successfully at-least once.

答:
I've run into this same problem with the order of the build in Android Studio 3 (and 2.3 I guess).

I don't know if this is a traditionally valid solution, but it -seems- to work in my Android/SWIG/NDK example (here: https://github.com/sureshjoshi/android-ndk-swig-example)

I added this into my Gradle file, so that CMake is called before the build fails out on missing files. CMake calls SWIG to auto-generate my Java files and place them appropriately.

```<code>project.afterEvaluate {
    javaPreCompileDebug.dependsOn externalNativeBuildDebug
}
</code>```

I probably also need a

```<code>javaPreCompileRelease.dependsOn externalNativeBuildRelease
</code>```

or something similar... Just haven't tested it yet.

Stemmed from this issue: https://github.com/sureshjoshi/android-ndk-swig-example/issues/8

Body:
I am using Android Studio 2.2 Beta 3 and my test project uses CMake to build a hybrid C++ and Java app. The JNI interface is generated by SWIG. This means that I would want to generate the SWIG wrappers before the externalNativeBuild and JavaCompile gradle tasks; ie my CMakeLists.txt specifies the cpp wrapper file generated by SWIG and my java code imports the java wrapper files generated by SWIG.

To ensure SWIG is run and generates the necessary wrapper files before any tasks, I specifies the following in my app/build.gradle file

project.afterEvaluate {
    preBuild.dependsOn("runSwig")
}

When I run from the commandline using the command

./gradlew assembleDebug

I do not face any issues and as expected my task "runSwig" runs before any of the other tasks

:app:runSwig
:app:preBuild
:app:preDebugBuild
<blah blah more tasks>
:app:externalNativeBuildDebug

But issue is when the project is first opened in Android Studio, it looks like the external native build gets invoked before runSwig and I get the error

CMake Error at CMakeLists.txt:79 (add_library):
  Cannot find source file:

    ../../../wrap.cxx

  Tried extensions .c .C .c++ .cc .cpp .cxx .m .M .mm .h .hh .h++ .hm .hpp
  .hxx .in .txx

FAILURE: Build failed with an exception.

The error does not go away till I either assemble using command line OR, remove the wrap.cxx file from my CMakeLists.txt and re-add it after swig gets run successfully at-least once.

Body:
I've run into this same problem with the order of the build in Android Studio 3 (and 2.3 I guess).

I don't know if this is a traditionally valid solution, but it -seems- to work in my Android/SWIG/NDK example (here: https://github.com/sureshjoshi/android-ndk-swig-example)

I added this into my Gradle file, so that CMake is called before the build fails out on missing files. CMake calls SWIG to auto-generate my Java files and place them appropriately.

project.afterEvaluate {
    javaPreCompileDebug.dependsOn externalNativeBuildDebug
}

I probably also need a

javaPreCompileRelease.dependsOn externalNativeBuildRelease

or something similar... Just haven't tested it yet.

Stemmed from this issue: https://github.com/sureshjoshi/android-ndk-swig-example/issues/8


问:
Where did RU/m go?
This used to be a feature of CosmosDb to provision Request Units Per Minute (as well as Request Units Per Second) however the option appears to have disappeared from the portal and all online documentation has been removed?

Thanks, Oliver

答:
RU/m is dead

Just received a response from Microsoft

We received a ton of feedback from our customers who participated in the Preview program; starting 8/25/2017, we have officially closed the Preview program for RU/M. Based on all customer feedback, we believe that we have a good understanding of how we can dramatically improve the capability by making it easier to use and by making it useful across all workloads (instead of a just few).

Title: Where did RU/m go?


问:
Method .click() in JavaScript
I have this textarea:

```<code><textarea id="updElement"></textarea>
</code>```

And I use it with the script:

```<code>    document.getElementById('updElement').onchange = function () {
    var l = document.getElementsByClassName("dijitTreeRowSelected");
    l[0].click();
};
</code>```

So when I change manually the textarea by adding some symbols, my script is running. But my problem is, that I need to run the script by calling like a function for example:

```<code>function changeTree(){
    var l = document.getElementsByClassName("dijitTreeRowSelected");
    l[0].click();
}
</code>```

but it does not work. I am not using any library.

答:
I tested the code here, it is working,

  document.getElementById('updElement').onchange = function() {
    changeTree();
  };

function changeTree() {
  var l = document.getElementsByClassName("dijitTreeRowSelected");
  l[0].click();
} ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><textarea id="updElement"></textarea>
<button class="dijitTreeRowSelected" onclick="alert('element click event triggred from somewhwre')">
        Test DOM Element
        </button></code>```

Test example Fiddle: https://jsfiddle.net/vesm7n45/7/

Title: Method .click() in JavaScript

Body:
I have this textarea:

<textarea id="updElement"></textarea>

And I use it with the script:

    document.getElementById('updElement').onchange = function () {
    var l = document.getElementsByClassName("dijitTreeRowSelected");
    l[0].click();
};

So when I change manually the textarea by adding some symbols, my script is running. But my problem is, that I need to run the script by calling like a function for example:

function changeTree(){
    var l = document.getElementsByClassName("dijitTreeRowSelected");
    l[0].click();
}

but it does not work. I am not using any library.

Body:
I tested the code here, it is working,

  document.getElementById('updElement').onchange = function() {
    changeTree();
  };

function changeTree() {
  var l = document.getElementsByClassName("dijitTreeRowSelected");
  l[0].click();
}

<textarea id="updElement"></textarea>
<button class="dijitTreeRowSelected" onclick="alert('element click event triggred from somewhwre')">
        Test DOM Element
        </button>

Test example Fiddle: https://jsfiddle.net/vesm7n45/7/


问:
NSDate - one year ago, dilemma
I'm trying to do something that, for me, is a bit difficult. But I'm sure someone has some insight.

Given a date, say January 17, 2011, I'm trying to figure out the day that corresponds to this date one year ago. So January 17, 2011 is a Monday, and one year ago, this day fell on January 18, 2010 (a Monday as well). It turns out that January 18, 2010 is 354 days before January 17, 2011. I originally thought to just simply subtract 365 days for a non-leap year and 366 days for a leap year, but if you do that in this case, you would get January 17, 2010, which is a Sunday, not a Monday.

So, in Objective-C with NSDate and NSCalendar, how could I implement a function such as:

```<code>-(NSDate *)logicalOneYearAgo:(NSDate *)from {
}
</code>```

In other words, the nth "weekday" of the nth month (where "weekday" is Monday or Tuesday or Wednesday etc)

答:
The answer turned out to be pretty simple. It turned out from trial and error. Here's the answer.

if the year is a leap year, subtract 365 days.

if the year is not a leap year, subtract 364 days.

Title: NSDate - one year ago, dilemma

Body:
I'm trying to do something that, for me, is a bit difficult. But I'm sure someone has some insight.

Given a date, say January 17, 2011, I'm trying to figure out the day that corresponds to this date one year ago. So January 17, 2011 is a Monday, and one year ago, this day fell on January 18, 2010 (a Monday as well). It turns out that January 18, 2010 is 354 days before January 17, 2011. I originally thought to just simply subtract 365 days for a non-leap year and 366 days for a leap year, but if you do that in this case, you would get January 17, 2010, which is a Sunday, not a Monday.

So, in Objective-C with NSDate and NSCalendar, how could I implement a function such as:

-(NSDate *)logicalOneYearAgo:(NSDate *)from {
}

In other words, the nth "weekday" of the nth month (where "weekday" is Monday or Tuesday or Wednesday etc)


问:
Passing Parameters to template While Launching using Dataflow API
I have to Pass Parameters to Template While launching Using Dataflow API's in App Engine Dataflow Job.

```<code> com.google.api.services.dataflow.Dataflow.Projects.Locations.Templates.Launch request1 =

    dataflowService.projects().locations().templates().launch(projectId,"us-central1",null);

                request1.setGcsPath(template);
                request1.setLocation("us-central1");
                request1.setValidateOnly(false);

                //Storing launch Response
                LaunchTemplateResponse response1 = request1.execute();
</code>```

In My Code, I am Able to Set GCS path, Location, and Validity but not able to set Parameters Like in Cloud Function. is Thier any method to Set Parameters Using java. Because in Python its Possible So I thought So in Java.

答:
To Pass A parameter I Used -:
LaunchTemplateParameters parameters = new LaunchTemplateParameters();</p>

```<code>LaunchTemplateParameters parameters = new LaunchTemplateParameters();
    Map<String,String> map = new HashMap<String,String>();
            map.put("inputFile", "gs://xyz-bucket/Temp.txt");
parameters.setParameters(map);
        com.google.api.services.dataflow.Dataflow.Projects.Locations.Templates.Launch request1 =
                        dataflowService.projects().locations().templates().launch(projectId,"us-central1",parameters);

            request1.setGcsPath(template);
            request1.setLocation("us-central1");
            request1.setValidateOnly(false);

            LaunchTemplateResponse response1 = request1.execute();
</code>```

Body:
I have to Pass Parameters to Template While launching Using Dataflow API's in App Engine Dataflow Job.

 com.google.api.services.dataflow.Dataflow.Projects.Locations.Templates.Launch request1 =

    dataflowService.projects().locations().templates().launch(projectId,"us-central1",null);

                request1.setGcsPath(template);
                request1.setLocation("us-central1");
                request1.setValidateOnly(false);

                //Storing launch Response
                LaunchTemplateResponse response1 = request1.execute();

In My Code, I am Able to Set GCS path, Location, and Validity but not able to set Parameters Like in Cloud Function. is Thier any method to Set Parameters Using java. Because in Python its Possible So I thought So in Java.

Body:
To Pass A parameter I Used -:
LaunchTemplateParameters parameters = new LaunchTemplateParameters();

LaunchTemplateParameters parameters = new LaunchTemplateParameters();
    Map<String,String> map = new HashMap<String,String>();
            map.put("inputFile", "gs://xyz-bucket/Temp.txt");
parameters.setParameters(map);
        com.google.api.services.dataflow.Dataflow.Projects.Locations.Templates.Launch request1 =
                        dataflowService.projects().locations().templates().launch(projectId,"us-central1",parameters);

            request1.setGcsPath(template);
            request1.setLocation("us-central1");
            request1.setValidateOnly(false);

            LaunchTemplateResponse response1 = request1.execute();


问:
Java: I keep on getting an odd output
Whenever I run this code I keep on getting: </p>

```<code>java.lang.NumberFormatException: null

at java.lang.Integer.parseInt(Unknown Source)

at java.lang.Integer.parseInt(Unknown Source)

at UseEmployeeRecord.main(UseEmployeeRecord.java:24)
</code>```

<p>as an output. </p>

```<code>// The "UseEmployeeRecord" class.
import java.awt.*;
import hsa.Console;
import java.io.*;

public class UseEmployeeRecord {

   public static void main (String[] args) throws IOException {

       BufferedReader fr = new BufferedReader (new FileReade("employees.txt"));
        String name;
        int num;
        double hr, hw;

        EmployeeRecord employee[] = new EmployeeRecord [10];

        for (int i = 0 ; i < employee.length ; i++)
        {
            name= fr.readLine ();
            num = Integer.parseInt (fr.readLine ());
            hr = Double.parseDouble (fr.readLine ());
            hw = Double.parseDouble (fr.readLine ());

            employee [i] = new EmployeeRecord (name, num, hr, hw);

       }
   }
}
</code>```

答:
You have not pasted the contents of employees.txt

Exception is clear.

If the value from employees.txt is String representation of "Integer" e.g

Integer.parseInt("1") will not throw exception but for sure Integer.parseInt(null) or Integer.parseInt("x")  will throw exception. So for debugging, print the value of readLine and see if it really represents an integer.

Title: Java: I keep on getting an odd output

Body:
Whenever I run this code I keep on getting:

java.lang.NumberFormatException: null

at java.lang.Integer.parseInt(Unknown Source)

at java.lang.Integer.parseInt(Unknown Source)

at UseEmployeeRecord.main(UseEmployeeRecord.java:24)

as an output.

// The "UseEmployeeRecord" class.
import java.awt.*;
import hsa.Console;
import java.io.*;

public class UseEmployeeRecord {

   public static void main (String[] args) throws IOException {

       BufferedReader fr = new BufferedReader (new FileReade("employees.txt"));
        String name;
        int num;
        double hr, hw;

        EmployeeRecord employee[] = new EmployeeRecord [10];

        for (int i = 0 ; i < employee.length ; i++)
        {
            name= fr.readLine ();
            num = Integer.parseInt (fr.readLine ());
            hr = Double.parseDouble (fr.readLine ());
            hw = Double.parseDouble (fr.readLine ());

            employee [i] = new EmployeeRecord (name, num, hr, hw);

       }
   }
}


问:
Child UIViews unable to receive touch events
I have a UIViewController that embeds a UITableView. This table view is 3/4 the size of the entire screen in height. the remaining 1/4th of the UIViewController has a rounded UIButton that triggers a new UIView on top of the parent view. (UITableView).

Upon instantiating and calling a UIView with a background that is set to:
 self.backgroundColor = UIColor(black: 1, alpha: 0.5) it would normally fill the entire view with a black see-through background that will then have an additional UIView with the following constraints:

```<code>Leading: 10
Trailing: 10
Top: 50
Bottom: 50
</code>```

this, in turn, gives me a 'Card' effect on top of the tableView. This 'Card' view then has a UITextview property that is supposed to show the keyboard when the user taps the view with the textview embedded.

The Problem:
Upon selecting the UITextview, or even touching this 'Card' view, the background table is being selected and interacted with. Neither the 'Card' textfield raises the keyboard nor does it make itself solely interactive as the parent table controller seems to be getting the touch events.

Is there any solution to this problem that is encountered in iOS 11? I never experienced this issue in iOS 10. I am using iPhone X for the further note on my issue.

Here is an example of the actual issue occurring.

NOTE: If I were to select the dark area of the card itself, the table view would receive touch events but not the text area within the card view. The reason this card view has the keyboard showing is that I called it manually in code with the textview.becomeFirstResponder method.

ADDITIONAL NOTES: I have also enabled the isUserInteractionEnabled = false on the overall presenting child view. Still does not work and parent view receives touches only.

Code for the Card

```<code>class Card: UIView {

// instantiating the textview
var textview = UITextview()
var cardView = UIView()

private override init(frame: CGRect) {
    super.init(frame: frame)

    self.backgroundColor = UIColor(black: 1, alpha: 0.5)
    self.cardView.backgroundColor = UIColor.white
    self.cardView.layer.cornerRadius = 8

    // Just demo the textview
    self.textview.frame = CGRect(x: 10, y: 100, width: 300. height: 100)

    self.addSubview(cardView) // adding the cardView as a subview to the background colored view
    cardView.addSubview(textview)

}

required init?(coder aDecoder: NSCoder) {
    fatalError("Error")
}

private func ConstrainCardWith() {
    // Constraints

}

}
 extension UIView {

func Width()-> CGFloat {
    return UIScreen.main.bounds.size.width
}
func Height()-> CGFloat{
    return UIScreen.main.bounds.size.height
}
}
</code>```

答: The question is your container view(cardview) has no frame, so your child view(textview) can not be touch cause it is out of bounds, so just add some frame in your card view will solve this question</p>

Body:
I have a UIViewController that embeds a UITableView. This table view is 3/4 the size of the entire screen in height. the remaining 1/4th of the UIViewController has a rounded UIButton that triggers a new UIView on top of the parent view. (UITableView).

Upon instantiating and calling a UIView with a background that is set to:
 self.backgroundColor = UIColor(black: 1, alpha: 0.5) it would normally fill the entire view with a black see-through background that will then have an additional UIView with the following constraints:

Leading: 10
Trailing: 10
Top: 50
Bottom: 50

this, in turn, gives me a 'Card' effect on top of the tableView. This 'Card' view then has a UITextview property that is supposed to show the keyboard when the user taps the view with the textview embedded.

The Problem:
Upon selecting the UITextview, or even touching this 'Card' view, the background table is being selected and interacted with. Neither the 'Card' textfield raises the keyboard nor does it make itself solely interactive as the parent table controller seems to be getting the touch events.

Is there any solution to this problem that is encountered in iOS 11? I never experienced this issue in iOS 10. I am using iPhone X for the further note on my issue.

Here is an example of the actual issue occurring.

NOTE: If I were to select the dark area of the card itself, the table view would receive touch events but not the text area within the card view. The reason this card view has the keyboard showing is that I called it manually in code with the textview.becomeFirstResponder method.

ADDITIONAL NOTES: I have also enabled the isUserInteractionEnabled = false on the overall presenting child view. Still does not work and parent view receives touches only.

Code for the Card

class Card: UIView {

// instantiating the textview
var textview = UITextview()
var cardView = UIView()

private override init(frame: CGRect) {
    super.init(frame: frame)

    self.backgroundColor = UIColor(black: 1, alpha: 0.5)
    self.cardView.backgroundColor = UIColor.white
    self.cardView.layer.cornerRadius = 8

    // Just demo the textview
    self.textview.frame = CGRect(x: 10, y: 100, width: 300. height: 100)

    self.addSubview(cardView) // adding the cardView as a subview to the background colored view
    cardView.addSubview(textview)

}

required init?(coder aDecoder: NSCoder) {
    fatalError("Error")
}

private func ConstrainCardWith() {
    // Constraints

}

}
 extension UIView {

func Width()-> CGFloat {
    return UIScreen.main.bounds.size.width
}
func Height()-> CGFloat{
    return UIScreen.main.bounds.size.height
}
}


问:
Convert(int, value) causes error based on where clause
Following one works perfectly (notice convert):

```<code>select (select Twr_Kod from whm.CDN.TwrKarty where Twr_GIDNumer=Convert(int, value))
 from Workflow.ControlValues
 inner join Workflow.Controls on Controls.ID=ControlID and Controls.ValueTypeID=1
</code>```

However if I will make it subquery if causes error on converting value:

```<code>select
(select (select Twr_Kod from whm.CDN.TwrKarty where Twr_GIDNumer=Convert(int, value))
 from Workflow.ControlValues
 inner join Workflow.Controls on Controls.ID=ControlID and Controls.ValueTypeID=1
  where ItemID=Items.ID
   for XML path(''))
    from Offers.Items
</code>```

I thought that where will exclude some rows, so it shouldn't cause any issues with convert. Do you know what is the reason of that behavior and how to prevent it?

P.S. I've checked row from error message and it does not match Controls.ValueTypeID=1 from on clause.

答:
Use TRY_CONVERT:

```<code>SELECT (
        SELECT (
                SELECT Twr_Kod
                FROM whm.CDN.TwrKarty
                WHERE TRY_CONVERT(INT, Twr_GIDNumer) = TRY_Convert(INT, value)
                )
        FROM Workflow.ControlValues
        INNER JOIN Workflow.Controls ON Controls.ID = ControlID
            AND Controls.ValueTypeID = 1
        WHERE ItemID = Items.ID
        FOR XML path('')
        )
FROM Offers.Items;
</code>```

Excluding based on WHERE depends on execution plan. If query optimizer decides to execute WHERE Twr_GIDNumer = Convert(INT, value) first then you will get error.

Body:
Following one works perfectly (notice convert):

select (select Twr_Kod from whm.CDN.TwrKarty where Twr_GIDNumer=Convert(int, value))
 from Workflow.ControlValues
 inner join Workflow.Controls on Controls.ID=ControlID and Controls.ValueTypeID=1

However if I will make it subquery if causes error on converting value:

select
(select (select Twr_Kod from whm.CDN.TwrKarty where Twr_GIDNumer=Convert(int, value))
 from Workflow.ControlValues
 inner join Workflow.Controls on Controls.ID=ControlID and Controls.ValueTypeID=1
  where ItemID=Items.ID
   for XML path(''))
    from Offers.Items

I thought that where will exclude some rows, so it shouldn't cause any issues with convert. Do you know what is the reason of that behavior and how to prevent it?

P.S. I've checked row from error message and it does not match Controls.ValueTypeID=1 from on clause.

Body:
Use TRY_CONVERT:

SELECT (
        SELECT (
                SELECT Twr_Kod
                FROM whm.CDN.TwrKarty
                WHERE TRY_CONVERT(INT, Twr_GIDNumer) = TRY_Convert(INT, value)
                )
        FROM Workflow.ControlValues
        INNER JOIN Workflow.Controls ON Controls.ID = ControlID
            AND Controls.ValueTypeID = 1
        WHERE ItemID = Items.ID
        FOR XML path('')
        )
FROM Offers.Items;

Excluding based on WHERE depends on execution plan. If query optimizer decides to execute WHERE Twr_GIDNumer = Convert(INT, value) first then you will get error.