问:
Stuck Thread Weblogic
Am using spring mvc with hibernate, application is hosted in weblogic. Getting stuck thread issues on few hibernate calls via DAO IMPL. Could anyone suggest on how to move forward.</p>

```<code>####<May 21, 2017 9:09:08 AM CDT> <Error> <WebLogicServer> <AUSPWDCPPROD01> <AdminServer> <[ACTIVE] ExecuteThread: '12' for queue: 'weblogic.kernel.Default (self-tuning)'> <<WLS Kernel>> <> <> <1495375748894> <BEA-000337> <[STUCK] ExecuteThread: '9' for queue: 'weblogic.kernel.Default (self-tuning)' has been busy for "624" seconds working on the request "Workmanager: default, Version: 0, Scheduled=true, Started=true, Started time: 624704 ms
", which is more than the configured time (StuckThreadMaxTime) of "600" seconds in "server-failure-trigger". Stack trace:
    sun.misc.Unsafe.park(Native Method)
    java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2039)
    org.apache.commons.pool2.impl.LinkedBlockingDeque.takeFirst(LinkedBlockingDeque.java:583)
    org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:442)
    org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:363)
    org.apache.commons.dbcp2.PoolingDataSource.getConnection(PoolingDataSource.java:134)
    org.apache.commons.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1533)
    org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
    org.hibernate.internal.NonContextualJdbcConnectionAccess.obtainConnection(NonContextualJdbcConnectionAccess.java:35)
    org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.acquireConnectionIfNeeded(LogicalConnectionManagedImpl.java:99)
    org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getPhysicalConnection(LogicalConnectionManagedImpl.java:129)
    org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getConnectionForTransactionManagement(LogicalConnectionManagedImpl.java:247)
    org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.begin(LogicalConnectionManagedImpl.java:254)
    org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.begin(JdbcResourceLocalTransactionCoordinatorImpl.java:203)
    org.hibernate.engine.transaction.internal.TransactionImpl.begin(TransactionImpl.java:56)
    org.hibernate.internal.AbstractSharedSessionContract.beginTransaction(AbstractSharedSessionContract.java:387)
    com.dell.dcp.dao.Impl.ClaimDaoImpl.submitClaimAction(ClaimDaoImpl.java:339)
    sun.reflect.GeneratedMethodAccessor1025.invoke(Unknown Source)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:497)
    org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
    org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
    com.sun.proxy.$Proxy271.submitClaimAction(Unknown Source)
    com.dell.dcp.services.Impl.ClaimServiceImpl.submitClaimAction(ClaimServiceImpl.java:68)
    com.dell.dcp.controllers.ClaimController.submitClaimAction(ClaimController.java:234)
    sun.reflect.GeneratedMethodAccessor1024.invoke(Unknown Source)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:497)
    org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
    org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:751)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:844)
    weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:280)
    weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:254)
    weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:136)
    weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:346)
    weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:25)
    weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:79)
    com.dell.dcp.controllers.AuthenticationFilter.doFilter(AuthenticationFilter.java:42)
    weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:79)
    weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3436)
    weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3402)
    weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
    weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
    weblogic.servlet.provider.WlsSubjectHandle.run(WlsSubjectHandle.java:57)
    weblogic.servlet.internal.WebAppServletContext.doSecuredExecute(WebAppServletContext.java:2285)
    weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2201)
    weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2179)
    weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1572)
    weblogic.servlet.provider.ContainerSupportProviderImpl$WlsRequestExecutor.run(ContainerSupportProviderImpl.java:255)
    weblogic.work.ExecuteThread.execute(ExecuteThread.java:311)
    weblogic.work.ExecuteThread.run(ExecuteThread.java:263)
</code>```

答: The issue was due Session.close(); was not implemented in many places.

Title: Stuck Thread Weblogic

Body:
Am using spring mvc with hibernate, application is hosted in weblogic. Getting stuck thread issues on few hibernate calls via DAO IMPL. Could anyone suggest on how to move forward.

####<May 21, 2017 9:09:08 AM CDT> <Error> <WebLogicServer> <AUSPWDCPPROD01> <AdminServer> <[ACTIVE] ExecuteThread: '12' for queue: 'weblogic.kernel.Default (self-tuning)'> <<WLS Kernel>> <> <> <1495375748894> <BEA-000337> <[STUCK] ExecuteThread: '9' for queue: 'weblogic.kernel.Default (self-tuning)' has been busy for "624" seconds working on the request "Workmanager: default, Version: 0, Scheduled=true, Started=true, Started time: 624704 ms
", which is more than the configured time (StuckThreadMaxTime) of "600" seconds in "server-failure-trigger". Stack trace:
    sun.misc.Unsafe.park(Native Method)
    java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2039)
    org.apache.commons.pool2.impl.LinkedBlockingDeque.takeFirst(LinkedBlockingDeque.java:583)
    org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:442)
    org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:363)
    org.apache.commons.dbcp2.PoolingDataSource.getConnection(PoolingDataSource.java:134)
    org.apache.commons.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1533)
    org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
    org.hibernate.internal.NonContextualJdbcConnectionAccess.obtainConnection(NonContextualJdbcConnectionAccess.java:35)
    org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.acquireConnectionIfNeeded(LogicalConnectionManagedImpl.java:99)
    org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getPhysicalConnection(LogicalConnectionManagedImpl.java:129)
    org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getConnectionForTransactionManagement(LogicalConnectionManagedImpl.java:247)
    org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.begin(LogicalConnectionManagedImpl.java:254)
    org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.begin(JdbcResourceLocalTransactionCoordinatorImpl.java:203)
    org.hibernate.engine.transaction.internal.TransactionImpl.begin(TransactionImpl.java:56)
    org.hibernate.internal.AbstractSharedSessionContract.beginTransaction(AbstractSharedSessionContract.java:387)
    com.dell.dcp.dao.Impl.ClaimDaoImpl.submitClaimAction(ClaimDaoImpl.java:339)
    sun.reflect.GeneratedMethodAccessor1025.invoke(Unknown Source)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:497)
    org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
    org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
    com.sun.proxy.$Proxy271.submitClaimAction(Unknown Source)
    com.dell.dcp.services.Impl.ClaimServiceImpl.submitClaimAction(ClaimServiceImpl.java:68)
    com.dell.dcp.controllers.ClaimController.submitClaimAction(ClaimController.java:234)
    sun.reflect.GeneratedMethodAccessor1024.invoke(Unknown Source)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:497)
    org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
    org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:751)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:844)
    weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:280)
    weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:254)
    weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:136)
    weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:346)
    weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:25)
    weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:79)
    com.dell.dcp.controllers.AuthenticationFilter.doFilter(AuthenticationFilter.java:42)
    weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:79)
    weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3436)
    weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3402)
    weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
    weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
    weblogic.servlet.provider.WlsSubjectHandle.run(WlsSubjectHandle.java:57)
    weblogic.servlet.internal.WebAppServletContext.doSecuredExecute(WebAppServletContext.java:2285)
    weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2201)
    weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2179)
    weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1572)
    weblogic.servlet.provider.ContainerSupportProviderImpl$WlsRequestExecutor.run(ContainerSupportProviderImpl.java:255)
    weblogic.work.ExecuteThread.execute(ExecuteThread.java:311)
    weblogic.work.ExecuteThread.run(ExecuteThread.java:263)


来源: stackexchange

问:
How to resolve the error "No resource found that matches the given name" when adding library v7 AppCompat in Eclipse?
I have a project target to API Level 10 and i want to implement the new ActionBar support library.
After follow all the instrutions in the Support Library Setup, when adding the library to my project I came across with dozens of error messages like this:

android-support-v7-appcompat\res\values-v14\styles_base.xml:24: error: Error retrieving parent for item: No resource found that matches the given name 'android:Widget.Holo.....

OK, i know that they are many answers to this question, but, after trying all the more obvious, i still could not solve the error.

I kept searching and found the cause, which is not so obvious, at least for newbies like me.

My intent is provide a full answer to help all those who are like me and do not master all the secrets of the Android development.

答: also keep one thing in mind you should change min sdk version to 11 if you want to support("android:windowActionBar")property in your project.   </p>

ContentLicense: CC BY-SA 3.0


问:
How to assign css?
I assign the css for the element.

HTML:

```<code><div class = "mydiv">Text</div>
  ....
<div class = "mydiv1">Content</div>
</code>```

CSS:

```<code>.mydiv {
   position: absolute;
}
</code>```

Here I want to assign the width for mydiv1 class inside the class mydiv in css. ie) I want to assign the width for 'mydiv2' when it follows 'mydiv'.
How can I achieve it?

答:
You could do something like: </p>

```<code>.mydiv .mydiv1 {
  width: //your width
}
</code>```

Title: How to assign css?

Body:
I assign the css for the element.

HTML:

Text

  ....

Content

CSS:

.mydiv {
   position: absolute;
}

Here I want to assign the width for mydiv1 class inside the class mydiv in css. ie) I want to assign the width for 'mydiv2' when it follows 'mydiv'.
How can I achieve it?

Body:
You could do something like:

.mydiv .mydiv1 {
  width: //your width
}


问:
evaluating else if after an if condition is true
Consider this snippet:

```<code>private void button1_Click(object sender, EventArgs e)
{
    if (textBox1.MaxLength > 0)
    {
        textBox2.Text = Convert.ToBoolean(Math.Sqrt(textBox1.MaxLength)).ToString();
    }
    else if (textBox1.MaxLength < 32768)
    {
        textBox2.Text = Convert.ToBoolean(Math.Sqrt(textBox1.MaxLength)).ToString();
    }
}
</code>```

