text:
Q: org.jinterop.dcom.common.JIException: Access is denied. [0x80070005] I am trying to connect to GRAYBOX Simulator using utgard java api for opc connection, I am getting the below error. I have followed all the dcom instructions. Still I am getting access denied. I am running this code through eclipse. Is there anything I am missing ? Do I need to authorize java.exe to make the dcom calls?
JISystem.setAutoRegisteration(false);
         final ConnectionInformation ci = new ConnectionInformation();
            ci.setHost("10.11.203.34");
            ci.setDomain("AD");
            ci.setUser("user");
            ci.setPassword("pass");
            ci.setProgId("Graybox.Simulator.1");
            ci.setClsid("2C2E36B7-FE45-4A29-BF89-9BFBA6A40857"); // if ProgId is not working, try it using the Clsid instead
            final String itemId = "numeric.sin.double";

//          ci.setProgId("Matrikon.OPC.Simulation.1");
//          ci.setClsid("F8582CF2-88FB-11D0-B850-00C0F0104305"); // if ProgId is not working, try it using the Clsid instead
//          final String itemId = "Random.ArrayOfReal8";

            // create a new server
            final Server server = new Server(ci, Executors.newSingleThreadScheduledExecutor());

 server.connect();

This happens when I try to connect to local graybox simulator or a remote one
Jan 5, 2016 4:07:36 PM org.jinterop.dcom.common.JISystem logSystemPropertiesAndVersion
INFO: j-Interop Version = null

Jan 5, 2016 4:07:36 PM org.jinterop.dcom.common.JISystem logSystemPropertiesAndVersion
INFO: java.runtime.name = Java(TM) SE Runtime Environment
sun.boot.library.path = D:\jdk1.6.0_45\jre\bin
java.vm.version = 20.45-b01
java.vm.vendor = Sun Microsystems Inc.
java.vendor.url = http://java.sun.com/
path.separator = ;
java.vm.name = Java HotSpot(TM) 64-Bit Server VM
file.encoding.pkg = sun.io
sun.java.launcher = SUN_STANDARD
user.country = US
sun.os.patch.level = Service Pack 1
java.vm.specification.name = Java Virtual Machine Specification
user.dir = D:\iefs_ws\OPC_TEST
java.runtime.version = 1.6.0_45-b06
java.awt.graphicsenv = sun.awt.Win32GraphicsEnvironment
java.endorsed.dirs = D:\jdk1.6.0_45\jre\lib\endorsed
os.arch = amd64
java.io.tmpdir = C:\Users\irajjad\AppData\Local\Temp\
line.separator =

java.vm.specification.vendor = Sun Microsystems Inc.
user.variant =
os.name = Windows 7
sun.jnu.encoding = Cp1252
java.library.path = D:\jdk1.6.0_45\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;D:\jdk1.6.0_45\jre\bin;C:\Program Files\Teradata\Client\15.10\bin;C:\Program Files (x86)\Teradata\Client\15.10\bin;D:\app\IRajjad\product\11.2.0\client_2;c:\Program Files (x86)\Intel\iCLS Client\;c:\Program Files\Intel\iCLS Client\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x86;C:\Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x64;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;D:\apache-maven-3.2.5\bin;D:\jdk1.7.0_67\bin;D:\path;D:\ArcGIS\Desktop10.3\bin;C:\Program Files (x86)\ArcGIS\DeveloperKit10.2\java\tools\ant\bin;.
java.specification.name = Java Platform API Specification
java.class.version = 50.0
sun.management.compiler = HotSpot 64-Bit Tiered Compilers
os.version = 6.1
user.home = C:\Users\irajjad
user.timezone = Asia/Karachi
java.awt.printerjob = sun.awt.windows.WPrinterJob
file.encoding = Cp1252
java.specification.version = 1.6
java.class.path = D:\iefs_ws\OPC_TEST\bin;D:\java_opc\org.openscada.jinterop.sdk-R.1.0.0\org.openscada.jinterop.core_2.0.8.201303051454.jar;D:\java_opc\org.openscada.jinterop.sdk-R.1.0.0\org.openscada.jinterop.deps_1.0.0.201303051454.jar;D:\java_opc\org.openscada.utgard.sdk-R.1.0.0\org.openscada.opc.dcom_1.0.0.201303051455.jar;D:\java_opc\org.openscada.utgard.sdk-R.1.0.0\org.openscada.opc.lib_1.0.0.201303051455.jar;D:\eclipse-jee-luna-SR1-win32\eclipse\plugins\org.junit_4.11.0.v201303080030\junit.jar;D:\eclipse-jee-luna-SR1-win32\eclipse\plugins\org.hamcrest.core_1.3.0.v201303031735.jar;D:\java_opc\org.openscada-1.2.0-SNAPSHOT\plugins\org.openscada.external.jcifs_1.2.25.v20140625-1257.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\ch.qos.logback.classic_1.0.0.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\ch.qos.logback.core_1.0.0.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\cal10n.api_0.7.4.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\com.google.gson_2.2.2.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\com.google.guava_10.0.1.v201203051515.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\com.jcraft.jzlib_1.1.1.v201205102305.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\com.springsource.antlr_2.7.7.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\com.springsource.javassist_3.9.0.GA.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\com.springsource.javax.activation_1.1.1.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\com.springsource.javax.ejb_3.0.0.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\com.springsource.javax.jms_1.1.0.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\com.springsource.javax.jws_2.0.0.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\com.springsource.javax.transaction_1.1.0.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\com.springsource.javax.xml.rpc_1.1.0.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\com.springsource.javax.xml.soap_1.3.0.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\com.springsource.javax.xml.stream_1.0.1.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\com.springsource.net.sf.cglib_2.2.0.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\com.springsource.org.antlr_3.1.3.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\com.springsource.org.aopalliance_1.0.0.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\com.springsource.org.apache.commons.beanutils_1.8.0.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\com.springsource.org.apache.commons.collections_3.2.1.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\com.springsource.org.apache.xmlbeans_2.4.0.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\com.springsource.org.dom4j_1.6.1.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\com.springsource.org.hsqldb_1.8.0.10.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\com.springsource.org.jvnet.staxex_1.0.0.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\jackson-core-lgpl_1.5.2.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\jackson-mapper-lgpl_1.5.2.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\javax.xml_1.3.4.v201005080400.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\jcl.over.slf4j_1.6.4.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\jsr305_0.1.0.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\jul.to.slf4j_1.6.4.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\log4j.over.slf4j_1.6.4.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\org.apache.commons.daemon_1.0.10.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\org.apache.commons.dbcp_1.4.0.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\org.apache.commons.io_2.3.0.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\org.apache.commons.lang_2.6.0.v201205030909.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\org.apache.commons.pool_1.6.0.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\org.apache.mina.core_2.0.7.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\org.apache.mina.filter.compression_2.0.7.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\org.apache.mina.transport.socket.apr_2.0.7.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\org.apache.tomcat-apr_5.5.23.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\org.apache.xerces_2.9.0.v201101211617.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\org.apache.xml.resolver_1.2.0.v201005080400.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\org.apache.xml.serializer_2.7.1.v201005080400.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\org.openscada.external.apache.poi_3.7.0.201303051448.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\org.openscada.external.jbzip2_0.9.1.201303051448.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\org.openscada.external.jcifs_1.2.25.201303051448.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\org.openscada.external.logback.default_1.0.0.201303051448.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\org.openscada.external.odfdom_0.8.7.201303051448.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\org.openscada.external.osgi.enterprise_4.2.0.201303051448.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\org.openscada.external.postgresql_9.1.901.201303051448.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\org.springframework.aop_3.1.2.RELEASE.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\org.springframework.beans_3.1.2.RELEASE.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\org.springframework.context_3.1.2.RELEASE.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\org.springframework.core_3.1.2.RELEASE.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\org.springframework.jdbc_3.1.2.RELEASE.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\org.springframework.orm_3.1.2.RELEASE.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\org.springframework.transaction_3.1.2.RELEASE.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\org.springframework.web_3.1.2.RELEASE.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\slf4j.api_1.6.4.jar;D:\java_opc\org.openscada.external.sdk-R.1.0.0\slf4j.ext_1.6.4.jar;D:\java_opc\bcprov-jdk15on-154.jar;/D:/eclipse-jee-luna-SR1-win32/eclipse/configuration/org.eclipse.osgi/362/0/.cp/;/D:/eclipse-jee-luna-SR1-win32/eclipse/configuration/org.eclipse.osgi/361/0/.cp/
user.name = IRajjad
java.vm.specification.version = 1.0
sun.java.command = org.eclipse.jdt.internal.junit.runner.RemoteTestRunner -version 3 -port 52910 -testLoaderClass org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader -loaderpluginname org.eclipse.jdt.junit4.runtime -test Test:test
java.home = D:\jdk1.6.0_45\jre
sun.arch.data.model = 64
user.language = en
java.specification.vendor = Sun Microsystems Inc.
awt.toolkit = sun.awt.windows.WToolkit
java.vm.info = mixed mode
java.version = 1.6.0_45
java.ext.dirs = D:\jdk1.6.0_45\jre\lib\ext;C:\Windows\Sun\Java\lib\ext
sun.boot.class.path = D:\jdk1.6.0_45\jre\lib\resources.jar;D:\jdk1.6.0_45\jre\lib\rt.jar;D:\jdk1.6.0_45\jre\lib\sunrsasign.jar;D:\jdk1.6.0_45\jre\lib\jsse.jar;D:\jdk1.6.0_45\jre\lib\jce.jar;D:\jdk1.6.0_45\jre\lib\charsets.jar;D:\jdk1.6.0_45\jre\lib\modules\jdk.boot.jar;D:\jdk1.6.0_45\jre\classes
java.vendor = Sun Microsystems Inc.
file.separator = \
java.vendor.url.bug = http://java.sun.com/cgi-bin/bugreport.cgi
sun.io.unicode.encoding = UnicodeLittle
sun.cpu.endian = little
sun.desktop = windows
sun.cpu.isalist = amd64

Jan 5, 2016 4:07:36 PM rpc.DefaultConnection processOutgoing
INFO:
 Sending BIND
Jan 5, 2016 4:07:36 PM rpc.DefaultConnection processIncoming
INFO:
 Recieved BIND_ACK
Jan 5, 2016 4:07:36 PM rpc.DefaultConnection processOutgoing
INFO:
 Sending AUTH3
Jan 5, 2016 4:07:36 PM rpc.DefaultConnection processOutgoing
INFO:
 Sending ALTER_CTX
Jan 5, 2016 4:07:36 PM rpc.DefaultConnection processIncoming
INFO:
 Recieved ALTER_CTX_RESP
Jan 5, 2016 4:07:36 PM rpc.DefaultConnection processOutgoing
INFO:
 Sending REQUEST
Jan 5, 2016 4:07:36 PM rpc.DefaultConnection processIncoming
INFO:
 Recieved RESPONSE
