text:
Q: How can i generate soap service from wsdl in spring boot? I am trying to create a soap service in soap1.2.
So I am using spring boot and JAX-WS.
I have tried using these tutorials :
https://www.baeldung.com/jax-ws
https://glenmazza.net/blog/entry/switch-soap11-to-soap12
https://examples.javacodegeeks.com/enterprise-java/jws/jax-ws-annotations-example/
However, nothing i tried works. My manually-created service doesn't work.
Is there a way to generate the service automatically from WSDL, along with the request and response classes ?

A: After a long google search, i have found a maven plugin that does just that :
<plugin>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-codegen-plugin</artifactId>
    <version>3.2.7</version>
    <executions>
        <execution>
            <id>generate-sources</id>
            <phase>generate-sources</phase>
            <configuration>
                <sourceRoot>${project.build.directory}/generated-code/mysoapservice</sourceRoot>
                <wsdlOptions>
                    <wsdlOption>
                        <wsdl>${basedir}/src/main/resources/wsdl/my_soap_service.wsdl</wsdl>
                        <extraargs>
                            <extraarg>-all</extraarg>
                        </extraargs>
                    </wsdlOption>
                </wsdlOptions>
            </configuration>
            <goals>
                <goal>wsdl2java</goal>
            </goals>
        </execution>
    </executions>
</plugin>

This worked for me. Maybe it will fork for someone else too.


text:
Q: Is it possible to have text that is as wide as the title or smaller, but not larger? I need a container, that grows with the width of the title (so the title always needs just one line) but it may not grow with the remaining text content, which is supposed to break lines as usual.
Here is what I am thinking about:

The container grows in width if the title grows, but the remaining text does not make the container grow.
Does anyone know, how that could be done?
I tried this with flex grow properties but couldn't get it to work.

redpajama_set_name: RedPajamaStackExchange


text:
Q: AS3- create a loopable random path in 3D space I'm trying to optimize a 3d demo by populating a lookup table with 3d points(Vector 3D http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/geom/Vector3D.html) which I will then access later on.
These 3D points will define a random and loopable path in 3D space.
Does anyone know a way of achieving this?
I was thinking modifying the Greensock Bezier tween to create a bezier in 3d space, and then somehow grabbing the xyz values of the resulting tween.

A: Ok, you'll need to do two things:

*

*Create a looped 3D cubic bezier curve from several fragments

*Create a custom tween function that will take your object as a target, your bezier loop as a path and your total loop time.
One fragment of your cubic bezier curve will always take 4 vertices, a full loop must contain at least 2 segments, so you will need to randomly create at least 7 vertices. The number of vertices will always be 3 * NumberOfSegments + 1, but we will store just 3 * NumberOfSegments as the first vertex will be equal to the last one
Most simple case (2 segments, 6 vertices):
...
private function generateRandomPoints():Vector<Vector3D>
{
    var resultingVector:Vector<Vector3D> = new Vector<Vector3D>();
    for(var i:int = 0; i < 6; i++)
    {
        var x:Number = Math.random() * 10;
        var y:Number = Math.random() * 10;
        var z:Number = Math.random() * 10;
        var currentPoint3D:Vector3D = new Vector3D(x, y, z);
        resultingVector.push(currentPoint3D);
    }
    return resultingVector;
}
...

Now when we have our path, we can parse it to get this tweening effect. You can either call this function every time you'll need new coordinates (but you'll need to store your initial time somewhere), or create a tweener object that will handle everything for you. I'll show the most basic example - autonomous function:
public static function getNextCoordinates(loopStartTime:int, totalLoopTime:int, path:Vector.<Vector3D>):Vector3D
    {
        var resultingPoint:Vector3D = new Vector3D();
        var passedTime:int = getTimer() - loopStartTime;

        //Total passed ratio
        var passedRatio:Number = passedTime / totalLoopTime;
        var totalSegments:int = path.length / 3;

        var totalTimePerSegment:Number = totalLoopTime / totalSegments;

        //So it can loop forever
        while (passedRatio > 1)
        {
            passedRatio -= 1;
        }
        //Let's find our current bezier curve segment number
        var currentSegment:int = Math.floor( passedRatio * totalSegments);
        var currentSegmentRatio:Number = (passedTime - currentSegment * totalTimePerSegment) / totalTimePerSegment;
        //It can be optimized here
        while (currentSegmentRatio > 1)
        {
            currentSegmentRatio -= 1;
        }

        var startingIndex:int = currentSegment * 3;
        //our four path vertices
        var point0:Vector3D = path[startingIndex];
        var point1:Vector3D = path[startingIndex + 1];
        var point2:Vector3D = path[startingIndex + 2];

        //if it's a last segment, we need to "connect" to the first vertex
        if (startingIndex + 3 >= path.length)
        {
            var point3:Vector3D = path[0];
        }
        else
        {
            point3 = path[startingIndex + 3];
        }
        //At last, we find our coordinates
        var tempRatio:Number = 1 - currentSegmentRatio;
        resultingPoint.x = tempRatio * tempRatio * tempRatio * point0.x + 3 * tempRatio * tempRatio * currentSegmentRatio * point1.x + 3 * tempRatio * currentSegmentRatio * currentSegmentRatio * point2.x + currentSegmentRatio * currentSegmentRatio * currentSegmentRatio * point3.x;
        resultingPoint.y = tempRatio * tempRatio * tempRatio * point0.y + 3 * tempRatio * tempRatio * currentSegmentRatio * point1.y + 3 * tempRatio * currentSegmentRatio * currentSegmentRatio * point2.y + currentSegmentRatio * currentSegmentRatio * currentSegmentRatio * point3.y;
        resultingPoint.z = tempRatio * tempRatio * tempRatio * point0.z + 3 * tempRatio * tempRatio * currentSegmentRatio * point1.z + 3 * tempRatio * currentSegmentRatio * currentSegmentRatio * point2.z + currentSegmentRatio * currentSegmentRatio * currentSegmentRatio * point3.z;

        return resultingPoint;
    }

You can extend this function to be a part of the tweening object.
I've tested it in 2D space and it perfectly loops sprite's movement along a random multi-segment bezier curve
Cheers!


text:
Q: How to get a css property of an externally styled element with javascript lets say i have a div style externally like this
 .box{
  background: red;
 }

then maybe in javascript i want to toggle the background color, so i have to check first if it has a partcular background color before applying
var box = document.querySelector('.box');

if(box.style.background=='red'){

box.style.background='pink';
}else{
box.style.background='red';

}

NOTE: i am not using this for development just a js student
To add a tiny question, if i want to apply css transition to the background change how will that be applied.
the below code works though but i feel there is a cleaner way
if(!box.style.background){ //this is because background property is null when reading from external css

    box.style.background='pink';

}else{

    box.style.background="";
}

but for the transition i tried applying the transition
 box.style.WebkitTransition='background 0.5s easeout';

but didnt transits

A: To get the computed style of an element (e.g., with stylesheets applied), you use getComputedStyle:
var box = /*...get a specific element...*/;
var style = getComputedStyle(box);
// Use the properties on `style`, which are like the ones on `element.style`

On older IE, you use the currentStyle property of the element instead. You can partially polyfill getComputedStyle like this:
if (!window.getComputedStyle) {
    window.getComputedStyle = function(element, pseudoElement) {
        if (pseudoElement) {
            throw "The second argument for getComputedStyle cannot be polyfilled";
        }
        return element.currentStyle;
    };
}

Example:

if (!window.getComputedStyle) {
  window.getComputedStyle = function(element, pseudoElement) {
    if (pseudoElement) {
      throw "The second argument for getComputedStyle cannot be polyfilled";
    }
    return element.currentStyle;
  };
}

var foo = document.getElementById("foo");
var style = getComputedStyle(foo);
if (style) {
  snippet.log("Current color of #foo is: " + style.color);
}
.box {
  color: green;
}

This is a box


text:
Q: Novel about a society returning from deep underground finding robot inhabitants Science fiction book about human society living deep underground Earth's surface; very deep for so long nobody knows there is possibly something of interest in the upper levels, until some make their way up to the surface for the first time. published in around the 1970's. They are astounded by the 'Huge spaces, ocean, moon, immaculate landscape and very friendly robot inhabitants of the Earth's surface that has not seen Humans for thousands of years.
Read this in late seventies I think, and would love to know the Author and Title so that I can track it down. Don't think there is a film version. Love to get the book. Anybody old enough to have read it will surely (hopefully) have a better memory than me. Many thanks, in anticipation.

A: The querent has confirmed that the book is Kuldesak by Richard Cowper, published in 1973, as suggested by Danny3414 in the comments.
Thanks for the replies folks. Danny 3414 hit the jackpot, Richard Cowper wrote Kuldesak, published 1973. Again, much appreciated. – davepj

Earth, 2000 years after the final holocaust which drove man deep underground; a ghostly, deserted planet peopled only by the diligent robots who, century after century, silently harvest grain which no man will eat.
Up into this eerie world comes Mel, a questioning young Roamer who has disobeyed the Law which says he must never venture into or beyond the Lost Levels. Together with three companions, and a companion not of this Earth, Mel takes on the awesome task of freeing human beings from the tyranny imposed on them by their remote ancestors; of justifying the agonized cry of Barney as he died in a Forbidden Level: "I am a man! Everything is for man!"

Edit by Danny3414
I've been looking at the 'blurb' posted above and am editing in a bit more info (I owned this book for a couple of years and read it at least three times) as there is very little available online.
No real spoilers, this is world building and is given in first two chapters:-
The 'holocaust' referred to wasn't quite like that, with humanity taking refuge underground, instead man had been forced to move there to free up valuable land for crops.
Then the worldwide controlling computer decided there was too many people so had itself a Skynet /" I have no mouth but I must scream" moment and wiped out most of mankind.
It kept a million or so tame people ("Plants" so called because of metal implants in their temples) to maintain systems at main globular node points.
It also kept a few thousand free humans ("Roamers" who, as the name implies, acted like gypsies and went from Plant town to Plant town in small clans) to ensure a genetic mix.
The young Roamers congregate whenever an area is having a "Plant High", this is electronic pleasure waves sent out from the computer to the implants, the Plant people sit around moaning in delight and the women don't realise they are being sexually molested by these young men...until a few months later when they develop a bump!


text:
Q: Proving two domains are not conformally equivalent Let $D$ be the open unit disk. Show that $D - [-1/2, 1/2]$ and $D - \{0\}$ are not conformally equivalent.
Thoughts so far: I'm not sure where to begin, but a hint would most helpful to get me started.