Why is it not evaluating the second condition (the lesser than condition)? It's also true, isn't it?

If I have to make the second one to work in the same condition, what minor change must be made?

答: I'm not quite sure if I understand your question correctly, but if you want both if-then statements to execute, you have to remove the "else". Otherwise it will only execute the firt if (if it's true).</p>

ContentLicense: CC BY-SA 2.5

Body:
Consider this snippet:

private void button1_Click(object sender, EventArgs e)
{
    if (textBox1.MaxLength > 0)
    {
        textBox2.Text = Convert.ToBoolean(Math.Sqrt(textBox1.MaxLength)).ToString();
    }
    else if (textBox1.MaxLength < 32768)
    {
        textBox2.Text = Convert.ToBoolean(Math.Sqrt(textBox1.MaxLength)).ToString();
    }
}

Why is it not evaluating the second condition (the lesser than condition)? It's also true, isn't it?

If I have to make the second one to work in the same condition, what minor change must be made?


问:
ASP.NET Core Dependency injection for Common.Logging
I want to be able to configure ASP.NET's dependency injection framework to be able to resolve me an instance of Common.Logging's ILog interface. Creating an instance of ILog is done via the Common.Logging's static LogManager.GetLogger methods which require a type as a parameter.

This means that when resolving an instance of ILog I need to know the target type that the DI engine is trying to inject into. In the past I've used autofac modules to solve this problem which other have asked about here, but it would nice to be able to do this purely with ASP.NET's built in Ioc.

I can see that there is the ability to resolve an instance by creating a method that takes an IServiceProvider, but there is no context of the type being injected into that I can see.

Does anyone know how a service can be resolved at runtime with knowledge of the type its being injected into?

答: I posted the same question in the ASPNET dependencyinjection repo issue register and apparently its not possible.</p>


问:
Javascript and website loading time optimization
I know that best practice for including javascript is having all code in a separate .js file and allowing browsers to cache that file.

But when we begin to use many jquery plugins which have their own .js, and our functions depend on them, wouldn't it be better to load dynamically only the js function and the required .js for the current page?

Wouldn't that be faster, in a page, if I only need one function to load dynamically embedding it in html with the script tag instead of loading the whole js with the js plugins?

In other words, aren't there any cases in which there are better practices than keeping our whole javascript code in a separate .js?

答:
One problem with having separate js files is that will cause more HTTP requests.

Yahoo have a good best practices guide on speeding up your site: http://developer.yahoo.com/performance/rules.html

I believe Google's closure library has something for combining javascript files and dependencies, but I havn't looked to much into it yet. So don't quote me on it: http://code.google.com/closure/library/docs/calcdeps.html

Also there is a tool called jingo http://code.google.com/p/jingo/ but again, I havn't used it yet.


问:
How to clear browser cache between routes AngularJS
I have tried several things to clear browser cache while routing between pages.like cache: false , index.html?x=1 ,target="_self" ,disableCache: true, in $routeProvider as well.but any of this didn't worked for me.finaly $window.location.reload(); worked.but i do not want reload the page every time when routing.is there any perfect solution for route cache in AngulerJs?

scenario

In my header.html have ng-if="currentPath ==='/store'".it's check current path and display some styles regarding to store in header.html

header.html

```<code><div class="container" ng-if="currentPath ==='/store'">
    <div class="col-xs-8 buttons" >
      <a class="brand" href="#" target="_self"><img src="img/logo.png" /></a>
      <a class="btns" href="#Store" target="_self">Store</a>
    </div>

<ul class="col-xs-4 icons">
      <li ><a href="#/profile" class="display_name"><i class="fa"></i>{{user.email}}</a></li>
      <li><a href="#/cart"> <span ng-show="cart_size > 0" class="count">{{cart_size}}</span></a></li>
 </ul>
<--some styles for store.......-->
</div>
<div class="container" ng-if="currentPath !=='/store'">
    <div class="col-xs-8 buttons" >
      <a class="brand" href="#" target="_self"><img src="img/logo.png" /></a>
      <a class="btns" href="#Store" target="_self">Store</a>
    </div>

  </div>
</code>```

current issue

when i go into store page i have to refresh browser to display store styles in header.
after that go into another page,store styles still display in header.then i have to refresh again.
how to solve this issue?

答:
You may try

```<code>angular.element('html[manifest=saveappoffline.appcache]').attr('content', '');
</code>```

where you want to disable cache.

The manifest attribute specifies the location of the document's cache manifest.

As per w3schools.com

HTML5 introduces application cache, which means that a web application
  is cached, and accessible without an internet connection.

Application cache gives an application three advantages:

Offline browsing - users can use the application when they're offline
  Speed - cached resources load faster

Reduced server load - the browser will only download updated/changed resources from the server

The manifest attribute should be included on every page of your web
  application that you want cached.

The manifest file is a simple text file that lists the resources the
  browser should cache for offline access.

To learn more about how to create the manifest file, please read our
  HTML5 Application Cache chapter.

Another solution that you can try is add following snippet on your angular apps header so that your page will never be cached.

```<code><meta http-equiv='cache-control' content='no-cache'>
<meta http-equiv='expires' content='0'>
<meta http-equiv='pragma' content='no-cache'>
</code>```

Body:
I have tried several things to clear browser cache while routing between pages.like cache: false , index.html?x=1 ,target="_self" ,disableCache: true, in $routeProvider as well.but any of this didn't worked for me.finaly $window.location.reload(); worked.but i do not want reload the page every time when routing.is there any perfect solution for route cache in AngulerJs?

scenario

In my header.html have ng-if="currentPath ==='/store'".it's check current path and display some styles regarding to store in header.html

header.html

      Store

{{user.email}}

  0" class="count">{{cart_size}}

<--some styles for store.......-->

      Store

current issue

when i go into store page i have to refresh browser to display store styles in header.
after that go into another page,store styles still display in header.then i have to refresh again.
how to solve this issue?

Body:
You may try

angular.element('html[manifest=saveappoffline.appcache]').attr('content', '');

where you want to disable cache.

The manifest attribute specifies the location of the document's cache manifest.

As per w3schools.com

HTML5 introduces application cache, which means that a web application
  is cached, and accessible without an internet connection.

Application cache gives an application three advantages:

Offline browsing - users can use the application when they're offline
  Speed - cached resources load faster

Reduced server load - the browser will only download updated/changed resources from the server

The manifest attribute should be included on every page of your web
  application that you want cached.

The manifest file is a simple text file that lists the resources the
  browser should cache for offline access.

To learn more about how to create the manifest file, please read our
  HTML5 Application Cache chapter.

Another solution that you can try is add following snippet on your angular apps header so that your page will never be cached.

<meta http-equiv='cache-control' content='no-cache'>
<meta http-equiv='expires' content='0'>
<meta http-equiv='pragma' content='no-cache'>


问:
How to run appium test scripts through jenkins
I am new to testing framework for Appium and Jenkins,My question is, it is possible to run appium test scripts through jenkins? If possible please provide the links or example for that.

Thanks Advance.

答:
Step 1: Install Jenkins in your system visit the Jenkins url in browser.
In my local I access Jenkins using "http://localhost:8080"

Step 2: Tap "New Item" > "Freestyle Project" > 'OK'

Step 3: Scroll to 'Build' section > Add Build Step > 'Execute Shell' and enter the below commands:

```<code>#!/bin/bash --login -x
appium &
sleep 5s
</code>```

Step 4: Click on 'Build Now'.

Step 5: Open the running job > 'Console Output' to ensure Appium server is running.

The following text should be displayed in console logs:

```<code>[Appium] Welcome to Appium v1.6.4
[Appium] Appium REST http interface listener started on 0.0.0.0:4723
</code>```

Step 6: All the test scripts should be placed inside 'workspace' directory of Jenkins. My scripts are in this location:
    /Users/Shared/Jenkins/Home/workspace/appium-android/

Step 7: I use pytest in Python, so my command is as follows:

```<code>cd $WORKSPACE
pytest /Users/Shared/Jenkins/Home/workspace/appium-android/tests/listings/test_listing_create.py
</code>```

Ensure you have all dependencies installed in Jenkins machine, like Python, Appium python client, Appium server etc

Body:
Step 1: Install Jenkins in your system visit the Jenkins url in browser.
In my local I access Jenkins using "http://localhost:8080"

Step 2: Tap "New Item" > "Freestyle Project" > 'OK'

Step 3: Scroll to 'Build' section > Add Build Step > 'Execute Shell' and enter the below commands:

#!/bin/bash --login -x
appium &
sleep 5s

Step 4: Click on 'Build Now'.

Step 5: Open the running job > 'Console Output' to ensure Appium server is running.

The following text should be displayed in console logs:

[Appium] Welcome to Appium v1.6.4
[Appium] Appium REST http interface listener started on 0.0.0.0:4723

Step 6: All the test scripts should be placed inside 'workspace' directory of Jenkins. My scripts are in this location:
    /Users/Shared/Jenkins/Home/workspace/appium-android/

Step 7: I use pytest in Python, so my command is as follows:

cd $WORKSPACE
pytest /Users/Shared/Jenkins/Home/workspace/appium-android/tests/listings/test_listing_create.py

Ensure you have all dependencies installed in Jenkins machine, like Python, Appium python client, Appium server etc