Jan 5, 2016 4:07:36 PM rpc.DefaultConnection processOutgoing
INFO:
 Sending BIND
Jan 5, 2016 4:07:36 PM rpc.DefaultConnection processIncoming
INFO:
 Recieved BIND_ACK
Jan 5, 2016 4:07:36 PM rpc.DefaultConnection processOutgoing
INFO:
 Sending AUTH3
Jan 5, 2016 4:07:36 PM rpc.DefaultConnection processOutgoing
INFO:
 Sending REQUEST
Jan 5, 2016 4:07:36 PM rpc.DefaultConnection processIncoming
INFO:
 Recieved RESPONSE
org.jinterop.dcom.common.JIException: Access is denied.  [0x80070005]
    at org.jinterop.dcom.core.JIRemUnknownServer.call(Unknown Source)
    at org.jinterop.dcom.core.JIRemUnknownServer.addRef_ReleaseRef(Unknown Source)
    at org.jinterop.dcom.core.JIComObjectImpl.addRef(Unknown Source)
    at org.jinterop.dcom.core.JIComServer.createInstance(Unknown Source)
    at org.openscada.opc.lib.da.Server.connect(Server.java:130)
    at Test.test(Test.java:59)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.jinterop.dcom.common.JIRuntimeException: Access is denied.  [0x80070005]
    at org.jinterop.dcom.core.JICallBuilder.readResult(Unknown Source)
    at org.jinterop.dcom.core.JICallBuilder.read(Unknown Source)
    at ndr.NdrObject.decode(Unknown Source)
    at rpc.ConnectionOrientedEndpoint.call(Unknown Source)
    at rpc.Stub.call(Unknown Source)
    ... 32 more
16:07:36.716 [OPCSessionDestructor] WARN  org.jinterop.dcom.core.JISession - prepareForReleaseRef: Releasing numInstancesfirsttime + 5 references of IPID: 0000b415-0e50-0000-3e4f-747113678f6a session: -1394010222 , numInstancesfirsttime is 5

A: step 1:
Administrative tools ->component and services ->computers->mycomputer-> DCOM CONFIG
step2:
select your server, right click>properties >security Tab>
step3:
Launch and Activation permission > edit> Add your username and give all the permission
step 4: Access permission, repeat as above
step 5: configuration permission, repeat as in step 3
The error will be resolved.


text:
Q: Connecting Bluetooth Heart rate monitor to Windows 8.1 I am currently creating an Windows store app which connects to Bluetooth Low Energy sensors. Before being able to use a device in your app you must pair it with windows. When I try to pair the device in [control panel -> hardware and sound -> add device], it shows the device but as soon as it try to pair it, it gives me the message: Make sure your device is still discoverable. I have been able to pair other device types(Bike speed and cadence sensor).
I know that Windows Phone couldn't connect to heart rate monitors before an update fixed it, so I was wondering if a similar problem exists for Windows 8.1(Desktop). I have been searching for an anwser but I cannot find anything anywhere, I have also been asking for help on the bluetooth developer site and on MSDN, but with no luck.
The device I am trying to pair with is a Wahoo Tickr(Heart rate monitor) on Windows 8.1 64 bit. My laptop has a Intel(R) Centrino(R) Wireless Bluetooth(R) 4.0 + High Speed Adapter.

redpajama_set_name: RedPajamaStackExchange


text:
Q: High latency in fetching the messages from google pubsub pull model through java client We have one application which navigates the bigquery logs to pubsub topic, and we have one pull subscription on that topic. I have implemented synchronous pull with lease management, in that I set the maxMessages to 100, which indicates pulling 100 messages at max from the topic in one request.
I had ran a terraform script which will run hundreds of jobs concurrently and that will generate hundreds of logs within in few seconds, My pull mechanism will fetch the messages every 30 seconds. Since there are a lot of logs, I expected 100 messages in one request, but that was not happening, in every request, I am getting arbitrary no of messages like 14, 7, 10, and 3. It takes a lot of time to fetch all the messages about my jobs. I don't know what exactly the issue.
Please help me in identifying how to get the desired messages and decrease my latency when there are a lot of messages on the topic. Is PubSub service throttling the response or any configuration I have to do on my end?
public List<ReceivedMessage> getMessagesFromSubscription(String projectId, String subscriptionId, int numOfMessages,
                                                         CredentialsProvider credentialsProvider) {

    List<ReceivedMessage> receivedMessages = new ArrayList<>();
    try {
        SubscriberStubSettings subscriberStubSettings = getSubscriberStubSettings(credentialsProvider);
        try (SubscriberStub subscriber = GrpcSubscriberStub.create(subscriberStubSettings)) {
            String subscriptionName = ProjectSubscriptionName.format(projectId, subscriptionId);
            PullRequest pullRequest = PullRequest.newBuilder()
                    .setMaxMessages(100)
                    .setSubscription(mypubsub)
                    .build();
            PullResponse pullResponse = subscriber.pullCallable().call(pullRequest);
            List<String> ackIds = new ArrayList<>();
            for (ReceivedMessage message : pullResponse.getReceivedMessagesList()) {
                ackIds.add(message.getAckId());
                ModifyAckDeadlineRequest modifyAckDeadlineRequest = ModifyAckDeadlineRequest.newBuilder()
                        .setSubscription(subscriptionName)
                        .addAckIds(message.getAckId())
                        .setAckDeadlineSeconds(30)
                        .build();
                subscriber.modifyAckDeadlineCallable().call(modifyAckDeadlineRequest);
            }
            if (ackIds.isEmpty()) {
             // my logic
            } else {
                AcknowledgeRequest acknowledgeRequest = AcknowledgeRequest.newBuilder()
                        .setSubscription(subscriptionName)
                        .addAllAckIds(ackIds)
                        .build();
                subscriber.acknowledgeCallable().call(acknowledgeRequest);
                receivedMessages = new ArrayList<>(pullResponse.getReceivedMessagesList());
            }
        }
        LOG.info("getMessagesFromSubscription: Received {} Messages for Project Id: {} and" +
                " Subscription Id: {}.", receivedMessages.size(), projectId, subscriptionId);
    } catch (Exception e) {
        LOG.error("getMessagesFromSubscription: Error while pulling message from Pub/Sub " +
                "from Project ID: {} and Subscription ID: {}", projectId, subscriptionId, e);
    }
    return receivedMessages;
}

private SubscriberStubSettings getSubscriberStubSettings(CredentialsProvider credentialsProvider) throws IOException {
    SubscriberStubSettings.Builder subscriberStubSettingsBuilder = SubscriberStubSettings
            .newBuilder()
            .setTransportChannelProvider(SubscriberStubSettings
                    .defaultGrpcTransportProviderBuilder()
                    .setMaxInboundMessageSize(20 << 20)
                    .build());
    if (credentialsProvider != null) {
        subscriberStubSettingsBuilder = subscriberStubSettingsBuilder.setCredentialsProvider(credentialsProvider);
    }
    return subscriberStubSettingsBuilder.build();
}

A: The documentation calls out specifically the need to have lots of pull requests outstanding simultaneously to achieve high throughput and low latency:
"To achieve low message delivery latency with synchronous pull, it is important to have many simultaneously outstanding pull requests. As the throughput of the topic increases, more pull requests are necessary. In general, asynchronous pull is preferable for latency-sensitive applications."
Making a single, synchronous pull request at a time is not going to be an efficient way to pull messages. The Pub/Sub service tries to trade off full pull responses with latency, preferring to send some messages back quickly rather than a full pull response, which is why you see fewer than 100 messages returned. If you make a lot more pull requests simultaneously, you are more likely to get full responses as the service will recognize that the subscriber can handle more load and fetch more messages to fulfill the pull requests.
If you want to maximize throughput and minimize latency, you should instead use asynchronous streaming pull.


text:
Q: Creating a sub class that doesn't uses super constructor automatically I've got several classes:
import java.io.File;
public interface Filter {

    public boolean passes();

}

import java.io.File;

abstract public class PFilter implements Filter {
    String val;
    File file;

    public PFilter(String value, File f){
        val = value;
        file = f;
    }
    @Override
    abstract public boolean passes();

}

and at last;
import java.io.File;

public class HFilter extends PFilter {
    public HFilter(String val, File f) {
        super(value, f);
    }

    @Override
    public boolean passes() {
        return file.isHidden();
    }
}

I'd like to if it's possible for me to not call super() in the HFilter class. Is it possible then when creating an instance of HFilter, once I put in the two arguments It will automatically call the super() and then I wont need a constructor?


text:
Q: XML parsing and treeview parse the xml file:
XmlTextReader reader = new XmlTextReader(fileName);
while (reader.Read())
{
    switch (reader.NodeType)
    {
        case XmlNodeType.Element: // The node is an element.
            Console.Write("<" + reader.Name);
            Console.WriteLine(">");
            break;
        case XmlNodeType.Text: //Display the text in each element.
            Console.WriteLine(reader.Value);
            break;
        case XmlNodeType.EndElement: //Display the end of the element.
            Console.Write("</" + reader.Name);
            Console.WriteLine(">");
            break;
    }
}

How do i now enter nodes to get a tree view of the xml file i'm parsing? This is what i have thus far:
<TreeView Margin="177,61" Name="myTreeView" ItemsSource="{Binding XPath=XmlNodeType.Element}" >
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding XPath=XmlNodeType.Element}">
            <TextBlock Text="{Binding XPath=XmlNodeType.Text}" />
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

but nothing shows up.... just don't understand how to add nodes i guess...

A: You have to add the nodes in code behind like that:
var newNode = new TreeViewItem
{
    Header = "New Node"
};
myTreeView.Items.Add(newNode);

This adds a node to the top of the tree. If you want to build a hierarchy you have to add the node at the appropiate position like that:
// Find the node you want to have as parent.
var parentNode = myTreeView.Items.Cast<TreeViewItem>().FirstOrDefault(item => item.Header = "Parent Node");
if (parentNode != null)
{
    var newNode = new TreeViewItem
    {
        Header = "New Node"
    };
    parentNode.Items.Add(newNode);
}

BTW: I would use to x:Name Property to name the elements in Xaml, sometimes there is some trouble in code behind when you use only Name


text:
Q: How to count the number of relationships to a table in MySQL? I am arranging an ERD diagram of an existing database with about a 100 tables, to add some structure to the process, how rank out the number of relations the tables have to each other?
For example, table 1 is related directly to ten tables. Table 2 is related to four tables and so on.
I am using MySQL workbench and the diagram is drawing using the programs Reverse Engineer on an existing database.

A: select referenced_table_name, count(distinct constraint_name)
from information_schema.key_column_usage
where referenced_table_schema=?
and constraint_name <> 'PRIMARY'
group by referenced_table_name;

I put ? for the schema name, you would supply a query parameter for the schema you need to analyze.
Note that this works only if you have FOREIGN KEY constraints defined. If you don't have such constraints, there is no way for any tool to guess at the table relationships.
Dbfiddle


