text:
Q: TypeScript SyntaxError: Unexpected identifier when using type declarations I'm new to TypeScript, when I try to declare types I get this error:
SyntaxError: Unexpected identifier

Here's the full Error:
C:\Users\Irian\Documents\bots\hatsune\src\config.ts:2
    token: String = "No"

SyntaxError: Unexpected identifier
    at wrapSafe (internal/modules/cjs/loader.js:1053:16)
    at Module._compile (internal/modules/cjs/loader.js:1101:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
    at Module.load (internal/modules/cjs/loader.js:985:32)
    at Function.Module._load (internal/modules/cjs/loader.js:878:14)
    at Module.require (internal/modules/cjs/loader.js:1025:19)
    at require (internal/modules/cjs/helpers.js:72:18)
    at Object.<anonymous> (C:\Users\Irian\Documents\bots\hatsune\src\bot.ts:3:16)
    at Module._compile (internal/modules/cjs/loader.js:1137:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)

config.ts:
class Config {
    token: String = "No"
    prefix: String = "hat"
};

So why is it not working if typescript is for type definitions?


text:
Q: MySQL Server :: My C Code can remotely create a database, but not "INSERT INTO" it I've written a C program which does the following when it starts:

*

*Connects to a remote Linux MySQL server over the network

*Creates a new, uniquely-named database

*Sends a "USE _____" command to specify we want to use that database

*Creates a single table within the database

Here's examples of the actual commands my code is sending:

*

*(no command sent to initiate connection)

*"CREATE DATABASE IF NOT EXISTS myDB_2019424_205718;"

*"USE myDB_2019424_205718;"

*"CREATE TABLE IF NOT EXISTS myTable ( timestamp VARCHAR(15) ,
Column1 VARCHAR(8) , Column2 VARCHAR(4) , Column3 VARCHAR(4) );"

All of the above works great.  The trouble is, once the database is set up and ready, I need the C program to crunch a lot of numbers on-the-fly, and periodically send "INSERT INTO" commands to the server.  Here's the first "INSERT INTO" command my code sends:
INSERT INTO myTable VALUES ( '1556139439', NULL, NULL, NULL );
When my code sends its first "INSERT INTO" command, the server immediately sends back an error and my code reports "****** MySQL server has gone away ******"
I Googled that error, of course, and I see from posts like this that the two possible culprits are a low timeout or small packet threshold.  So I've reset those to maximum on my server:
mysql> SELECT @@wait_timeout;
+----------------+
| @@wait_timeout |
+----------------+
|          28800 |
+----------------+
1 row in set (0.00 sec)

mysql> SELECT @@max_allowed_packet;
+----------------------+
| @@max_allowed_packet |
+----------------------+
|            107373568 |
+----------------------+
1 row in set (0.00 sec)

mysql>

But still no luck.  Worse, when I examine /var/log/mysql/error.log after a failed session, I see no error message recorded.
One more clue…  I've tried manually logging into the MySQL server and pasting these commands in one-by-one.  All commands are accepted on the manual interface.  There's something buggy when my code sends the "INSERT INTO" command, and I can't figure out what.  Has anyone seen this before?
Some system information…  My C code is running on an Ubuntu container, version 16.04.3 LTS.  I've installed the latest mysql library.  The SQL server is running on an identical container; the actual version of MySQL Server is Ver 14.14 Distrib 5.7.25.
Sooo… what could be the problem here?  I've included an excerpt of my C code below.  (The full code is too long and confusing to include here.)  Any suggestions or advice will be appreciated.