A: Any  bounded one-to-one analytic function  $\phi$ on  $ D \backslash \{0\}$
has a removable singularity at $0$.  Thus there is $\widetilde{\phi}$ analytic on $D$ whose restriction to $D \backslash \{0\}$ is $\phi$.
Now $\widetilde{\phi}$ must also be one-to-one, because if $\widetilde{\phi}(0)  = w_0 \in \phi(D)$ there would be at least two members of
$\phi^{-1}(w)$ for all $w$ in a deleted neighbourhood of $w_0$.   Moreover, $\widetilde{\phi}(D) = \phi(D) \cup \{\widetilde{\phi}(0)\}$ is open.
So any
bounded domain $\tilde{D}$ conformally equivalent to $D \backslash \{0\}$ has the property that $\tilde{D} \cup \{w\}$ is open for some $w \notin \tilde{D}$.  This is not the case for $D \backslash [-1/2,1/2]$.


text:
Q: values received are not the desired result I have a jagged array called gMul and in it are 4 arrays, i want to take the first one and all the others equal to that array shifted n times (n represents their index in the jagged array)
the last array was equal to the array before it for some reason, for example:
gMul[0] = new byte[] {2 , 3 , 2 , 2}

then the result should be
gMul[0] - {2 , 3 , 2 , 2}
gMul[1] - {2 , 2 , 3 , 2}
gMul[2] - {2 , 2 , 2 , 3}
gMul[3] - {3 , 2 , 2 , 2}

but for some reason the result I get is this:
gMul[0] - {2 , 3 , 2 , 2}
gMul[1] - {2 , 2 , 3 , 2}
gMul[2] - {2 , 2 , 2 , 3}
gMul[3] - {2 , 2 , 2 , 3}

my code:
for (int i = 1; i < gMul.GetLength(0); i++)
{
    //shift is a function that shifts the given array one item to the right
    //and returns an array of bytes
    byte[] shifted = shift(gMul[i - 1]);
    gMul[i] = shifted;
}

public byte[] shift(byte[] row)
    {

        byte tmp = row[0];
        for (int i = row.Length - 1; i >= 0; i--)
        {
            row[(i + 1) % row.Length] = row[i];

        }
        row[1] = tmp;
        return row;
    }

A: Problem is in shift algorithm. Correct algorithm is this
public byte[] ShiftRight(byte[] row)
{
    var newRow = new byte[row.Length];
    byte tmp = row[row.Length - 1];
    for(int i = row.Length - 1; i > 0; i--)
    {
       newRow[i] = row[i - 1];
    }
    newRow[0] = tmp;
    return newRow;
}

Or simply use Array.Copy.
public byte[] ShiftRight(byte[] row)
{
    var newRow = new byte[row.Length];
    byte tmp = row[row.Length - 1];
    Array.Copy(row, 0, newRow, 1, row.Length - 1);
    newRow[0] = tmp;
    return newRow;
}


text:
Q: Entity Framework and pre-existing models mapping I already have a project with all of my models in it.
I want to use EF 6 to call stored procs.
And when the data is passed to and from the stored proc, I want EF to handle the object model mapping
Is that possible?
I am using MVC.net and c#
Thanks!

A: Absolutely possible with EF6! See this tutorial (scroll past the bit on async) for a quick and easy way to map your entities to CRUD based stored procs.


text:
Q: What is ::class in PHP? What is the ::class notation in PHP?
A quick Google search returns nothing because of the nature of the syntax.
colon colon class
What's the advantage of using this notation?
protected $commands = [
    \App\Console\Commands\Inspire::class,
];

A: If you're curious in which category it falls into (whether it's a language construct, etc),
It's just a constant.
PHP calls it a "Special Constant". It's special because it's provided by PHP at compile time.

The special ::class constant is available as of PHP 5.5.0, and allows
for fully qualified class name resolution at compile time, this is
useful for namespaced classes:

https://www.php.net/manual/en/language.oop5.constants.php

A: class is special, which is provided by php to get the fully qualified class name.
See http://php.net/manual/en/migration55.new-features.php#migration55.new-features.class-name.
<?php

class foo {
    const test = 'foobar!';
}

echo foo::test; // print foobar!

A: Please be aware to use the following:
if ($whatever instanceof static::class) {...}

This will throw a syntax error:

unexpected 'class' (T_CLASS), expecting variable (T_VARIABLE) or '$'

But you can do the following instead:
if ($whatever instanceof static) {...}

or
$class = static::class;
if ($whatever instanceof $class) {...}

A: SomeClass::class will return the fully qualified name of SomeClass including the namespace. This feature was implemented in PHP 5.5.
Documentation: http://php.net/manual/en/migration55.new-features.php#migration55.new-features.class-name
It's very useful for 2 reasons.

*

*You don't have to store your class names in strings anymore. So, many IDEs can retrieve these class names when you refactor your code

*You can use the use keyword to resolve your class and you don't need to write the full class name.

For example :
use \App\Console\Commands\Inspire;

//...

protected $commands = [
    Inspire::class, // Equivalent to "App\Console\Commands\Inspire"
];

Update :
This feature is also useful for Late Static Binding.
Instead of using the __CLASS__ magic constant, you can use the static::class feature to get the name of the derived class inside the parent class. For example:
class A {

    public function getClassName(){
        return __CLASS__;
    }

    public function getRealClassName() {
        return static::class;
    }
}

class B extends A {}

$a = new A;
$b = new B;

echo $a->getClassName();      // A
echo $a->getRealClassName();  // A
echo $b->getClassName();      // A
echo $b->getRealClassName();  // B


text:
Q: How do I merge 2 properties of 1 JSON file if the key name is the same? I have the following JSON:
[
    {
        "computers": {
            "available": [
                6,
                2
            ],
            "held": [],
            "upgrades": [],
            "installed": [
                "PC-1"
            ]
        },
        "version": "0.6.55-0ubuntu12~20.04.4",
        "name": "accountsservice",
        "summary": "query and manipulate user account information"
    },
    {
        "computers": {
            "available": [
                209,
                211,
                210
            ],
            "held": [],
            "upgrades": [],
            "installed": [
                "PC-3"
            ]
        },
        "version": "0.6.45-1ubuntu1.3",
        "name": "accountsservice",
        "summary": "query and manipulate user account information"
    }
]

I want to make a check against the data to check to see if the name property has any duplicate values. As such above, there are 2 accountservices but they have different version values.
How would I combine the 2 so that I only have 1 accountservices but 2 version in it using ReactJS? The other data is not relevant so can either be removed or merged also, I am only interested in listing different version for each name.
Expected output:
[
    {
        "version": "0.6.55-0ubuntu12~20.04.4, 0.6.45-1ubuntu1.3",
        "name": "accountsservice",
        "summary": "query and manipulate user account information"
    }
]

I have tried using the following function that I found online but can't get it working:
const sanitize = (source_array) => {
      let output = [];

      source_array.forEach( e => {
        if (output.filter( e1 => e1.name === e.name ).length === 0) {
         let unique_e = source_array.filter(j => j.name === e.name );
         let model = {};
        if (unique_e.length === 1)
          model = e;
        else {
          model.name = e.name;
          model.computers.installed = e.computers.installed;
          model.version = [];
          for ( const el of unique_e ) {
              const { version } = el;
              model.version.push({version});
        }
      }
     output.push(model)
     }
    });
      return output
    }

A: This is a perfect use case for the reduce function
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
Your sanitize function could look like something like this:
const sanitize = (source_array) => {
  const output = source_array.reduce((acc, { name, version, summary }) => {
    // try to find an entry with same name
    const entry = acc.find(e => e.name === name)
    if (entry) {
      // There was already an entry with this name !
      entry.version += `,${version}`
    } else {
      acc.push({ name, version, summary })
    }
    return acc
  }, []);
  return output
}

A: This would get the job done

let source_array = [
  {
    computers: {
      available: [6, 2],
      held: [],
      upgrades: [],
      installed: ["PC-1"]
    },
    version: "0.6.55-0ubuntu12~20.04.4",
    name: "accountsservice",
    summary: "query and manipulate user account information"
  },
  {
    computers: {
      available: [209, 211, 210],
      held: [],
      upgrades: [],
      installed: ["PC-3"]
    },
    version: "0.6.45-1ubuntu1.3",
    name: "accountsservice",
    summary: "query and manipulate user account information"
  }
];

let output = [];

source_array.map((item) => {
  let filter = output.filter((i) => i.name === item.name);
  if (filter.length) {
    filter[0].version += `, ${item.version}`;
  } else {
    output.push({
      version: item.version,
      name: item.name,
      summary: item.summary
    });
  }
});

console.log(output);

A: This would also work. This solution uses the name for grouping and lists the versions for each name and groups computers under different versions.

const input = [ { computers: { available: [6, 2], held: [], upgrades: [], installed: ["PC-1"], }, version: "0.6.55-0ubuntu12~20.04.4", name: "accountsservice", summary: "query and manipulate user account information", }, { computers: { available: [209, 211, 210], held: [], upgrades: [], installed: ["PC-3"], }, version: "0.6.45-1ubuntu1.3", name: "accountsservice", summary: "query and manipulate user account information", }, ];

const output = Object.entries(
  input.reduce((prev, { name, version, computers }) => {
    // check for the same name
    if (prev[name]) {
      prev[name].version.push(version);
      // check for the same version of computers in under same name
      if (prev[name].computers[version]) {
        prev[name].computers[version].push(computers);
      } else {
        prev[name].computers[version] = [computers];
      }
    } else {
      // name is identified for the first time
      // create a new entry for that
      prev[name] = {
        version: [version],
        computers: { [version]: [computers] },
      };
    }
    return prev;
  }, {})
).map(([key, { version, computers }]) => ({
  name: key,
  versions: version,
  computers,
}));

console.log(output);


text:
Q: Removing   from a json file in php I have a JSON file that I'm requesting from a remote URL. I noticed that the resulting file has   characters within it. What would be the best way to remove all of them and replace them with a regular space.
I tried html_entity_decode but it ended up breaking the json file. Also, string replace didn't remove them.

A: $clean_json = str_replace(" ", " ", "your json file string");


text:
Q: How to set up filter in logstash config file kubernetes with Date: component: level: message? I am setting up elk cluster with filebeat. I am trying to create filter in logstash config file with following format (Date: component: level: message). But the filter is not working.
2021-08-17 18:57:33 component INFO msg

grok {
   match => { "message" => "%{TIMESTAMP_ISO8601:timestamp}  %{DATA:component} %{LOGLEVEL:logLevel}  -%{GREEDYDATA:logMessage}" }
}

A: Try this:
input:
2021-08-17 18:57:33 component INFO msg

grok pattern:
%{TIMESTAMP_ISO8601:timestamp} %{DATA:component} %{LOGLEVEL:logLevel} %{GREEDYDATA:logMessage}