text:
Q: fparsec to parse sequence of string I have an user input text like "abc,def,ghi". I want to parse it to get list of string as ["abc", "def"].
I tried
let str : Parser<_> = many1Chars (noneOf ",")
let listParser : Parser<_> = many (str);;

but it always give me the first item only ["abc"]. "Def" and others are not coming in result list

A: You're parsing up to the first comma, but not parsing the comma itself.
To parse a list of things separated by other things, use sepBy:
let comma = pstring ","
let listParser = sepBy str comma

If you need to parse "at least one", use sepBy1 instead.


text:
Q: How do I read the state of 3 output pins on an Arduino UNO and then NAND them together? So I am working on software to control a H8 inverter. I got code that does SPWM for a 3 phase inverter online. I then applied a software NAND gate on 3 outputs from the Arduino UNO and this is the result I got:

and this:

I used a hardware NAND gate and I got this:

//-------www<electronics-project-hub>com--------//
#include <math.h>
int Output1 = 11;
int Output2 = 10;
int Output3 = 9;

int Output4 = 8;

uint8_t a = 0;
uint8_t w = 0;  //PB3
uint8_t x = 0;   //PB2
uint8_t y = 0;  //PB1
uint8_t z = 0;  //PB0

int potVal = 0;
float A = 0;
float B = 0.104;
int Freq_IN = A0;
int var1 = 0;
int var2 = 0;
int var3 = 0;
int var4 = 0;
int var5 = 0;
int var6 = 0;
float Phase1 = 2 * PI / 3;
float Phase2 = 4 * PI / 3;
float Phase3 = 2 * PI;
boolean toggle = true; // true = Enabling Serial Plotter Output
void setup()
{
  Serial.begin(9600);
  pinMode(Output1, OUTPUT);
  pinMode(Output2, OUTPUT);
  pinMode(Output3, OUTPUT);
  pinMode(Freq_IN, INPUT);
}
void loop()
{
  A += B;
  analogWrite(Output1, var1);
  analogWrite(Output2, var2);
  analogWrite(Output3, var3);

  //digitalWrite(Output4,!
(digitalRead(Output1)&&digitalRead(Output2)&&digitalRead(Output3)));

   /*g1 = (PORTD & B00100000) >> 5;
    g3 = (PORTB & B00000100) >> 2;
    g5 = (PORTD & B00001000) >> 3;
    g7 = ~((g1&g3)&g5);
    digitalWrite(G7,g7);*/
    /*
    g4 = (PORTD & B01000000) >> 6;
    g6 = (PORTB & B00000010) >> 1;
    g2 = (PORTB & B00001000) >> 3;
    g8 = !((g4&&g6)&&g2);
    digitalWrite(G7,g8);*/
  a = PORTB & 0b00001111;
  w = (a & 0b00001000) >> PORTB3;
  x = (a & 0b00000100) >> PORTB2;
  y = (a & 0b00000010) >> PORTB1;
  z = ~(w&x&y&z);
  PORTB = PORTB | z;
  if (toggle == true)
  {
    Serial.print(var1);
    Serial.print(" ");
    Serial.print(var2);
    Serial.print(" ");
    Serial.println(var3);
  }
  var4 = 126 * sin(A + Phase1);
  var1 = var4 + 128;
  var5 = 126 * sin(A + Phase2);
  var2 = var5 + 128;
  var6 = 126 * sin(A + Phase3);
  var3 = var6 + 128;
  if (A >= 2 * PI)
  {
    A = 0;
  }
  potVal = analogRead(Freq_IN);
  delay(potVal);
}
//-------www<electronics-project-hub>com--------//

I would like to point out that the software NAND output stayed ON all the time. The hardware NAND output varied, which is the result I am trying to get.

A: According to https://en.wikipedia.org/wiki/NAND_logic, your code should be good:
digitalWrite(Output4, !(digitalRead(Output1) && digitalRead(Output2) && digitalRead(Output3)));

Or
digitalWrite(Output4, (!digitalRead(Output1) || !digitalRead(Output2) || !digitalRead(Output3)));

Maybe the problem comes from the fact that you are using the analogWrite function and the digitalRead on the same pin. Or the simulation tools is not working properlly (I don't know).

A: Create another pin for reading the (NAND) all together

A: Another question here is do you want to combine all the signal like interference I don't think using NAND would make that possible maybe you should try using another function


text:
Q: c++ eclipse juno build error I'm getting the following error with my C++ Eclipse Juno project, with Linux 64bits:
Error:
  description:Error 127 occurred while running autoreconf
  resource: MyProject
  location: -1
  type: Configure Problem

However my project builds successfully from command line.

A: To remove this error, you need to install (GNU Autotools - which include autoconf and automake):
sudo apt-get install automake
If you "just want to write some C++" - select "Executable" instead of GNU AutoTools in the NEW, C++ project  (Hello World or Empty) menu.

A: This thread may help. I think you would like to create executable project rather than GNU Autotools project.


text:
Q: How to add quoting for all fields in Doctrine DBAL? I have some special field names which will work without problems if field names are quoted like this:
`field`

But my code produces SQL statements without quotes:
$schema = $this->database->getSchemaManager();
$table = new \Doctrine\DBAL\Schema\Table('teachers');
foreach($header as $field) {
    $table->addColumn($field, "string");
}
$schema->createTable($table);

$this->database->insert('teachers', $data);
// ...

How to force DBAL to use quoting for field names?


text:
Q: Replying to old chat conversations I couldn't use the reply to this message to a chat message that is a day old. Why is this? I had to resort to typing @username so as to grab the person's attention.

A: If you know the chat transcript URL, you can do this instead:

example url: http://chat.meta.stackoverflow.com/transcript/message/620858#620858

enter the chatroom in question (since this came from the tavern, I would go to the tavern) and in the message box key the following:
:620858 message

notice the space after the :nnnnnn
In this manner, you can reply to any message, no matter how old, provided the message has not been deleted. At least, that's how I do it.

A: Although I'm not 100% sure what your precise issue was, I think this is fixed since replying from the transcript is now possible.

A: Press Ctrl+F5 on your browser to refresh the page and load all the scripts then try again. It should work.


text:
Q: How to bind a parents property to the child elements datatemplate I need to bind the RowStyle property of my DataGrid to the Visibility if the DataGrids childrens through a converter. The thing is that the children exists in a DataTemplate. My code below is a simplified version of what I am doing right now, so It might not make much sence. But anyway:
<DataGrid Name="dataGrid"
              ItemsSource="{Binding Path=ListOfData}"
              RowStyle="{StaticResource DataGridRowStyle}"
              >
        <DataGrid.RowDetailsTemplate>
              <DataTemplate>
                    <StackPanel>
                         <TextBlock Name="textBlock" Source={Binding Path=Title}
                         <Image Name="image" Source="{Binding Path=Image}"/>
                    </StackPanel>
              </DataTemplate>
        </DataGrid.RowDetailsTemplate>
  </DataGrid>

The thing is, that the TextBlock and Image can individually get collapsed. If both are collapsed, I need the DataGridRow to collapse or hide so you wont see it in the grid. My plan was to define a RowStyle named 'DataGridRowStyle'. The style will get triggered by the TextBlock and Images's Visibility property and set the RowStyle's Visibility to collapsed.
  <Style TargetType="{x:Type DataGridRow}" x:Key="DataGridRowStyle">
    <Setter Property="Visibility" Value="Visible" />
    <Style.Triggers>
        <MultiDataTrigger>
            <MultiDataTrigger.Conditions>
                <Condition Value="True">
                    <Condition.Binding>
                        <MultiBinding Converter="{StaticResource VisibilityConverter}">
                            <Binding ElementName="textBlock" Path="Visibility" />
                            <Binding ElementName="image" Path="Visibility" />
                        </MultiBinding>
                    </Condition.Binding>
                </Condition>
            </MultiDataTrigger.Conditions>
            <Setter Property="Visibility"  Value="Collapsed"/>
        </MultiDataTrigger>
    </Style.Triggers>
</Style>

Unfortunately, I get a warning in runtime, where System.Data can't fint my textBlock or image element. I guess you can't bind to a DataTemplate or what do I do wrong? Can I somehow do the same differently?

A: you indeed cannot bind to your dataTemplate here, since it is out of the RowStyle's scope.
I would do it in an other manner:

*

*As I see it, you should be able to determine in your ItemViewModel if the TextBox and the image are both collapsed at the same time

*Add a property to your ItemViewModel ('VisibilityProperty' for instance) and set it to 'Collapsed' when they both the TextBox and Image are collapsed.

*Bind the VisibilityProperty of your DataGridRow to this property of your ItemViewModel through the RowStyle.

this should do it
edit:
if you cannot change your itemViewModel, you have an other option (quite ugly though):
bind the Row's Visibility to the Item itself and use a converter to look for the items children and see if they are collapsed at runtime.
something along those lines:
<Style TargetType="{x:Type DataGridRow}" x:Key="DataGridRowStyle">
    <Setter Property="Visibility" Value="{Binding Converter=MyRowViewModelToVisibilityconverter}" />
</Style>

and your converter's code you have the item obviously, so just look for the TextBox's ViewModel and the Image's Viewmodel and see if they would collapse the Image & TextBox, then return the Visibility Accordingly:
public class MyRowViewModelToVisibilityconverter: MarkupExtension, IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var item = value as ItemViewModel;
        bool isImageCollapsed = false, isTextBoxCollapsed = false;

        // Look into your ItemViewModel for the properties inducing a Visibility=Collapsed on the Image and the TextBox

        return (isImageCollapsed && isTextBoxCollapsed) ? Visibility.Collapsed : Visbility.Visible;

    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return new MyRowViewModelToVisibilityconverter();
    }
}


text:
Q: android post and receive json Asyc I am working on an android application that posts a JSON object to a server and gets one back in response. I am stuck in how to get the JSON that the server responds with back to the main thread. Below is the code that I have so far. Even after I run my background process, when I call getResponse it returns null.
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import android.os.AsyncTask;

public class AsyncHttpPost extends AsyncTask<String, String, HttpResponse> {
    private JSONObject mData = null;// post data
    private HttpResponse response = null;
    /**
     * constructor
     */
    public AsyncHttpPost(JSONObject json) {
        mData = json;
    }

    public HttpResponse getResponse() {
        return response;
    }
    /**
     * background
     */
    @Override
    protected HttpResponse doInBackground(String... params) {

        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(params[0]);
        try {
            post.setEntity(new StringEntity(mData.toString()));
            response = client.execute(post);

        }catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        catch (Exception e) {
        }
        return response;
    }
}

A: U need to get data first , have u create a an adapter for it ?
when u want to get something using json, for an example title
this is how it loooks like.. you would also need to write in your main activity(depending what java use to display) to display the data.
I help this will help you. C:
//Declare variables
String title;

// call out the variables
public (ClasName) (String title) {

    this.title = title;
                }