问:
OneDrive REST API and Sharepoint Online
I have the app that uses OneDrive API (MS graph) to access OneDrive free accounts and OneDrive for business.

The app works fine.
In docs of the API i can see same API can be used also to access Sharepoint Online sites data.

How to do this? When i auth a user who has Sharepoint Online account with MS graph, there is only his drive (ondrive) but there is no his site listed.

How to get access to his sharepoint site too using same API?

答:
I have found how to work with sites using the Graph API.

To get list of sites there is the call

```<code>GET /v1.0/sites/
</code>```

Then use the SITEID to get list of drives (in fact, top level folders)

```<code>GET /v1.0/sites/SITEID/drives
</code>```

Then to get contents of a drive user

```<code>GET /v1.0/sites/SITEID/drives/DRIVEID/root/children
</code>```

And all next calls are same as for onedrive drive

However, there is the problem i still can not solve. How to create new top level folder (new drive on a site). There is no API call for this

Title: OneDrive REST API and Sharepoint Online

Body:
I have found how to work with sites using the Graph API.

To get list of sites there is the call

GET /v1.0/sites/

Then use the SITEID to get list of drives (in fact, top level folders)

GET /v1.0/sites/SITEID/drives

Then to get contents of a drive user

GET /v1.0/sites/SITEID/drives/DRIVEID/root/children

And all next calls are same as for onedrive drive

However, there is the problem i still can not solve. How to create new top level folder (new drive on a site). There is no API call for this


问:
ratingbar not working (not clickable) when using ratingBarStyleSmall style
ratingbar didn't change when the user click on it ?

her is my xml code

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.soulhis.testmaterialdesign.Test">
<RatingBar
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/ratingBar4"
    android:layout_centerVertical="true"
    style="?android:attr/ratingBarStyleSmall"
     android:layout_centerHorizontal="true" />
 </RelativeLayout>
</code>```

the problem occur just when using ratingBarStyleSmall
tested on android jellybean api level 17

答:
Properly Working example and no need to remove style="?android:attr/ratingBarStyle"...

```<code>      <RatingBar
        style="?android:attr/ratingBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:isIndicator="false"
        android:numStars="5"
        android:stepSize="0.5" />
</code>```

Body:
ratingbar didn't change when the user click on it ?

her is my xml code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.soulhis.testmaterialdesign.Test">
<RatingBar
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/ratingBar4"
    android:layout_centerVertical="true"
    style="?android:attr/ratingBarStyleSmall"
     android:layout_centerHorizontal="true" />
 </RelativeLayout>

the problem occur just when using ratingBarStyleSmall
tested on android jellybean api level 17

Body:
Properly Working example and no need to remove style="?android:attr/ratingBarStyle"...

      <RatingBar
        style="?android:attr/ratingBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:isIndicator="false"
        android:numStars="5"
        android:stepSize="0.5" />


问:
hide only this part of datatable (filtered from x total entries)
i want to show only this content of data table Showing 0 to 0 of 0 entries but want to hide later part of it (filtered from x total entries)how is it possible help me</p>

答:
You can acheive this by specifying empty string for infoFiltered in Language configuration options for DataTables

```<code>$(document).ready(function() {
    $('#example').DataTable( {
        "language": {
            "infoFiltered": ""
        }
    } );
} );
</code>```

Pleasee see this Example for demostration.

Body:
You can acheive this by specifying empty string for infoFiltered in Language configuration options for DataTables

$(document).ready(function() {
    $('#example').DataTable( {
        "language": {
            "infoFiltered": ""
        }
    } );
} );

Pleasee see this Example for demostration.


问:
White Space Around Adobe Illustrator Generated SVG
Thank you in advance for all the help, I have been trying various resources on the web but is still not able to make this work.

I am trying to create a 3D rectangle box using svg. I prepared the graphic in Adobe Illustrator by apply the 3D feature in the software to a regular rectangle shape and finally exported it as a SVG file. While it looks ok on the screen of illustrator, on browser; the object appears to have a small white border around each of its polygon.

The following is the svg code generated by illustrator. You Can see the whitespace around the polygon after running the snippet. I have to remove the whitespace around it.

<?xml version="1.0" encoding="utf-8"?>

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
  width="965px" height="720.3px" viewBox="0 0 965 720.3" enable-background="new 0 0 965 720.3" xml:space="preserve">
<g id="sections_2_">
 <g>
  <g enable-background="new    ">
   <g>
    <polygon fill="#836EA6" points="595.6,337.1 596.8,344.9 581.8,357.8 580.6,349.9     "/>
   </g>
   <g>
    <polygon fill="#8670A9" points="532,311.5 595.6,337.1 580.6,349.9 568.3,360.1     "/>
   </g>
   <g>
    <polygon fill="#736092" points="568.3,360.1 569.4,368 533.1,319.3 532,311.5     "/>
   </g>
   <g>
    <polygon fill="#BF4142" points="568.3,360.1 569.4,368 508,340.3 506.9,332.5     "/>
   </g>
   <g>
    <polygon fill="#836EA6" points="580.6,349.9 581.8,357.8 569.4,368 568.3,360.1     "/>
   </g>
   <g>
    <polygon fill="#DE4D4E" points="531.9,311.5 568.3,360.1 506.9,332.5 511.7,328.6 524.8,317.8     "/>
   </g>
  </g>
 </g>
</g>
</svg>```

The following image is how it look like on the screen which is the desired look. It has to be a .svg file, so exporting it as jpeg or png is not an option.

Body:
Thank you in advance for all the help, I have been trying various resources on the web but is still not able to make this work.

I am trying to create a 3D rectangle box using svg. I prepared the graphic in Adobe Illustrator by apply the 3D feature in the software to a regular rectangle shape and finally exported it as a SVG file. While it looks ok on the screen of illustrator, on browser; the object appears to have a small white border around each of its polygon.

The following is the svg code generated by illustrator. You Can see the whitespace around the polygon after running the snippet. I have to remove the whitespace around it.

<?xml version="1.0" encoding="utf-8"?>

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
  width="965px" height="720.3px" viewBox="0 0 965 720.3" enable-background="new 0 0 965 720.3" xml:space="preserve">
<g id="sections_2_">
 <g>
  <g enable-background="new    ">
   <g>
    <polygon fill="#836EA6" points="595.6,337.1 596.8,344.9 581.8,357.8 580.6,349.9     "/>
   </g>
   <g>
    <polygon fill="#8670A9" points="532,311.5 595.6,337.1 580.6,349.9 568.3,360.1     "/>
   </g>
   <g>
    <polygon fill="#736092" points="568.3,360.1 569.4,368 533.1,319.3 532,311.5     "/>
   </g>
   <g>
    <polygon fill="#BF4142" points="568.3,360.1 569.4,368 508,340.3 506.9,332.5     "/>
   </g>
   <g>
    <polygon fill="#836EA6" points="580.6,349.9 581.8,357.8 569.4,368 568.3,360.1     "/>
   </g>
   <g>
    <polygon fill="#DE4D4E" points="531.9,311.5 568.3,360.1 506.9,332.5 511.7,328.6 524.8,317.8     "/>
   </g>
  </g>
 </g>
</g>
</svg>

The following image is how it look like on the screen which is the desired look. It has to be a .svg file, so exporting it as jpeg or png is not an option.

Body:
Adjust the viewBox to get rid of the whitespace. I've added a black background rect so the whitespace around the shape is visible but you can remove that.

<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 19.2.1, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
  width="400px" height="200.3px" viewBox="502 307 98 63" enable-background="new 0 0 965 720.3" xml:space="preserve" overflow="hidden">
<rect x="502" y="307" width="98" height="63"/>
<g id="sections_2_">
 <g>
  <g enable-background="new    ">
   <g>
    <polygon fill="#836EA6" points="595.6,337.1 596.8,344.9 581.8,357.8 580.6,349.9     "/>
   </g>
   <g>
    <polygon fill="#8670A9" points="532,311.5 595.6,337.1 580.6,349.9 568.3,360.1     "/>
   </g>
   <g>
    <polygon fill="#736092" points="568.3,360.1 569.4,368 533.1,319.3 532,311.5     "/>
   </g>
   <g>
    <polygon fill="#BF4142" points="568.3,360.1 569.4,368 508,340.3 506.9,332.5     "/>
   </g>
   <g>
    <polygon fill="#836EA6" points="580.6,349.9 581.8,357.8 569.4,368 568.3,360.1     "/>
   </g>
   <g>
    <polygon fill="#DE4D4E" points="531.9,311.5 568.3,360.1 506.9,332.5 511.7,328.6 524.8,317.8     "/>
   </g>
  </g>
 </g>
</g>
</svg>


答:
You must change a bit your html. Heres a proposition that makes mydiv and mydiv1 the same width since it's container control it.

.container {
  position: absolute;
  width: 100px;
}

.mydiv {
  background: pink;
}