output:
{
  "timestamp": [
    [
      "2021-08-17 18:57:33"
    ]
  ],
  "YEAR": [
    [
      "2021"
    ]
  ],
  "MONTHNUM": [
    [
      "08"
    ]
  ],
  "MONTHDAY": [
    [
      "17"
    ]
  ],
  "HOUR": [
    [
      "18",
      null
    ]
  ],
  "MINUTE": [
    [
      "57",
      null
    ]
  ],
  "SECOND": [
    [
      "33"
    ]
  ],
  "ISO8601_TIMEZONE": [
    [
      null
    ]
  ],
  "component": [
    [
      "component"
    ]
  ],
  "logLevel": [
    [
      "INFO"
    ]
  ],
  "logMessage": [
    [
      "msg"
    ]
  ]
}


text:
Q: Send about ten two digit numbers at a time to a Bluetooth device at random intervals I am building a BLE remote controller application.
I am paring a BLE device with the Android phone with the tested and working code below.
Intent intentOpenBluetoothSettings = new Intent();
intentOpenBluetoothSettings.setAction(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS);
startActivity(intentOpenBluetoothSettings);

I want to connect to one of the devices in the paired list, and I know the name, which is always the same.
Later, I want to send about ten two digit numbers at a time to that device at random intervals (from a listener for a button), and I don't need any information back.  Simplex communication only, Android phone to BLE device.

A:                 @Override
                public void uiDeviceFound(final BluetoothDevice device, final int rssi, final byte[] record )
                {
                    String msg                                                                      ;
                    String deviceName = device.getName()                                            ;
                    String redRacer   = "Red Racer"                                                 ;
                    if (redRacer.equals(deviceName))
                    {
                        boolean status                                                              ;
                        status = mBleWrapper.connect(device.getAddress().toString())                ;
                        if (status == false)
                        {
                            msg = "Sorry, could not connect to Red Racer"                           ;
                            Toast.makeText(SecondaryActivity.this,msg,Toast.LENGTH_SHORT).show()    ;
                        }
                        else
                        {
                            msg = "Connected to Red Racer"                                          ;
                            Toast.makeText(SecondaryActivity.this,msg + "   " + deviceName + "   " + redRacer,Toast.LENGTH_SHORT).show()    ;
                        }
                    }
                }

A: During my research to resolve the issue I found this brief, but informative article on the differences between pairing and bonding as far as BLE is concerned:
https://piratecomm.wordpress.com/2014/01/19/ble-pairing-vs-bonding/
Giving credit where credit is due. The above code which resolved my issue was taken from Getting Started with Bluetooth Low Energy (O'REILLY), although the code copied directly from their book continually crashed the activity whenever it was called.  After correcting the problems, as per the above code, it works flawlessly.  Now that the connection is made, I have to push my control code out the established link to the Simblee chip on my slave board.
Overall the code is what I would define as plug-in reusable code which I think will be applicable to others who might want the same functionality.  I will post the complete code, once I have it up and running.

A: Here is the answer to my own question which was, is there any copy an paste code to implement a simple open loop control system with BLE, with the phone being the master which sends control codes to a BLE slave which can control several real world devices, like motors, lights, heaters, etc.
First of all, I realize an open loop control system is the least desirable control system there is, but in my case the Simblee RFD77101 does not have a characteristic which will return the value written to it, so a closed loop control system is not possible.
Eventually I would like to embellish this code to include read capabilities, etc. but that is not a current priority for me.
Finally, I am a complete newbie at Android/Java development, so if you have any comments or questions, please be nice, and I will do what I can.

A:         package com.my_android_app.my_android_app;

import android.app.Activity                             ;
import android.content.Intent                           ;
import android.content.SharedPreferences                ;
import android.content.pm.PackageManager                ;
import android.os.Bundle                                ;
import android.os.Handler                               ;
import android.support.v7.app.AppCompatActivity         ;
import android.util.Log                                 ;
import android.view.Gravity                             ;
import android.view.View                                ;
import android.widget.Button                            ;
import android.widget.TextView                          ;
import android.widget.Toast                             ;

import java.util.List                                   ;
import java.util.UUID                                   ;
import java.util.Calendar                               ;

import android.bluetooth.BluetoothAdapter               ;
import android.bluetooth.BluetoothDevice                ;
import android.bluetooth.BluetoothGatt                  ;
import android.bluetooth.BluetoothGattCharacteristic    ;
import android.bluetooth.BluetoothGattService           ;

public class BLE_Test_Activity extends AppCompatActivity {
    public  BLE_Test_Activity.mSensorState mState               ;
    private enum mSensorState {IDLE, ACC_ENABLE, ACC_READ}      ;
    boolean connectedTo                     = false             ;
    boolean okButtonClicked                 = false             ;
    boolean receivedRSSI                    = false             ;
    private byte[] mRawValue                = null              ;
    private int mIntValue                   = 0                 ;
    private String mAsciiValue              = ""                ;
    private String mStrValue                = ""                ;
    private String mLastUpdateTime          = ""                ;
    private boolean mNotificationEnabled    = false             ;
    private final String LOGTAG             = "BLETEST"         ;
    private final String TARGET_BLE         = "My BLE Device"   ;
    private String gattList                 = ""                ;
    private int rssi_1                      = 0                 ;
    private int rssi_2                      = 0                 ;
    private int rssi_3                      = 0                 ;
    private int rssi_4                      = 0                 ;
    private int valueRSSI                   = 0                 ;
    private String mDeviceRSSI                                  ;
    private TextView mDeviceStatus                              ;
    private TextView mDeviceRssiView                            ;
    private String mDeviceAddress                               ;
    private static final long SCANNING_TIMEOUT = 5 * 1000; /* 5 seconds */
    // The UUID variable values below are only applicable to the RFD77101 BLE chip.
    // Enter values here which are applicable to the BLE device you are using.
    private static final UUID
        UUID_SIMBLEE_SERVICE          = UUID.fromString("0000fe84-0000-1000-8000-00805f9b34fb") ,
        UUID_SIMBLEE_CHARACTERISTIC_2 = UUID.fromString("2d30c083-f39f-4ce6-923f-3484ea480596") ;
    private boolean mScanning = false                           ;
    private Handler mHandler = new Handler()                    ;
    private BleWrapper mBleWrapper = null                       ;   // Add this line to instantiate the BLE wrapper
    private BluetoothGattCharacteristic mCharacteristic = null  ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState)                                                          ;
    setContentView(R.layout.activity_ble__test_)                                                ;
    connectViewsVariables()                                                                     ;
    final String dataSentMessage    = "Your " + TARGET_BLE + " put your transmitted message here."    ;

    mBleWrapper = new BleWrapper(this, new BleWrapperUiCallbacks.Null() {
        @Override
        public void uiDeviceFound(final BluetoothDevice device, final int rssi, final byte[] record) {
        if (TARGET_BLE.equals(device.getName())) {
            if (mBleWrapper.connect(device.getAddress())) {
//                        Toast.makeText(BLE_Test_Activity.this, device.getAddress(), Toast.LENGTH_SHORT).show();  // This is included for debugging purposes
            } else {
            Toast.makeText(BLE_Test_Activity.this, "Sorry, could not connect to " + TARGET_BLE, Toast.LENGTH_SHORT).show();
            }
        }
        }  // ********************** uiDeviceFound *************************************

        public void uiDeviceConnected(final BluetoothGatt gatt, final BluetoothDevice device) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
            mDeviceStatus.setText   ("connected ")      ;
            mDeviceRssiView.setText ("measuring .")     ;
            connectedTo = true;
            }
        });
        }  // ********************** uiDeviceConnected *************************************

        public void uiDeviceDisconnected(final BluetoothGatt gatt, final BluetoothDevice device)  // Takes about 20 seconds to display disconnected,
        {                                                                                // then more than thirty minutes to reconnect.
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
            mDeviceStatus.setText  ("disconnected")     ;
            mDeviceRssiView.setText("disconnected")     ;
            connectedTo = false;
            }
        });
        }  // ********************** uiDeviceDisconnected *************************************

        @Override
        public void uiCharacteristicForService(    BluetoothGatt gatt,
                               BluetoothDevice device,
                               BluetoothGattService service,
                               List<BluetoothGattCharacteristic> chars)
        {
        super.uiCharacteristicForService(gatt, device, service, chars);
        for (BluetoothGattCharacteristic c : chars)
        {
            String charName = BleNamesResolver.resolveCharacteristicName(c.getUuid().toString())    ;
            gattList += "Characteristic: " + charName + "\n"                                        ;
        }
        }  // ********************** uiCharacteristicForService *************************************

        public void uiNewRssiAvailable(final BluetoothGatt gatt, final BluetoothDevice device, final int rssi) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
            if (rssi_4 == 0)
            {
                mDeviceRSSI = "measuring ....."         ;
                mDeviceRssiView.setText(mDeviceRSSI)    ;
            }
            if (rssi_3 == 0)
            {
                mDeviceRSSI = "measuring ...."          ;
                mDeviceRssiView.setText(mDeviceRSSI)    ;
            }
            if (rssi_2 == 0)
            {
                mDeviceRSSI = "measuring ..."           ;
                mDeviceRssiView.setText(mDeviceRSSI)    ;
            }
            if (rssi_1 == 0)
            {
                mDeviceRSSI = "measuring .."            ;
                mDeviceRssiView.setText(mDeviceRSSI)    ;
            }
            rssi_4 = rssi_3     ;
            rssi_3 = rssi_2     ;
            rssi_2 = rssi_1     ;
            rssi_1 = rssi       ;
            if (rssi_4 != 0) {
                valueRSSI = (rssi_1 + rssi_2 + rssi_3 + rssi_4) / 4 ; // This is a simple moving average to filter out noise
                mDeviceRSSI = (valueRSSI) + " dBm"                  ;
                mDeviceRssiView.setText(mDeviceRSSI)                ;
            }
            receivedRSSI = true                                     ;
            }
        })                                                              ;

        if (okButtonClicked)
        {
            okButtonClicked = false                             ;

            // Build up newValue with the data you want to send out the BLE link.
            // I have hard coded 0202 just for testing purposes.
            // Make sure the contents of newValue is Hex only 0 - 9, A - F
            String newValue =  "0202"                                                                                ;
            byte[] dataToWrite = parseHexStringToBytes(newValue)                                                        ;
            BluetoothGattCharacteristic mCharacteristic                                                                 ;
            mCharacteristic = gatt.getService(UUID_SIMBLEE_SERVICE).getCharacteristic(UUID_SIMBLEE_CHARACTERISTIC_2)    ;
            mBleWrapper.writeDataToCharacteristic(mCharacteristic, dataToWrite)                                         ;
        }
        }  // *************************** uiNewRssiAvailable ***********************************************

        @Override
        public void uiNewValueForCharacteristic(BluetoothGatt gatt,
                            BluetoothDevice device,
                            BluetoothGattService service,
                            BluetoothGattCharacteristic ch,
                            String strValue,
                            int intValue,
                            byte[] rawValue,
                            String timestamp)
        {
        super.uiNewValueForCharacteristic(gatt, device, service, ch, strValue, intValue, rawValue, timestamp);
        for (byte b:rawValue)
        {
            Log.d(LOGTAG,"Val: + b") ;
        }
        }  // ********************** uiNewValueForCharacteristic *************************************

        @Override
        public void uiGotNotification(  BluetoothGatt gatt,
                        BluetoothDevice device,
                        BluetoothGattService service,
                        BluetoothGattCharacteristic characteristic)
        {
        super.uiGotNotification(gatt, device, service, characteristic)                              ;
        String ch = BleNamesResolver.resolveCharacteristicName(characteristic.getUuid().toString()) ;
        Log.d(LOGTAG,"uiGotNotification: " + ch)                                                    ;
        }  // *************************** uiNewValueForCharacteristic *************************************

    } ) ;  // *************************** new BleWrapper **************************************************

    if (!mBleWrapper.checkBleHardwareAvailable()) {
        Toast.makeText(this, "No BluetoothLE compatible hardware detected", Toast.LENGTH_SHORT).show()  ;
        finish()                                                                                ;
    }  // ********************** checkBleHardwareAvailable *************************************

    Button activity6Button = (Button) findViewById(R.id.button6);    // Green check mark button
    activity6Button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
        if  (connectedTo)
        {
            okButtonClicked = true                                                                          ;
            if (receivedRSSI)
            {
            Toast toast = Toast.makeText(BLE_Test_Activity.this, dataSentMessage, Toast.LENGTH_SHORT)   ;
            TextView v = (TextView) toast.getView().findViewById(android.R.id.message)                  ;
            if (v != null) v.setGravity(Gravity.CENTER)                                                 ;
            toast.show()                                                                                ;
            receivedRSSI = false                                                                        ;
            }
        }
        SharedPreferences prefs = getSharedPreferences("saveUserSettings", MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit()      ;
        editor.putString("AppIsOn", "yes")                  ;
        editor.apply()                                      ;
        }
    }) ;  // ********************** green check mark *************************************

    Button activity7Button = (Button) findViewById(R.id.button7);    // Blue back arrow
    activity7Button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
        setResult(Activity.RESULT_CANCELED)                                                 ;   // Page 60 Sams
        finish()                                                                            ;
        }
    }) ;   // ********************** back arrow *************************************

    }   // ********************************** onCreate ********************************************

    public byte[] parseHexStringToBytes(final String hex) {
    String tmp = hex.substring(2).replaceAll("[^[0-9][a-f]]", "")       ;
    byte[] bytes = new byte[tmp.length() / 2]                           ; // every two letters in the string are one byte finally
    String part = ""                                                    ;
    for(int i = 0; i < bytes.length; ++i) {
        part = "0x" + tmp.substring(i*2, i*2+2)                         ;
        bytes[i] = Long.decode(part).byteValue()                        ;
    }
    return bytes                                                        ;
    }  // ********************** parseHexStringToBytes *************************************

    @Override
    protected void onResume() {
    super.onResume();
    if (!mBleWrapper.isBtEnabled())     // Check for Bluetooth enabled on each resume
    {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)                                                  ;
        startActivity(enableBtIntent)                                                                                ;
        Toast.makeText(BLE_Test_Activity.this, "Sorry but BluetoothLE is not supported on your phone", Toast.LENGTH_SHORT).show()   ;
        finish()                                                                                ;
    }
    if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
        Toast.makeText(BLE_Test_Activity.this, "mBleWrapper.isBtEnabled", Toast.LENGTH_SHORT).show()                                ;
        finish()                                                                                ;
        return                                                                                ;
    }
    connectedTo = false                                 ;
    mBleWrapper.initialize()                            ;
    mDeviceStatus.setText  ("searching ...")            ;
    mDeviceRssiView.setText("searching ...")            ;
    mBleWrapper.startScanning()                         ;
    }  // ************************************ onResume **********************************************

    @Override
    protected void onStart() {
    super.onStart();
    }   // *********************************** onStart *******************************

    @Override
    protected void onPause() {
    connectedTo = false                                                                 ;
    super.onPause()                                                                     ;
    mBleWrapper.stopScanning()                                                          ;
    mBleWrapper.diconnect()                                                             ;
    mBleWrapper.close()                                                                 ;
    }  // ********************** onPause *************************************

    @Override
    protected void onStop() {
    SharedPreferences prefs = getSharedPreferences("saveUserSettings", MODE_PRIVATE)    ;
    SharedPreferences.Editor editor = prefs.edit()                                      ;
    editor.putString("AppIsOn", "no")                                                   ;
    editor.apply()                                                                      ;
    mBleWrapper.stopScanning()                                                          ;
    mBleWrapper.diconnect()                                                             ;
    mBleWrapper.close()                                                                 ;
    super.onStop()                                                                      ;
    }  // ********************** onStop *************************************

    @Override
    protected void onDestroy() {
    SharedPreferences prefs = getSharedPreferences("saveUserSettings", MODE_PRIVATE)    ;
    SharedPreferences.Editor editor = prefs.edit()                                      ;
    editor.putString("AppIsOn", "no")                                                   ;
    editor.apply()                                                                      ;
    mBleWrapper.stopScanning()                                                          ;
    mBleWrapper.diconnect()                                                             ;
    mBleWrapper.close()                                                                 ;
    super.onDestroy()                                                                   ;
    }  // ********************** onDestroy *************************************

    private void connectViewsVariables() {
    mDeviceStatus   = (TextView) findViewById(R.id.peripheral_status)                   ;
    mDeviceRssiView = (TextView) findViewById(R.id.peripheral_rssi)                     ;
    }   // ********************** connectViewsVariables ********************************
}       // ***************************** BLE_Test_Activity *****************************