public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}


text:
Q: postgres database : Insufficient privilege, permission denied for relation table I have been using the postgres database on heroku for a while. and suddenly I had some problems on saving to database
I got this error all the time
 Insufficient privilege, permission denied for relation table

its a problem of user permission , but I'm confused why it happened , because it was working correctly before

A: Check your heroku pg:info output - chances are you've exceeded the free plan permitted number of rows (assuming you're using a hobby-basic)


text:
Q: D3: Spiral plot Error I had used following link for spiral plot:
https://bl.ocks.org/arpitnarechania/027e163073864ef2ac4ceb5c2c0bf616
I'm playing around with the code and I am facing one issue when I change the currentDate to currentDate.toDateString() when it is reading the data i.e
...
var someData = [];

for (var i = 0; i < N; i++) {
  var currentDate = new Date();
  currentDate.setDate(currentDate.getDate() + i);
  someData.push({
    date: currentDate.toDateString(),
    value: Math.random(),
    group: currentDate.getMonth()
  });

}
...

The issue that I'm facing is, after changing currentdate it is not able to display the spiral chart.
I check that it is storing the data in the someData array but while creating "rect" there is a function used for "x" axis that is having some issue when it calling the timeScale(d.date) function.
I am not getting why this is happening.
Even though when I try to use another data in place of currentdate it is not displaying chart.
Kindly please help me on this.
Thanks
Amit Sah


text:
Q: Best way to share database connection param with mongoose/node.js I'm using Mongoose to manage a Mongo database. My connection file is quite simple:
var mongoose = require('mongoose')

mongoose.connection.on("open", function(){
  console.log("Connection opened to mongodb at %s", config.db.uri)
});
console.log("Connecting to %s", config.db.uri)
mongoose.connect(config.db.uri)

global.mongoose = mongoose

Then in my app.js I just
require('./database)

and the "mongoose" variable is available globally. I'd prefer not to use globals (at least not directly). Is there a better way of sharing the database connection variable across node (I'm using express.js) via a singleton pattern or some other method?

A: if you follow commonjs exports
exports.mongoose = mongoose

let us say your module name is connection.js
you can require
   var mongoose = require('connection.js')

you can use mongoose connection

A: I just do the following in my app.js file:
var mongoose = require('mongoose');
mongoose.connect('mongodb://address_to_host:port/db_name');
modelSchema = require('./models/yourmodelname').YourModelName;
mongoose.model('YourModelName', modelSchema);
// TODO: write the mongoose.model(...) command for any other models you have.

At this point any file that needs access to that model can do:
var mongoose = require('mongoose');
YourModelName = mongoose.model('YourModelName');

And finally in your model, you can have the file written normally then export it at the bottom:
module.exports.YourModelName = YourModelName;

I don't know if this the best most awesome solution (just started wrapping my head around exporting modules about 2 days ago) but it does work. Maybe someone can comment if this is a good way to do it.

A: I generally wrap my models like this
var MySchema = (function(){
//Other schema stuff

//Public methods
GetIdentifier = function() {
return Id;
};

GetSchema = function() {
return UserSchema;
};

return this;
})();

if (typeof module !== 'undefined' && module.exports) {
exports.Schema  = MySchema;
}

And in my main class, I do this var schema = require('./schema.js').Schema; and call conn.model(schema.GetIdentifier(), schema.GetSchema()) and of course after calling connect, or createConnection. This allows me to plugin schema in to standard set of methods. This generalization is good because you can concentrate on your schema after you have mastered connection and error handling. I also extend the schema with plugins, and that allows me to share plugins with other schemas.
I was looking to see if some body has done this better, but can't see to find a good pattern, and I am fairly new to Mongo.
I hope this helps.


text:
Q: How to display new data changes on the front end using Polymer 1.0? I am a complete noob at google Polymer. I am currently using Polymer 1.0. I am building a dashboard that actively displays the health status of servers. I have a function that grabs URLs from table X in a database, checks if they are responding, and then accordingly updates table X with "success" or "failure" for each of the URLs. I then have the table X rows show up as JSON text at a specific http URL. I used the iron-ajax element to access this URL and bind that JSON text to a polymer element. So when I go to my locally hosted website, I see a bunch of polymer element squares show up reading either success or failure. The problem is that I ping these URLs every 1 minute, but once the page is loaded, the polymer element squares showing the URL status do not change accordingly. So for example, lets say I go to my locally hosted website and it is showing that all of my URLs are responding. However, 2 minutes later, my scheduled function rechecks these URLs and updates table X in the database with a "failure" reading for one of the URLs. The polymer element on my locally hosted website won't refresh itself and display the failure status.
How do I make sure that any updates made to table X show up accordingly on the user interface. Is there a way to do this with Polymer?
Here is the piece of code I am working with:
<iron-ajax
            auto="true"
            url="http://localhost:1500"
            last-response="{{statusSquare}}"
            handle-as="json">
    </iron-ajax>

        <template is="dom-repeat" items="{{statusSquare}}">

{{item.appName}}

{{item.statusURLTxt}}

        </template>


text:
Q: Indexing ID after we created a new table with primary key ID Since the table will have primary key id, Microsoft SQL Server will automatically make it as the clustered index upon creation.
Does it mean that it's already optimized right from the start whenever we do queries like Select * from tableX where id = 1 ?


text:
Q: When should I use multiple texture units? When should I use multiple texture units via the glActiveTexture command (TEXTURE 0 and TEXTURE 1)?  From the examples I've seen multiple textures can be used on the texture unit TEXTURE0.