A: User error, my apologies.  I had put a "close_connection()" line in my code for troubleshooting purposes, then forgot about it.  This wasn't a problem until I added an "INSERT INTO" command after the "close_connection()".  So of course the connection was closed when my code tried to INSERT.
The online documentation for the "**** MySQL server has gone away ****" error assumes that the sending code wasn't closed the connection, which is what confused me.  Now I know...

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I designate the location of a library in order for a "using" statement to work (C#) I'm used C# -some- but not recently.
I've got this header from some code, and it calls a custom non-system library, (Dynastream.Fit, at the bottom), but I need to know how to tell the program where it resides so it can compile.  Pretty sure the library is in the SDK I downloaded, just need to find it.  This is the FitSDK from ANT+.
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Diagnostics;
using Dynastream.Fit;

A: You need to add the dll of Dynastream.Fit to your project Reference folder by right clicking the reference folder -> add reference -> Browse -> choose the dll; unless you have already installed the assembly in GAC.


text:
Q: Error UiElement is not longer valid after publish process to UiPath Orchastrator I created a robot on UiPath Studio and it were working well running at my machine.
Then I followed the steps to publish it at Orchestrator:

*

*I created a machine on Orchestrator(and linked the key license to the Uipath Assistant)

*I created a robot

*I created an environment

*I created a process linked to the robot

So when I run it from Orchestrator I got the error:
Process: IMPEXTRCOBR
Environment:
Robot: IMPEXTRCOB
Machine name: C205
Info: The UiElement is no longer valid
RemoteException wrapping UiPath.Core.InvalidUiElementException: O UiElement já não é válido ---> RemoteException wrapping System.Runtime.InteropServices.COMException: Exception from HRESULT: 0x80040215
at UiPath.UiNodeClass.get_visibility()
at UiPath.Core.UiElement.IsVisible()
--- End of inner exception stack trace ---
at UiPath.Core.Activities.ScopeActivity.OnFaulted(NativeActivityFaultContext faultContext, Exception propagatedException, ActivityInstance propagatedFrom)
at System.Activities.Runtime.FaultCallbackWrapper.Invoke(NativeActivityFaultContext faultContext, Exception propagatedException, ActivityInstance propagatedFrom)
at System.Activities.Runtime.FaultCallbackWrapper.FaultWorkItem.Execute(ActivityExecutor executor, BookmarkManager bookmarkManager)
Start Time: 04/24/2020 11:16:22 AM
End Time: 04/24/2020 11:16:29 AM
Input Values: null
Output Values: Empty
Has Recording: false

And now If I try to run it from my machine I got the same error. And if I try to "fix" the selector of the activity I got the error:

What am I doing wrong?

A: Is it possible for you to give us a screenshot of your UiPath Sequence project?
Typically these errors occur when a selector is too specific and information that might change, like a page title, is included.
Inherited properties
Often properties in a selector are inherited. So a UiPath scraping activity might be getting its title property from an Attach Browser activity from which it is connected. In that case, the ability to delete the title in the attached activity will be disabled. You'd have to go to the parent.

A: I have the same problem like you,
when I used the click method
I have gotten through this problem by changing the method using Click Image Activity instead of Click Activity.

This can solve common click errors of not using any selectors to click on specific UI elements.
maybe far from your expectations but this method can help.


text:
Q: jQuery-Only slider not sliding Basic jQuery-only slider that is supposed to fade between slides on arrow click.
Can't seem to figure out why this one won't work, as I've made similar ones before using a similar method without plugins.
JSFiddle: https://jsfiddle.net/b988tfna/1/.
I've also got the code for a testimonials slider below the main slider in JSFiddle, where I'm having problems aligning the buttons/dots for this slider and also sizing them properly. The height and width are set the same, but they're taller than they are wide, and margin-left/right:auto isn't centrally aligning them.
Would rather not combine these issues into one post but I've been trying to solve them for hours now without any solution.
Thanks.
HTML:

Creating Digital Success Stories.

Intro | Innovation | Results

Mauris sed ipsum nisi, Aliquam eget sagittis erat. Nam ut auctor erat. Maecenas sollicitudin dignissim urna, eu elementum ante varius at. Mauris porttitorultrices mauris, eget pretium lorem blandit in. Nulla sollicitudin viverra ante sed venenatis.

            Enquire Now

Slide 2.

Intro | Innovation | Results

Mauris sed ipsum nisi, Aliquam eget sagittis erat. Nam ut auctor erat. Maecenas sollicitudin dignissim urna, eu elementum ante varius at. Mauris porttitorultrices mauris, eget pretium lorem blandit in. Nulla sollicitudin viverra ante sed venenatis.

            Enquire Now

Slide 3.

Intro | Innovation | Results

Mauris sed ipsum nisi, Aliquam eget sagittis erat. Nam ut auctor erat. Maecenas sollicitudin dignissim urna, eu elementum ante varius at. Mauris porttitorultrices mauris, eget pretium lorem blandit in. Nulla sollicitudin viverra ante sed venenatis.

            Enquire Now

Slide 4.

Intro | Innovation | Results

Mauris sed ipsum nisi, Aliquam eget sagittis erat. Nam ut auctor erat. Maecenas sollicitudin dignissim urna, eu elementum ante varius at. Mauris porttitorultrices mauris, eget pretium lorem blandit in. Nulla sollicitudin viverra ante sed venenatis.

            Enquire Now

CSS:
#slider
{
margin-left:auto;
margin-right:auto;
width:100%;
height:100vh;
color:#fff;
z-index:2;
padding:100px 0;
}

.slide
{
display:none;
width:100%;
}

.activeSlide
{
display:block;
}

.sliderArrow
{
position:relative;
height:auto;
top:50%;
margin:-200px 10% 0 10%;
z-index:99;
}

.slideContent
{
width:65%;
margin-left:auto;
margin-right:auto;
}

JS:
$(document).ready(function() {

    $('#nextArrow').click(function() {

        var currentSlide = $('.activeSlide');
        var nextSlide = currentSlide.next();

        if (nextSlide.length == 0) {
            nextSlide = $('.slide').first();
        };

        currentSlide.fadeOut(1000).removeClass('activeSlide');
        nextSlide.fadeIn(1000).addClass('activeSlide');

    });

    $('#prevArrow').click(function() {

        var currentSlide = $('.activeSlide');
        var prevSlide = currentSlide.prev();

        if (prevSlide.length == 0) {
            prevSlide = $('.slide').last();
        };

        currentSlide.fadeOut(1000).removeClass('activeSlide');
        prevSlide.fadeIn(1000).addClass('activeSlide');

    });

};

A: CSS
.container {
      max-width: 400px;
      background-color: black;
      margin: 0 auto;
      text-align: center;
      position: relative;
    }
    .container div {
      background-color: white;
      width: 100%;
      display: inline-block;
      display: none;
    }
    .container img {
      width: 100%;
      height: auto;
    }

    button {
      position: absolute;
    }

    .next {
      right: 5px;
    }

    .prev {
      left: 5px;
    }

HTML

      <button class="next">Next</button>
      <button class="prev">Previous</button>

      Building a slideshow like pattern that can accurately cycle through a number of unknown divs, forwards and backwards. Trying to use as little code as possible. Leave a comment if you see a way to do it better!

JS
var currentIndex = 0,
  items = $('.container div'),
  itemAmt = items.length;

function cycleItems() {
  var item = $('.container div').eq(currentIndex);
  items.hide();
  item.css('display','inline-block');
}

var autoSlide = setInterval(function() {
  currentIndex += 1;
  if (currentIndex > itemAmt - 1) {
    currentIndex = 0;
  }
  cycleItems();
}, 3000);

$('.next').click(function() {
  clearInterval(autoSlide);
  currentIndex += 1;
  if (currentIndex > itemAmt - 1) {
    currentIndex = 0;
  }
  cycleItems();
});

$('.prev').click(function() {
  clearInterval(autoSlide);
  currentIndex -= 1;
  if (currentIndex < 0) {
    currentIndex = itemAmt - 1;
  }
  cycleItems();
});

Please try this link:-https://www.sitepoint.com/web-foundations/making-simple-image-slider-html-css-jquery/
Ok.  May be you can try this link:-http://visuallightbox.com/content/30-best-image-sliders-173.html


text:
Q: Azure Classic VM Migration Our cloud product has been transferred to another company. This company have their own Azure subscription and I need to transfer all the services to the new subscription. The cloud service includes an Azure SQL Database, a Cloud Service (classic, with 1 web role and 1 worker role), a storage account (classic) and VM (classic) running SQL Server with Reporting Services.
Our CI/CD server has been configured to deploy the database and cloud services. The storage service is being transferred using AzCopy.
The problem I have is, I don't have the details to reconfigure a Reporting Server. I have taken a copy of the VHDs (whilst the machine was switched off, but not sysprepped) and copied them to the new storage service. I need to find a way to create a new classic VM and attach the two VHDs to it without disrupting the existing environment. Once the environment has passed testing, the current environment will be torn down. Because the VM is a "classic" model, the Azure portal will not transfer it to another subscription. I'd like to avoid sysprepping the current live reporting server if possible because I cannot afford to disrupt the current service.
I have read a lot on here but most of it seems to apply to later (non-classic) VMs and refers to "managed" and "unmanaged" disks, which I don't understand. There are scripts that create virtual networks, etc. that the current environment does not seem to have anything comparable.
I'm hoping someone can help me with the easiest way to transfer this VM?

A: According to your scenario, if you want your original VMs and  new VMs exist at the same time, you need to execute sysprep. Now, you could not execute on original VMs, I suggest you could download the VM's VHDs to your local and use the VHD to create new VM in Hyper, then you could execute sysprep. Please refer to the following steps:
1.Download your original VM's VHD to your local PC from Azure, you could use Azcopy.
2.Create a new VM in Hyper, you could refer to this link.
3.On Hyper VM, you need to execute sysprep.
4.Upload VHD to Azure classic storage account. Important: If using AzCopy to copy the VHD from local storage to Azure Storage, make sure you specify /BlobType:Page for the copy.
5.Create a new Image on classic Portal.

6.Create new VM on Azure with your Image.


text:
Q: Do any JVM's JIT compilers generate code that uses vectorized floating point instructions? Let's say the bottleneck of my Java program really is some tight loops to compute a bunch of vector dot products. Yes I've profiled, yes it's the bottleneck, yes it's significant, yes that's just how the algorithm is, yes I've run Proguard to optimize the byte code, etc.
The work is, essentially, dot products. As in, I have two float[50] and I need to compute the sum of pairwise products. I know processor instruction sets exist to perform these kind of operations quickly and in bulk, like SSE or MMX.
Yes I can probably access these by writing some native code in JNI. The JNI call turns out to  be pretty expensive.
I know you can't guarantee what a JIT will compile or not compile. Has anyone ever heard of a JIT generating code that uses these instructions? and if so, is there anything about the Java code that helps make it compilable this way?
Probably a "no"; worth asking.

A: Here is nice article about experimenting with Java and SIMD instructions written by my friend:
http://prestodb.rocks/code/simd/
Its general outcome is that you can expect JIT to use some SSE operations in 1.8 (and some more in 1.9). Though you should not expect much and you need to be careful.

A: So, basically, you want your code to run faster. JNI is the answer. I know you said it didn't work for you, but let me show you that you are wrong.
Here's Dot.java:
import java.nio.FloatBuffer;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;

@Platform(include = "Dot.h", compiler = "fastfpu")
public class Dot {
    static { Loader.load(); }

    static float[] a = new float[50], b = new float[50];
    static float dot() {
        float sum = 0;
        for (int i = 0; i < 50; i++) {
            sum += a[i]*b[i];
        }
        return sum;
    }
    static native @MemberGetter FloatPointer ac();
    static native @MemberGetter FloatPointer bc();
    static native @NoException float dotc();

    public static void main(String[] args) {
        FloatBuffer ab = ac().capacity(50).asBuffer();
        FloatBuffer bb = bc().capacity(50).asBuffer();

        for (int i = 0; i < 10000000; i++) {
            a[i%50] = b[i%50] = dot();
            float sum = dotc();
            ab.put(i%50, sum);
            bb.put(i%50, sum);
        }
        long t1 = System.nanoTime();
        for (int i = 0; i < 10000000; i++) {
            a[i%50] = b[i%50] = dot();
        }
        long t2 = System.nanoTime();
        for (int i = 0; i < 10000000; i++) {
            float sum = dotc();
            ab.put(i%50, sum);
            bb.put(i%50, sum);
        }
        long t3 = System.nanoTime();
        System.out.println("dot(): " + (t2 - t1)/10000000 + " ns");
        System.out.println("dotc(): "  + (t3 - t2)/10000000 + " ns");
    }
}

and Dot.h:
float ac[50], bc[50];

inline float dotc() {
    float sum = 0;
    for (int i = 0; i < 50; i++) {
        sum += ac[i]*bc[i];
    }
    return sum;
}

We can compile and run that with JavaCPP using this command:
$ java -jar javacpp.jar Dot.java -exec

With an Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz, Fedora 30, GCC 9.1.1, and OpenJDK 8 or 11, I get this kind of output:
dot(): 39 ns
dotc(): 16 ns

Or roughly 2.4 times faster. We need to use direct NIO buffers instead of arrays, but HotSpot can access direct NIO buffers as fast as arrays. On the other hand, manually unrolling the loop does not provide a measurable boost in performance, in this case.

A: To address some of the scepticism expressed by others here I suggest anyone who wants to prove to themselves or other use the following method:

*

*Create a JMH project

*Write a small snippet of vectorizable math.

*Run their benchmark flipping between -XX:-UseSuperWord and -XX:+UseSuperWord(default)

*If no difference in performance is observed, your code probably didn't get vectorized

*To make sure, run your benchmark such that it prints out the assembly. On linux you can enjoy the perfasm profiler('-prof perfasm') have a look and see if the instructions you expect get generated.

Example:
@Benchmark
@CompilerControl(CompilerControl.Mode.DONT_INLINE) //makes looking at assembly easier
public void inc() {
    for (int i=0;i<a.length;i++)
        a[i]++;// a is an int[], I benchmarked with size 32K
}

The result with and without the flag (on recent Haswell laptop, Oracle JDK 8u60):
-XX:+UseSuperWord :  475.073 ± 44.579  ns/op (nanoseconds per op)
-XX:-UseSuperWord : 3376.364 ± 233.211 ns/op
The assembly for the hot loop is a bit much to format and stick in here  but here's a snippet(hsdis.so is failing to format some of the AVX2 vector instructions so I ran with -XX:UseAVX=1): -XX:+UseSuperWord(with '-prof perfasm:intelSyntax=true')
  9.15%   10.90%  │││ │↗    0x00007fc09d1ece60: vmovdqu xmm1,XMMWORD PTR [r10+r9*4+0x18]
 10.63%    9.78%  │││ ││    0x00007fc09d1ece67: vpaddd xmm1,xmm1,xmm0
 12.47%   12.67%  │││ ││    0x00007fc09d1ece6b: movsxd r11,r9d
  8.54%    7.82%  │││ ││    0x00007fc09d1ece6e: vmovdqu xmm2,XMMWORD PTR [r10+r11*4+0x28]
                  │││ ││                                                  ;*iaload
                  │││ ││                                                  ; - psy.lob.saw.VectorMath::inc@17 (line 45)
 10.68%   10.36%  │││ ││    0x00007fc09d1ece75: vmovdqu XMMWORD PTR [r10+r9*4+0x18],xmm1
 10.65%   10.44%  │││ ││    0x00007fc09d1ece7c: vpaddd xmm1,xmm2,xmm0
 10.11%   11.94%  │││ ││    0x00007fc09d1ece80: vmovdqu XMMWORD PTR [r10+r11*4+0x28],xmm1
                  │││ ││                                                  ;*iastore
                  │││ ││                                                  ; - psy.lob.saw.VectorMath::inc@20 (line 45)
 11.19%   12.65%  │││ ││    0x00007fc09d1ece87: add    r9d,0x8            ;*iinc
                  │││ ││                                                  ; - psy.lob.saw.VectorMath::inc@21 (line 44)
  8.38%    9.50%  │││ ││    0x00007fc09d1ece8b: cmp    r9d,ecx
                  │││ │╰    0x00007fc09d1ece8e: jl     0x00007fc09d1ece60  ;*if_icmpge

Have fun storming the castle!

A: You could write OpenCl kernel to do the computing and run it from java http://www.jocl.org/.
Code can be run on CPU and/or GPU and OpenCL language supports also vector types so you should be able to take explicitly advantage of e.g. SSE3/4 instructions.

A: Have a look at Performance comparison between Java and JNI for optimal implementation of computational micro-kernels. They show that Java HotSpot VM server compiler supports auto-vectorization using Super-word Level Parallelism, which is limited to simple cases of inside the loop parallelism. This article will also give you some guidance whether your data size is large enough to justify going JNI route.

A: I'm guessing you wrote this question before you found out about netlib-java ;-) it provides exactly the native API you require, with machine optimised implementations, and does not have any cost at the native boundary due thanks to memory pinning.

A: Java 16 introduced the Vector API (JEP 417, JEP 414, JEP 338). It is currently "incubating" (ie, beta), although anyone can use it. It will probably become GA in Java 19 or 20.
It's a little verbose, but is meant to be reliable and portable.
The following code can be rewritten:
void scalarComputation(float[] a, float[] b, float[] c) {
   assert a.length == b.length && b.length == c.length;
   for (int i = 0; i < a.length; i++) {
        c[i] = (a[i] * a[i] + b[i] * b[i]) * -1.0f;
   }
}

Using the Vector API:
static final VectorSpecies<Float> SPECIES = FloatVector.SPECIES_PREFERRED;

void vectorComputation(float[] a, float[] b, float[] c) {
    assert a.length == b.length && b.length == c.length;
    int i = 0;
    int upperBound = SPECIES.loopBound(a.length);
    for (; i < upperBound; i += SPECIES.length()) {
        // FloatVector va, vb, vc;
        var va = FloatVector.fromArray(SPECIES, a, i);
        var vb = FloatVector.fromArray(SPECIES, b, i);
        var vc = va.mul(va)
                   .add(vb.mul(vb))
                   .neg();
        vc.intoArray(c, i);
    }
    for (; i < a.length; i++) {
        c[i] = (a[i] * a[i] + b[i] * b[i]) * -1.0f;
    }
}

Newer builds (ie, Java 18) are trying to get rid of that last for loop using predicate instructions, but support for that is still supposedly spotty.

A: In HotSpot versions beginning with Java 7u40, the server compiler provides support for auto-vectorisation. According to JDK-6340864
However, this seems to be true only for "simple loops" - at least for the moment. For example, accumulating an array cannot be vectorised yet JDK-7192383

A: I dont believe most if any VMs are ever smart enough for this sort of optimisations. To be fair most optimisations are much simpler, such as shifting instead of multiplication whena power of two. The mono project introduced their own vector and other methods with native backings to help performance.


text:
Q: if statement for columns in 2D list I need to iterate two different lists of integers with an if-statement that requires a mathematic operation. I've approached this in several ways, the latest one shown below.
I have 4 lists that I've extracted from columns in a CSV file:
unique_names = ["Ian", "Laura", "Winona", "Garfield"]
arrivaltime = ["12:14:31", "12:15:02", "12:14:14", "13:00:00"]
score = [83, 99, 90, 100]
personalbest=[75, 100, 89, 90]

I need to identify the names for those competitors who are outperforming,
i.e. where the score > personalbest*1.1.
No imported modules allowed (except for csv).
outperforming = []
tdlist = [[arrivaltime], [unique_names], [score], [personalbest]]
for i in tdlist[2]:
    if i*1.1 > (tdlist[3][i]):
        outperforming.append("tdlist[1][i]")

I get this error: TypeError: can't multiply sequence by non-int of type 'float'
I also tried this to check for other errors:
for i in tdlist[2]:
    if i > (tdlist[3][i]):
        outperforming.append("tdlist[1][i]")

Then I get this error:  TypeError: list indices must be integers or slices, not list.

A: Use the zip() function to group your data by index, then use an if to check the condition you want:
Code:
unique_names = ["Ian", "Laura", "Winona", "Garfield"]
arrivaltime = ["12:14:31", "12:15:02", "12:14:14", "13:00:00"]
score = [83, 99, 90, 100]
personalbest=[75, 100, 89, 90]

performers = []
for u, a, s, pb in zip(unique_names, arrivaltime, score, personalbest):
    if s > pb * 1.1:
        performers.append((u, a, s, pb))

print(performers)

Output:
[('Ian', '12:14:31', 83, 75), ('Garfield', '13:00:00', 100, 90)]

A: You can use the zip function to iterate over multiple sequences at once. For example:
for name, attempt, pb in zip(unique_names, score, personal_best):
    print(name, attempt, pb)

A: zip() solutions are certainly nice. And elegant. I would also be tempted to use enumerate(), which goes through a list and gives you the each item and the index:
for idx,x in enumerate(score):
    if s > 1.1*personalbest[idx]:
        outperforming.append(unique_names[idx])


text:
Q: Issues reading a characteristic from a paired BLE device Using CoreBluetooth on iOS(10.3) i'm unable to read a characteristics value when bonded(paired?) to a custom BLE HID Device.  If I remain unbonded I can read the characteristic fine.
The BLE device implements HID over GATT(HOGP) and an additional service with a single notify characteristic.  This additional service/characteristic is what I'm trying to read, not the HID over GATT data which I know is filtered out.
It appears that didDiscoverServices never gets called. I do see didConnect being called.
I'm able to accomplish this on Android so I don't think it's an issue with the BLE device.
Relevant code below:
func centralManagerDidUpdateState(_ central: CBCentralManager) {
    var showAlert = true
    var message = ""

    switch central.state {
    case .poweredOff:
        message = NSLocalizedString("Bluetooth on this device is currently powered off.", comment: "")
    case .unsupported:
        message = NSLocalizedString("This device does not support Bluetooth Low Energy.", comment: "")
    case .unauthorized:
        message = NSLocalizedString("This app is not authorized to use Bluetooth Low Energy.", comment: "")
    case .resetting:
        message = NSLocalizedString("The BLE Manager is resetting; a state update is pending.", comment: "")
    case .unknown:
        message = NSLocalizedString("The state of the BLE Manager is unknown.", comment: "")
    case .poweredOn:
        showAlert = false
        message = NSLocalizedString("Bluetooth LE is turned on and ready for communication.", comment: "")

        let lastPeripherals = centralManager.retrieveConnectedPeripherals(withServices: [CBUUID(string: Device.DeviceServiceUUID)])

        print("count: \(lastPeripherals.count)")
        if lastPeripherals.count > 0{
            let device = lastPeripherals.last!;
            connectingPeripheral = device;
            centralManager.connect(connectingPeripheral, options: nil)
        } else {
            centralManager.scanForPeripherals(withServices: [CBUUID(string: "7340")], options: nil)
        }

    }
}

func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {

    if let peripheralName = advertisementData[CBAdvertisementDataLocalNameKey] as? String {
        if peripheralName == deviceName {

            // save a reference to the device
            device= peripheral
            device!.delegate = self

            // Request a connection to the peripheral
            centralManager.connect(device!, options: nil)
        }
    }
}

func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
    peripheral.discoverServices(nil)
}

func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {

}

func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
    if error != nil {
        print("****** DISCONNECTION DETAILS: \(error!.localizedDescription)")
    }
    device = nil
}