A: <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/ble_test"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:background="#FFFFFF"
    tools:context="com.my_android_app.my_android_app.BLE_Test_Activity">

    <TextView
    android:text="TextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/peripheral_status"
    android:gravity="center"
    android:layout_marginTop="10dp"
    android:layout_below="@+id/textView20"
    android:layout_toStartOf="@+id/button39" />

    <TextView
    android:text="TextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/peripheral_rssi"
    android:layout_marginLeft="200dp"
    android:layout_marginTop="10dp"
    android:layout_below="@+id/textView20" />

    <Button
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:textAllCaps="false"
    style="@style/Widget.AppCompat.Button.Borderless"
    android:id="@+id/button7"
    android:background="@drawable/returnicon"
    android:layout_alignParentBottom="true"
    android:layout_toEndOf="@+id/button39"
    android:layout_marginStart="46dp" />

    <Button
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:textAllCaps="false"
    style="@style/Widget.AppCompat.Button.Borderless"
    android:id="@+id/button6"
    android:background="@drawable/checkmark"
    android:layout_alignParentBottom="true"
    android:layout_toStartOf="@+id/button39"
    android:layout_marginEnd="44dp" />

</RelativeLayout>

A: Resources used by this demo.

*

*https://www.bluetooth.com/develop-with-bluetooth/developer-resources-tools/app-acc-2 Download the Bluetooth Application Accelerator kit here, it contains several classes you will need to make this demo work, along with working Java code you can use in you app.
The BLE Demo app included in this kit is formatted for Android Studio thankfully.  The BLE Demo app is excellent.  In addition to being built around the BLE wrapper which is part of the the Applicaton Accelerator, the BLE Demo drills down into your BLE devices and displays all parameters and their values.  The value of this can not be underestimated because in my case, the manufacturer of the BLE device I am using did not even document the UUIDs for the services and characteristics I needed to write to.

*https://github.com/microbuilder/IntroToBLE  Here is the source code from the excellent book 'Getting Started with Bluetooth Low Energy', O'REILLY.  If all you want to do is read and write to a BLE device, this book contains far to much information, especially the marketing information for BLE, however the tutorial for Android development is excellent.  Be aware that there are mistakes in the sample code in the book, and the sample code is not the same, but is similar as per this download.

*https://evothings.com/2.1/doc/tutorials/how-to-connect-to-ble-devices.html This is an excellent tutorial on connecting with a BLE device with JavaScript which is useless of course for a Java program, however the connection methodology is the same.  Also this tutorial explains in simple terms the sequence of events which are required to connect to a BLE device.

*https://piratecomm.wordpress.com/category/bluetooth-le Here is a brief, but excellent article on Pairing and Bonding, relative to BLE devices.

Usage instructions:

*

*Install the BLE Demo app from the Bluetooth application accelerator onto your Android phone.

*Copy several classes from the BLE Demo app and put them into your app.
    These classes are: BleWrapper, BleNamesResolver, BleDefinedUUIDs, BleWrapperUiCallbacks and FetchAddressIntentService.

*Create a new empty activity in your app which you will use to place switches, seek bars etc. whose values you wish to send out the BLE link.

*Copy and paste the BLE_JAVA into the class created by the new activity you just created.
    Replace every occurrence of my_android_app with whatever is applicable for your app.
    Replace every occurrence of BLE_Test_Activity with whatever is applicable for your activity.
    For the string private final String TARGET_BLE = "My BLE Device" , put the device name of your target device at "My BLE Device" .
    In the section private static final UUID, you will need to enter the UUID values applicable to your device. You can use the BLE Demo app to find them if you do not know what they are.

*Copy and paste the BLE_XML into the XML file which was just created, and replace every occurrence of my_android_app with whatever is applicable for your app.
    Replace every occurrence of BLE_Test_Activity with whatever is applicable for your activity.

*I have included a stripped down version of my manifest for an example which I feel has the necessary ingredients for the BLE implementation.

*Now you can put the switches, seek bars, etc. into the new activity you just created, and put the values of those controls in the string, 'newValue' which will be the data which will be sent out via BLE.
I hope I have included all necessary steps, if not please let me know so that I can make the applicable changes.


text:
Q: determinant of the table of characters I am certain that the answer to this question exists somewhere. It might be a classical exercise.
Let $G$ be a finite group. Its table of characters is a square matrix, whose rows are indexed by the conjugacy classes and the columns are indexed by the irreducible characters. It is well defined, up to the order of rows and columns. In particular, its determinant if well-defined up to the sign. Let us define $\Delta$ to be the square of this determinant (this is well-defined). Because the characters form a basis of the space of class functions, we know that $\Delta\ne0$. When $G={\mathbb Z}/n{\mathbb Z}$, $\Delta=n^n$.

Is there a close formula for $\Delta$ for a general group? Is it always an integer?