A: There is a difference between using multiple textures (draw object A with texture X, draw object B with texture Y) and multitexturing. Multitexturing means drawing object A with textures X and Y. The resulting color is based on various "texture environment" state (or shaders if you're using them); this state tells OpenGL how to combine the values from the two textures into one color.
If you're using fixed-function, then each texture has its own set of texture coordinates. The final color value computed is based on the colors fetched by those texture coordinates on their corresponding textures. These texture colors are fed through the texture environment, which is a sequence of operations applied to those colors that compute a final color.
If you're using shaders, then you can do pretty much whatever you want. Make up texture coordinates on the fly, use arbitrary operations to combine texture "colors", etc.
Texture units are for doing multitexturing.

A: You need multi-texturing for example when you use: normal mapping, parallax mapping, terrain texturing.
In detail for normal mapping you need the diffuse texture unit for the model, but also the normal map and you need to sample both textures, however you can't activate the same channel for both textures, you need to activate TEXTURE0 and TEXTURE1 and bind them to the respective id textures.
After you activate them and drew the model using those textures in the color buffer you can use them for other textures.
Think of them as flags to activate different textures channels on the GPU.


text:
Q: Vertical text on a Gnome2::Canvas (Perl/Gtk2) Drawing on a Gnome2::Canvas, I want to draw X and Y axes, with a horizontal label and a vertical label.
Gnome2::Canvas::Text objects allow Pango markup. A Pango tag like this should work, but doesn't.
...

Is there any way to overcome Gtk's reluctance to draw rotated text?
#!/usr/bin/perl
package vertical;

use strict;
use diagnostics;
use warnings;

use Gtk2 '-init';
use Gnome2::Canvas;

my $window = Gtk2::Window->new('toplevel');
$window->set_title('Hello world');
$window->set_position('center');
$window->set_default_size(500, 500);
$window->signal_connect('delete-event' => sub {

    Gtk2->main_quit();
    exit;
});

my $canvasFrame = Gtk2::Frame->new(undef);
$window->add($canvasFrame);
$canvasFrame->set_border_width(3);

my $canvasScroller = Gtk2::ScrolledWindow->new();
$canvasFrame->add($canvasScroller);
$canvasScroller->set_border_width(3);
$canvasScroller->set_policy('always','always');

my $canvas = Gnome2::Canvas->new();
$canvasScroller->add($canvas);
$canvas->set_scroll_region(0, 0, 400, 400);
$canvas->set_center_scroll_region(1);

# White background
my $canvasObj = Gnome2::Canvas::Item->new (
    $canvas->root(),
    'Gnome2::Canvas::Rect',
    x1 => 0,
    y1 => 0,
    x2 => 400,
    y2 => 400,
    fill_color => '#FFFFFF',
    outline_color => '#FFFFFF',
);
$canvasObj->lower_to_bottom();

# Black text
my $canvasObj2 = Gnome2::Canvas::Item->new(
    $canvas->root(),
    'Gnome2::Canvas::Text',
    x => 100,
    y => 300,
    fill_color => '#000000',
    font => 'Sans',
    size => 20000,
    anchor => 'GTK_ANCHOR_W',
    markup => "this is not vertical",
);
$canvasObj2->raise_to_top();

$window->show_all();

Gtk2->main();

A: I think the use of the gravity attribute in the Pango markup is not supported, at least I was not able to make it work.
However, instead of using Gnome2::Canvas, you could try using the rotate() function in Cairo::Context. Here is an example using Gtk3:
use strict;
use warnings;
use Gtk3 '-init';
use Glib qw/TRUE FALSE/;
use Cairo;
use Pango;

use constant PI     => 3.1415927;

my $window = Gtk3::Window->new('toplevel');
$window->set_title("Cairo Basics");
$window->set_position("mouse");
$window->set_default_size(600, 400);
$window->set_border_width(5);
$window->signal_connect (delete_event => sub { Gtk3->main_quit });

my $frame = Gtk3::Frame->new("Cairo Drawings");
$window->add($frame);
my $drawable = Gtk3::DrawingArea->new;
$drawable->signal_connect( draw => sub { cairo_draw($drawable, @_ ) });
$frame->add($drawable);
$window->show_all;
Gtk3->main;

sub cairo_draw {
    my ( $drawable, $widget, $context, $ref_status ) = @_;

    my $pango_layout = $drawable->create_pango_layout("");
    $pango_layout->set_markup(
        ""
        . "This is vertical"
    );
    my $pango_context = $pango_layout->get_context();
    $context->move_to(200, 100);
    $context->rotate(PI*(90/180));
    Pango::Cairo::show_layout( $context, $pango_layout );
    return FALSE;
}

Alternatively, you can skip the Pango markup altogether and only use Cairo:
sub cairo_draw {
    my ( $drawable, $widget, $context, $ref_status ) = @_;

    $context->set_source_rgba(1, 0.4, 0.4, 1);
    $context->select_font_face( "Sans", "normal", "bold" );
    $context->set_font_size( 35 );
    $context->move_to(220, 50);
    $context->rotate(PI*(90/180));
    $context->show_text( "This is vertical");
    return FALSE;
}


text:
Q: Symbolic inverse of a linear combination of two matrices This question is very much related to Inverse of the sum of matrices .
Let $d\ge 1$ be an integer and let $a\in(-1,1)$ and $b\in(-1,1)$ be real numbers.
Let ${\bf C}:=\left( f(|i-j|) \right)_{i,j=1}^{d+1}$ be a symmetric positive definite matrix for dimension $(d+1)$ and finally let ${\bf U}:= \left( b^{l-1} a^{k-l-1} 1_{l\ge 1} 1_{k \ge l+1}\right)_{l,k=0}^d$. It appears that the matrix ${\bf U}$ has a rank equal to $(d-1)$.
The problem is now to find:
\begin{equation}
\tilde{{\bf C}}(k):=\left( {\bf C}^{-1} + k \cdot {\bf U} \right)^{-1} = ?
\end{equation}
Ideally we would like to find the function above symbolically as a function of the parameter $k$.
Now, by using the invertible matrix theorem we have shown that:
\begin{eqnarray}
\lim_{k\rightarrow \infty} \tilde{{\bf C}}(k) =
\left(
\begin{array}{ccccc}
f(0) +\kappa_{1,1} & 0 & \cdots & 0 & f(d) + \kappa_{1,d+1} \\
f(1) +\kappa_{2,1} & 0 & \cdots & 0 & f(d-1) + \kappa_{2,d+1}\\
0 & 0 & \cdots & 0 & 0\\
\vdots \\
0 & 0 & \cdots & 0 & 0
\end{array}
\right)_{(d+1)\times (d+1)}
\end{eqnarray}
where
\begin{eqnarray}
\kappa_{1,1} &=& \frac{1}{{\mathfrak D}} \cdot \sum\limits_{j=0}^{d-2}(-1)^{j+1} f(j+2) \cdot \mbox{det} \left( f(|k-l-1+1_{k\ge 1}+1_{k\ge j+1}|) \right)_{k,l=0}^{d-2}\\
\kappa_{1,d+1} &=& \frac{1}{{\mathfrak D}} \cdot \sum\limits_{j=0}^{d-2}(-1)^{j+1} f(d-2-j) \cdot \mbox{det} \left( f(|k-l-1+1_{k\ge 1}+1_{k\ge j+1}|) \right)_{k,l=0}^{d-2}\\
\kappa_{2,1} &=& \frac{1}{{\mathfrak D}} \cdot \sum\limits_{j=0}^{d-2}(-1)^{j+1} f(j+2) \cdot \mbox{det} \left( f(|k-l+1_{k\ge j+1}|) \right)_{k,l=0}^{d-2}\\
\kappa_{2,d+1} &=& \frac{1}{{\mathfrak D}} \cdot \sum\limits_{j=0}^{d-2}(-1)^{j+1} f(d-2-j) \cdot \mbox{det} \left( f(|k-l+1_{k\ge j+1}|) \right)_{k,l=0}^{d-2}
\end{eqnarray}
and
\begin{equation}
{\mathfrak D}:= \mbox{det} \left( f(|i-j+1|)\right)_{i,j=1}^{d-2}
\end{equation}
Note 1: Our result is consistent with the Woodbury matrix theorem https://en.wikipedia.org/wiki/Woodbury_matrix_identity. Indeed our inverse is a sum of the original matrix ${\bf C}$ and a rank-$(d-1)$ correction to it (at least in the limit $k\rightarrow \infty$) as the theorem states.
Now, it is plausible that finding our function ${\tilde{\bf C}}(k)$ in full symbolic form is a very hard task and in fact is not really necessary because we can always use the theorem in question to compute our function numerically. Yet the temptation is strong to find at least the $1/k$-corrections to the large-$k$ behavior stated above.
How can we do that?

A: In the following we replace $d+1$ by $d$ without loss of generality.
Since the matrix $C$ is invertible we can write:
\begin{equation}
\left( C^{-1}+ k \cdot U \right)^{-1}= \left(C^{-1} \cdot (1+k \cdot C\cdot  U) \right)^{-1} = \left(1+k \cdot C \cdot U\right)^{-1} \cdot C
\end{equation}
The Cayley-Hamilton theorem for matrix $A:=C \cdot U$ reads:
\begin{equation}
\sum\limits_{l=0}^d {\mathcal a}_{d-l} (-1)^l A^l = 0
\end{equation}
Using this theorem it is not hard to see that :
\begin{equation}
\left(1+k \cdot C \cdot U\right)^{-1} = \sum\limits_{l=0}^{d-1} {\bf O}(k)_{d,d-l} \cdot [C\cdot U]^l
\end{equation}
where
\begin{eqnarray}
[{\bf O}(k)]^{-1} = {\mathbb 1}_{d\times d} + k \cdot \left( \begin{array}{rrrr} {\mathcal a}_1 & -{\mathcal a}_2 & {\mathcal a}_3 & \cdots & (-1)^{d-2} {\mathcal a}_{d-1} &(-1)^{d-1} {\mathcal a}_d \\ 1& 0 & 0 & \cdots & 0 & 0\\0 & 1 & 0 & \cdots & 0 & 0\\ 0 & 0 & 1 & \cdots & 0 & 0\\
\vdots & \vdots & \vdots & \cdots & \vdots & \vdots \\ 0 & 0 & 0 & \cdots &1 & 0\end{array}\right)_{d\times d}
\end{eqnarray}
and the coefficients $\left( {\mathcal a}_l \right)_{l=1}^d$ are the rotational invariants of the matrix $A$, i.e:
\begin{eqnarray}
{\mathcal a}_1 &:=& Tr(A) \\
{\mathcal a}_2 &:=& \frac{1}{2} \left( Tr(A)^2 - Tr(A^2) \right) \\
{\mathcal a}_3 &:=& \frac{1}{6} \left( Tr(A)^3 - 3Tr(A^2)Tr(A)+2 Tr(A^3) \right) \\
{\mathcal a}_4 &:=& \frac{1}{4!} \left( Tr(A)^4 - 6 Tr(A)^2 Tr(A^2) + 8 Tr(A) Tr(A^3) + 3 Tr(A^2)^2-6 Tr(A^4)\right) \\
\vdots\\
{\mathcal a}_{d} &=& \det(A)
\end{eqnarray}
It is not hard to see that the matrix ${\bf O}(k)$ can be found in closed form. One way to do it is to fix $d$, generate that matrix in Mathematica, then symbolically invert and see the pattern. Then the final result is the following:
\begin{eqnarray}
\left(1+k \cdot C \cdot U\right)^{-1} = \sum\limits_{l=0}^{d-1} (-1)^l
\left(
\frac{\sum\limits_{j=0}^{d-l-1} {\mathcal a}_j k^{l+j}}
{ \sum\limits_{j=0}^d {\mathcal a}_j k^j} \right) \cdot [C\cdot U]^l
\end{eqnarray}
subject to ${\mathcal a}_0=1$.
So far this result is quite general. Now in our case it appears that the matrix $A$ is singular,i.e. both ${\mathcal a}_d = {\mathcal a}_{d-1}=0$.
We take this into account and we calculate the large-$k$ limit of our matrix inverse:
\begin{eqnarray}
\left(C^{-1}+ k \cdot U \right)^{-1} &=&
k \sum\limits_{l=0}^{d-1} (-1)^l \frac{a_{d-1-l} k^{d-2} + a_{d-l-2}k^{d-3} 1_{l\le d-2} + O(k^{d-4})}{a_{d-2} k^{d-2} + a_{d-3} k^{d-3} + O(k^{d-4})} \cdot [C.U]^l \cdot C \\
&=&
k \sum\limits_{l=0}^{d-1} (-1)^l \left( \frac{a_{d-l-1}}{a_{d-2}} + \frac{a_{d-l-2} a_{d-2} - a_{d-l-1} a_{d-3}}{a_{d-2}} \cdot \frac{1}{a_{d-3}+a_{d-2} k} + O(\frac{1}{k^2})\right) \cdot [C.U]^l \cdot C \\
& \underset{k\rightarrow \infty}{\rightarrow} & \frac{1}{a_{d-2}} \sum\limits_{l=0}^{d-2} (-1)^l a_{d-l-2} \cdot [C.U]^l\cdot C
\end{eqnarray}
where in the last line we used the fact that $\sum\limits_{l=0}^{d-1} (-1)^l a_{d-l-1} \cdot A^l = 0 $.
Now we have checked numerically that the limit above is exactly equal to the limit stated in the formulation of the question.


text:
Q: How do i get data from records in C# MVC I have this code to get the list of record from database, in the list of iDConfig there are some columns i wants to get and put it in model to display as table in the view how do i loop through the list and get the wanted columns?
public ActionResult iDeal_Table_Display(Guid? SA=null)
{
    var iDConfig = blergo.Get_iDealConfigs(SA, out retStatus, out errorMsg);
    ViewBag.iDconfigs = iDConfig;
    return PartialView();
}

this are the column in each row

the following image is the database columns that i want in iDConfig

using model below
public class iDealModel
{
    [Required]
    [DisplayName("Product")]
    public Guid ProductId { get; set; }

    [Required]
    [DisplayName("Request Type")]
    public Guid RequestTypeId { get; set; }

    [Required]
    [DisplayName("Sales Agreement Prefix")]
    public Guid SaPrefix { get; set; }

    [DisplayName("Calendar Code")]
    public System.Nullable<System.Guid> CalendarCode { get; set; }

    [DisplayName("Cash & Carry")]
    public bool CashnCarry { get; set; }

    [DisplayName("Free MM")]
    public bool FreeMM { get; set; }

    [DisplayName("On Contract")]
    public bool OnContract { get; set; }
}

A: You can do:
var product = iDConfig[0].Product

Or something like:
foreach(var ic in iDConfig)
{
    //get data like
    var product = ic.Product;

In your view you can do something like:

@foreach(var ic in iDConfig)
{

@ic.Product

}

A: Use LINQ to map your DB entity to your model, like this:
var model = iDConfig.Select(ic => new iDealModel {
        SaPrefix = ic.PrefixSA,
        CalendarCode = ic.CodeCalendar,
        CashnCarry = ic.isCashnCarry,
        FreeMM = ic.isFreeMM,
        OnContract = ic.isOnContract,
        ProductId = ic.Product,
        RequestTypeId = ic.RequestType
    });


text:
Q: How to project a vector $x$ onto the eigen-space, i.e. $x = \sum_{i=1}^{n} \langle w_i, x \rangle v_i$? Assume $A$ is a complex-valued square matrix, i.e. $A\in \mathbb{C}^{n\times n}$, and $A$ has a full set of eigenvectors denoted as $V=[v_1, v_2, \cdots, v_n]$. Then we known the following facts
\begin{align}
Av_i &= \lambda_i v_i,\cr
[w_1, w_2, \cdots, w_n] &= [v_1, v_2, \cdots, v_n]^{-*}, \cr
A^*w_i &= \bar\lambda_i w_i,\cr
w_i^*v_j &= 1, ~\text{if}~ i=j;~ \text{otherwise}~~ w_i^*v_j = 0,
\end{align}
where the superscript $*$ denotes the conjugate transpose of a matrix.
My question is given a vector $x\in \mathbb{C}^n$, how to prove the reality below
\begin{align}
x = \sum_{i=1}^{n} \langle w_i, x \rangle v_i,
\end{align}
where $\langle \cdot, \cdot \rangle$ denotes the inner product between two complex-valued vectors?

A: Since $V$ is a basis, we may expand $x$ as
$$
x = \sum_{i = 1}^n a_i v_i
$$
Then
\begin{align}
w_j^* x &= w_j^* \left(\sum_{i = 1}^n a_i v_i \right)
\\&= \sum_{i =1}^n w_j^* (a_i v_i)
\\&= \sum_{i = 1}^n a_i (w_j^* v_i)
\\&= a_j (w_j^* v_j) + \sum_{i = 1, i \neq j}^n a_i (w_j^* v_i)
\\&= a_j \cdot (1) \sum_{i = 1, i \neq j}^n a_i \cdot (0)
\\&= a_j + \sum_{i = 1, i \neq j}^n 0
\\&= a_j
\end{align}
Hence $w_j^* x = a_j$. This holds for all $j \in \{1, \ldots, n\}$. Therefore, we may substitute into our expansion of $x$ in $V$ to obtain
$$
x = \sum_{i = 1}^n (w_i^* x) v_i
$$
Since $w_i^* x = \langle w_i , x \rangle$, we finally find
$$
x = \sum_{i = 1}^n \langle w_i , x \rangle v_i
$$
as desired.
It is worth noting that we never used the fact that the $w_i$ or the $v_i$ are eigenvectors. All we really needed was that $V$ is a basis and that $w_i^* v_j = 1$ if $i = j$ and is $0$ otherwise.


text:
Q: Why ViewPager get wrong position in android? I tried to find an answer everywhere but I have found none.
Explanation: I have a Viewpager in my fragment. I called an adapter into my fragment and set it into ViewPager. My ViewPager is dynamic according to the JSONArray data.I have a jsonArray which has five objects. I added every object into List and passed it to the adapter. So, my viewpager is created according to list.size(), but the problem is when my HomeFragment.java has loaded. The adapter is called twice (not sure) but log shows it is called twice.
Here is my Homefragment.java
private class TabJson extends AsyncTask<String,String,String> {

    String jsonStr="";

    private static final String url="http://10.0.2.2/JSON/recentmatch.php";
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params) {

        ServiceHandler sh=new ServiceHandler();
        jsonStr=sh.makeServiceCall(url,ServiceHandler.POST);
        try{
            JSONObject obj=new JSONObject(jsonStr);
            JSONObject data=obj.getJSONObject("data");
            JSONArray card=data.getJSONArray("cards");

            PagerLength=0;
            lst_obj=new ArrayList<>();
            for(int i=0;i<card.length();i++){
                JSONObject card_obj=card.getJSONObject(i);

                if(card_obj.getString("status").equals("started") || card_obj.getString("status").equals("notstarted")){
                    PagerLength++;
                    lst_obj.add(card_obj);
                }
            }
        }
        catch (JSONException e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        LiveAdapter adapterTabRecent=new LiveAdapter(getContext(),lst_obj);
        pagerRecentMatches.setAdapter(adapterTabRecent);
        pagerRecentMatches.setCurrentItem(0);

        float scaledDensity = getResources().getDisplayMetrics().scaledDensity;
        LinearLayout.LayoutParams param1=new LinearLayout.LayoutParams(10*(int)scaledDensity,10*(int)scaledDensity);
//        for(int i=0;i<PagerLength-1;i++){
//            ImageView img=new ImageView(getContext());
//            TextView space=new TextView(getContext());
//            img.setId(R.id.selected_id);
//            img.setLayoutParams(param1);
//            img.setImageResource(R.drawable.unselect);
//            space.setText(" ");
//            selector_dynamic.addView(img);
//        }
    }
}

Above is the code where I got the data from a JSON and where I set it to my adapter.
Here is my LiveAdapter.java
public class LiveAdapter extends PagerAdapter{

    private Context context;
    List<JSONObject> lst;
    JSONObject mainObj=null;
    View itemView;
    private LayoutInflater inflater;
    String status="";
    public LiveAdapter(Context context,List<JSONObject> lst){
        this.context=context;
        this.lst=lst;
        inflater=(LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    @Override
    public int getCount() {
        return lst.size();
    }

    @Override
    public int getItemPosition(Object object) {
        int index=lst.indexOf((List)object);

        if(lst.contains((List)object)){
            return index;
        }
        else{
            return POSITION_NONE;
        }
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view==((LinearLayout)object);
    }

    private class Holder{
        TextView txt_one_country_name;
        TextView txt_two_country_name;
        TextView txt_venue;
        TextView match;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        itemView=inflater.inflate(R.layout.tab_slider,container,false);
        Holder holder=new Holder();
        String[] parts;
        String[] state_parts;
        String[] match_parts;

        Log.e("POSITION",""+position);
        mainObj=this.lst.get(position);

        holder.txt_one_country_name=(TextView)itemView.findViewById(R.id.txt_one_country_name);
        holder.txt_two_country_name=(TextView)itemView.findViewById(R.id.txt_two_country_name);
        holder.txt_venue=(TextView)itemView.findViewById(R.id.venue);
        holder.match=(TextView)itemView.findViewById(R.id.match);

        try {

            status=mainObj.getString("status");
            Log.e("POSITION INSIDE TRY",""+position);
            Log.e("Status-->>>",""+status);
            String name = mainObj.getString("name");
            String state=mainObj.getString("venue");
            String title=mainObj.getString("title");

            parts=name.split("vs");
            match_parts=title.split("-");
            state_parts=state.split(",");

            holder.txt_one_country_name.setText(parts[0]);
            holder.txt_two_country_name.setText(parts[1]);
            holder.txt_venue.setText(state_parts[1]);
            holder.match.setText(match_parts[1]);
        }
        catch (JSONException e){
            e.printStackTrace();
        }
        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(status.equals("notstarted")) {
                    Log.e("STATUS INSIDE ONCLICK",""+status);
                    Intent intent = new Intent(context, NotStartedMatchDetails.class);
                    context.startActivity(intent);
                }

            }
        });
        container.addView(itemView);
        return itemView;
    }

    @Override
    public void setPrimaryItem(ViewGroup container, int position, Object object) {
//        super.setPrimaryItem(container, position, object);
        itemView=(View)object;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((LinearLayout)object);
    }
}

I set the log in instantiateItem().
When I run the application position set to me by default as 0 and 1.
Here, is my position value
01-18 15:47:02.295 31593-31593/com.example.myworld.materialdesign E/POSITION: 0
01-18 15:47:02.295 31593-31593/com.example.myworld.materialdesign E/POSITION INSIDE TRY: 0
01-18 15:47:02.295 31593-31593/com.example.myworld.materialdesign E/Status-->>>: notstarted
01-18 15:47:02.306 31593-31593/com.example.myworld.materialdesign E/POSITION: 1
01-18 15:47:02.306 31593-31593/com.example.myworld.materialdesign E/POSITION INSIDE TRY: 1
01-18 15:47:02.306 31593-31593/com.example.myworld.materialdesign E/Status-->>>: started

The problem is when I swipe right to left, the position value mentioned below:
I have five tabs dynamically created it' value is
2,3,4 that's it. where is 0 and 1?
but when I swipe left to right, the position value mentioned below:
2,1,0 that's it where is 3 and 4?
Please, help me to overcome this problem.

A: do this
when you instantiate the object
@Override
public Object instantiateItem(ViewGroup container, int position) {
.....
itemView.setTag(position);
.....

}
//now on click of the item view you can get it back as follows
itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int position = (int) v.getTag();// v here is your itemView
}