.mydiv1 {
  background: yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="mydiv">Text</div>
  <div class="mydiv1">Content</div>
</div></code>```

Title: How to assign css?

Body:
You must change a bit your html. Heres a proposition that makes mydiv and mydiv1 the same width since it's container control it.

.container {
  position: absolute;
  width: 100px;
}

.mydiv {
  background: pink;
}

.mydiv1 {
  background: yellow;
}

<div class="container">
  <div class="mydiv">Text</div>
  <div class="mydiv1">Content</div>
</div>


问:
how to have make a web service for android applications
I want to make a web service for android application and only accepts every request that come from my application not other applications like jquery in web and other android applications
anyone can help?</p>

答: Build a Simple REST API for Mobile Applications using PHP or .Net.. PHP such Laravel already have API configuration and REST APi Authenticate in it can be simply setup..


问:
PHP + Mysql : How to insert data having , " ' (Semicolon, Single + Double Quotation Marks)
Sometimes it sucks when you have these ; " ' (semicolon, single and double quotation marks) everything in a string.

Question is simple what is the easiest way to send those sting into the database.

```<code>base64_encode();
base64_decode();
// Is not an option. I need to keep those data just same as it is.
</code>```

答:
You need </p>

```<code>addslashes('your text') // in your php page
</code>```

Body:
Sometimes it sucks when you have these ; " ' (semicolon, single and double quotation marks) everything in a string.

Question is simple what is the easiest way to send those sting into the database.

base64_encode();
base64_decode();
// Is not an option. I need to keep those data just same as it is.

Body:
You need

addslashes('your text') // in your php page


问:
Algorithms to find the distance/similarity among the user tags?
I want to find the semantic/similarity of user tags.

Each user can use maximum four tags. For example, User-1["Machine learning", "Photography", "data science", "neural network"], User-2 ["Machine learning", "Data Science", "Statistics", "Mathematics"],  User-2 ["Geophysics", "Machine learning", "Art and printing", "Mathematics"].

Tags are from wide range of skills. I want to find the distance/similarity among the tags.  For example: "Machine learning," "Data science," and "neural network" will be close to each other, similarly "Photography" and "Art and printing" would be close to each other.

I was thinking to use word2vec. But I am hesitating to use it in production since I have to train it with thousand categories of skill set documents. Not only that in real life users always change/update their tags. So I want to build/develop a dynamic algorithm that will be adjusted according to user tag.

I am a newbie in machine learning world.

答: Every tag can be presented as a BitMap(BitSet), a single bit represents a specific user has this tag or not. Then you can use some similarity functions like Jaccard or Ochiai</p>


问:
Angular 2 custom form validation working only after user clear the textbox value
I'm trying to validate my input box immediately after the input box gets blur. But some how the validation message only appears when i write something in textbox and than delete it.

Here's my HTML template;

<input type="text"
placeholder="First Name"
class="form-control"
name="firstName"
id="firstName"
[ngModel]="typeValidation.firstName"
#firstName="ngModel"
(blur)="firstNameBlur(firstName.value)"
autofocus
required>

     First Name is required.
```
</div>
</div>
</p>

<p>Here's my typescript;</p>

```firstNameBlur(value:string) {

    if (value == "" || value == undefined) {
        return false;
    }
    else {
        return true;
    }

}
```

Please help me out.
Thanks in advance!

答:
I'm not sure why you are binding to the blur event? The required attribute should cause Angular to automatically validate the required field when the user leaves the field.

And what is that code doing? Since the firstNameBlur() is executed on an event ... returning false is setting preventDefault. (See this link: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) Is that what is intended?

Try removing the blur event and see if it works without it. If so, then you don't need the firstNameBlur method.

Body:
I'm trying to validate my input box immediately after the input box gets blur. But some how the validation message only appears when i write something in textbox and than delete it.

Here's my HTML template;

<input type="text"
placeholder="First Name"
class="form-control"
name="firstName"
id="firstName"
[ngModel]="typeValidation.firstName"
#firstName="ngModel"
(blur)="firstNameBlur(firstName.value)"
autofocus
required>

     First Name is required.

Here's my typescript;

firstNameBlur(value:string) {

    if (value == "" || value == undefined) {
        return false;
    }
    else {
        return true;
    }

}

Please help me out.
Thanks in advance!


问:
ValueError: Chunks and shape must be of the same length/dimension
I read book "Introducing Data Science. Big data, machine learning, and more, using Python tools"
There is a code in Chapter4 about blocking matrix calculation:

```<code>import dask.array as da
import bcolz as bc
import numpy as np
import dask

n = 1e4 #A

ar = bc.carray(np.arange(n).reshape(n/2,2)  , dtype='float64', rootdir     = 'ar.bcolz', mode = 'w') #B
y  = bc.carray(np.arange(n/2), dtype='float64', rootdir = 'yy.bcolz', mode = 'w') #B,

dax = da.from_array(ar, chunks=(5,5)) #C
dy = da.from_array(y,chunks=(5,5)) #C

XTX = dax.T.dot(dax) #D
Xy  = dax.T.dot(dy) #E

coefficients = np.linalg.inv(XTX.compute()).dot(Xy.compute()) #F

coef = da.from_array(coefficients,chunks=(5,5)) #G

ar.flush() #H
y.flush() #H

predictions = dax.dot(coef).compute() #I
print (predictions)
</code>```

I get ValueError:

```<code>ValueError                                Traceback (most recent call last)
<ipython-input-4-7ae8e9cf2346> in <module>()
     10
     11 dax = da.from_array(ar, chunks=(5,5)) #C
---> 12 dy = da.from_array(y,chunks=(5,5)) #C
     13
     14 XTX = dax.T.dot(dax) #D

C:\Users\F\Anaconda3\lib\site-packages\dask\array\core.py in from_array(x, chunks, name, lock, fancy, getitem)
   1868     >>> a = da.from_array(x, chunks=(1000, 1000), lock=True)  # doctest: +SKIP
   1869     """
-> 1870     chunks = normalize_chunks(chunks, x.shape)
   1871     if len(chunks) != len(x.shape):
   1872         raise ValueError("Input array has %d dimensions but the supplied "

C:\Users\F\Anaconda3\lib\site-packages\dask\array\core.py in normalize_chunks(chunks, shape)
   1815             raise ValueError(
   1816                 "Chunks and shape must be of the same length/dimension. "
-> 1817                 "Got chunks=%s, shape=%s" % (chunks, shape))
   1818
   1819     if shape is not None:

ValueError: Chunks and shape must be of the same length/dimension. Got chunks=(5, 5), shape=(5000,)
</code>```

What the problem is?

答:
Problem is here:

```<code>np.arange(n/2).reshape(n)
</code>```

you create an array of size n/2 and then try to reshape it to size n.  You can't change the size with reshape.

It's probably a copy/paste mistake? It's not in your original code and It seems you're doing

```<code>np.arange(n).reshape(n/2,2)
</code>```

elsewhere, which works as long as n is an even number (be careful, if n isn't even this will also fail.)

Body:
I read book "Introducing Data Science. Big data, machine learning, and more, using Python tools"
There is a code in Chapter4 about blocking matrix calculation:

import dask.array as da
import bcolz as bc
import numpy as np
import dask

n = 1e4 #A

ar = bc.carray(np.arange(n).reshape(n/2,2)  , dtype='float64', rootdir     = 'ar.bcolz', mode = 'w') #B
y  = bc.carray(np.arange(n/2), dtype='float64', rootdir = 'yy.bcolz', mode = 'w') #B,

dax = da.from_array(ar, chunks=(5,5)) #C
dy = da.from_array(y,chunks=(5,5)) #C

XTX = dax.T.dot(dax) #D
Xy  = dax.T.dot(dy) #E

coefficients = np.linalg.inv(XTX.compute()).dot(Xy.compute()) #F

coef = da.from_array(coefficients,chunks=(5,5)) #G

ar.flush() #H
y.flush() #H

predictions = dax.dot(coef).compute() #I
print (predictions)

I get ValueError:

ValueError                                Traceback (most recent call last)
<ipython-input-4-7ae8e9cf2346> in <module>()
     10
     11 dax = da.from_array(ar, chunks=(5,5)) #C
---> 12 dy = da.from_array(y,chunks=(5,5)) #C
     13
     14 XTX = dax.T.dot(dax) #D

C:\Users\F\Anaconda3\lib\site-packages\dask\array\core.py in from_array(x, chunks, name, lock, fancy, getitem)
   1868     >>> a = da.from_array(x, chunks=(1000, 1000), lock=True)  # doctest: +SKIP
   1869     """
-> 1870     chunks = normalize_chunks(chunks, x.shape)
   1871     if len(chunks) != len(x.shape):
   1872         raise ValueError("Input array has %d dimensions but the supplied "

C:\Users\F\Anaconda3\lib\site-packages\dask\array\core.py in normalize_chunks(chunks, shape)
   1815             raise ValueError(
   1816                 "Chunks and shape must be of the same length/dimension. "
-> 1817                 "Got chunks=%s, shape=%s" % (chunks, shape))
   1818
   1819     if shape is not None:

ValueError: Chunks and shape must be of the same length/dimension. Got chunks=(5, 5), shape=(5000,)

What the problem is?

Body:
Problem is here:

np.arange(n/2).reshape(n)

you create an array of size n/2 and then try to reshape it to size n.  You can't change the size with reshape.

It's probably a copy/paste mistake? It's not in your original code and It seems you're doing

np.arange(n).reshape(n/2,2)

elsewhere, which works as long as n is an even number (be careful, if n isn't even this will also fail.)


问:
Counting number of words in Python file
I'm trying to count the number of instances several words appear in a file.

Here is my code:

```<code>#!/usr/bin/env python

file = open('my_output', 'r')

word1 = 'wordA'
print('wordA', file.read().split().count(word1))
word2 = 'wordB'
print('wordB', file.read().split().count(word2))
word3 = 'wordC'
print('wordC', file.read().split().count(word3))
</code>```

The issue in the code is that it only counts the number of instances of word1. How can this code be fixed to count word2 and word3?

Thanks!

答:
i think instead of continuously reading and splitting the file , this code would work better if you did : [ this way you could find the term frequency of any number of words you find in the file ]</p>

```<code> file=open('my_output' , 'r')
 s=file.read()
 s=s.split()
 w=set(s)
 tf={}
 for i in s:
     tf[i]=s.count(i)
 print(tf)
</code>```

Title: Counting number of words in Python file

Body:
I'm trying to count the number of instances several words appear in a file.

Here is my code:

#!/usr/bin/env python

file = open('my_output', 'r')

word1 = 'wordA'
print('wordA', file.read().split().count(word1))
word2 = 'wordB'
print('wordB', file.read().split().count(word2))
word3 = 'wordC'
print('wordC', file.read().split().count(word3))

The issue in the code is that it only counts the number of instances of word1. How can this code be fixed to count word2 and word3?

Thanks!

Body:
i think instead of continuously reading and splitting the file , this code would work better if you did : [ this way you could find the term frequency of any number of words you find in the file ]

 file=open('my_output' , 'r')
 s=file.read()
 s=s.split()
 w=set(s)
 tf={}
 for i in s:
     tf[i]=s.count(i)
 print(tf)


答:
You seem to want the sibling combinator (~):

```<code>.mydiv ~ .mydiv1 {
   width: 234px;
 }
</code>```

This will set the width on the .mydiv1 element if it follows the .mydiv element.

Title: How to assign css?

Body:
I assign the css for the element.

HTML:

Text

  ....

Content

CSS:

.mydiv {
   position: absolute;
}

Here I want to assign the width for mydiv1 class inside the class mydiv in css. ie) I want to assign the width for 'mydiv2' when it follows 'mydiv'.
How can I achieve it?

Body:
You seem to want the sibling combinator (~):

.mydiv ~ .mydiv1 {
   width: 234px;
 }

This will set the width on the .mydiv1 element if it follows the .mydiv element.


问:
Option value doesn't keep and display after selecting
I am working on the homepage of this site.

I added to 2 selections, one for country and one for province.

It works, but after selecting, the data doesn't keep and display anymore.

Can anybody help me to inspect and solve this problem?

答:
Done an inspection and it seems that the data is being retained but you are just not able to see it since the color inherited is #fff. If you change the color attribute to #000 or something of your choice, it would then be visible.

So just change the font color of your select.

After disabling inherit:


问:
How to set more than one limit on for loop : javascript
I am working with javascript arrays, here i am using for loop to get the top three results.(no .length limit)

Attempting to have something like

```<code>for(let a=0;a<usss.length || a<3;a++)
</code>```

Simple

```<code>var users = ['s','g','h','i'];
for(let a=0;a<3;a++){//dont want to use a < users.length
   console.log(users[a]);
}
</code>```

problem

```<code>var users2 = ['s','g'];
for(let a=0;a<3;a++){
  console.log(users2[a]);
}
</code>```

The way around,

```<code>var users2 = ['s','g'];
for(let a=0;a<users2.length;a++){
 if(a<3){
  console.log(users2[a]);
 }
}
</code>```

Real Question

How can i avoid using extra if() condition in my last stated code?

I am sorry if its very basic question, i just stuck on it.
Any help or information will be appreciated. Thanks for your time.

答:
You could use also use Array.some()

Note: Check browser compatibility and/or use polyfill

[1, 2, 3, 4, 5, 6, 7].some((el, idx) => {
  console.log(el);
  return ++idx === 4; /* <-- return top 4 */
});```

Body:
I am working with javascript arrays, here i am using for loop to get the top three results.(no .length limit)

Attempting to have something like

for(let a=0;a<usss.length || a<3;a++)

Simple

var users = ['s','g','h','i'];
for(let a=0;a<3;a++){//dont want to use a < users.length
   console.log(users[a]);
}

problem

var users2 = ['s','g'];
for(let a=0;a<3;a++){
  console.log(users2[a]);
}

The way around,

var users2 = ['s','g'];
for(let a=0;a<users2.length;a++){
 if(a<3){
  console.log(users2[a]);
 }
}

Real Question

How can i avoid using extra if() condition in my last stated code?

I am sorry if its very basic question, i just stuck on it.
Any help or information will be appreciated. Thanks for your time.


问:
how to add a button or link in fullcalender based on condition
I am new in Fullcalendr.I want to add a button or link in a full calender cell,if number of events in that date is greater than 3.Also when user clicks on that button I want to append a div,that will show all of my events.I had tried

```<code> $(".fc-day-number").prepend("(+) ");
</code>```

this,but it add a plus to all cells.Who will I do this
with thanks, Naeem

答:
eg. Condition. Here it sets the green color on cells which are exists event description:

eventRender: function (event, element) {

```<code>        if (event.description != null) {
            element.css('background-color', 'Green');
        }

    }
</code>```

Body:
I am new in Fullcalendr.I want to add a button or link in a full calender cell,if number of events in that date is greater than 3.Also when user clicks on that button I want to append a div,that will show all of my events.I had tried

 $(".fc-day-number").prepend("(+) ");

this,but it add a plus to all cells.Who will I do this
with thanks, Naeem

Body:
eg. Condition. Here it sets the green color on cells which are exists event description:

eventRender: function (event, element) {

        if (event.description != null) {
            element.css('background-color', 'Green');
        }

    }


问:
Split a string into character efficiently
I am searching for an efficient way to split word into char( I have some special characters like ",). ) . I have done something using loop and substring function but it is super slow.

Example:
Code Input

```<code>words <- data.frame(V1 = c("blibli","blabla","\"","]"))
words$V1 <- as.character(words$V1)
</code>```

Input looks like:

```<code>      V1
1 blibli
2 blabla
3      "
4      ]
</code>```

Code that i have done:

```<code>char_df <- NULL
for(i in 1:nrow(words)){
  print(i)
  temp <- substring(words[i,][1],1:nchar(words[i,]),1:nchar(words[i,]))
  char_df <- rbind(char_df,
                   data.frame(char = temp,
                              idx = 1:nchar(words[i,]) )
  )

}
</code>```

expected output:

```<code> char idx
1     b   1
2     l   2
3     i   3
4     b   4
5     l   5
6     i   6
7     b   1
8     l   2
9     a   3
10    b   4
11    l   5
12    a   6
13    "   1
14    ]   1
</code>```

I am open to any technique dplyr , data.table , base R.

答:
After splitting the 'V1' by '' into a list, we get the sequence of the lengths of the list and create a data.frame by unlisting the list

```<code>lst <- strsplit(words$V1, "")
data.frame(char = unlist(lst), idx = sequence(lengths(lst)))
#    char idx
#1     b   1
#2     l   2
#3     i   3
#4     b   4
#5     l   5
#6     i   6
#7     b   1
#8     l   2
#9     a   3
#10    b   4
#11    l   5
#12    a   6
#13    "   1
#14    ]   1
</code>```

Body:
I am searching for an efficient way to split word into char( I have some special characters like ",). ) . I have done something using loop and substring function but it is super slow.

Example:
Code Input

words <- data.frame(V1 = c("blibli","blabla","\"","]"))
words$V1 <- as.character(words$V1)

Input looks like:

      V1
1 blibli
2 blabla
3      "
4      ]

Code that i have done:

char_df <- NULL
for(i in 1:nrow(words)){
  print(i)
  temp <- substring(words[i,][1],1:nchar(words[i,]),1:nchar(words[i,]))
  char_df <- rbind(char_df,
                   data.frame(char = temp,
                              idx = 1:nchar(words[i,]) )
  )

}

expected output:

 char idx
1     b   1
2     l   2
3     i   3
4     b   4
5     l   5
6     i   6
7     b   1
8     l   2
9     a   3
10    b   4
11    l   5
12    a   6
13    "   1
14    ]   1

I am open to any technique dplyr , data.table , base R.

Body:
After splitting the 'V1' by '' into a list, we get the sequence of the lengths of the list and create a data.frame by unlisting the list

lst <- strsplit(words$V1, "")
data.frame(char = unlist(lst), idx = sequence(lengths(lst)))
#    char idx
#1     b   1
#2     l   2
#3     i   3
#4     b   4
#5     l   5
#6     i   6
#7     b   1
#8     l   2
#9     a   3
#10    b   4
#11    l   5
#12    a   6
#13    "   1
#14    ]   1


问:
MYSQL - 2 contraints from the same column
I have a table as follow

My question is sometimes an address can have 2 or 3 different zones.

My column "zone (TINYINT)" is linked to an other table "db_zone" with a foreign key constraint

Is it possible to add a second parameter to my column like

I know I could change my column to varchar, and remove my constraint then add like "Zone: 1/2" and explode the value of my column "zone" to do my query later, but I want to keep my constraint.

I don't want either to duplicate my entry as the column "id" is also linked from an other table so I will have the same problem later.

How can I solve this ?

答:
I do not quite understand your question
But hope this helps
You can design a relation like this :

This is an example of data input :


问:
Generate a list of existing functions across multiple files in C
Due to paperwork that has to be filled out, I need to know how many functions exist in an entire C project.

The project is split across multiple folders, so ideally what I am looking for is something where you can type in:

```<code>FindAllTheFunctions --recursive /path/to/folder
</code>```

And the result is written something like:

```<code>/path.../filename: int foo(float bar)
.
.
.
/path.../final/filename: double foo2(int bar2)
</code>```

How could I get results of this nature?

Many thanks!

答:
Thanks everyone for all of your useful comments!

In the end, this is what I did:
I created the tags file using ctags:

```<code>ctags --recurse=yes path/to/base/of/code
</code>```

This generates an output file called tags

I use vim as a text editor. So I opened the tags file and typed:

```<code>:v/f$/d
</code>```

Which searches for all lines in the file that don't end with f and deletes them.

What I was left with were all of the functions from the code. How many functions?

```<code>wc -l tags
</code>```

It is only 535 functions, now I have to document them all...

Body:
Due to paperwork that has to be filled out, I need to know how many functions exist in an entire C project.

The project is split across multiple folders, so ideally what I am looking for is something where you can type in:

FindAllTheFunctions --recursive /path/to/folder

And the result is written something like:

/path.../filename: int foo(float bar)
.
.
.
/path.../final/filename: double foo2(int bar2)

How could I get results of this nature?

Many thanks!

Body:
Thanks everyone for all of your useful comments!

In the end, this is what I did:
I created the tags file using ctags:

ctags --recurse=yes path/to/base/of/code

This generates an output file called tags

I use vim as a text editor. So I opened the tags file and typed:

:v/f$/d

Which searches for all lines in the file that don't end with f and deletes them.

What I was left with were all of the functions from the code. How many functions?

wc -l tags

It is only 535 functions, now I have to document them all...


问:
How to access EntityManager into a RabbitMQBundle custom producer class?
I am using RabbitMQBundle in a Symfony 2.8 project, and I would like to use a custom producer class which persists an entity (Message) in database before publishing the RabbitMQ message.

I defined the custom producer class in config.yml:

```<code>old_sound_rabbit_mq:
  ...
  producers:
    myproducer:
      class: AppBundle\Services\GenericProducer
      connection: default
      exchange_options: {name: 'my_exchange', type: direct}
</code>```

And the custom Producer class:

```<code><?php

namespace AppBundle\Services;

use AppBundle\Entity\Message;
use OldSound\RabbitMqBundle\RabbitMq\Producer;

/**
 * Customised Producer, that publishes AMQP Messages
 * but also:
 * - writes an entry in the Message table
 */
class GenericProducer extends Producer
{
    /**
     * Entity Manager
     */
    protected $em;

    public function setEntityManager($entityManager)
    {
        $this->em = $entityManager;

        return $this;
    }

    /**
     * Publishes the message and merges additional properties with basic properties
     * And also:
     * - writes an entry in the Message table
     *
     * @param string $action
     * @param array $parameters
     * @param string $routingKey
     * @param array $additionalProperties
     * @param array|null $headers
     */
    public function publish($action, $parameters = array() , $routingKey = '', $additionalProperties = array(), array $headers = null)
    {
        $message = new Message();
        $message->setAction($action)
            ->setParameters($parameters);
        $this->em->persist($message);
        $this->em->flush();

        $msgBody = array(
            'action' => $action,
            'parameters' => $parameters
        );
        parent::publish($msgBody, $routingKey, $additionalProperties, $headers);
    }
}
</code>```

How can I make a call to GenericProducer->setEntityManager, as the producer is not defined in services.yml, like other services ?

Is there another way to achieve this ?

Thanks for your time.

答:
the producer service definition is generated dynamically by the bundle in the Dependency Injection Extension of the bundle.

You can either try to decorate the existing service or create a compiler pass where you fetch the existing service and extend it by calling the setEntityManager function.

Body:
I am using RabbitMQBundle in a Symfony 2.8 project, and I would like to use a custom producer class which persists an entity (Message) in database before publishing the RabbitMQ message.

I defined the custom producer class in config.yml:

old_sound_rabbit_mq:
  ...
  producers:
    myproducer:
      class: AppBundle\Services\GenericProducer
      connection: default
      exchange_options: {name: 'my_exchange', type: direct}

And the custom Producer class:

<?php

namespace AppBundle\Services;

use AppBundle\Entity\Message;
use OldSound\RabbitMqBundle\RabbitMq\Producer;

/**
 * Customised Producer, that publishes AMQP Messages
 * but also:
 * - writes an entry in the Message table
 */
class GenericProducer extends Producer
{
    /**
     * Entity Manager
     */
    protected $em;

    public function setEntityManager($entityManager)
    {
        $this->em = $entityManager;

        return $this;
    }

    /**
     * Publishes the message and merges additional properties with basic properties
     * And also:
     * - writes an entry in the Message table
     *
     * @param string $action
     * @param array $parameters
     * @param string $routingKey
     * @param array $additionalProperties
     * @param array|null $headers
     */
    public function publish($action, $parameters = array() , $routingKey = '', $additionalProperties = array(), array $headers = null)
    {
        $message = new Message();
        $message->setAction($action)
            ->setParameters($parameters);
        $this->em->persist($message);
        $this->em->flush();

        $msgBody = array(
            'action' => $action,
            'parameters' => $parameters
        );
        parent::publish($msgBody, $routingKey, $additionalProperties, $headers);
    }
}

How can I make a call to GenericProducer->setEntityManager, as the producer is not defined in services.yml, like other services ?

Is there another way to achieve this ?

Thanks for your time.


问:
jQuery incrementing a cloned elements instead of cloned div
I had this HTML script which contains a drop list and a text box, and I just need to clone those two instead of the whole div, and then send the data to AJAX, and each drop list with text box will form an array that should be add as a single row in a table, that's what I have now:

```<code>        <div class="col-sm-4 rounded" style="background-color: #D3D3D3">
          <div class="row clonedInput" id="clonedInput1">
          <div class="col-sm-6 ">
              <label for="diagnosis_data">Medication</label>
                <fieldset class="form-group">
                  <select class="form-control select" name="diagnosis_data" id="diagnosis_data">
                    <option value="choose">Select</option>
                  </select>
                </fieldset>
            <!-- End class="col-sm-6" -->
            </div>
            <div class="col-sm-6">
              <label for="medication_quantity">Quantity</label>
                <fieldset class="form-group">
                  <input type="number" class="form-control" name="medication_quantity" id="medication_quantity">
                </fieldset>
            <!-- End class="col-sm-6" -->
            </div>
            <!-- End class="col-sm-6" -->
          </div>
          <div class="actions pull-right">
            <button class="btn btn-danger clone">Add More</button>
            <button class="btn btn-danger remove">Remove</button>
          </div>

        <!-- End class="col-sm-4" -->
        </div>
</code>```

And here is the jQuery Script:

```<code>$(document).ready(function()
  {
    $("button.clone").on("click", clone);

    $("button.remove").on("click", remove);
  })
    var regex = /^(.+?)(\d+)$/i;
    var cloneIndex = $(".clonedInput").length;
    function clone(){

        $(this).closest(".rounded").clone()
            .insertAfter(".rounded:last")
            .attr("id", "rounded" +  (cloneIndex+1))
            .find("*")
            .each(function() {
                var id = this.id || "";
                var match = id.match(regex) || [];
                if (match.length == 3) {
                    this.id = id.split('-')[0] +'-'+(cloneIndex);
                }
            })
            .on('click', 'button.clone', clone)
            .on('click', 'button.remove', remove);
        cloneIndex++;
    }
    function remove(){
        $(this).parent().parent(".rounded").remove();
    }
</code>```

The problem is that the whole div is being cloned and just the div id is being changed:

Here is the id of each div is being incremented:

I need to clone the 2 elements only not the whole div and buttons

At the end I need t add them to database using Ajax and PHP

答:
Here you can go with the code.

In this code i made changes in clone()

Here the changes

You first find existing child element.

Than clone that element and append it after last element

var cloneIndex = $(".clonedInput").length; this should be in clone() So it will pass proper incremented value of child element as id in your cloned html

the below code just only make clone of clonedInput not a whole div

Edit

I also edit remove function also.

It will only removes last element which was cloned.

Hope this will helps you. :)

$(document).ready(function()
{
  $("button.clone").on("click", clone);
  $("button.remove").on("click", remove);
});

var regex = /^(.+?)(\d+)$/i;

function clone() {
  var cloneIndex = $(".clonedInput").length;
  $(".rounded").find("#clonedInput1").clone().insertAfter(".clonedInput:last").attr("id", "clonedInput" +  (cloneIndex+1));
}

function remove() {
  $(".rounded").find(".clonedInput:last").remove();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-4 rounded" style="background-color: #D3D3D3">
          <div class="row clonedInput" id="clonedInput1">
          <div class="col-sm-6 ">
              <label for="diagnosis_data">Medication</label>
                <fieldset class="form-group">
                  <select class="form-control select" name="diagnosis_data" id="diagnosis_data">
                    <option value="choose">Select</option>
                  </select>
                </fieldset>
            <!-- End class="col-sm-6" -->
            </div>
            <div class="col-sm-6">
              <label for="medication_quantity">Quantity</label>
                <fieldset class="form-group">
                  <input type="number" class="form-control" name="medication_quantity" id="medication_quantity">
                </fieldset>
            <!-- End class="col-sm-6" -->
            </div>
            <!-- End class="col-sm-6" -->
          </div>
          <div class="actions pull-right">
            <button class="btn btn-danger clone">Add More</button>
            <button class="btn btn-danger remove">Remove</button>
          </div>

        <!-- End class="col-sm-4" -->
        </div></code>```

Body:
I had this HTML script which contains a drop list and a text box, and I just need to clone those two instead of the whole div, and then send the data to AJAX, and each drop list with text box will form an array that should be add as a single row in a table, that's what I have now:

              Medication
                <fieldset class="form-group">
                  <select class="form-control select" name="diagnosis_data" id="diagnosis_data">
                    <option value="choose">Select</option>
                  </select>
                </fieldset>

              Quantity
                <fieldset class="form-group">
                  <input type="number" class="form-control" name="medication_quantity" id="medication_quantity">
                </fieldset>

            <button class="btn btn-danger clone">Add More</button>
            <button class="btn btn-danger remove">Remove</button>

And here is the jQuery Script:

$(document).ready(function()
  {
    $("button.clone").on("click", clone);

    $("button.remove").on("click", remove);
  })
    var regex = /^(.+?)(\d+)$/i;
    var cloneIndex = $(".clonedInput").length;
    function clone(){

        $(this).closest(".rounded").clone()
            .insertAfter(".rounded:last")
            .attr("id", "rounded" +  (cloneIndex+1))
            .find("*")
            .each(function() {
                var id = this.id || "";
                var match = id.match(regex) || [];
                if (match.length == 3) {
                    this.id = id.split('-')[0] +'-'+(cloneIndex);
                }
            })
            .on('click', 'button.clone', clone)
            .on('click', 'button.remove', remove);
        cloneIndex++;
    }
    function remove(){
        $(this).parent().parent(".rounded").remove();
    }

The problem is that the whole div is being cloned and just the div id is being changed:

Here is the id of each div is being incremented:

I need to clone the 2 elements only not the whole div and buttons

At the end I need t add them to database using Ajax and PHP

Body:
Here you can go with the code.

In this code i made changes in clone()

Here the changes

You first find existing child element.

Than clone that element and append it after last element

var cloneIndex = $(".clonedInput").length; this should be in clone() So it will pass proper incremented value of child element as id in your cloned html

the below code just only make clone of clonedInput not a whole div

Edit

I also edit remove function also.

It will only removes last element which was cloned.

Hope this will helps you. :)

$(document).ready(function()
{
  $("button.clone").on("click", clone);
  $("button.remove").on("click", remove);
});

var regex = /^(.+?)(\d+)$/i;

function clone() {
  var cloneIndex = $(".clonedInput").length;
  $(".rounded").find("#clonedInput1").clone().insertAfter(".clonedInput:last").attr("id", "clonedInput" +  (cloneIndex+1));
}

function remove() {
  $(".rounded").find(".clonedInput:last").remove();
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-4 rounded" style="background-color: #D3D3D3">
          <div class="row clonedInput" id="clonedInput1">
          <div class="col-sm-6 ">
              <label for="diagnosis_data">Medication</label>
                <fieldset class="form-group">
                  <select class="form-control select" name="diagnosis_data" id="diagnosis_data">
                    <option value="choose">Select</option>
                  </select>
                </fieldset>
            <!-- End class="col-sm-6" -->
            </div>
            <div class="col-sm-6">
              <label for="medication_quantity">Quantity</label>
                <fieldset class="form-group">
                  <input type="number" class="form-control" name="medication_quantity" id="medication_quantity">
                </fieldset>
            <!-- End class="col-sm-6" -->
            </div>
            <!-- End class="col-sm-6" -->
          </div>
          <div class="actions pull-right">
            <button class="btn btn-danger clone">Add More</button>
            <button class="btn btn-danger remove">Remove</button>
          </div>

        <!-- End class="col-sm-4" -->
        </div>


问:
T-SQL query to find jobs and tables
I want to find the sql server agent jobs that operate upon a particular table. For ex:
I have a table called TAB1 which is updated daily by a job called SAJ1. I need a query to extract this information.</p>

答:
You can start with this select if the job step in T-SQL then it will find the text what you will declare as table name.</p>

```<code>use msdb
Declare @table_name varchar(50)

set  @table_name='Test'

select j.name,js.command from dbo.sysjobs j
inner join
dbo.sysjobsteps js
on j.job_id=js.job_id
where command like '%'+@table_name+'%'
</code>```

Title: T-SQL query to find jobs and tables

Body:
You can start with this select if the job step in T-SQL then it will find the text what you will declare as table name.

use msdb
Declare @table_name varchar(50)

set  @table_name='Test'

select j.name,js.command from dbo.sysjobs j
inner join
dbo.sysjobsteps js
on j.job_id=js.job_id
where command like '%'+@table_name+'%'


问:
How to copy single lines into single file for each one
I don't know what's wrong with the code it doesn't get me any kind of error message from the shell.
What I'm trying to do is:

Merge all list files from a directory into a single list(with one single column with a single string per row) - done!

Compare that list with a big-file and copy every single correspondent line into a new single file for each line - (maybe?) done! But not working. =/

save the files from step 2 in a new output_directory. - not working.

Remove the correspondent lines from the big-file and save it in the same output_directory - no idea. (maybe pop?)

It's possible to name the output 'singlelinefiles' with the same string used to in step 2? Can anyone show me how?
It would be much appreciated

Here's the code so far:

```<code>#!/usr/bin/python

import os, sys, glob

#use: thisone.py <lists_dir><majorfile><out_dir>

lists = glob.glob(sys.argv[1]+ '*.txt')
listsmatrix = []
for line in lists:
    listsmatrix.append(line.strip().split('\n'))

majorfile = open(sys.argv[2],'r')
majormatrix = []
for line in majorfile:
    majormatrix.append(line.strip().split('\t'))

os.mkdir(sys.argv[3])

i=0
for line in majormatrix:
    if line [0] in listsmatrix:
        outfile = open(sys.argv[3]+ 'file'+str(i), 'w')
        outfile.write(line)
        outfile.close()
        i+=1
</code>```

I'll be thankful for any help from you.

答:
When you open the file with 'w', the file gets cleared. So every time you open the file, the new line overrides the previous one.

Two possible solutions:

1) Replace 'w' with 'a', so you're appending to the file rather than overwriting it.

2) Open the file once, ideally using a 'with' block so that the file gets closed correctly even if an exception occurs:

```<code>with open(sys.argv[3]+ 'file'+str(i), 'w') as outfile:
    for line in majormatrix:
        if line [0] in listsmatrix:
            outfile.write(line)
            i+=1
</code>```

Body:
I don't know what's wrong with the code it doesn't get me any kind of error message from the shell.
What I'm trying to do is:

Merge all list files from a directory into a single list(with one single column with a single string per row) - done!

Compare that list with a big-file and copy every single correspondent line into a new single file for each line - (maybe?) done! But not working. =/

save the files from step 2 in a new output_directory. - not working.

Remove the correspondent lines from the big-file and save it in the same output_directory - no idea. (maybe pop?)

It's possible to name the output 'singlelinefiles' with the same string used to in step 2? Can anyone show me how?
It would be much appreciated

Here's the code so far:

#!/usr/bin/python

import os, sys, glob

#use: thisone.py <lists_dir><majorfile><out_dir>

lists = glob.glob(sys.argv[1]+ '*.txt')
listsmatrix = []
for line in lists:
    listsmatrix.append(line.strip().split('\n'))

majorfile = open(sys.argv[2],'r')
majormatrix = []
for line in majorfile:
    majormatrix.append(line.strip().split('\t'))

os.mkdir(sys.argv[3])

i=0
for line in majormatrix:
    if line [0] in listsmatrix:
        outfile = open(sys.argv[3]+ 'file'+str(i), 'w')
        outfile.write(line)
        outfile.close()
        i+=1

I'll be thankful for any help from you.

Body:
When you open the file with 'w', the file gets cleared. So every time you open the file, the new line overrides the previous one.

Two possible solutions:

1) Replace 'w' with 'a', so you're appending to the file rather than overwriting it.

2) Open the file once, ideally using a 'with' block so that the file gets closed correctly even if an exception occurs:

with open(sys.argv[3]+ 'file'+str(i), 'w') as outfile:
    for line in majormatrix:
        if line [0] in listsmatrix:
            outfile.write(line)
            i+=1


问:
Is there a way to figure out what is using a Linux kernel module?
If I load a kernel module and list the loaded modules with lsmod, I can get the "use count" of the module (number of other modules with a reference to the module). Is there a way to figure out what is using a module, though?

The issue is that a module I am developing insists its use count is 1 and thus I cannot use rmmod to unload it, but its "by" column is empty. This means that every time I want to re-compile and re-load the module, I have to reboot the machine (or, at least, I can't figure out any other way to unload it).

答: All you get are a list of which modules depend on which other modules (the Used by column in lsmod).  You can't  write a program to tell why the module was loaded, if it is still needed for anything, or what might break if you unload it and everything that depends on it.

OwnerDisplayName: mipadi

LastEditorDisplayName: mipadi

OwnerDisplayName: Norman Ramsey


问:
evaluating else if after an if condition is true
Consider this snippet:

```<code>private void button1_Click(object sender, EventArgs e)
{
    if (textBox1.MaxLength > 0)
    {
        textBox2.Text = Convert.ToBoolean(Math.Sqrt(textBox1.MaxLength)).ToString();
    }
    else if (textBox1.MaxLength < 32768)
    {
        textBox2.Text = Convert.ToBoolean(Math.Sqrt(textBox1.MaxLength)).ToString();
    }
}
</code>```

Why is it not evaluating the second condition (the lesser than condition)? It's also true, isn't it?

If I have to make the second one to work in the same condition, what minor change must be made?

答: You'll never reach the second if, because any number larger than 0 will satisfy the first if before the second, more restrictive condition. To put it in simpler terms, the first if will match all numbers n where n > 0, whereas the second if matches numbers 32768 > n > 0.

Body:
Consider this snippet:

private void button1_Click(object sender, EventArgs e)
{
    if (textBox1.MaxLength > 0)
    {
        textBox2.Text = Convert.ToBoolean(Math.Sqrt(textBox1.MaxLength)).ToString();
    }
    else if (textBox1.MaxLength < 32768)
    {
        textBox2.Text = Convert.ToBoolean(Math.Sqrt(textBox1.MaxLength)).ToString();
    }
}

Why is it not evaluating the second condition (the lesser than condition)? It's also true, isn't it?

If I have to make the second one to work in the same condition, what minor change must be made?


问:
this query taking long time to execute in sql server manegment studio 2012
```<code>SELECT s.option_code,s.seasonal_template_id,s.T900,s.T901,s.creator_id,s.creator_date,s.revisor_id,s.revisor_date,s.costing_sr_no,s.[T902],s.[T903]
FROM   [dbo].[tna870_seasonal_bulk_option_code_details_vendor_temp] s
   INNER JOIN mst703_master_field_values S5
   ON S5.field_value_id = s.T900
      AND S5.field_id = (select s1.field_id from mst703_master_field s1
                         where s1.field_code='t900')

WHERE s.seasonal_template_id = 35

AND ( s.option_code+CAST(s.seasonal_template_id AS VARCHAR(20))+s.costing_sr_no
  NOT IN (SELECT DISTINCT s2.option_code+CAST(s2.seasonal_template_id AS VARCHAR(20))+s2.costing_sr_no
          FROM tna870_seasonal_bulk_option_code_details_vendor s2
          WHERE s2.seasonal_template_id = 35) )
</code>```

答:
You can try this</p>

```<code>SELECT
s.option_code,
s.seasonal_template_id,
s.T900,
s.T901,
s.creator_id,
s.creator_date,
s.revisor_id,
s.revisor_date,
s.costing_sr_no,
s.[T902],
s.[T903]
FROM
(
    SELECT
    *
    FROM [dbo].[tna870_seasonal_bulk_option_code_details_vendor_temp] s
    WHERE s.seasonal_template_id = 35
    AND NOT EXISTS(
                   SELECT 1
                   FROM  tna870_seasonal_bulk_option_code_details_vendor s2
                   WHERE s2.seasonal_template_id = s.seasonal_template_id
                   AND s2.option_code+CAST(s2.seasonal_template_id AS VARCHAR(20))+s2.costing_sr_no = s.option_code+CAST(s.seasonal_template_id AS VARCHAR(20))+s.costing_sr_no
                  )
) s
INNER JOIN mst703_master_field_values S5
   ON S5.field_value_id = s.T900
      AND S5.field_id = (select s1.field_id from mst703_master_field s1
                         where s1.field_code='t900')
</code>```

Body:
You can try this

SELECT
s.option_code,
s.seasonal_template_id,
s.T900,
s.T901,
s.creator_id,
s.creator_date,
s.revisor_id,
s.revisor_date,
s.costing_sr_no,
s.[T902],
s.[T903]
FROM
(
    SELECT
    *
    FROM [dbo].[tna870_seasonal_bulk_option_code_details_vendor_temp] s
    WHERE s.seasonal_template_id = 35
    AND NOT EXISTS(
                   SELECT 1
                   FROM  tna870_seasonal_bulk_option_code_details_vendor s2
                   WHERE s2.seasonal_template_id = s.seasonal_template_id
                   AND s2.option_code+CAST(s2.seasonal_template_id AS VARCHAR(20))+s2.costing_sr_no = s.option_code+CAST(s.seasonal_template_id AS VARCHAR(20))+s.costing_sr_no
                  )
) s
INNER JOIN mst703_master_field_values S5
   ON S5.field_value_id = s.T900
      AND S5.field_id = (select s1.field_id from mst703_master_field s1
                         where s1.field_code='t900')


问:
how to avoid or handle request for `favicon.ico` from the browser for a servlet?
UPDATE:
Even though another request is being sent for favicon.ico and function is getting executed again (two console.log(data) outputs), why isn't the response object being sent twice?

Also, is there a way to not send a request for favcion.ico as I wouldn't want my function to uselessly run twice?

I have created a very simple servlet to accept a GET (default) and return the contents to the browser after reading a file

```<code>var http = require("http");
var fs = require("fs");
var num=0;

http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
var data = '';
// Create a readable stream
var readerStream = fs.createReadStream('input.txt');

// Set the encoding to be utf8.
readerStream.setEncoding('UTF8');

// Handle stream events --> data, end, and error
readerStream.on('data', function(chunk) {
   data += chunk;
});

readerStream.on('end',function(){
console.log(data); //To print same file content in the console
response.end(data);
});

readerStream.on('error', function(err){
   console.log(err.stack);
   data+="\n\n"+err.stack;
});

}).listen(8081);

// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
</code>```

But every time I run this servlet and make a request at http://localhost:/8081, I get the content of the file printed twice on the console but only once at the browser window (this is the expected behaviour).

What is the cause for the console behaviour?

Also, I modified the program by adding a counter to count how many times the function is run for every request (appended the value as data+num for both console and response) and it was found to be two but the response from the first execution of the function was the one received by the browser, not the second one(browser window printed data+1 for the first ever request).

答:
Most browsers make a call to grab /favicon.ico for example.

Try to log the url and you can see what's being called.

```<code>console.log(req.url);
</code>```

Body:
UPDATE:
Even though another request is being sent for favicon.ico and function is getting executed again (two console.log(data) outputs), why isn't the response object being sent twice?

Also, is there a way to not send a request for favcion.ico as I wouldn't want my function to uselessly run twice?

I have created a very simple servlet to accept a GET (default) and return the contents to the browser after reading a file

var http = require("http");
var fs = require("fs");
var num=0;

http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
var data = '';
// Create a readable stream
var readerStream = fs.createReadStream('input.txt');

// Set the encoding to be utf8.
readerStream.setEncoding('UTF8');

// Handle stream events --> data, end, and error
readerStream.on('data', function(chunk) {
   data += chunk;
});

readerStream.on('end',function(){
console.log(data); //To print same file content in the console
response.end(data);
});

readerStream.on('error', function(err){
   console.log(err.stack);
   data+="\n\n"+err.stack;
});

}).listen(8081);

// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');

But every time I run this servlet and make a request at http://localhost:/8081, I get the content of the file printed twice on the console but only once at the browser window (this is the expected behaviour).

What is the cause for the console behaviour?

Also, I modified the program by adding a counter to count how many times the function is run for every request (appended the value as data+num for both console and response) and it was found to be two but the response from the first execution of the function was the one received by the browser, not the second one(browser window printed data+1 for the first ever request).

Body:
Most browsers make a call to grab /favicon.ico for example.

Try to log the url and you can see what's being called.

console.log(req.url);


问:
Automatic embeded script
I have a free website on 000webhost. The problem is it automatically puts its analytics code in all my files. It does not show up everywhere but it causes me problem when I use AJAX calls and display the returned data in a div, it displays the data as well as that particular code. Is there any type of method to avoid this or make this code invisible.
Also when I used Google webmaster tools, when it crawls my robots.txt file the code is also shown to the crawler on that file also which is a text file and it returns error.
Please help!
Here is the link to my website:
Portfolio</p>

答:
Your hosting provider seems to inject the following line at the end of some requests:

```<code><!-- www.000webhost.com Analytics Code -->
<script type="text/javascript" src="http://analytics.hosting24.com/count.php"></script>
<noscript><a href="http://www.hosting24.com/"><img src="http://analytics.hosting24.com/count.php" alt="web hosting" /></a></noscript>
<!-- End Of Analytics Code -->
</code>```

The injection point of their code is simply at the end of the request. When I checked, it meant that it was outside the HTML tag (and thus broke HTML syntax validity.

I see 2 possible solutions:

Work the issue out with them.

Find a work-around (your provider might be injecting this content on when they detect certaint type of requests. If you find out that they only inject the content on requests to URLs ending in .html (for example), you could try changing the destination of your AJAX call towards another URL)

Title: Automatic embeded script

Body:
Your hosting provider seems to inject the following line at the end of some requests:

<!-- www.000webhost.com Analytics Code -->
<script type="text/javascript" src="http://analytics.hosting24.com/count.php"></script>
<noscript><a href="http://www.hosting24.com/"><img src="http://analytics.hosting24.com/count.php" alt="web hosting" /></a></noscript>
<!-- End Of Analytics Code -->

The injection point of their code is simply at the end of the request. When I checked, it meant that it was outside the HTML tag (and thus broke HTML syntax validity.

I see 2 possible solutions:

Work the issue out with them.

Find a work-around (your provider might be injecting this content on when they detect certaint type of requests. If you find out that they only inject the content on requests to URLs ending in .html (for example), you could try changing the destination of your AJAX call towards another URL)


问:
How to make an object jump automatically in unity 5.6?
I'm developing a game which has the thematic Cubes. I make that game in Unity3D and c#. I want to make a cube(obstacle) jump automatically infinite times, without ever stopping.

How can I do this?

答:
You should look up transform.position in the unity docs. https://docs.unity3d.com/ScriptReference/Transform-position.html

Also read up on creating a coroutine.

ContentLicense: CC BY-SA 4.0