A: I found the following answer after posting it:
$$\Delta=\epsilon\prod_c\frac{|G|}{|c|},\qquad\epsilon=(-1)^m,$$
where the product is taken over the conjugacy class. And $m$ is the number of pairs of complex conjugate irreducible characters.
Proof. On the one hand, the complex conjugate of the table is itself, up to $m$ transpositions of rows. This is because the conjugate of an IC is an IC. Therefore
$$\overline{\det(TC)}=\epsilon\det(TC)$$
($TC$ stands for ``table of characters''.)
Hence $\det(TC)$ is real if $m$ is even, pure imaginary if $m$ is odd. hence $\Delta$ is real and its sign is $\epsilon$.
Now the characters form a unitary basis. Because a unitary matrix has a unit determinant, we may compute $|\Delta|$ by taking any unitary basis. Take $\phi_c(g)$ to be $0$ if $g\not\in c$ and $|G|^{1/2}/|c|^{1/2}$ if $g\in c$. In particular $|\Delta|$ is an integer because $$\frac{|G|}{|c|}=|{\mathcal Z}(a)|,\qquad a\in c.$$
Another Proof: Let $D$ be the diagonal matrix whose diagonal entries are the cardinals of the congugacy classes. We may assume that the first rows of $TC$ are the real characters and the $2m$ last ones are the pairs of complex conjugate characters. Then the $(i,j)$-entry of $M:=(TC)D(TC)^T$ is $|G|\langle\overline{\chi_i},\chi_j\rangle$. From the orthogonality relations, we see that $M={\rm diag}(1,\ldots,1,J,\ldots,J)$ where
$$J=\begin{pmatrix} 0 & 1 \\\\ 1 & 0 \end{pmatrix}.$$
The number of blocks $J$ is precisely $m$. Now take the determinant; we obtain $\Delta\det D=(-1)^m|G|^r$ where $r\times r$ is the size of $TC$. Hence the formula.

A: Hasn't this been discussed at length in the recent Annals paper
An Elementary Exposition of Frobenius's Theory of Group-Characters and Group-Determinants
Leonard Eugene Dickson
(1902)?
The Determinant the OP discusses is NOT the group determinant per se, but comes up shortly after the definition of the group determinant.

A: Corrected version
I believe it is always an integer.  We can assume that all our representations are over the algebraic closure $\overline{\mathbb Q}$ of $\mathbb Q$.  If $\Gamma$ is the absolute Galois group, then clearly $\Gamma$ acts on the characters of $G$ (if you have a representation, then twist it by the action of $\Gamma$).  It thus follows that the determinant squared is fixed by $\Gamma$ (since $\Gamma$ permutes the rows) and so is a rational number.  But it is also an algebraic integer so it is an integer.

A: If $A$ is the character table and $A^\ast$ is its conjugate transpose, then the orthogonality relations tell us that $A A^\ast = \text{diag}\{|C_G(g)|\} $, where the enties run over a fixed choice of elements of $G$, one from each conjugacy class. Thus $|\Delta| = \det A A^\ast = \prod |C_G(g)|$ is an integer. On the other hand, $\Delta$ must be rational. This follows from the fact that the action of $\text{Gal}(\overline{\mathbb Q}/\mathbb Q)$ permutes the columns of $A$, hence fixes $\Delta  = (\det A)^2$. Thus $\Delta=\pm |\Delta|$ is an integer.


text:
Q: How to solve "Request Timeout" error from Node.js project on Heroku When I run my node.js project on heroku, some time it works but after some time it shows such errors and I can't connect to my backend node.js server.
at=error code=H12 desc="Request timeout" method=GET path="/socket.io/?EIO=3&transport=websocket" host=mjgame.herokuapp.com request_id=e21eb048-580b-426c-a881-4a4f982d4ed7 fwd="82.102.233.32" dyno=web.1 connect=0ms service=30001ms status=503 bytes=0 protocol=https
at=error code=H19 desc="Backend connection timeout" method=GET path="/socket.io/?EIO=3&transport=websocket" host=mjgame.herokuapp.com request_id=bc321d89-3298-4b2e-9986-6feee15cb780 fwd="86.6.77.76" dyno=web.1 connect=5001ms service= status=503 bytes= protocol=https
I can't know what is the solution of this issue.


text:
Q: pyspark only escapes the first quote after a backslash from csv I have a csv data in which I've escaped existing backslash characters using another backslash:
year,content
2021,"\\"foo\\",bar"

I'd like to read it using spark and display the data. The expected data on the dataframe:
+----------+--------------+
| year     | content      |
+----------+--------------+
| 2021     | \"foo\",bar  |
+----------+--------------+

But when I ran this:
schema = StructType(
        [
            StructField("year", IntegerType(), False),
            StructField("content", StringType(), False),
        ]
   )

    df = (
        spark.read.csv(
            f"s3://path/to/csv",
            schema=schema,
            header=True
        )
    )

    df.show(20,False)

I'm getting this:
+----------+--------------+
| year     | content      |
+----------+--------------+
| 2021     | "\"foo\\"    |
+----------+--------------+

Any idea how to handle this properly?

A: If you can save your data like this (single escape instead of double escape)
year,content
2021,"\"foo\", bar"

then you can read it as you're doing and the output would be
# +----+----------+
# |year|content   |
# +----+----------+
# |2021|"foo", bar|
# +----+----------+


text:
Q: All elements are replaced by last element in an arraylist of hashmap I have values as
Question Q-id
Q1        1
Q2        2
...and so on
I want to retrieve them by calling a function. So i used an arraylist of HashMaps as follows..
public ArrayList<HashMap<String,String>> getAllQuestions(Integer id)
 {
     try
     {
         HashMap<String,String> QuesList = new HashMap<String,String>();
         ArrayList<HashMap<String, String>> QuestionArrayList = new ArrayList<HashMap<String, String>>();
         // Select All Query
         String selectQuery = <some query here>;

          cursor = mDb.rawQuery(selectQuery, null);

         // looping through all rows and adding to list
         if (cursor.moveToFirst())
         {
             do
             {

                 QuesList.put("ques_id", cursor.getString(2));
                 QuesList.put("ques_text", cursor.getString(8));
                 QuestionArrayList.add(QuesList);
                 Log.i("ques",cursor.getString(8) );
             } while (cursor.moveToNext());
         }

         Log.i("check"," Ques list returned");
         return QuestionArrayList;

     }
     catch (SQLException mSQLException)
     {
         Log.e(TAG, "getTestData >>"+ mSQLException.toString());
         throw mSQLException;
     }
 }

Now the Logcat shows that all questions are retrieved successfully at the time of individual fetch (as shown by the Log.i statement) but whe i run the following loop at the end all the elements are replaced by the last fetched question. Any help is much appreciated.
   for(HashMap<String, String> t : QuesList )
    {
        Log.d("out there", "count" + t.getString());
        Log.i("mapping....",t.get("ques_id"));
     }

A: When you call the add method, only the reference to the object is added. So next time you modify the object, the reference refers to the modified object and the old state of the object is not retained.
In your case, you will have to create new objects every time you want to add them to the List:
     // looping through all rows and adding to list
     if (cursor.moveToFirst())
     {
         do
         {
             //Create a new object instance of the Map
             HashMap<String,String> QuesList = new HashMap<String,String>();

             QuesList.put("ques_id", cursor.getString(2));
             QuesList.put("ques_text", cursor.getString(8));
             QuestionArrayList.add(QuesList);
             Log.i("ques",cursor.getString(8) );
         } while (cursor.moveToNext());
     }

A: The reason for this is that, inside your loop, you are only using a single instance of Questlist which is added in the QuestionArrayList.
Try moving
 HashMap<String,String> QuesList = new HashMap<String,String>();

inside  the loop.
 do
         {

             HashMap<String,String> QuesList = new HashMap<String,String>();

             QuesList.put("ques_id", cursor.getString(2));
             QuesList.put("ques_text", cursor.getString(8));
             QuestionArrayList.add(QuesList);
             Log.i("ques",cursor.getString(8) );
         } while (cursor.moveToNext());

A: You don't need a list here, use the map to store all your key/value pairs:
QuesList.put(cursor.getString(2), cursor.getString(8));

Will store your questions in the map. You can then loop:
for(String q : QuesList.values()) {…}

Ps: your problem is that you only use one map and keep using the same key, overriding previous entries.


text:
Q: Clearing multiple comboboxes and inputfields - Ext JS I have the following container with a combobox and textField (I also have an add function to dynamically add pairs of combo/textfields):
{ xtype: 'container', layout: 'hbox', style: {margin: '0px 0px 0px 330px'},
   items: [
     { xtype: 'combobox', padding: 5,   id: 'criteria_1_dropdown', store: filters},
     { xtype: 'textfield', padding: 5,  id: 'criteria_1_input', width: 145}
   ]
 }

And button:
{ xtype: 'button', id: 'clear_criteria', iconCls: 'clear' }

What I want to do is enable the Clear button to clear any and all combo/textField components on click, I don't believe it needs it's own controller to achieve this. Any ideas?

A: I solved the issue by putting my form into a variable and resetting that form with the reset() function:
{ xtype: 'button', id: 'clear_criteria', iconCls: 'clear',
     handler: function() {
         var hi = Ext.getCmp('contain');
         hi.getForm().reset();
         console.log('Cleared Search');
   }
}


text:
Q: '0' is null or not an object I just switched from jquery mobile alpha 2 to jquery mobile beta 1.0. I am using CDN access for the jquery javascript files and the css. I am getting some data from the server and displaying it in the list format. I am building list dynamically in the javasript file.
I was using
$('#detail').html(html);

$('#detail ul').listview();

to refresh my list after building it.
It was working well with alpha version of jquery mobile but now without changing a single line of code I am trying to run it using jquery mobile beta  and it is breaking with the following error:
Webpage error details

Message: '0' is null or not an object
  Line: 133
  Char: 183
  Code: 0
  URI: http://user.mydomain.com/scripts/jquery.mobile-1.0b1.min.js

Am I doing something wrong or some issue with beta version of css file?
EDIT:
I am getting the data in json format (say result object)using ajax call and displaying it like this:
var html = "
";

html += "
<Email:" + result.Data.email_address_1 + "
";

html += 'ul close tag'
$('div#page2 div#contentMain div#details ul#customerDetails').html(html)
$('div#page2 div#contentMain div#details ul').listview();

Althought I can see the data coming and displaying properly BUT without the style.
Hope this helps to understand the problem.
Raman

A: In your examples you are doing
$('div#page2 div#contentMain div#details ul#customerDetails').html(html)
$('div#page2 div#contentMain div#details ul').listview();