text:
Q: How to get to terminal? I am a novice, using Ubuntu 14,04.  I have tried to install Skype, and it does not work.  I need it installed, but I read all the suggestions, and they all refer to using some sudo commands in  what I believe is a DOS-like command prompt menu - and I cannot find anywhere to access that?
I am sure this is a trivial question thousands have asked before, so a simple direction to where this is explained would suffice for me as help.
I also realize that I need to know  what "distribution" my Ubuntu is, and if is 32 or 64 bit - where do I find that information?
Thank you in advance.

A: To open the DOS-like terminal, press Ctrl+Alt+T all together on your keyboard to open the terminal.
From the terminal prompt to find out what your distribution is, type in the following:
cat /etc/*release

it will produce text looking like this:
terrance@terrance-ubuntu:~$ cat /etc/*release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=14.04
DISTRIB_CODENAME=trusty
DISTRIB_DESCRIPTION="Ubuntu 14.04.3 LTS"
NAME="Ubuntu"
VERSION="14.04.3 LTS, Trusty Tahr"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 14.04.3 LTS"
VERSION_ID="14.04"
HOME_URL="http://www.ubuntu.com/"
SUPPORT_URL="http://help.ubuntu.com/"
BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/"

To find out if it is 32bit or 64bit, type in:
getconf LONG_BIT

Example:
terrance@terrance-ubuntu:~$ getconf LONG_BIT
64

Then to install Skype, type in the following:
sudo apt-get install skype

When sudo is used in front of the command, it is running at an elevated permission level, so it will ask for your password to continue to install the application.
To add a Desktop icon of skype, type in the following to copy one to your desktop, then make it executable.
cp /usr/share/applications/skype.desktop ~/Desktop/
chmod +x ~/Desktop/skype.desktop

Hope this helps!


text:
Q: Memcache Unknown error (0) I'm randomly getting a flood of Memcache errors in my log file that look like this:

PHP Warning:  Memcache::pconnect(): Can't connect to 127.0.0.1:11211, Unknown error (0)
  PHP Warning:  Memcache::close(): No servers added to memcache connection

After the flood, everything seems fine. I can telnet to the server.
memcached start up settings are -m 200 and -c 4096.
Here is a sample 'stats':

statsSTAT pid 7431STAT uptime 507682STAT time
  1396973622STAT version 1.4.15STAT libevent
  1.4.13-stableSTAT pointer_size 64STAT rusage_user 914.539968STAT rusage_system 2714.912270STAT curr_connections 6STAT total_connections 1000139STAT connection_structures
  757STAT reserved_fds 20STAT cmd_get 98098231STAT cmd_set
  606357STAT cmd_flush 0STAT cmd_touch 0STAT get_hits
  97491874STAT get_misses 606357STAT delete_misses 185STAT
  delete_hits 109STAT incr_misses 0STAT incr_hits 0STAT
  decr_misses 0STAT decr_hits 0STAT cas_misses 0STAT
  cas_hits 0STAT cas_badval 0STAT touch_hits 0STAT
  touch_misses 0STAT auth_cmds 0STAT auth_errors 0STAT
  bytes_read 6509263367STAT bytes_written 8760129521STAT
  limit_maxbytes 209715200STAT accepting_conns 1STAT
  listen_disabled_num 0STAT threads 4STAT conn_yields 0STAT
  hash_power_level 16STAT hash_bytes 524288STAT
  hash_is_expanding 0STAT bytes 1942744STAT curr_items
  16104STAT total_items 519747STAT expired_unfetched
  5154STAT evicted_unfetched 0STAT evictions 0STAT reclaimed
  290295END


text:
Q: SharePoint New and Edit Form Javascript Date Time Field I have a custom list that contains a date time field. The client requested we trim the time portion of the field to only show two available appointment times of 8:30 am and 1:30 pm. In order to do this I added the following javascript code to the New and Edit forms of the list. The problem I am having is when the users open the edit form it does not maintain the previously selected time value. It shows the first available value of 8:30 AM, so if the users open the edit form and change some other field than the time field they inadvertently change the originally selected time field to 8:30 am even if the originally selected time was 1:30PM. How can I get the code to default to the originally selected time value from the New form within Edit form?
<script type="text/javascript">
    $(document).ready(function () {
        var str=['8 AM','1 PM'];
        $("select[id$='_DateTimeField_DateTimeFieldDateHours']").each(function(i){
            $(this).html("");
            for(var i=0;str[i]!=null;i++){
                $(this).append('<OPTION value="'+str[i]+'">'+str[i]+'</OPTION>');
            }
        });
    });
</script>

<script src="http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>

<script type="text/javascript">
    $(document).ready(function () {
        var str=['30'];
        $("select[id$='_DateTimeField_DateTimeFieldDateMinutes']").each(function(i){
            $(this).html("");
            for(var i=0;str[i]!=null;i++){
                $(this).append('<OPTION value="'+str[i]+'">'+str[i]+'</OPTION>');
            }
        });
    });
</script>

A: Simply check if the input field contains a value:
$(document).ready(function () {
    var hours=['8 AM','1 PM'],
        minutes = ['30']; //don't see the point in putting a single value in an array, but I suppose if you decide to add more options later
    $("select[id$='_DateTimeField_DateTimeFieldDateHours']").each(function(){
        if ($(this).val()) return 1; //Returning non-false is the same as a continue statement in a for loop
        $(this).empty();
        for(var i=0, hour; hour = hours[i]; i++) {
            $(this).append('<OPTION value="'+ hour +'">'+ hour +'</OPTION>');
        }
    });
    $("select[id$='_DateTimeField_DateTimeFieldDateMinutes']").each(function(){
        if ($(this).val()) return 1;
        $(this).empty();
        for(var i=0, minute; minute = minutes[i]; i++){
            $(this).append('<OPTION value="'+ minute +'">'+ minute +'</OPTION>');
        }
    });
});

A: You need to save the value before killing the contents of the drop down field with $(this).html("");, you need to save the selected value, if there is any:
var selectedHour = $(this).find("option:selected").text();

// .text() could fail
If it is set and it matches the appointment time in your loop, i would just call this:
$(this).append('<OPTION value="'+ hour +'" selected="selected">'+ hour +'</OPTION>');

Or attach the attribute in some better way.
Instead of calling $(this).html("") you can also call $(this).empty(), I believe.


text:
Q: Mouse wheel event alternative for moblie I have a container has overflow to x axis, i'm doing the scroll event using js
this is scroll code
const scrollContainer = document.querySelector('.horizontal-scroll');

scrollContainer.addEventListener('wheel', (e) => {
    e.preventDefault();
    scrollContainer.scrollLeft += e.deltaY;
});

And for mobiles the x scroll stops at 992px, so the problem i faced it's in mobile devices that has screen larger then 992px,
It doesn't have scroll wheel to scroll left, and the vertical scroll is closed cause its larger then mobile.
I tried touchmove event but it doesn't have deltaY property

A: I'v found an answer on a similar question which is Detect scrolling after scrolling distance from current position in browser and there was useful answer i'v used
So the code i wrote to fix my problem was
let touchstartX = 0
let touchendX = 0

scrollContainer.addEventListener('touchstart', e => {
    touchstartX = e.changedTouches[0].screenX;
})

scrollContainer.addEventListener('touchend', e => {
    touchendX = e.changedTouches[0].screenX;
    scrollContainer.scrollLeft += touchstartX - touchendX;
})


text:
Q: When did mathematicians think of axiomatically building or defining operations etc? Edited question: In response to  Qiaochu Yuan's comment asking me to narrow down the question,the edited question is as follows: When did mathematicians first think of axiomatically building set theory with the level of rigour seen nowadays?(I am asking this because I learnt of the Peano's axioms and was amazed at how little needs to be assumed to build the number system)
Original question: I am interested to know when and under what circumstances mathematicians first thought of axiomatically building the number system and defining binary operations like addition and subtraction or for that matter the theory of sets ?


text:
Q: Limit $\lim\limits_{x\to0}{\frac{\ln{(e+x)}-e^x}{\cos^2{x} -e^x}}$ Without using L'Hopital's rule find:
$$\lim_{x\rightarrow 0}{\frac{\ln{(e+x)}-e^x}{\cos^2{x} -e^x}}$$
I found the first derivative because I planned to use Taylor series:
\begin{align}
\frac{d}{dx}{\left(\frac{\ln{(e+x)}-e^x}{\cos^2{x} -e^x}\right)}
&=\frac{\left(\frac{1}{x+e}-e^x\right)\left(\cos^2{x} -e^x\right)-\left(\ln(x+e)-e^x\right)\left(\sin{2x}-e^x\right)}
{(\cos^2{x} -e^x)^2}\\
&=\frac{\frac{1}{x+e}-e^x}{\cos^2{x}-e^x}-\frac{\left(\ln(x+e)-e^x\right)\left(\sin{2x}-e^x\right)}{(\cos^2{x} -e^x)^2}
\end{align}
However, it seems I haven't gone so far. Should I start from the beginning and try a different method?
Source in Croatian: 2.kolokvij, matematička analiza

A: We have that
$$\frac{\ln{(e+x)}-e^x}x=\frac{\ln{(e+x)}-1}x-\frac{e^x-1}x \to\frac1e-1$$
$$\frac{\cos^2{x} -e^x}x=\frac{\cos^2 x-1}{x}-\frac{e^x-1}x=$$
$$=x(\cos x+1)\frac{\cos x-1}{x^2}-\frac{e^x-1}x \to 0\cdot 2\cdot \left(-\frac12\right)-1=-1$$
then
$$\frac{\ln{(e+x)}-e^x}{\cos^2{x} -e^x}=\frac{\ln{(e+x)}-e^x}{x}\cdot\frac{x}{\cos^2{x} -e^x}$$

A: Hint: show that $\frac {\ln (e+x)-e^{x}} x \to e^{-1}-1$ and $\frac {cos^{2}x -e^{x}} x \to -1$. Hence the limit is $(1-e^{-1})$.

A: If you want the Taylor series, work separately numerator and denominator
$$\log (x+e)-e^x=\left(\frac{1}{e}-1\right) x-\frac{\left(1+e^2\right) }{2 e^2}x^2+\left(\frac{1}{3
   e^3}-\frac{1}{6}\right) x^3+O\left(x^4\right)$$
$$\cos ^2(x)-e^x=-x-\frac{3 }{2}x^2-\frac{1}{6}x^3+O\left(x^4\right)$$
$$\frac{\log (x+e)-e^x } { \cos ^2(x)-e^x}=\frac{\left(\frac{1}{e}-1\right) x-\frac{\left(1+e^2\right) }{2 e^2}x^2+\left(\frac{1}{3
   e^3}-\frac{1}{6}\right) x^3+O\left(x^4\right) } {-x-\frac{3 }{2}x^2-\frac{1}{6}x^3+O\left(x^4\right)}$$
Now, use the long division to get
$$\frac{\log (x+e)-e^x } { \cos ^2(x)-e^x}=\frac{e-1}{e}+\frac{1}{2} \left(-2+\frac{1}{e^2}+\frac{3}{e}\right) x+O\left(x^2\right)$$ which shows the limit and also how it is approached.

A: I suggest using Taylor after some simplification:
\begin{eqnarray*}\frac{\ln{(e+x)}-e^x}{\cos^2{x} -e^x}
& = & \frac{1+\ln(1+\frac{x}{e}) - e^x}{\frac 12(1+\cos 2x)-e^x} \\
& = & \frac{1+\frac{x}{e}+o(x) - (1+x + o(x))}{\frac 12(1+ 1 +o(x))-(1+x+o(x))} \\
& = & \frac{\frac 1e -1 +o(1)}{-1+o(1)}\\
& \stackrel{x\to 0}{\longrightarrow}& 1-\frac 1e
\end{eqnarray*}


text:
Q: Cannot send SMTP email from windows service on Win7 I am writing a Windows service using c# .NET 4.0 (my development workstation is Windows 7).
The aim is to send an email from the service directly in case of errors during processing.
I've included a code snippet to show what i am trying to achieve:
try
        {
                string emailAddresses = "me@sample.com";
                string emailCCAddresses = "you@sample.com";

                //Send the email
                using (MailMessage mailMsg = new MailMessage())
                {
                    mailMsg.To.Add(emailAddresses);
                    mailMsg.From = new MailAddress("winService@sample.com");
                    mailMsg.CC.Add(emailCCAddresses);
                    mailMsg.Subject = " Error Message ";
                    mailMsg.Body = DateTime.Now + " : Invalid File Encountered." ;

                    ////Creating the file attachment
                    using (Attachment data = new Attachment("C:\\users\\sample.xml", MediaTypeNames.Application.Octet))
                    {
                        //Add timestamp info for the file
                        ContentDisposition disposition = data.ContentDisposition;
                        disposition.ModificationDate = File.GetLastWriteTime("C:\\users\\sample.xml");
                        mailMsg.Attachments.Add(data);

                    SmtpClient emailClient = new SmtpClient("example.Sample.com", 25);
                    emailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                    emailClient.UseDefaultCredentials = true;
                    emailClient.Send(mailMsg);
                    }
                }//end using

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

The issue i am facing is - the email option does not work from a win service on any windows 7 machine. However the exact same code will work on a Win XP machine perfectly fine. Caveat, this cannot be tested as a console app. It needs to be run as a service to see the behavior. I put the same code in a console application and it worked fine on my win 7 machine.
Additionally, i enabled the telnet client and server windows features and was able to send email via the command prompt successfully.
I tried a few things to try and isolate the cause (none worked) -

*

*Setting the NetworkCredential explicitly and setting UseDefaultCredentials = false.
emailClient.Credentials = new System.Net.NetworkCredential("username","pwd","Domain1");

*changing the Log On As option of the service to be my userid and pwd

*The From and To email addresses are authentic, not dummy addresses(in my real code that is!)

The only differences i can find is that the windows service is installed under the local system account. But changing the log on as should have caused it to use my authentication details/the credentials specified in the code. The IT guy in my office said the only difference he saw was that my message was sent as a relay(not sure what this means as the from/to and log on as accounts when updated to my login did not change the outcome)
the exception i see being caught is :

SMTP Exception thrown : System.Net.Mail.SmtpException: Failure sending mail. ---> System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: An attempt was made to access a socket in a way forbidden by its access permissions XXX.XXX.XXX.XXX XX
     at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
     at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)

Any ideas are appreciated!
I feel it has to do with a windows 7 security policy/feature and hopefully might be as simple as changing a default setting.

A: You can run service as current user. Just select option USER in service installer and it will work as current user. I got the same error today and I found this solution. I hope it will be helpful for anybody.

A: I found it was the security policy on our new work laptops and the IT department refused to let us change it. Our test server doesn't have the same issue , of ourse it's not windows 7 either so I can't be 100% sure. Try sending email via command line to see if smtp is allowed from your pc.
The same code worked fine whn run on a win xp or windows server machine which didn't hav any restrictions


text:
Q: Is there any way to make my javascript time wont reset when the user refreshes the browser Here is my code. Is there any way to make my javascript time wont reset when the user refreshes the browser ?

function startTimer(duration, display) {
        var timer = duration,
            minutes, seconds;
        setInterval(function() {
            minutes = parseInt(timer / 60, 10);
            seconds = parseInt(timer % 60, 10);

            minutes = minutes < 10 ? "0" + minutes : minutes;
            seconds = seconds < 10 ? "0" + seconds : seconds;

            display.textContent = minutes + ":" + seconds;

            if (--timer < 0) {

                document.getElementById("testik4").submit();
            }
        }, 1000);
    }

    window.onload = function() {
        var fiveMinutes = 60 * 18,
            display = document.querySelector('#time');
        startTimer(fiveMinutes, display);
    };

A: Here is a simple working example which uses cookies to keep the timer value on client browser. Please read the comments to understand the code better.
Because StackOverflow does not allow usage of cookies in Code Snippets, I wrote a code sample instead of a snippet. Copy-paste it on your web page and test it.
Feel free to ask in comments if anything is unclear. Someone also suggested to use LocalStorage. That's an option too, the main difference between Cookies and LocalStorage in this case would be that cookies can be read by server too.
// Copied from https://www.w3schools.com/js/js_cookies.asp
function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

window.addEventListener('DOMContentLoaded', function() {

    let timer = 60 * 18, // default value
        display = document.querySelector('#time'),
        // set cookie name and read its value
        // empty string means is not set
        cname = 'my_timer',
        cvalue = getCookie(cname);

    // If there is something in cookie, overwrite default value
    if (cvalue != '') {
        timer = parseInt(cvalue);
    }

    setInterval(function() {

        let minutes = parseInt(timer / 60, 10),
            seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.textContent = minutes + ":" + seconds;

        // Update cookie value
        document.cookie = cname + '=' + timer;

        if (--timer < 0) {
            document.getElementById("testik4").submit();
        }
    }, 1000);
});

A: you can use session/local storage or cookies.If you set session/local storage or cookies then not reset time.


text:
Q: Is it possible to add a custom channel on an image? I am trying to make a custom image format, that has custom channels. Essentially I am trying to store some metadata for each pixel but on the same image. I know each pixel has 4 channela, a,r,g,b. I was wondering if its possible to do something like a,r,g,b,z, where z is some new number I can set and get.
Anyone know?
Thanks

A: Most programs, i.e. Photoshop, GIMP, ImageMagick and the OSX Finder will ignore extraneous data at the end of JPEG, PNG or GIF images, so you could potentially add one or more extra channels of data to the end of such files - WITH THE PROVISO that you don't let them write the files when they will promptly lose all your appended data.
So, bearing that in mind you could generate an extra channel/band of data with ImageMagick and append it to the end of the normal RGBA image. So, let's create a red-yellow gradient as a conventional PNG image. You could equally use a JPEG or TIFF.
convert -size 256x256 gradient:red-yellow.png

and that is 935 bytes on my machine.
Now create a checkerboard pattern the same size and a single channel, i.e. grayscale to simulate your "extra channel", and append it to the end of the PNG file:
convert -size 256x256 pattern:checkerboard -depth 8 gray:- >> image.png

Now the PNG file is 66,471 bytes but still viewable. So, to extract your extra channel, we need to determine that the greyscale image is 256x256 bytes, i.e. 65,536 bytes and subtract that from 66,471 to get 935 bytes which is the offset to our binary checkerboard. We can now read it in like this and make it into a PNG or JPEG:
convert -size 256x256+935 -depth 8 gray:image.png checkerboard.png

and you get your checkerboard out:

If you want to store a 4-byte float for each pixel, rather than the 8bit greyscale i used, you need to use
-define quantum:format=floating-point

and
-depth 32

and remember that your image size is HxWx4 bytes when calculating the offset.
ImageMagick is installed on most Linux distros and is available for OSX (preferably using homebrew) and Windows from here.
Yes, this is an ugly hack, but no uglier than the original question :-)


text:
Q: Text Field Style Crashes on Android Devices in an app with Sencha I am having problems with the default style of Sencha (or Android not sure) for the text inputs and password fields, it works ok on iOS devices and on some android devices, but HTC and others put their awful default style (white background and grey border) which i can nohow change or hide. Because of that all the layout looks very awful....
see the image please.
Even the sample of Sencha Touch has the same problem.
see please the second image here.
Please if you have any suggestion what is the reason of it or how it is possible to hide i
would be very grateful!! here is all i have tried for that
input {
background: transparent !important;
border: 0 transparent !important;
-webkit-appearance: none;
}
input[type=text] {
background: transparent !important;
border: 0 transparent !important;
-webkit-appearance: none;
}
input:focus{
outline:none;
background: transparent !important;
border-color: transparent !important;
-webkit-focus-ring-color: transparent;
-webkit-appearance: none;
}

Thanks in advance
Andrei

A: What you're seeing is actually an Android "feature" that generates a native control on top of your styled input field.
If you try to move your field on focus you should see that the field is intact, try the following css rule to see the phenomena:
input:focus {
    position: absolute;
    left: -20px;
}

What you could do is try to set -webkit-user-modify: read-write-plaintext-only; which works on some phones (not sure about < 2.3), but can break some functionality. E.g. for a number field you still get a qwerty-keyboard instead of a number pad etc.
So try it out, hopefully it helps you and is suitable for your needs.


text:
Q: Can I choose what language or software to install with the 12.04 DVD? I was wondering is it possible to choose what language or software to install with ubuntu 12.04 DVD, when we're installing it ?

A: The default Setup CDs use the language you select in the setup dialog. After installation you can add or remove whatever you need (including language packs).
If you use an alternative Setup CD you should be able to customize the installation much more during setup but i don't remember if you can go down to individual package selection with these as well. At least you can select groups of packages like LAMP and so on.


text:
Q: Get Parent Attribute in the Current Position with XSLT I have the following data:
<books>
    <entry id="8">
        <author name="tony-blair">Tony Blair</author>
    </entry>
    <entry id="9">
        <author name="william-campbell">William Campbell</author>
    </entry>
</books>

And use the following template
<xsl:template match="books/entry">
    <xsl:value-of select="author"/>
    <xsl:value-of select="ancestor::books/entry/@id"/>
</xsl:template>

I try to use ancestor::books/entry/@id but it results only the first id.
How to get the parent entry id while we are in the current position entry?

A: <xsl:template match="books/entry">
    <xsl:value-of select="author"/>
    <xsl:value-of select="@id"/>
</xsl:template>

A: Within a
<xsl:template match="books/entry">

the current context node is the entry element, so you can just use
<xsl:value-of select="@id" />

You don't need to go up to the books element and back down again.

A: <xsl:template match="entry">
    <xsl:value-of select="author"/>
    <xsl:value-of select="@id"/>
</xsl:template>

As others have said, you don't need to go up and down the tree.
books/entry is a tiny performance optimisation but it seems you're not there yet, so keep things simple and you're probably not processing massive documents anyway.


text:
Q: Make the following statement ACID compliant I can't figure this out. How to make this update statement ACID compliant?
Update Students Set Career = 'GRD' where Joined > '2012'

A: If below command is executed it will only update records where it is actually required to change the value of career to 'GRD', if the value is already 'GRD' it won't do anything. Also in case below command is executed multiple times, it won't update the same record again and again:
Update Students Set Career = 'GRD' where Joined > 2012 and Career <> 'GRD'

A: It is joined columns.
Try this query
Update Students Set Career = 'GRD'
where Cast(joined as date) > cast(01-Jan-2015 as date)

2012


text:
Q: weird behaviour from $(window).load I am sending a lot of data through socket.io when a user connects and rather than loading the page as and when a div has been loaded with the data I am trying to use $(window).load to wait until everything has been loaded.
If I hard refresh the website, clearing all the cache the website loads fine and everything fades in as normal but on a soft refresh the website finishes loading but nothing fades in.
Any ideas? Thanks
Here is the full code minus the unimportant bits:
socket.on('websiteLoad', function(data) {
    $('#pot_players, #pot_players_pics, #wheelInfo, #wheelArrow, #all_pot_items, #prev_win, #luck_win, #itemCounter, #timeCounter').hide().promise().done(function() {

        // Load Pot Data
        $('#pot_players').load('headers/pot.php')
        // 4 more .load here
        $('#wheelArrow').html('')

        // Load Chart Data
        for (i=0;i<data.allData.chartData.length;i++) {
            // Data
        }

        // Load timers
        if (data.allData.itemData == null) {
            $('#itemCounter').html('
0 /
 50 Items')
            $('#timeCounter').html('starting in 50 seconds...')
        }
        else {
            $('#itemCounter').html('
' + data.allData.itemData + ' /
 50 Items')
            $('#timeCounter').html('starting in 50 seconds...')
        }

        // Load Luckiest Data
        if(data.allData.luckiestData == null) {
            var luckCon = '

Luckiest Player

No One

won 0🍓
With 0% chance!

';
        }
        else {
            var luckCon = '

Luckiest Player

' + data.allData.luckiestData.name + '

won ' + data.allData.luckiestData.winnings + '🍓
With ' + data.allData.luckiestData.percentage + '% chance!

';
        }
        $('#luck_win').html(luckCon)
    });

    $('.welcome').css("display", "block").delay(5000).fadeOut();

    $(window).load(function(){
        $('#pot_players, #pot_players_pics, #wheelInfo, #wheelArrow, #all_pot_items, #prev_win, #luck_win, #itemCounter, #timeCounter').fadeIn(1500);
        myChart.update();
    });
});


text:
Q: KDE Plasma 5 - where do I check the patterns for the "in an application based on the contents of the URL" setting? In KDE Plasma 5 (e.g. install Kubuntu 20.04.2):

*

*Open "System Settings";

*Go "Applications" -> "Default Applications" -> "Web Browser";

*There is an "Open http and https URL" setting; one of the possible values is "in an application based on the contents of the URL".

I assume it's supposed to open different applications based on patterns in the URL, e.g. if I have the Zoom app installed, Zoom meeting invitation URLs might automatically open the Zoom app instead of the default web browser.
Where do I check the patterns that are registered?