func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
    if error != nil {
        print("ERROR DISCOVERING SERVICES: \(error?.localizedDescription)")
        return
    }

    if let services = peripheral.services {
        for service in services {
            print("DISCOVERED SERVICE: \(service)")
            if (service.uuid == CBUUID(string: Device.DeviceServiceUUID)) {
                peripheral.discoverCharacteristics(nil, for: service)
            }
        }
    }
}

func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
    if error != nil {
        print("ERROR DISCOVERING CHARACTERISTICS: \(error?.localizedDescription)")
        return
    }

    if let characteristics = service.characteristics {

        for characteristic in characteristics {
            // Message Data Characteristic
            if characteristic.uuid == CBUUID(string: Device.MessageCharacteristicUUID) {
                // Enable the message notifications
                messageCharacteristic = characteristic
                device?.setNotifyValue(true, for: characteristic)
            }

        }
    }
}

func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
    if error != nil {
        print("ERROR ON UPDATING VALUE FOR CHARACTERISTIC: \(characteristic) - \(error?.localizedDescription)")
        return
    }

    // extract the data from the characteristic's value property and display the value based on the characteristic type
    if let dataBytes = characteristic.value {
        if characteristic.uuid == CBUUID(string: Device.MessageCharacteristicUUID) {
            displayMessage(dataBytes)
        }
    }
}


text:
Q: Leading Digit of $2^{4242}$ How could I solve this problem?

Find the first digit of $2^{4242}$ without using a calculator.

I know how to find the last digit with modular arithmetic, but I can't use that here.

A: If you have memorized that $\log_{10}2\approx 0.30103$ you can multiply by $4242$ and take the fractional part as $0.9692$ which looks like it should be greater than $\log_{10}9$ (and it is, but it is closer than I would have thought, it is $\approx 0.9542$).  I don't know how to do it without log tables.

A: Presenting an alternate method (no logs, but needs the knowledge that doubling time is ~ $70$/rate)
Starting with
$$2^{10}=1024$$
which is
$$1000 \times 1.024$$ or a 2.4% increase.
Then,
$$70/2.4 \approx 29$$
implies that
$$2^{290}\sim 2 \times 10^k$$
for some k.
Then, $$2^{4242} = {2^{290}}^{14} \times 2^{182}$$
So, it would suffice to calculate $$2^{16} \approx 1.6 \times 10^l$$
and to get $2^{182}$, first note that $1.024^{29} \approx 2$ so, $1.024^{18} \approx 1.5$ (pure hand waving, but sounds logical) So, from that $$2^{182} \approx 6 \times 10^m$$ and thus we can get the fist digit to be close to $1.6 \times 6 > 9$