But ids are unique so there is no reason to use multiple id to define the hierarchy..
Just use
$('#customerDetails').html(html);
$('#details ul').listview();

Also make sure you fix your string concatenations .. and that result.Data contains what you think it does..

A: I checked this with Jquery Mobile forum and the following solution works for me.
     $('#details').html(html)
     $('#page2').page();
     $('ul#customerDetails').listview('refresh');


text:
Q: If, else in jQuery Ok, i have this
$("#Tab_Ads").click(function(){
    $.ajax({
        type: "GET",
        url: "_Ajax.AdQuestions.php",
        data: "AdID=<?php echo $_SESSION['SessionAdId']; ?>",
        success: function(data){
        $("#Ads_InfoContent").html(data);
        }
    });
});
 $("#Tab_Questions").click(function(){
    $.ajax({
        type: "GET",
        url: "_Ajax.AdQuestions.php",
        data: "QuesionID=<?php echo $_SESSION['SessionAdId']; ?>",
        success: function(data){
        $("#Ads_InfoContent").html(data);
        }
    });
});

Now I want display the data in div #Ads_InfoContent by default (before I click #Tab_Questions or else other), how i have to write the condition in jquery to display it? I'm a beginner in jQuery, thank you so much!

A: This should trigger the click event as soon as the page has loaded:
$("#Tab_Questions").trigger("click");

Place this after the click event declaration


text:
Q: Android-Arduino Bluetooth communication: Data is not received properly in Android app I am creating an app for Android-Arduino bluetooth serial communication. I am able to connect to arduino successfully. My app can send data to arduino without hassle and I have verified it. But While receiving data from arduino, my app only receives a part of data being send. For example if "404" is being send from arduino, my app only show "4" as being received.
I checked with other such apps and all other apps are able to receive "404" itself. So problem is with my code.
This is my code which read data from arduino:
public String read(byte[] bytes){
            try {
                mInput.read(bytes);
                strInput = new String(bytes);
            }catch(Exception e){
                e.printStackTrace();
            }
            return strInput;
}
//mInput is the input stream of bluetooth connection

As you can see data is recived to a byte buffer and converted to a string using new String(bytes); method. How ever when I toast the string, only 4 is being toasted instead of 404 send from arduino.
The byte buffer is of size 256.
EDIT: as requested the full code for BluetoothManager.java is this:
public class BluetoothManager {
    private BluetoothAdapter bluetoothAdapter;
    private BluetoothDevice bluetoothDevice;
    private BluetoothSocket bluetoothSocket;
    private ConnectedThread connectedThread;
    private byte[] buffer;