A: This is probably not the answer you are looking for, and wil probably only be appreciated by people of my age ...
I can still remember from school days that $\log_{10} 2 = 0,30102999$ (I always thought it was noteworthy that it is so close to $0.30103$) - people who went to school in the 1950's can probably recall using logs to base 10 for lots of tedious calculations.
You can then do the multiplication by 4242 without a calculator, and get the fractional part ($=x$, say, but you are likely to need a calculator to find out the first digit of $10^x$, unless you have also memorised $\log 2, \log3, \dots, \log 9$ (I can't!)
Edit:
With a bit more digging in the recesses of my memory, I can just recall that $\log 3$ is something like $0.477$, so $\log 9 = 2 \log 3 = 0.954$, so that should do it ...


text:
Q: JW Pagination not working vue 3 with error: Invalid array length I'm using jw pagination for my vue 3 app, but when I render it in my page everything disappears with the error of
Uncaught (in promise) RangeError: Invalid array length

but i didn't ever give it any data. just the import part
if it doesn't work at all, can anyone suggest something that can help me with paginating my users data?


text:
Q: MVC3 Conditional Jquery Validation w/ Dropdown I been trying to do some jquery validation where a textfield or dropdown is validated only if a checkbox is checked.
Here is what I have:
@using (Ajax.BeginForm("SomeAction", "SomeController", new { id = Model.Id }, new AjaxOptions { HttpMethod = "Post", UpdateTargetId = "somePanel", InsertionMode = InsertionMode.Replace }, new { @id = "testForm" }))
{
 @Html.DropDownListFor(x => Model.SelectedValue, Model.YesNoList, " ", new { @id ="drpYesNo" })
 @Html.TextAreaFor(x => x.CriminalText, new { @id = "txtSomeField" })

<input type="submit" value="Save" />
}

In the javascript I have this:
<script type="text/javascript">
    jQuery.validator.messages.required = "";
    $("#testForm").validate(
    {
        rules: {
            txtSomeField: {
                required: function (element) {
                    return $("input:checkbox[name='drpYesNo']:checked").val() == 'Yes';
                }
            }
        }

    });

    $("#testForm").on("submit", function () {
        if (!$(this).valid()) {
            return false;
        }
    });
</script>

I am following some of the example that are online, but can't seem to work. Any help is much appreciated. Happy Fourth of July!

A: When you define a jquery validator rule you should use the name and not the id of the element you are defining the rule for. So in your case the name of your <textarea> is CriminalText and not txtSomeField (Obviously if this is inside an editor template the name might be different, such as for example Foo.Bar[3].CriminalText).
So the first step is to use the proper name:
rules: {
    CriminalText: {
        required: function (element) {
            ...
        }
    }
}

Now let's see the second step. In your selector you used some :checkbox that I cannot see anywhere in your DOM. All I can see (at least in what you have shown here) is a DropDownList and a textarea. So if you want the <textarea> to be required only if the user selected the value Yes inside the <select> list, here's how you could define the rule:
rules: {
    CriminalText: {
        required: function (element) {
            return $('#drpYesNo').val() == 'Yes';
        }
    }
}

This obviously assumes that you have the following option selected:
<select>
    <option value="Yes">Yes, of course</option>
    ...
</select>

And one final remark: make sure that you have not included the jquery.validate.unobtrusive.js script to your page as it will use Microsoft's unobtrusive library to automatically write the jQuery.validate rules based on the HTML5 data-* attributes generated by the helpers and thus completely messing up your custom rule setup.

A: The selector here is the problem, using input:checkbox is for checkboxes.  Typically, jquery prefers css class names or id's.
required: function (element) {
  return $("#drpYesNo").val() === 'Yes';
}


text:
Q: How to check values in column in Select query I need to check whether the column middle name contain any value or not.
If it is empty, then it should not be concatenated with the name.
    Select
     ..
     Agent,
     FirstName + ' ' MiddleName + ' ' + LastName as Name,
     ...
     from tbSystemUser

In above query it adds space two times in Name if MiddleName is empty.

A: You could use CASE expression with COALESCE in following:
 select
 ..
 Agent,
 case when coalesce(MiddleName, '') = '' then FirstName + ' ' + LastName
      else FirstName + ' ' + MiddleName + ' ' + LastName
 end as Name,
 ...
 from tbSystemUser

A: You can use case statement
Select
     ..
     Agent,
     Case MiddleName
     when ' ' then
     FirstName + ' ' + LastName
     else
     FirstName + ' ' MiddleName + ' ' + LastName
     end
     as Name,
     ...
     from tbSystemUser

OR
Select
         ..
         Agent,
         Case
         when MiddleName = ' ' then
         FirstName + ' ' + LastName
         else
         FirstName + ' ' MiddleName + ' ' + LastName
         end
         as Name,
         ...
         from tbSystemUser

A: Select
 ..
 Agent,
 FirstName + CASE WHEN MiddleName is not null THEN  ' ' + MiddleName else '' END  + ' ' + LastName as Name,
 ...
 from tbSystemUser

A: Use a case expression to only add the MiddleName + ' ' part if MiddleName is not null:
Select
     ...
     Agent,
     FirstName +
     case when MiddleName is not null then MiddleName + ' ' end +
     LastName as Name,
     ...
     from tbSystemUser

A: I believe you can use subqueries as such:
 Select Agent, Name from
 (
     Select t1.Agent as Agent, t1.FirstName + ' ' t1.MiddleName + ' ' + t1.LastName as Name,
     from tbSystemUser as t1 WHERE t1.MiddleName IS NOT NULL
 )
 NATURAL JOIN
 (
      Select t2.Agent as Agent, t2.FirstName + ' ' + t2.LastName as Name,
      from tbSystemUser as t2 WHERE t2.MiddleName IS NULL
 )

This will construct your answer based on the Name created by the two selects.

A: SELECT FirstName
   +IIF(ISNULL(LTRIM(RTRIM(MiddleName)),'')<>'',' '+MiddleName,'')
   +' '+LastName as Name

Or in case your SQL Server version is older than 2012:
SELECT FirstName
   +CASE WHEN ISNULL(LTRIM(RTRIM(MiddleName))) <> ''
      THEN ' '+MiddleName
      ELSE '' END
   +' '+LastName as Name

You didn't specify what empty meant. Unlike most of the other solutions here, this will deal with any length of empty strings including nulls, but not special characters. I'm going to assume nobody went and added line breaks as middle names? :)


text:
Q: How to visualize Data in a Webapplication? I implemented a wireless sensor network with my own sensornodes, the famous MQTT-protocol and a Raspberry Pi. All data, which are published by the nodes, are stored in a SQLite database on the Pi. Except the database, on the RPi is a webserver located for the communication over HTTP to enddevices like smartphones or laptops. I created a HTML-form for user inputs with Bootstrap. The users can decide between different nodes, parameters and timestamps to plot charts, tables and gauges. On the server side I programmed a PHP-application which querys the user input, the database and also calls the webside. For the client side I wrote a short JavaScript file using Ajax to recieve the userinput interactiv. So far so good, now I want to viszualize the charts, gauges and tables containing the data which the PHP-application determines.
I searched a long while for dashbaords-examples and obviously I found many different, but everytime I fail with the handling of the JS sources.
My question: Can someone recommend me a lightwight and easy to handle dashboard with following characteristics?

*

*beginner tutorials with less JS-knowledge

*extensive presentation possibilities (Barcharts, Linecharts, gauges etc.)

*able to embed in an existing webpage

*interactive usage

*sufficient support

Maybe I'm to inexperienced with the development of webapplication and I need to get some knowledge about JS. So it would be also useful if someone recommend me  JS tutorials with jQuery.


text:
Q: how do i compare values with key as row and column I am trying to compare values based on the row values and column values. Below are the tables,
TABLE1
Column1  column2 column3 column4
row1       a       b       c
row2       d       d       e
row3       f       g       h

TABLE2
COLUMN1   ROW1    ROW2    ROW3
COLUMN2   a        b       c
COLUMN3   d        e       f
COLUMN4   g        h       i

and I have compare the values as,
table1 row1,column2 values = table2 column2,row1 values
I have 120 columns to compare with the corresponding rows. Please help.


text:
Q: /usr/bin/python not found I am setting up an Ansible server to manage my other servers. Unfortunately on two of them I got the following error message:

fatal: [server1.programster.org]: FAILED! => {"changed": false,
  "module_stderr": "Shared connection to server1.programster.org
  closed.\r\n", "module_stdout": "/bin/sh: 1: /usr/bin/python: not
  found\r\n", "msg": "MODULE FAILURE", "rc": 0}

I noticed that which python output nothing, and I was able to "fix" the situation by creating a symlink of /usr/bin/python that pointed to /usr/bin/python3.
Was there a "more correct" way to fix this than me creating symlinks? I know Ubuntu 16.04 dropped python2 for python3 but I would have thought it would come out of the box with /usr/bin/python pointing to python3 no?

A: No, /usr/bin/python is never supposed to point to python3. It sounds like the script in question is broken, and a bug should be reported.


text:
Q: Listings - How to extend the indentation of lines Is there an opportunity to extend the indentation of lines in a listing?
My MWE looks like that:
\documentclass{beamer}

\usepackage{listings}

\begin{document}

    \begin{frame}[fragile]

\begin{lstlisting}
public class Foo{
 Object obj;

 void method() {
  // do anything
  {
   // do another thin
  }
 }
}
\end{lstlisting}
    \end{frame}

\end{document}

The indentation I used here is only one space. Is there an opportunity to extend each space before the beginning of text by for example four spaces?
Thank you very much for your help!

A: \documentclass{beamer}
\usepackage{listings}
\begin{document}
\begin{frame}[fragile]
Normal text
\begin{lstlisting}[xleftmargin=4em]
public class Foo{
 Object obj;

 void method() {
  // do anything
  {
   // do another thin
  }
 }
}
\end{lstlisting}
More mormal text
\end{frame}
\end{document}


text:
Q: what does rich:isUserInRole call? I am using RichFaces 3.3.3 with JSF 1.2 and I would like to understand the behaviour behind rich:isUserInRole. What is being called? When and where it is fired in server side?
For reference: http://docs.jboss.org/richfaces/latest_4_2_X/Component_Reference/en-US/html/chap-Component_Reference-Functions.html#sect-Component_Reference-Functions-richisUserInRole

A: It returns, or should return, the result of HttpServletRequest.isUserInRole().


text:
Q: Generated Shim does not contain generic overloads of a method (that their types are constrained to be struct) I am using Microsoft fakes to test our code base which is using a third party assembly.
Our code is calling a static generic method of a class that has several non-generic overloads.
Something like this :
ILookupResult Serivce.Lookup<T>(int code);
ILookupResult Service.Lookup(Type type,int code);

The problem is that the generated shim has an entry for each non-generic method like this :
ShimService.LookupTypeInt32

but there's no enrty for generic methods and I don't have any clue why it's like this.
UPDATE 1: it may worth mentioning that:

*

*Generating stubs for this third party assembly is not possible I have
disabled stub generation.

*Other generic methods are generated.

UPDATE 2: Okay now I know what is the problem by setting Diagnostic attribute of Fake node into true.It said "unsupported constraint type" which made me take a better look at the interface and I noticed that T should be struct:
 ILookupResult Serivce.Lookup<T>(int code) where T:struct;

now the question is why struct is unsupported in shim generation ?


text:
Q: WPF mvvm backgroundworker UI displaying different results So finally i managed to create a working BackgroundWorker.
I used the ReportProgress method to updated UI elements in this way:
 bw.ReportProgress(1, node);
 bw.ReportProgress(2, connection);
 bw.ReportProgress(3);
 bw.ReportProgress(4, system);

Where the connection is a model Object, this is my progress method:
 void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        if (e.ProgressPercentage == 1)       //update nodes
        {
            this.Network.Nodes.Add((NodeViewModel)e.UserState);
        }
        if (e.ProgressPercentage == 2)       //update connections
        {
            this.Network.Connections.Add((ConnectionViewModel)e.UserState);
        }
        if (e.ProgressPercentage == 3)
        {
            this.Network.Connections.Clear();
            this.Network.Nodes.Clear();
        }
        if (e.ProgressPercentage == 4)
        {
            MainNet.Systems.Add((Common.Model.System)e.UserState);
        }
    }

I have multiple objects to update so I used the percentage as a filter.
I'm getting different results every time i run the code, as if some of the data is not rendered correctly in the UI
The correct form of UI:

Not correct:

A: If you need to synchronize your worker(s) to avoid reentrancy or a race, there are several different ways.  You can try an approach like this...
    private static void ManageBackgroundWorkers()
    {
        BackgroundWorker backgroundWorker1 = new BackgroundWorker();
        BackgroundWorker backgroundWorker2 = new BackgroundWorker();
        BackgroundWorker backgroundWorker3 = new BackgroundWorker();
        backgroundWorker1.DoWork += (s, a) =>
        {
            /* do stuff*/
        };
        backgroundWorker2.DoWork += (s, a) =>
        {
            /* do some more stuff*/
        };
        backgroundWorker3.DoWork += (s, a) =>
        {
            /* do even more different stuff*/
        };
        backgroundWorker1.RunWorkerCompleted += (s, a) =>
        {
            //this.Network.Nodes.Add((NodeViewModel)e.UserState);
            backgroundWorker2.RunWorkerAsync();
        };
        backgroundWorker2.RunWorkerCompleted += (s, a) =>
        {
            //this.Network.Connections.Add((ConnectionViewModel)e.UserState);
            backgroundWorker3.RunWorkerAsync()
        };
        backgroundWorker3.RunWorkerCompleted += (s, a) =>
        {
            // finish remaining tasks here
        };
        /* start the queue */
        backgroundWorker1.RunWorkerAsync();
    }

Each worker signals a completion and its event handler simply starts the next worker in the series.  It is not a massive difference in what you have, but it repackages the steps that you were using the 'Percentage' property for.  Percentage is really a bad proxy for state anyway.  Refactoring your code should take about 5 minutes.
An alternative method is to instrument the callback with an ManualResetEvent that signals each time it is called.  And the ManualResetEven is waited upon in the worker after each call to the ReportProgress handler.  Messier, less modular, but indeed workable.


text:
Q: Как сделать двойной фон при наведении?
Ребята,как сделать такой же эффект при наведении? чтобы под оригинальным изображением был зеленый прямоугольник со смещением, и на нем же(оригинале) было второе изображение и надпись.

A: Используйте псевдокласс :after
Т.е. у вас должен быть написан следующий стиль:
.image-block:hover:after{
    position: absolute;
    z-index: -1;
    content: '';
    width: 100%;
    height:100%;
    top: 10px;
    left: 10px;
    background: 'green';
}

Для этого псевдокласса обязательно указывается content, иначе он не будет отображаться. У image_block - позиционирование relative - это нужно для того чтобы position: absolute для псевдокласса работал относительно этого блока. z-index прописываете отрицательный, чтобы было под картинкой, а картинку - фоном.
Для того чтобы получить рамку - делаете уже псевдокласс :before у которого характеристики как и у :after за парой исключений - z-index положительный, чтобы рамка была сверху, box-sizing:border-box для того, чтобы блок не был больше из-за рамки. Ну и фон ставите прозрачный. И прописываете сам бордер, для бордера.

.image_block{
    position:relative;
    width: 300px;
    height: 180px;
    background: url(https://www.askideas.com/media/18/Angry-Face-Animal-Funny-3D-Picture.jpg);
    background-size: cover;
    background-position: center;
}
.image_block:hover:before{
    position: absolute;
    z-index: 1;
    content: '';
    width: 100%;
    height:100%;
    top: 10px;
    left: 10px;
    background: rgba(0,0,0,0);
    box-sizing:border-box;
    border: 2px solid green;
}
.image_block:hover:after{
    position: absolute;
    z-index: -1;
    content: '';
    width: 100%;
    height:100%;
    top: 10px;
    left: 10px;
    background: #82de82;
}

A: Можно использовать контейнер с фоновым цветом и изображение имеющее абсолютное позиционирование.

.image {
  position: absolute;
  top: 0;
  left: 0;
  background-color: green;
  width: 200px;
  height: 200px;
}

.image:hover,
.image:hover {
  top: -10px;
  left: -10px;
  opacity: 1;
}

.image_text {
  position: absolute;
  top: 0;
  left: 0;
  width: 200px;
  height: 200px;
  opacity: 0;
  line-height: 200px;
  text-align: center;
}

.wrapper {
  position: relative;
  margin: 20px;
  background-color: red;
  width: 200px;
  height: 200px;
}

.wrapper:hover .image,
.wrapper:hover .image_text {
  top: -10px;
  left: -10px;
  opacity: 1;
}

Котик не унывай


text:
Q: Create file with logger I am creating a .log file in a specific path, but I have a problem, create a static class and every time I call the method of writingLike a new .log file is created, it is necessary that the registry always remain on the same file.
Here is the test code:
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

public class Utils {

    public static void escribirLog(String rutaArchivo, String mensaje) {

        Logger logger = Logger.getLogger("MyLog");
        FileHandler fh;

        try {

            fh = new FileHandler(rutaArchivo);
            logger.addHandler(fh);

            SimpleFormatter formatter = new SimpleFormatter();
            fh.setFormatter(formatter);

            logger.info(mensaje);

        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String... args){
        for(int i=1;i<6;i++){
            escribirLog("C:\\rutaLog\\archivo.log", "MensajePrueba"+i);
        }
    }
}

What can I do to always write the log on the same file?

A: You need to construct a FileHandler with the append option enabled to append to an existing log file.
On the line where you construct your fileHandler, change it from
    new FileHandler(fileName)

to
    new FileHandler(fileName, true)

This makes use of this constructor which tells FileHandler to append to the file.

A: You're creating a new FileHandler and adding it to the logger instance every time you call that method. You end up with multiple handlers trying to write to the same filename at the same time, the first one creates the file and locks it so the rest have to use alternate filenames.


text:
Q: sas, proc export, version number, delete xlsx I have noticed that when I add new fields, I have to keep changing the version number on the proc export excel file. Is there SAS code I can run before this to delete that xlsx on the unix server? That would greatly help, therefore I would not need to keep on changing the version number in the file. Thanks for your help.
proc export DATA=OUT.REQ_1_1_19T1
            OUTFILE= "/server/project/users/myid/case/case_WORKING_DATA_V6.xlsx"
            DBMS=xlsx REPLACE ;
                        SHEET = "REQ_1_1";

A: You can refer to this page: http://support.sas.com/documentation/cdl/en/lrdict/64316/HTML/default/viewer.htm#a000245893.htm
Basically it just checks if the file exist and then delete it.


text:
Q: SDL2 program crashes in 64bit mode but works fine in 32bit (compiled using cmake and mingw32-make) cmake works just fine (I guess! I just started using cmake) with no error so does mingw32-make. I suppose compilation and linking is done correctly. But when I open the program (graphics.exe) it immediately stops working. (BTW I'm not missing SDL2.dll) whats wrong?
edit:
It works just fine when using 32bit libraries and 32bit dll and "-m32". BUT it crashes when using 64bit stuff.
CMakeList.txt:
cmake_minimum_required(VERSION 3.8)
project(graphics)

set(CMAKE_C_STANDARD 11)

set(SOURCE_FILES main.c)
set(DEPS ${CMAKE_CURRENT_SOURCE_DIR}/Deps)

include_directories("${DEPS}/include")

add_executable(graphics ${SOURCE_FILES})
#find sdl2 libraries
find_library(SDL2MAIN_LIB SDL2main ${DEPS}/lib)
find_library(SDL2_LIB SDL2 ${DEPS}/lib)

message("SDL2main found at: ${SDL2MAIN_LIB}")
message("SDL2 found at: ${SDL2_LIB}")

target_link_libraries(graphics ${SDL2MAIN_LIB})
target_link_libraries(graphics ${SDL2_LIB})

main.c:
#include <stdio.h>
#include <SDL2/SDL.h>

int main(int argc,char** argv) {
    if(SDL_Init(SDL_INIT_EVERYTHING) == 0)
        printf("SDL2 up and running\n");
    else
        printf("Could not initialize SDL2");
    SDL_Quit();
    return 0;
}


text:
Q: How to Insert (save) data into two table using one form in cakephp? i have two table in DB named users and demos.
users fields has (id, username, password, email, phone)
and demos fields has (id, user_id[forign key], sex, city)

A: First of all, in your form (your view), you must have your data ready. Make sure that every input has the following format
$this->Format->input('Model.field', array(...));

That way you can specify to which model belongs every input.
Now you have two options
If your models have ANY relationship between
Then you can use saveAll() or saveAsociated() methods, just make sure your data has the propper format, for example:
$data = array(
    'Article' => array('title' => 'My first article'),
    'Comment' => array(
        array('body' => 'Comment 1', 'user_id' => 1),
        array('body' => 'Comment 2', 'user_id' => 12),
        array('body' => 'Comment 3', 'user_id' => 40),
    ),
);

In that case you can do a saveAll() or saveAssociated() (for simplicity I would recommend saveAll())
If your models DOESN'T have relationship between
then in your controller you have to import the outer model, like this
$this->loadModel('ImportedModel');

After that you save your current model, and then create and save the outer model.
$this->Model->save($this->request->data);
$this->ImportedModel->save($this->request->data);


text:
Q: How do you set specific properties to a class created by an abstract factory? Is it possible to have concrete factories create concrete classes with type specific parameters for them, using the abstract factory pattern? Or do the different concrete classes created by their respective concrete factories need to to have the same fields?
Ex) In the image below how would you go about to instantiate the WinButton and the OSXButton with different set of arguments given by the client (Application)?

A: One of the approaches to address such problems is to send object parameters. Example, in C# Object is the base class & you can pass parameter of type Object which can take any derived class. In the implementation, this object can be casted back to the desired derived type. Even specific properties can be set this way.

A: This is not easy without having more details. One thing I would do, is to try to pass the arguments to constructor of the concrete factory class. For different arguments you would have to create different factory instance, which might not be the best solution, but as said, this depends on details.
Example:

    GUIFactory factory = new WinFactory(WIN_9x_THEME);
    Button greyButton = factory.createButton();
    factory = new WinFactory(WIN_VISTA_THEME, 50);
    Button semiTransparentButton = factory.createButton();


text:
Q: Sessions in HAProxy vs. Google Analytics Visits I'm seeing numbers almost on a order of magnitude in difference between the total number of sessions served up by HAProxy and the number of Visits recorded in Google Analytics (10x higher number on the HAProxy stats page). Is there something wrong in my configuration or am I misinterpreting?

A: Sessions in HAproxy are TCP sessions. When you open a webpage, you can have 10, 20 or more TCP sessions to download the page and its components (images, css, javascript, etc...).
Session in Google Analytics are Visits. When a client visits your page, he/she download all of the components (so multiple TCP sessions) but that counts for one visit (the call to google analytic is done once when the client execute the corresponding javascript).

A: You've to take into account that is likely that Google Analytics visits are measured using a tracking cookie, so two different visits from the same user & browser in a given amount of time might count as just one visit, whereas HAProxy total sessions counter is, IIRC, the total number of HTTP connections made to your server, so in the previous example HAProxy will show you two total sessions instead of one.


text:
Q: JMeter CSV Data for filename With JMeter files can be sent successfully
Config:

Output (success):

But it doesn't work if changing the file name to a variable.
Attended images you will find file path is set to ${logname}, which can be resolved correctly, but the content-length is incorrect.
After changing the file name to the variable, the http will response  error message, saying "java.io.FileNotFoundException: ulog_5b9139cf-5542-42dc-ae76-7fde3a61c67b_235152af-feb7-4249-a168-12ed4abb426c_0.log (The system cannot find the file specified)".
I think the incorrect content-length led to server fail to read the file content. Is is right? How to fix it? Thanks.
Config:

Output (failure):
The filename is resolved correctly, but content length is incorrect:

A: JMeter is looking for the file in it's Base Dir.
If you look into your jmeter.log file you'll see something like:
2014/03/05 15:52:37 INFO  - jmeter.services.FileServer: Default base='/home/jmeter'
2014/03/05 15:52:37 INFO  - jmeter.services.FileServer: Set new base='/home/jmeter'

This is where JMeter expects file to be located.
So you can either prefix your ${logname} variable with full path to your user's Desktop like
C:\Users\youruser\Desktop\${logname}

Or alternatively change location where JMeter is looking for files via Beahshell Pre Processor as follows:
import org.apache.jmeter.services.FileServer;
FileServer.getFileServer().setBaseDir("C:/Users/youruser/Desktop");

But use it with caution as it may have impact on other relative paths.


text:
Q: ActiveRecord find and only return selected columns edit 2
If you stumble across this, check both answers as I'd now use pluck for this

I have a fairly large custom dataset that I'd like to return to be echoe'd out as json. One part is:
l=Location.find(row.id)
tmp[row.id]=l

but I'd like to do something like:
l=Location.find(row.id).select("name, website, city")
tmp[row.id]=l

but this doesn't seem to be working. How would I get this to work?
thx
edit 1
alternatively, is there a way that I can pass an array of only the attributes I want included?

A: In Rails 2
l = Location.find(:id => id, :select => "name, website, city", :limit => 1)

...or...
l = Location.find_by_sql(:conditions => ["SELECT name, website, city FROM locations WHERE id = ? LIMIT 1", id])

This reference doc gives you the entire list of options you can use with .find, including how to limit by number, id, or any other arbitrary column/constraint.
In Rails 3 w/ActiveRecord Query Interface
l = Location.where(["id = ?", id]).select("name, website, city").first

Ref: Active Record Query Interface
You can also swap the order of these chained calls, doing .select(...).where(...).first - all these calls do is construct the SQL query and then send it off.

A: My answer comes quite late because I'm a pretty new developer. This is what you can do:
Location.select(:name, :website, :city).find(row.id)

Btw, this is Rails 4

A: pluck(column_name)
This method is designed to perform select by a single column as direct SQL query Returns Array with values of the specified column name The values has same data type as column.
Examples:
Person.pluck(:id) # SELECT people.id FROM people
Person.uniq.pluck(:role) # SELECT DISTINCT role FROM people
Person.where(:confirmed => true).limit(5).pluck(:id)

see http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-pluck
Its introduced rails 3.2 onwards and accepts only single column. In rails 4, it accepts multiple columns


text:
Q: how to develop a function finding sum of customers in sql server? How can I write a function to find the total number of customers? User will enter a product name based upon the name and it should return the number of customers for that product. I use adventureworks database.

A: Select count(CustomerID), ProductID from Sales

This assumes there is a customer ID and a Product ID in a related table, sales for example

A: Function based on your query in command.
CREATE FUNCTION fnGetCustomerCount(@ProductKey AS INT)
RETURNS INT AS
BEGIN
    RETURN (SELECT P.EnglishProductName, count(C.FirstName) AS NoOfCustomers
            FROM Dimproduct AS P
                INNER JOIN FactInternetSales AS F ON P.ProductKey = F.ProductKey
                INNER JOIN DimCustomer AS C ON C.CustomerKey = F.CustomerKey
                WHERE P.ProductKey = @ProductKey
            GROUP BY P.EnglishProductName)
END

Creating function in sql is simple. Try to learn on your own.
http://msdn.microsoft.com/en-IN/library/ms191320.aspx


text:
Q: How to verify json array using rest assured? I have a JSON response:
["alice", "jason", "steve", "alex"]

then when use rest assured to test:
when().
       get("/names").
then().
       body(containsInAnyOrder("alice","jason","steve","alex"));

This is not working as I expected, it gives an error:
Expected: iterable over ["alice", "jason", "steve", "alex"] in any order
  Actual: ["alice", "jason", "steve", "alex"]

Also tried with:
when().
       get("/names").
then().
       body(hasItems("alice","jason","steve","alex"));

also not working.
How can I verify a simple JSON array in the response?

A: To save any clicking, you have to supply a redundant string to the body method call:
when().
   get("/names").
then().
   body("", hasItems("alice","jason","steve","alex"));

Additionally, even if you only have one item in your array, you still have to use hasItems rather than hasItem. For example:
when().
   get("/names").
then().
   body("", hasItems("alice"));


text:
Q: how to toggle a filter so that it selects only one item at a time? I have 2 charts. A bar chart and a donut chart (with 3 categories ['A','B','C']).
When I click on a segment of the donut, then I toggle that element's membership in the filter.
e.g. If ['A','B','C'] are selected, and I click on 'A', then I am left with ['B','C']. If I click again on 'A', then I am returned to the full set.
Is it possible to change this behaviour, so that a click, 'de-selects' everything that is not 'A'. So when I click on 'A', I get 'A', and when I click on 'B', I get 'B' etc.
This example achieves this for the rowChart in line 174, but I neither understand the implementation, nor can I reproduce this in my own work.
The relevant code is pasted here:
rowChart.width(340)
        .height(850)
        .dimension(cityDimension)
        .group(cityGroup)
        .renderLabel(true)
        .colors(["#a60000","#ff0000", "#ff4040","#ff7373","#67e667","#39e639","#00cc00"])
        .colorDomain([0, 0])
        .renderlet(function (chart) { // <-this bit onwards does the magic (I think)
            bubbleChart.filter(chart.filter());
        })
        .on("filtered", function (chart) {
            dc.events.trigger(function () {
                bubbleChart.filter(chart.filter());
            });
                    });

A: In d3 if you need to filter some data out of a bigger dataset you could do like so:
var filter = dataset.filter(function (d) { retrurn d.ValueToFilter == "FilterToApply"; });

For example, if you have a fruit dataset, and you just want orange, you do something like so:
var filter = dataset.filter(function (d) { return d.fruit == "orange"; })

This will return only values that have the "orange" property in d.fruit


text:
Q: how to invite same user multiple times using devise invitable I am working with devise invitable gem with rails 3.2 application . My problem is that
I have a user who involves in several groups , so group owner will send invitation to that user . Now I want to implement the functionality to send invitation for the same user from different groups , but devise invitable not allows me to do that ..
Can anyone help me .. thanks in advance ..

A: Devise is an authentication framework. Authentication only handles identifying who somebody is.
If you have a system where a user can get invited to multiple groups, then this is no longer authentication. Instead you need an authorization layer to manage what sort of access each user has.
You would still use Devise to log users into and out of your system but you need to use something like CanCan in order to implement this sort of access control.


text:
Q: List of applications of the Deformation theory of Galois Representations in contexts other that $R=T$ The Deformation theory of Galois representations developed by Mazur has been extensively used in proving that Galois representations with special properties are modular/automorphic through the application of $R=T$ theorems. It has also been used in proving geometric lifting theorems of residual Galois representations (in Serre's conjecture).
Here are four applications of Deformation theory of Galois representations in other contexts that I am aware of:

*

*Its Iwasawa theoretic applications in the papers of Ralph Greenberg.

*Its use in a theorem of Bockle and Khare which gives an alternate proof of de Jong's conjecture which is a conjecture about the finiteness of certain representations of arithmetic fundamental groups of nice curves over a finite field BK. Also related is their proof of Serre's conjecture in the function field case.

*Ohtani and Blondeau construct certain special Galois extensions over $\mathbb{Q}(\mu_{p^{\infty}})$.

*Ochai on deformations of Euler systems.

Are there any other applications missing from this list?


text:
Q: How to replace fragment by checking userinfo list Currently I am in settingsfragment and i have another Fragment called ProfileFragment. Now the problem is, by userinfo list i need to replace fragmnet like. If userinfo==null i should be in settingFragment or i should be in ProfileFragment.
if(userinfolist == null ){
        //login screen
        FragmentTransaction ft= getFragmentManager().beginTransaction();
        ft.replace(R.id.main_frame,settingsFragment);
        ft.commit();
    }else{
        //setting screen
        FragmentTransaction ft=getFragmentManager().beginTransaction();
        ft.replace(R.id.main_frame,profileFragment);
        ft.commit();
    }

But when I execute the code I am getting stuck.

A: if your userinfo list is arraylist then used below code and also make sure your both fragment are define ..
then used below code like  ..
        List<User> userinfolist = new ArrayList<>();
    SettingsFragment settingsFragment = new SettingsFragment();
    ProfileFragment profileFragment = new ProfileFragment();
    if (userinfolist.isEmpty()) {
        //login screen
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.replace(R.id.main_frame, settingsFragment);
        ft.commit();
    } else {
        //setting screen
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.replace(R.id.main_frame, profileFragment);
        ft.commit();
    }

A: You can typecast the layout in which the fragment is getting pushed and then clear the views of the layout using layout.removeAllViews();,and then do the rest for attaching a fragment,but by default you need to attach something i guess

A: You can create a common method to replace fragments which will be more efficient like below method
   public void replaceFragment(Fragment fragment) {
        getSupportFragmentManager().beginTransaction().replace(R.id.main_frame, fragment);
    }

Depending upon your condition, you can call fragment. In your case if userinfolist is a List then you can use below code.
 if(userinfolist!=null&&userinfolist.size()>0)

    replaceFragment(new profileFragment(), false);
    else
        replaceFragment(new SettingFragment(),false);

A: Try using below code piece, as initializing FragmentManager & FragmentTransaction once is sufficient.
    FragmentManager fm = getFragmentManager();
    FragmentTransaction fragmentTransaction = fm.beginTransaction();

    List<User> userinfolist = new ArrayList<>();

    if (userinfolist == null) {
        SettingsFragment settingsFragment = new SettingsFragment();
        fragmentTransaction.replace(R.id.main_frame,settingsFragment);

    } else {
        ProfileFragment profileFragment = new ProfileFragment();
        fragmentTransaction.replace(R.id.main_frame,profileFragment);
    }
    fragmentTransaction.commit();


text:
Q: Initial Heap size allocated to a C++ program on UNIX What is the initial heap size alloted typically to a C++ program running on UNIX based OS ?
How is it decided by the g++ compiler if at all it has a role to play in this regard ?

A: For C++, no matter what the platform, the heap is almost always extended dynamically by asking the OS for more memory as needed.  On some embedded platforms, or some very old platforms this may not be true, but then you probably have a really good idea how much heap you have because of the nature of the environment.
On Unix platforms this is doubly true.  Even most Unix embedded platforms work this way.
On platforms that work like this, the library usually doesn't have any kind of internal limit, but instead relies on the OS to tell it that it can't have any more memory.  This may happen well after you have actually asked for more memory than is available though for a variety of reasons.
On most Unix systems, there is a hard limit on how much total memory a process can have.  This limit can be queried with the getrlimit system call.  The relevant constant is RLIMIT_AS.  This limit governs the maximum number of memory pages that can be assigned to a process and directly limits the amount of heap space available.
Unfortunately that limit doesn't directly say how much heap you can use.  Memory pages are assigned to a process as a result of mmap calls, to hold the program code itself, and for the process' stack.
Additionally, this limit is frequently set well in excess of the total memory available to the whole system if you add together physical memory and swap space.  So in reality your program will frequently run out of memory before this limit is reached.
Lastly, some versions of Unix over-assign pages.  They allow you to allocate a massive number of pages, but only actually find memory for those pages when you write to them.  This means your program can be killed for running out of memory even if all the memory allocation calls succeed.  The rationale for this is the ability to allocate huge arrays which will only ever be partially used.
So, in short, there isn't a typical size, and no good way to find out what the size really is.

A: The heap is extended dynamically by asking the OS for more memory as needed.
It's not determined by the compiler, exactly, but by the library.
It is more typical to fix the size of the heap in dynamic languages with GC. In C and C++, it is a simple matter to ask the OS for more memory, since it is obvious when you need it. As a consequence, the initial heap size matters very little and is just an implementation decision on the part of the allocation library.

A: In short, there is not definit way to configure the heap size. But we do have some way to impact the heap memory size , as the heap memory size is part of the total availabe memory.
You can get the total amount of availabe memory in the sytem by :
 cat /proc/meminfo  | grep CommitLimit
 CommitLimit:    498080 kB

This CommitLimit is caculated with following formula:
      CommitLimit = ('vm.overcommit_ratio' * Physical RAM) + Swap
Supposing the swap is zero, by setting the overcommit_ratio you can configure total availble memory. You can set the overcommit_ratio by :
sysctl -w vm.overcommit_ratio=60

And it is important to notice that this limit is only adhered to if strict overcommit accounting is enabled (mode 2 in 'vm.overcommit_memory'). . This could be set by :
 sysctl -w vm.overcommit_memory=2

Here is the kernel document that explain this well.

A: you could try to write an small program with a while(true) loop. after run it, "cat /proc/{pid}/maps" you'll know its initial heap size.


text:
Q: Is it possible to switch variants in the value of a mutable reference to an enum? Is it possible to switch variants in the value of a mutable reference (&mut E<T>) without additional constraints on T, and without resorting to unsafe code?
That is, given an enum:
enum E<T> {
    VariantA(T),
    VariantB(T)
}

What is the correct way of writing this:
let x: E<???> = E::VariantA(??);
change_to_variant_b(&mut x);
assert_eq!(x, E::VariantB(??));

A: I am going to go on a limb here and say No.

It is possible with just a minor change to the signature though:
fn change_to_variant_b<T>(e: E<T>) -> E<T> {
    match e {
        E::VariantA(t) => E::VariantB(t),
        E::VariantB(t) => E::VariantB(t),
    }
}

It is possible using unsafe:
fn change_to_variant_b<T>(e: &mut E<T>) {
    use std::ptr;

    unsafe {
        match ptr::read(e as *const _) {
            E::VariantA(t) => ptr::write(e as *mut _, E::VariantB(t)),
            E::VariantB(t) => ptr::write(e as *mut _, E::VariantB(t)),
        }
    }
}

It is possible with additional bounds (Default, or Clone):
fn change_to_variant_b<T: Default>(e: &mut E<T>) {
    match std::mem::replace(e, E::VariantA(T::default())) {
        E::VariantA(t) => e = E::VariantB(t),
        E::VariantB(t) => e = E::VariantB(t),
    }
}

A: As an alternative for this particular case, you could consider changing to a struct with a T and a plain enum:
struct Outer<T> {
    val: T,
    kind: Inner,
}

impl<T> Outer<T> {
    fn promote_to_b(&mut self) {
        self.kind.promote_to_b()
    }
}

enum Inner {
    VariantA,
    VariantB,
}

impl Inner {
    fn promote_to_b(&mut self) {
        if let Inner::VariantA = *self {
            *self = Inner::VariantB;
        }
    }
}

A:
is it possible to switch variants in the value of a mutable reference

As Matthieu M. said, the general answer is "no". The reason is that doing so would leave the enum in an indeterminate state, which would allow accessing undefined memory, which would allow breaking Rust's safety guarantees. As an example, let's pretend that this code compiled without error:
impl<T> E<T> {
    fn promote_to_b(&mut self)  {
        if let E::VariantA(val) = *self {
            // Things happen
            *self = E::VariantB(val);
        }
    }
}

The problem is once you've moved the value from self into val, what should happen to the memory representing T inside self?
If we copied the bits and then a panic occurred in "Things happen", the destructor for both val and the T inside self would run, but since these point at the same data, this would lead to a double free.
If we didn't copy the bits, then you couldn't safely access the val inside "Things happen", which would be of marginal usefulness.

The by-value solution works because the compiler can track who is supposed to call the destructor: the function itself. Once you are inside the function, the compiler knows which specific lines might need to free the value and properly calls them in case of panic.
The Clone or Default solution works because you never move the value out of the original enum. Instead, you can replace the original enum with a dummy value and take ownership of the original (using Default) or duplicate the entire original value (using Clone).

The replace_with RFC (#1736) proposed to add a method that would allow this to work while ensuring that proper memory semantics were upheld, but that RFC was not accepted.


text:
Q: didRegisterForRemoteNotificationsWithDeviceToken is not calling after two or three execution In app , i am trying to implement push notification , supports iOS 7 in xcode 7.3 .
after couple of running , now the didRegisterForRemoteNotificationsWithDeviceToken is not called , this is a very strange issue , the device that im running has iOS 9.3.2
here is my functions in appdelegate
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.

    // self.registerForPushNotificationSystem(application)

//        let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
//        UIApplication.sharedApplication().registerUserNotificationSettings(settings)

    let notificationTypes: UIUserNotificationType = [UIUserNotificationType.Alert, UIUserNotificationType.Badge, UIUserNotificationType.Sound]
    let pushNotificationSettings = UIUserNotificationSettings(forTypes: notificationTypes, categories: nil)

    application.registerUserNotificationSettings(pushNotificationSettings)
    application.registerForRemoteNotifications()

    return true
}

func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
    if notificationSettings.types != .None {
        application.registerForRemoteNotifications()
    }
}

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
    let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
    var tokenString = ""

    for i in 0..<deviceToken.length {
        tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
    }

    print("Device Token:", tokenString)
    WebClient.sharedInstace.resgisterNotification(tokenString)
}

what might be the issue  this was perfectly working fine yesterday


text:
Q: Expected an assignment or function call and instead saw an expression. (W030) I know there are a lot of similar questions, and I read some of them. I even re-read the MDN of the ternary operator again, but I still don't understand why JSHint shows me the aforementioned error for the following code:
passHasNumber ? strength++ :
        passHasTwoNumbers ? strength++ :
        passHasCapitalLetter ? strength++ :
        passHasTwoCapitalLetters ? strength++ :
        passHasWhitespace ? strength++ :
        passHasSymbols ? strength++ :
        passVeryBad.innerHTML = `Only lowercase letters, huh?
        You can do better than that!`; // error appears here

I prefer not having code with errors, so I would appreciate a different take on this code that is as clean, if possible; I don't like to comment the code with the /* jshint -W030 */ comment.
P.S.: I get the same error on the first line of my file, which is the use strict statement, but with back ticks. How to solve that?

A: You're abusing the conditional operator as an if statement - JSHint is seeing the orphaned expression and complaining about it. Use if / else instead:
if (passHasNumber || passHasTwoNumbers || passHasCapitalLetter || passHasTwoCapitalLetters || passHasWhitespace || passHasSymbols) {
  strength++;
} else {
  passVeryBad.innerHTML = `Only lowercase letters, huh?
  You can do better than that!`; // error appears here
}

You should only use the conditional operator when you need to use the expression it evaluates to in something, for example:
const foo = condition ? 'foo' : 'error!';

But, it sounds like you might want to increment strength for every truthy boolean, which makes a bit more sense than incrementing strength only once, in which case:
const strength = passHasNumber + passHasTwoNumbers + passHasCapitalLetter + passHasTwoCapitalLetters + passHasWhitespace + passHasSymbols;
if (strength === 0) {
  passVeryBad.innerHTML = `Only lowercase letters, huh?
  You can do better than that!`; // error appears here
}


text:
Q: Optimal way to isolate an error I do not know the technical name of this problem but it goes something like this:
I have N modules and n of them are faulty. I can test for faults m modules at a time (testing m modules at once takes the same time as testing 1 module at a time)
What is the best strategy?
What if n is not known but it is defined by a probability function?


text:
Q: PHP: Switch weird behavior
Possible Duplicate:
PHP expresses two different strings to be the same

I have a problem understanding what's causes this weird behavior in a switch case instruction.
The code is this:
<?php
$myKey = "0E9";

switch ($myKey) {
    case "0E2":
        echo "The F Word";
        break;
    case "0E9":
        echo "This is the G";
        break;
    default:
        echo "Nothing here";
        break;
}
?>

The result of this instruction should be This is the G
Well, not so. always returns The F Word
If we reverse the 0E9 left instructions for the beginning and try to find the value 0E2
<?php
$myKey = "0E2";

switch ($myKey) {
    case "0E9":
        echo "The G String";
    break;
    case "0E2":
        echo "The F Word";
        break;
    default:
        echo "Nothing here";
        break;
}
?>

Now returns always This is the G
0E2 and 0E9 values are not interpreted as text? Those Values are reserved?
Someone can explain this behavior?

A: "0E2" == "0E9" is true because they are numerical strings.
Note: switch use loose comparision.
Check this question: PHP expresses two different strings to be the same.

A: Numeric strings such as these are equal to each other .. always.  Unfortunately, there is no way to force an equivalence comparison via switch.  You just have to use if:
if ($myKey === '0E9') {
   echo 'g';
}
else if ($myKey === '0E2') {
   echo 'f';
}
else {
   echo "Nothing here";
}

You could also trim the leading zero, I suppose.


text:
Q: How to perform an HTTP redirect (302) using Rack? I am messing around with my first Rack application (this is just for experimentation).
When a call comes in I do something like this:
class Application
    def call(env)
      # Totally ignore favicons for the time being
      if env['PATH_INFO'] == '/favicon.ico'
        return [ 404, {'Content-Type' => 'text/html'}, [] ]
      elsif env['PATH_INFO'] == '/'
        return [ 302, {'http-equiv' => "refresh", 'content' => "2;url=http://google.com"}, [] ]
      end
      ...

I know this is horrible... but, again, this isn't a serious project.
I'm trying to figure out how to do the redirect. What I have does not work. Basically, when you hit / on my site I want to redirect that require to google.com.

A: Here is working app with re-direct to Google
require 'rack'
require 'rack/server'

class HelloWorld
  def response
    [ 302, {'Location' =>"http://google.com"}, [] ]
  end
end

class HelloWorldApp
  def self.call(env)
    HelloWorld.new.response
  end
end

Rack::Server.start :app => HelloWorldApp


text:
Q: Using Knockout bindings to return string I'm trying to use Knockout to make the usage for an infinite scroll plugin I am using a bit nicer, but struggling with how to bind it. Not sure if it's even possible in the current form.
The scroller calls a data function which loads the next block of data via AJAX. It then calls a factory function that converts that data into HTML, and it then loads the HTML into the container, and updates its internal state for the current content size.
I'm stuck on the fact that it expects an HTML string.
What I want to do is this:

And my binding, which I'm completely stuck on, is this - which is currently just hardcoding the response, obviously - that's the bit I need to replace with the template binding:
ko.bindingHandlers.infiniteScroll = {
    init:
        function(el, f_valueaccessor, allbindings, viewmodel, bindingcontext)
        {
            if($.fn.infiniteScroll)
            {
                // Get current value of supplied value
                var field = f_valueaccessor();
                var val = ko.unwrap(field);

                var options = {};

                if(typeof(val.get) == 'function')
                    options = val;
                else
                    options.get = val;

                options.elementFactory = options.elementFactory ||
                    function(contentdata, obj, config)
                    {
                        var s = '';

                        for(var i = 0; i < contentdata.length; i++)
                        {
                            var o = contentdata[i];

                            // NEED TO REPLACE THIS
                            s += '

Item ' + o.page + '.' + i + ' ' + o.text + '

';
                        }

                        return s;
                    };

                $(el).infiniteScroll(options);

                return { controlsDescendantBindings: true };
            }
        }
};

contentdata is an array of objects e.g. [ { page:1, text:'Item1' }, { page:1, text:'Item2' } ... ]
Page sizes may differ between calls; I have no way of knowing what the service will return; it is not a traditional page, think of it more as the next block of data.
So in the element factory I want to somehow bind the contentdata array using the markup in .scroller as a template, similar to foreach, then return that markup to the scroller plugin.
Note that I can modify the infinite scroller source, so if if can't be done with strings, returning DOM elements would also be fine.
I just can't get how to a) use the content as a template, and b) return the binding results to the plugin so it can update its state.
NOTE: The page I eventually intend to use this is currently using a foreach over a non-trivial object model; thus the need to use the same markup; it needs to be pretty much a drop in replacement.

A: I have actually found out how to do it using the existing scroller following this question: Jquery knockout: Render template in-memory
Basically, you use applyBindingsToNode(domelement, bindings), which will apply KO bindings to a nodeset, which importantly does not have to be connected to the DOM.
So I can store the markup from my bound element as the template, then empty it, then for the element factory, create a temporary node set using jQuery, bind it using the above function, then return the HTML.
Admittedly, this would probably be better off refactored to use a pure KO scroller, but this means I can continue to use the tested and familiar plugin, and the code might help people as this seems to be quite a common question theme.
Here is the new code for the binding (markup is as above).
ko.bindingHandlers.infiniteScroll = {
    init:
        function(el, f_valueaccessor, allbindings, viewmodel, bindingcontext)
        {
            if($.fn.infiniteScroll)
            {
                // Get current value of supplied value
                var field = f_valueaccessor();
                var val = ko.unwrap(field);

                var options = {};

                if(typeof(val.get) == 'function')
                    options = val;
                else
                    options.get = val;

                var template = $(el).html();

                options.elementFactory = options.elementFactory ||
                    function(contentdata, obj, config)
                    {
                        // Need a root element for foreach to use as a container, as it removes the root element on binding.
                        var newnodes = $('
' + template + '
');

                        ko.applyBindingsToNode(newnodes[0], { foreach: contentdata });

                        return newnodes.html();
                    };

                $(el)
                    .empty()
                    .infiniteScroll(options);

                return { controlsDescendantBindings: true };
            }
        }
};


text:
Q: Use Route component and Route children in same route I am a beginner to react js and now I am practicing routes but stuck in an nested routes error below:

You should not use Route component and Route children in the same route; <Route children> will be ignored.

By above it can be seen route and children component cannot be used in the same route which I had, so how can I fix my below code so it can work:
  const About=(props)=>(

    {props.children}

About

  );

 const Cityimage=()=>(

In City

 );

 const Sportsimage=()=>(

In Sports

 );

ReactDOM.render(

<Router>
    <Switch>
        <Route path="/app" component={App} />

        <Route  path="/about" component={About}>
             <Route  path="city" component={Cityimage}/>
             <Route  path="sport" component={Sportsimage}/>
        </Route>

    </Switch>
</Router>
   ,document.getElementById('root'));

I have a parent route About and its two children route city and sport. How can I fix my code?

A: can you tried?
<Route  path="/about" component={About}/>
<Route  path="/about/city" component={Cityimage}/>
<Route  path="/about/sport" component={Sportsimage}/>


text:
Q: Классы C++, не понимаю выполнение строки кода Есть следующий код (фрагмент, который предоставил преподаватель):
int p::*ip2=&p::pub2;

известно, что p - это класс, pub2 переменная в классе.
Не понимаю значение операции :: , а также чем отличается при обращении к классу . от ->.

A: ip2 - адрес переменной типа int, но не простой, а члена класса p.
Ну, а p::pub2 - это и есть эта переменная, адрес которой помещается в ip2.
Операция :: - разрешение области видимости. Грубо говоря, где эта переменная объявлена. Так, ::p - имя глобальной переменной p - перед :: ничего нет.
Если есть объект класса c, и поле x, то к нему обращаются как к c.x, так? А если есть указатель на объект класса p, то как нам получить сам объект? как *p. Тогда обращение будет иметь вид (*p).x - и, чтоб не мучиться со скобочками и звездочками, это же можно записать как p->x.


text:
Q: Intellij generated Ant Build File, doesn't build jar I am trying to create a jar using the Intellij Generated Ant Build.

*

*I am using Intellij 12.1.4

*I am using Java 1.6.0_51 (Default on Mac).

When I create the ant build I am using the following options:

*

*Generate single-file ant build

*Overwrite previously generated files

*Use JDK definitions from project files

*Inline runtime classpaths

I then run the following command on my command line
ant -f buildfile.xml

It looks like it works on the command line.  There are a few notes, but no errors.  When it finishes it says BUILD SUCCESSFUL.  However a .jar is never created.
I found this link:  Ant build doesn't make jar file which seems to be my problem.  However, I can't seem to figure out how to create a "release" build file from Intellij.  I copied my current ant build file and renamed it "build.xml" and ran the command ant release.  When I ran that command I got the following error:
BUILD FAILED
Target "release" does not exist in the project "MyProject"
Any further help or ideas for next steps would be great.

A: I was able to figure it out.
I had to go to open the Project Settings (F4) and then went to Artifacts.  That allowed me to set the settings to create the jar when I ran "ant -f buildfile.xml"


text:
Q: Javascript method which iterates an object's properties I have a question about which method is used to iterate an object's properties.
I have two identical objects.  The first object is main, and the second object is clone.
There is a lot of nesting. I don't have time to write all of the  for, for in, forEach loops, because there is a lot of nesting.
How can I replace the value of each property of clone from main?  Does such a method already exist?

A: You can do something like that
function fillClone(source,target)
{
    if(typeof source == "array" && typeof target != "array")
       target = [];
    else if(typeof source == "object" && typeof target != "object")
       target = {};
    for (var i in source) {
       if(typeof i == "object" || typeof i == "array")
          fillClone(source[i],target[i]);
       else
          target[i] = source[i];
    }
    return target;
}


text:
Q: Autofac setup with Owin Web API in a AppBuilder.Map block with mixed MVC I want to move my Web API code into a .Map("/api" inner=>) block so that I can set the following configuration to not affect the MVC parts of my app.

config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(Startup.OAuthBearerOptions.AuthenticationType))

So I tried to put the web api logic in to the .Map but now I broke Autofac and it will no longer resolve dependencies.   here is what I had originally.

public void Configuration(IAppBuilder app)
{
    var config = new HttpConfiguration();
    var builder = new ContainerBuilder();
    BuildContainer(builder);
    this._container = builder.Build();
    // Middlewares
    app.UseAutofacMiddleware(this._container); //should be the first middleware added to IAppBuilder
    app.UseAutofacMvc();
    // WebApi config
    config.DependencyResolver = new AutofacWebApiDependencyResolver(this._container);

    //MVC
    DependencyResolver.SetResolver(new AutofacDependencyResolver(this._container));
    this.ConfigureAuth(app, _container.Resolve());
    WebApiConfig.Register(config);
    app.UseAutofacWebApi(config);
    app.UseWebApi(config);
}

Here is what I tried to do but failed with the web api no longer resolving the autofac dependencies.

public void Configuration(IAppBuilder app)
{
    var builder = new ContainerBuilder();
    BuildContainer(builder);
    this._container = builder.Build();
    // Middlewares
    app.UseAutofacMiddleware(this._container); //should be the first middleware added to IAppBuilder
    app.UseAutofacMvc();
    //MVC
    DependencyResolver.SetResolver(new AutofacDependencyResolver(this._container));
    this.ConfigureAuth(app, _container.Resolve());

    app.Map(
        "/api",
        inner =>
            {
            var config = new HttpConfiguration();
            config.DependencyResolver = new AutofacWebApiDependencyResolver(this._container);
            WebApiConfig.Register(config);
            //inner.UseAutofacMiddleware(this._container); //should be the first middleware added to IAppBuilder
            inner.UseAutofacWebApi(config); //Web.API enable lifetime scope created during the OWIN request to extend into WebAPI.
            inner.UseWebApi(config);
        });
}

Also If I'm doing anything that looks wrong please let me know.

A: My issue was WebApiConfig was still being registered in

protected void Application_Start()
{
  GlobalConfiguration.Configure(WebApiConfig.Register);
}

Removing this and autofac wired up everything great under the Map.  Strangely having that register there without the map allowed everything to work (perhaps there were other side effects unknown to me).
Final Config I used:

public void Configuration(IAppBuilder app)
{
        var builder = new ContainerBuilder();
        BuildContainer(builder);
        this._container = builder.Build();
        // OWIN Middlewares
        app.UseAutofacMiddleware(this._container); //should be the first middleware added to IAppBuilder
        app.UseAutofacMvc(); // Autofac MVC Integration -- http://alexmg.com/owin-support-for-the-web-api-2-and-mvc-5-integrations-in-autofac/
        //MVC
        DependencyResolver.SetResolver(new AutofacDependencyResolver(this._container)); //TODO: Still needed with OWIN?
        //app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
        this.ConfigureAuth(app, _container.Resolve());
        //WEB API config - Make Web Api urls use the config, avoiding ASP.NET MVC from inheriting the HttpConfig.
        app.Map(
            "/api",
            inner =>
                {
                var config = new HttpConfiguration();
                config.DependencyResolver = new AutofacWebApiDependencyResolver(this._container);
                WebApiConfig.Register(config);
                inner.UseAutofacWebApi(config); //Web.API enable lifetime scope created during the OWIN request to extend into WebAPI.
                inner.UseWebApi(config);
            });
}