    public BluetoothManager(){
        buffer=new byte[256];
        bluetoothSocket=null;
        bluetoothAdapter=null;
        bluetoothDevice=null;
        connectedThread=null;
        getBluetoothAdapter();
        if(!isBluetoothAvailable()){
            turnBluetoothOn();
        }
        scanToConnect();
    }
    public void turnBluetoothOff(){
        try {
            bluetoothSocket.close();
            bluetoothSocket=null;
            bluetoothAdapter.cancelDiscovery();
            bluetoothAdapter.disable();
            bluetoothAdapter=null;
            bluetoothDevice=null;
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    private boolean isBluetoothAvailable(){
        return bluetoothAdapter.isEnabled();
    }
    private void turnBluetoothOn(){
        bluetoothAdapter.enable();
    }
    public String readData(Context context){
        String outputString=null;
        if(isBluetoothAvailable()) {
            outputString = connectedThread.read(buffer);
        }else{
            Toast.makeText(context, "Error: Not Connected", Toast.LENGTH_LONG).show();
        }
        return outputString;
    }
    public void writeData(String string, Context context){
        if(isBluetoothAvailable()) {
            connectedThread.write(string.getBytes());
        }else{
            Toast.makeText(context, "Error: Not Connected", Toast.LENGTH_LONG).show();
        }
    }
    private void getBluetoothAdapter(){
        try{
            bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    private void scanToConnect(){
        Set<BluetoothDevice> pairedDevices=bluetoothAdapter.getBondedDevices();
        if(pairedDevices.size()>0){
            try {
                for (BluetoothDevice device : pairedDevices) {
                    if (device.getName().equals("HC-05")) {
                        bluetoothDevice = device;
                        new connectBt(bluetoothDevice);
                        break;
                    }
                }
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }
    private class connectBt extends Thread {
        public connectBt(BluetoothDevice device) {
            BluetoothSocket tmp = null;
            bluetoothDevice = device;
            UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
            try {
                tmp = device.createRfcommSocketToServiceRecord(uuid);
            } catch (IOException e) {
                e.printStackTrace();
            }
            bluetoothSocket = tmp;
            run();
        }
        public void run() {
            bluetoothAdapter.cancelDiscovery();
            try {
                bluetoothSocket.connect();
                connectedThread = new ConnectedThread(bluetoothSocket);
            } catch (IOException connectException) {
                closeSocket();
            }
        }
        private void closeSocket() {
            try {
                bluetoothSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    private class ConnectedThread extends Thread{
        private InputStream mInput=null;
        private OutputStream mOutput=null;
        private String strInput;

        public ConnectedThread(BluetoothSocket socket){
            bluetoothSocket=socket;
            InputStream tmpIn=null;
            OutputStream tmpOut=null;
            try{
                tmpIn=socket.getInputStream();
                tmpOut=socket.getOutputStream();
            }catch(IOException e){
                e.printStackTrace();
                closeSocket();
            }
            mInput=tmpIn;
            mOutput=tmpOut;
        }
        public void write(byte[] bytes){
            try{
                mOutput.write(bytes);
            }catch(IOException e){
                e.printStackTrace();
            }
        }
        public String read(byte[] bytes){
            try {
                mInput.read(bytes);
                strInput = new String(bytes);
            }catch(Exception e){
                e.printStackTrace();
            }
            return strInput;
        }
        public void closeSocket(){
            try{
                bluetoothSocket.close();
            }catch(IOException e){
                e.printStackTrace();
            }
        }
    }
}

Edit-2: On further debugging I found out that mInput.available() returns 0 while mInput.read(bytes) returns 1.Why is this behavior while in my arduino code I am using bluetooth.println("404");

A: http://felhr85.net/2014/11/11/usbserial-a-serial-port-driver-library-for-android-v2-0/
Try this it should work. Also please provide the full code of it.  May be the Error should be in the part where you are connecting the function to Serial Event handler.

A: I was having the same problem. I solved by adding delimiter(\n) while sending from arduino i.e println() and checking in android code. Try below code in android, its  working for me:
Try this code: http://pastebin.com/sfb3kuu6

A: Okey I solved this problem by putting a delay in my read() method.


text:
Q: Compact, not local uniform convergence of sequences of functions on the rationals I stumbled upon the following elementary problem while trying to come up with a certain counterexample in category theory.  (Basically, I am interested in the constant sheaf of $\mathbb F_2$-vector spaces on the topological space $\mathbb Q$ of rational numbers; but understanding this motivation in not at all necessary in order to understand the question.)
Let $\mathbb Q$ be the set of all rational numbers, embedded as a subset into the set of all real numbers $\mathbb R$ and endowed with the induced real topology.  Can one produce a sequence of locally constant $0$-$1$ valued functions $f_n$, $\,n=1$, $2$, $\dots$ on $\mathbb Q$ with the following properties?
On the one hand, for any compact subset $K$ in $\mathbb Q$ there should exist $N\in\mathbb N$ such that for all $n>N$ the restriction of $f_n$ to $K$ is identically zero.  On the other hand, there should be a point $q\in\mathbb Q$ such that for any neighborhood $U$ of $q$ in $\mathbb Q$ and any $N\in\mathbb N$ there exists $n>N$ such that $f_n$ is not identically zero on $U$.
Can one construct such a sequence of functions on $\mathbb Q$ ?
Let me mention that infinite compact subsets $K$ certainly exist in $\mathbb Q$; e.g., $\{1,1/2,1/4,\dots,0\}$ is such a subset.  On the other hand, there is a feeling that compact subsets in $\mathbb Q$ are "small" as compared to nonempty open subsets. Hence the question.

A: No, such sequence of functions does not exist, even without the local constantness hypothesis.
For every $k$, choose some $n>k$ and $q_k\in U_{1/k}(q)$ such that $f_n(q_k)=1$. Then the set $K=\{q_k\colon k\in\mathbb N\}\cup\{q\}$ is compact (since $q_k\to q$), but $(f_n)$ is not eventually vanishing on $K$.


text:
Q: Perl Form - Check Field Is Filled In I have a HTML form and a variable is set if a particular field is filled in, a Perl script I have inherited.
    for (my $i; $i<@raw_search_value; $i++) {
    ...
    $album_search=1 if $raw_search_column[$i] eq 'album_id';
    $top40_history_search=1 if $raw_search_column[$i]=~/^top40/;
    $album_ID=$raw_search_value[$i] if $album_search;
    $album_title_search=1 if $raw_search_column[$i] eq 'album_title';
    }

    $album_title_search=1 if $raw_search_column[$i] eq 'album_title';

A form field called album_title. The code reiterates through the form fields using my $i; $i<@raw_search_value[$i]
However I want the variable album_title_search to be set to one if ONLY this field has been filled in and others haven't.
In other words, Set to 1 if this field is filled in and other fields in the form are blank.
Can I do this with one line of Perl, or do I have to expand it to go through every field and check it is blank?
I'm a bit stuck with this and haven't dealt with Perl code very long. Would welcome any suggestions. Many thanks

A: You can do something like this:
$album_title_search=1
  if $raw_search_column[$i] eq 'album_title'
  && grep { length } @raw_search_value == 1   # only 1 value filled
  && length $raw_search_value[$i]             # and that value is for album_title

However it can be written much more concisely. Can you post some more code, particularly the loop, the @raw_search_column and the @raw_search_value?


text:
Q: Lambda Expression not giving desired result I have sql query as :-
SELECT CreatedOn,* FROM [dbo].[ClientConfigurationVersion] --order by CreatedOn
WHERE CONVERT(date,CreatedOn)>=CONVERT(date,'2019-03-15')
and CONVERT(date,CreatedOn)<=CONVERT(date,'2019-03-20')

This is giving me below 2 records :-

I want to fetch this result through Lambda Expression.
I written it as :-
var clientConfigurationVersion= context.ClientConfigurationVersions.Where(x => (x.CreatedOn >= _startDate) && (x.CreatedOn <= _endDate) );

I passed same dates , but it gives me only one record i.e. first record which we can see in Sql Result window.
What is wrong in my Lambda Expression ?


text:
Q: HTML include script with jsx, es2017 tags and other tags I have the following Javascript (JSX, es2017, and others) that works fine when included on a page, but when I fetch the content from a url in a src tag, it's no longer functional. How can I include the following when the source is from another file?
I cannot load my Javascript when imported from a src tag:
<script src="...some_url..." type="text/jsx" data-presets="es2017,react,stage-0" data-plugins="transform-decorators-legacy"></script>

However the following works when included on the page.
<script type="text/jsx" data-presets="es2017,react,stage-0" data-plugins="transform-decorators-legacy">
function test(div_id) {
        const {LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend} = Recharts;
        const data = [
              {name: 'Page A', uv: 4000, pv: 2400, amt: 2400},
              {name: 'Page B', uv: 3000, pv: 1398, amt: 2210},
              {name: 'Page C', uv: 2000, pv: 9800, amt: 2290},
              {name: 'Page D', uv: 2780, pv: 3908, amt: 2000},
              {name: 'Page E', uv: 1890, pv: 4800, amt: 2181},
              {name: 'Page F', uv: 2390, pv: 3800, amt: 2500},
              {name: 'Page G', uv: 3490, pv: 4300, amt: 2100},
        ];
        const SimpleLineChart = React.createClass({
                render () {
                return (
                <LineChart width={600} height={300} data={data}
                    margin={{top: 5, right: 30, left: 20, bottom: 5}}>
               <XAxis dataKey="name"/>
               <YAxis/>
               <CartesianGrid strokeDasharray="3 3"/>
               <Tooltip/>
               <Legend />
               <Line type="monotone" dataKey="pv" stroke="#8884d8" activeDot={{r: 8}}/>
               <Line type="monotone" dataKey="uv" stroke="#82ca9d" />
              </LineChart>
            );
          }
        })

        ReactDOM.render(
                <SimpleLineChart />,
                document.getElementById(div_id)
        );
}
</script>


text:
Q: Git diff : compare specific versions of specific file I have cloned linux kernel git repository:
git clone git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git

I am interested in the history of a particular file:
git log net/core/sock_diag.c

I see several commits:
commit 8e904550d0fffcda2b18d7ab12750b0c75757e89
Date:   Sat Feb 23 01:13:48 2013 +0000

commit 6e601a53566d84e1ffd25e7b6fe0b6894ffd79c0
Date:   Sat Feb 23 01:13:47 2013 +0000

commit 9f00d9776bc5beb92e8bfc884a7e96ddc5589e2e
Date:   Sat Sep 8 02:53:54 2012 +0000

How can I diff two particular versions of this file?
Lets say, I want to diff the versions from Sep-8 and Feb-23
I could use the following, but that gives me the diffs of the whole commits (not just my file)
git diff 9f00d9776bc5beb92e8bfc884a7e96ddc5589e2e 6e601a53566d84e1ffd25e7b6fe0b6894ffd79c0

could somebody please advise?

A: Add the filename to your diff command:
git diff 9f00d9776bc5beb92e8bfc884a7e96ddc5589e2e \
  6e601a53566d84e1ffd25e7b6fe0b6894ffd79c0 -- net/core/sock_diag.c

If you are interested in what changed between commits, you can use git log -p (or --patch):
git log -p net/core/sock_diag.c


text:
Q: Text Node Selector within single td using jQuery I need to extract the text after Name:, Phone:, Email:, Lead Submitted:, Comments:, Property Address 1:
The problem is all these text nodes are siblings. I don't know how to choose a sibling by number if it's a text node - e.g. the top sibling is a span but the rest are text nodes. I have tried different iterations but the only thing I'm getting to work is
var comments = $('span:contains("Renter's Information")').siblings().text().trim();
But this pulls all the text, not just the comments text. Ideally I'd like to get not just each text node but the text after 'Name:', 'Phone:' etc. but I will probably have to trim that off post jQuery though. Any guidance on pulling these individual text nodes would be appreciated.

Renter's Information

 Name: Shelby

 Phone: (555) 555-555

 Email: email@gmail.com

 Lead Submitted: 9/13/2020 1:42:37 PM

 Renter's Preferences

 Beds/Baths:

 Model:

 Unit:

 Move Date: 11/2/2020

 Comments: Hi there! Just came across your listing online. I was wondering if you could send us some updated photos and financial information, as in if anything is included in cost, how much the house needs paid off & just some details so we can look to see if we want to check it out. Thank you!

 Property Information

 Link: https://www.apartments.com/

 To: property

 Property Address 1: property

 Property Address 2:

 City: city

 State: NY

 Zip: 12345

 Wishing you success in converting this True Lead™ to a lease!

 The Apartments.com Network Team

A: I understood from your question that you want to get some text according to some keywords in your HTML, here is an implementation for that!
and I have edited my answer to store the content in an array instead of logging them on the fly

// the words you search for, note that in this solution they need to be ordered
// just to avoid nested for loops that leads to larger time complexity
let searchKeywords = ["Name", "Phone", "Email", "Lead Submitted", "Comments", "Property Address 1"];

function getTextContent(keywords, htmlContent) {
  // an array to store in the content
  let arr = [];
  // since there is a
 element before each span element that makes it
  // easy to just get the html and split it into lines
  htmlContent.split("
").forEach(function(e) {
    if(e.startsWith(` ${searchKeywords[arr.length]}`)) {
      // if the current line starts with the current keyword then if it has an
      //  tag then get the text of it, otherwise just slice the keyword name
      arr.push((e.includes("") + 1, e.indexOf("")) : e.slice(e.indexOf(":") + 1)).trim());
    }
  });
  return arr;
}

let result = getTextContent(searchKeywords, document.querySelector("td").innerHTML);
console.log(result);

      Renter's Information

 Name: Shelby

 Phone: (555) 555-555

 Email: email@gmail.com

 Lead Submitted: 9/13/2020 1:42:37 PM

 Renter's Preferences

 Beds/Baths:

 Model:

 Unit:

 Move Date: 11/2/2020

 Comments: Hi there! Just came across your listing online. I was wondering if you could send us some updated photos and financial information, as in if anything is included in cost, how much the house needs paid off & just some details so we can look to see if we want to check it out. Thank you!

 Property Information

 Link: https://www.apartments.com/

 To: property

 Property Address 1: property

 Property Address 2:

 City: city

 State: NY

 Zip: 12345

 Wishing you success in converting this True Lead™ to a lease!

 The Apartments.com Network Team

And for your comment:

The above HTML is part of a much larger section of HTML so to locate the td I'd have to search for the text "Renter's Information" and then from there I can implement the script you recommended

Well you can filter the span elements to get the one that has the text content "Renter's Information"
and then get its parent element which will be the td element you are looking for, here is the code
let tdElement = Array.prototype.filter.call(document.querySelectorAll("span"), function(e) {
  return e.textContent === "Renter's Information";
})[0].parentElement;

And then get your content by calling getTextContent() like this
let result = getTextContent(searchKeywords, tdElement.innerHTML);


text:
Q: Нужно из базы данных выводить значение ключа по id Всем привет.
Подскажите, плиз, ответ на задачку. Нужно из базы данных выводить значение ключа по id, но так, чтобы вставлять потом разные значения в разные места, и id уже заменять цифрой в конкретном месте html кода id= '3';
$db = new PDO('mysql:host=localhost; dbname=comments', 'root', '');
$query = $db->prepare("SELECT output FROM class_output WHERE id = '$id'");
$query->execute();

$com = $query->fetchAll(PDO::FETCH_ASSOC);

foreach ($com as $value){
    echo $value['output'] ;
}


text:
Q: how to query on particular keys in couchbase through java client? I am new to CouchBase. I have few simple documents as :
1. {
  "docType": "DeviceData",
  "id": "57 0F 75 00 C8 0B@2013-06-26 23:59:38.979",
  "time": 1372271378979,
  "group": "London"
}

2. {
  "docType": "DeviceData",
  "id": "57 0F 75 00 C8 0B@2013-06-27 10:02:46.197",
  "time": 1372307566197,
  "group": "Bristol"
}

3. {
  "docType": "DeviceData",
  "id": "57 0F 75 00 C8 0B@2013-06-27 10:03:36.4",
  "time": 1372307616400,
  "group": "Bristol"
}

I have requirement to query on group and time. for example I want to fetch all the documents with group = Bristol and time from 1372307616100 to 1372307616500. So i deal I should get the 2 of the 3 docs.
So i have create the view as:
function (doc, meta) {
  if(doc.docType == "DeviceData")
  emit([doc.group, doc.time], doc);
}

And in the java code setting the query as below:
String str = "[\"Bristol\", 1372307566100]";
        String end = "[\"Bristol\", 1372307616500]";
        query.setRange(str, end);
        List<DeviceData> deviceData = cbStore.getView("getDevices", DeviceData.class, query);

But getting zero documents.
Please let me know is there anything wrong I am doing? need help thanks.
*EDIT:
I tried using complexkeys as well like below but no luck.
ComplexKey startKey = ComplexKey.of("Bristol", "1372307566100");
ComplexKey endKey = ComplexKey.of("Bristol", "1372307616500");

A: The problem is that in your objects time is a long, not a String:
query.setStale(Stale.FALSE);
long firstParameter=1372307566197l;
long secondParameter=1372307616400l;
//["Bristol",1372307566197]
ComplexKey startKey = ComplexKey.of("Bristol", firstParameter);
//["Bristol",1372307616400]
ComplexKey endKey = ComplexKey.of("Bristol",  secondParameter);
query.setRange(startKey, endKey);
ViewResponse result = client.query(view, query);
Iterator<ViewRow> iter = result.iterator();
while(iter.hasNext()) {
    ViewRow row = iter.next();
    System.out.println( row.getId()); // ID of the document
    System.out.println(row.getKey()); // Key of the view row
    System.out.println(row.getValue()); // Value of the view row
    System.out.println(row.getDocument()); // Full document if included
    }


text:
Q: Windows Service Plus GUI/C# I've seen some apps that run as a windows service but can still provide a GUI that allows the user to see what's actually going on.
For example, we've got a windows service that builds reports. There are a number of stats that admins would like to see, such as how many reports are queued up, how much ram is in use, avg build time, etc.
What we'd like to do is provide a way for the admin to see this - such as an app that can connect to the window service to gather and display this information... or maybe a way that the app itself can provide its own GUI and display it when requested. Right now, the only thing the app does it create a log file.
Is there a way to do this?

A: Several.

*

*Have some sort of component that hooks into your windows service and sends information to another application via remoting.  If you have an IoC container a clever use of decorators can do that

*Use a service bus, MSMQ, WCF, Growl or something like that to broadcast interesting information.  Applications simply need to know how to hook in.

*Expose an HTTP endpoint or something where someone can connect to and download information on the windows service

*Or simply create a one-page WinForms app that reads the log file every so often and displays interesting results.

(Notice that last one is by far the simplest - hint hint, do that.)

A: Ideally services are completely separated from the User Interface for many reasons I won't get into.
However you can use some manner of IPC to view information such as this. My recommendation would be to use Remoting to request the data needed from the service, and then build whatever reports or graphs as needed into a separate application.

A: Services aren't allowed to make UI API calls (except one specific form of message box).  So services that appear to have have a wser interface are actually two processes.  The Service process is communicating with a standard Windows APP using some sort of proprietary backchannel.  Could be a named pipe, a socket, or a hunk of named shared memory.


text:
Q: Most efficient way to remove elements from vector, do a calculation and put them back in R I'm trying to find the best way to do a cut in a vector using 12 breaks, but I want the first cluster to contain values from 0 to a specific value (onePercentQuantile). So one way to do that is to remove all values below onePercentQuantile in vector while keeping track of the removed value indexes, then run a cut on vector with only 11 breaks and finally put back the removed indexes as cluster 1 in the new object, starting form the leftmost index.
I did not find a way to ignore values under a specific threshold in cut function, so I did it myself.
Here is an example with the most efficient way I could find :
vector_gene <- sample(1:100, 10000, replace=TRUE)
onePercentQuantile<- 5
indexUnderPercentQuantile <- which(vector_gene <= onePercentQuantile)
overPercentQuantile <- vector_gene[vector_gene > onePercentQuantile]

tmp <- as.numeric(cut(c(t(overPercentQuantile)),breaks=11))+1

if (1 == indexUnderPercentQuantile[1]){
  tmp <- insert(tmp, 1, values=1)
  indexUnderPercentQuantile <- indexUnderPercentQuantile[2:length(indexUnderPercentQuantile)]
}

for (i in 1:length(vector_gene)){
  if (i>length(tmp)){
    tmp <- c(tmp,rep(1,length(vector_gene)-i+1))
    break
  }
  else if (i == indexUnderPercentQuantile[1]){
    tmp <- c(tmp[1:i-1],1,tmp[i:length(tmp)])
    if (length(indexUnderPercentQuantile)>1){
      indexUnderPercentQuantile <- indexUnderPercentQuantile[2:length(indexUnderPercentQuantile)]
    }
  }
}

Using the profvis package I have traced memory usage and running time.
Up to 10.000 elements, result is instantaneous using barely no memory.
Up to 100.000 elements, memory usage is already around 9Go running in 3.5s
Up to 1.000.000 elements, the running time is so long that I shut it down.
The bottleneck is the reattribution of the removed indexes :
tmp <- c(tmp[1:i-1],1,tmp[i:length(tmp)])

I've tried the insert function in R.utils but it was worst in memory usage and running time
Is there a better way, especially in memory usage, to achieve this problem ? Thanks !


text:
Q: I'm designing a thick UI diagnostic tool, should it have a direct integration to PowerShell My team and I are designing a diagnostic test tool as part of our next product.  The test tool will exercise a request/response API and display asynchronous events.  As part of the diagnostic tool suite, we will also be providing cmdlets for the entire product API.
Is it worth embedding PowerShell execution into the tool UI ?  What are other development teams doing ?
The scripts can still run stand alone in any PowerShell window or tool.  From a user's perspective, they would gain the ability to launch scripts from our UI.  And, since the UI can be monitoring the same devices that the scripts act on, it brings some unity to the execution of a script and monitoring of the results.  Embedding script execution brings more work to the project and I'm not sure how we want to handle displaying the results of the scripts.
Do most PowerShell users expect to run their scripts from their own shell environments or within tools that come from their product vendors ?   Note, our diagnostic tool will not be automatically generating scripts for the users as some Microsoft tools do (it might be valuable for inexperienced PowerShell users, but we are expecting most scripts to be fairly simple, like executing a command on a series of devices).

A: Fortunately embedding the PowerShell engine and execute commands/scripts and getting the results back is pretty trivial.  That said, I'm not sure you scenario is one where I would embed PowerShell.  You ask if folks prefer to run scripts from their own shells or from within the Tool Vendors environment.  I can't speak for everybody but the shells and editors that I use support some nifty features for debugging, code folding, syntax highlighting, multiple runspaces, etc.  I'm not sure you would want to go through the effort to provide similar capabilities.
One reason to embed PowerShell is to execute the same PowerShell cmdlets as part of your core diagnostics and monitoring engine.  That way you don't have to duplicate functionality between your diagnostic tool app engine and the cmdlets that your customers use for automation.  It sounds like the code you use to do the diagnostics and monitoring in the app is different than the code in the cmdlets?  Or is there common code shared between the app and the cmdlets?
Another reason to embed PowerShell is to allow the app itself to be scriptable but this doesn't appear to fit your scenario.
Another reason to embed PowerShell is if you are implementing a new host - ie you provide some unique editing or shell functionality. Some apps that do this are PowerGUI (which allows you to launch scripts IIRC) and PowerShell Plus.
Yet another reason I have embedded PowerShell in an application is because I knew I could get certain results in much less code than the equivalent C# code.  This is a weaker reason and I probably wouldn't do this in a commercial app but I have used this for one-off programs.

A: I agree with both Jaykul and Keith Hill - the answer is yes.
There are several approaches you could use. But in general, I'd recommend you a) create key cmdlets as part of the UI for your app and b) you build the GUI on top of PowerShell (in the same way the Exchange team has done.
Doing this follows Microsoft's lead (all applications have to have a PowerShell interface) that is also being taken up by others (e.g. VMware, and even Symantec leverage PowerShell in their applications.
Creating cmdlets (and possibly a provider) is pretty straightforward - there's a great cmdlet designer recently released (see http://blogs.msdn.com/powershell/archive/2009/10/16/announcing-open-source-powershell-cmdlet-and-help-designer.aspx) for this tool.
Hope this helps!

A: Yeah, the main reason I'd consider actually embedding PowerShell in that scenario is if your UI could generate PowerShell scripts for the actions the users take in the UI, so they could see what was happening, and easily learn how to automate it.  That would require designing the UI based on PowerShell from the beginning  ... so it sounds to me like you're better off just providing the cmdlets and samples ;)


text:
Q: var undefined when using EJS with express I am using EJS as view engine for an express app, I am having the following issue: Whenever I want to use a variable on EJS, I got an error telling me that that variable is not defined, in order to solve this, I have to put locals before the variable, I don't know if this is some config problem or what, but I have been trying to look for an answer and haven't got one yet. The funny-sad thing, is that after I use the locals stuff, I can render the ejs with no problem, but the expected output does not appear, so I am not getting render erros, but I my variables aren't showing up neither.
Some of my code:
//app.js
var expressLayouts = require('express-ejs-layouts');
//...
    app.set('view engine', 'ejs');
    app.engine('html', require('ejs').renderFile);
    app.use(expressLayouts);
...

//layouts.ejs

          <% if(locals.user){%>   //-> As you may see here, If I dont use locals before user, I got the 'user' is undefined

              Dashboard (current)

              Logout

            <% }else{ %>

                Login

                Register

              <% } %>

//register.ejs

Register

<% if(locals.errors){ %>
    <% errors.forEach(function(err){ %>

        <%=err.msg%>

        <% });%>
<%}%>

So I don't know if this is a issue from my ejs config, or from my way of passing the variables from the controller.


text:
Q: Play specific video from loop OnClick in Vue.JS Let's assume that this 2 video is the output from a for loop with the the method of play() and with an index parameter. How can i play the specific video, because when i trigger the play method it also play the second video.
Component's HTML

  <video id="videoElement" class="sm:hidden block md:h-auto md:w-auto w-full h-auto object-cover object-center mx-auto focus:outline-none" controls="false" v-play="playing">
    <source src="~/assets/video/video1.mp4" type="video/mp4">
  </video>

  <video id="videoElement" class="sm:hidden block md:h-auto md:w-auto w-full h-auto object-cover object-center mx-auto focus:outline-none" controls="false" v-play="playing">
    <source src="~/assets/video/video2.mp4" type="video/mp4">
  </video>

Component's JavaScript
export default {
  data(){
  return {
    playing: false
  }
 },
 computed: {
    paused() {
      return !this.playing;
    }
  },
  directives: {
    play: {
      bind(el, binding, vnode) {
        el.addEventListener('playing', () => {
          vnode.context[binding.expression] = !el.paused;
        });
        el.addEventListener('pause', () => {
          vnode.context[binding.expression] = !el.paused;
        });
        vnode.context[binding.expression] = !el.paused;
      },
      update(el, binding) {
        if (el.paused) {
          if (binding.value) {
            el.play();
          }
        } else if (!binding.value) {
          el.pause();
        }
      }
    }
  },
  methods: {
    play(index) {
    this.playing = !this.playing;
    },
    pause() {
      this.playing = false;
    }
  }
 }
</script>

A: Converting comment to answer for future reference
My working fiddle version: https://jsfiddle.net/jfpwtkm0/1
Feel free share your thoughts:

*

*I used v-for since your HTML on video with duplicate id was weird as it would be practical in actual video datafetching case instead of manual-templating each video

*Custom directive was not mapped to each Object's playing state, so i've changed that format to be assigned to video with their id respectively

*updated toggle(id) method, since you're planning to change the playState, so i include id so the playState of videoObject toggled according the index.

*Same id value in multiple elements is not practical. I assigned the id of the videoArray to be unique.

If this answer solved your question, green tick will help alot, cheers :)


text:
Q: Pass main's *argv[] to a function that is being called by another function? So I have my main function, and 2 other functions, func1 and func2.
main is gettings the arguments from the user, passes them to func1.
fun1 checks something, and then wants to send the arguments to func2.
How can I do it?
 int main( int argc, char *argv[] )  {
  if( argc == 3 ){
    func1(argv);
  }

void func1(char **argv){
if(strcmp(argv[2], "-win"))
    func2(argv);
}

void func2(char ***argv){ //is this the right way?
......
}

I mean I know that func1 is receiving the arguments because when I tried it without sending them to func2, it worked.
But I'm trying to figure out how to send them to func2 from func1.

A: Look at this code in file main.c:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void func1(char **argv);
void func2(char **argv);

int main(int argc, char *argv[])
{
    // you are need to pass 2 things to run this
    if (argc == 3)
    {
        func1(argv);
    }
    return 0;
}

void func1(char **argv)
{
    if (strcmp(argv[2], "-win")==0)
        func2(argv);
}

void func2(char **argv)
{
    printf("%s\n", argv[2]);
}

Running gcc -Wall  main.c -o main  && ./main  f -win you get the
output: -win to the console. You shouldn't manipulate data within argv and it is a safer bet to just change func2 to:
char *func2(char **argv)
{
    // Return some value after receiving argv
}

and return whatever type your result is of the manipulation you are wanting to do.