text:
Q: Weak references and `OutOfMemoryError`s I have a SoundManager class for easy sound management. Essentially:
public class SoundManager {
    public static class Sound {
        private Clip clip; // for internal use

        public void stop() {...}
        public void start() {...}
        public void volume(float) {...}
        // etc.
    }

    public Sound get(String filename) {
        // Gets a Sound for the given clip
    }

    // moar stuff
}

Most of the uses of this are as follows:
sounds.get("zap.wav").start();

As I understand it, this should not keep a reference to the newly created sound in memory, and it should be garbage collected fairly rapidly. However, with a short sound file (108 KB, clocking in at a whopping 00:00:00 seconds, and about 0.8s in reality), I can only get to about 2100 invocations before I get an OutOfMemoryError:

# There is insufficient memory for the Java Runtime Environment to continue.
  # Native memory allocation (malloc) failed to allocate 3874172 bytes for jbyte in C:\BUILD_AREA\jdk6_34\hotspot\src\share\vm\prims\jni.cpp
  # An error report file with more information is saved as:
  # [path]

I tried implementing a private static final Vector<WeakReference<Sound>> in the SoundManager.Sound class, adding the following to the constructor:
// Add to the sound list.
allSounds.add(new WeakReference<SoundManager.Sound>(this));
System.out.println(allSounds.size());

This also allows me to iterate through at the end of the program and stop all sounds (in an applet, this is not always done automatically).
However, I still only get about 10 more invocations before the same OutOfMemoryError occurs.
If it matters, for each file name, I'm caching the file contents as a byte[], but this is only done once per file so it shouldn't accumulate.
So why are these references being retained, and how can I stop it without just increasing the heap size?

EDIT: The "error report with more information" contains, at line 32:
Java frames: (J=compiled Java code, j=interpreted, Vv=VM code)
J  com.sun.media.sound.DirectAudioDevice.nWrite(J[BIIIFF)I
J  com.sun.media.sound.DirectAudioDevice$DirectDL.write([BII)I
j  com.sun.media.sound.DirectAudioDevice$DirectClip.run()V+163
j  java.lang.Thread.run()V+11
v  ~StubRoutines::call_stub

Does this mean that this issue is completely out of my control? Does javasound need time to "cool down"? I'm spewing these sounds out at 300/second, for debugging purposes.

EDIT with more info on my use of JavaSound.
The first time I call sounds.get("zap.wav"), it sees that "zap.wav" has not been loaded before. It writes the file to a byte[] and stores it. It then proceeds as if it had been cached before.
The first and all subsequent times (after caching), the method takes the byte[] stored in memory, makes a new ByteArrayInputStream, and uses AudioSystem.getAudioInputStream(bais) on said stream. Could it be these streams holding memory? I would think that when the Sound (and thus the Clip) is collected, the stream would be closed also.

EDIT with the get method per request. This is public Sound get(String name).

*

*byteCache is a HashMap<String, byte[]>

*clazz is a Class<?>
byteCache is a HashMap<String, byte[]> and clazz is a Class<?>
try {
    // Create a clip.
    Clip clip = AudioSystem.getClip();

    // Find the full name.
    final String fullPath = prefix + name;

    // See what we have already.
    byte[] theseBytes = byteCache.get(fullPath);

    // Have we found the bytes yet?
    if (theseBytes == null) {
        // Nope. Read it in.
        InputStream is = clazz.getResourceAsStream(fullPath);

        // Credit for this goes to Evgeniy Dorofeev:
        // http://stackoverflow.com/a/15725969/732016

        // Output to a temporary stream.
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        // Loop.
        for (int b; (b = is.read()) != -1;) {
            // Write it.
            baos.write(b);
        }

        // Close the input stream now.
        is.close();

        // Create a byte array.
        theseBytes = baos.toByteArray();

        // Put in map for later reference.
        byteCache.put(fullPath, theseBytes);
    }

    // Get a BAIS.
    ByteArrayInputStream bais = new ByteArrayInputStream(theseBytes);

    // Convert to an audio stream.
    AudioInputStream ais = AudioSystem.getAudioInputStream(bais);

    // Open the clip.
    clip.open(ais);

    // Create a new Sound and return it.
    return new Sound(clip);
} catch (Exception e) {
    // If they're watching, let them know.
    e.printStackTrace();

    // Nothing to do here.
    return null;
}

EDIT after heap profiling.
Heapdumped about 5 seconds before crash. Well this is telling:

Problem Suspect #1:

2,062 instances of "com.sun.media.sound.DirectAudioDevice$DirectClip",
  loaded by "" occupy 230,207,264 (93.19%) bytes.
Keywords com.sun.media.sound.DirectAudioDevice$DirectClip

These Clip objects are strongly referenced by Sound objects but the Sound objects are only weakly referenced in a Vector<WeakReference<Sound>>.
I can also see that each Clip object contains a copy of the byte[].

EDIT per Phil's comments:
I've changed this:
// Convert to an audio stream.
AudioInputStream ais = AudioSystem.getAudioInputStream(bais);

// Open the clip.
clip.open(ais);

to this:
// Convert to an audio stream.
AudioInputStream ais = AudioSystem.getAudioInputStream(bais);

// Close the stream to prevent a memory leak.
ais.close();

// Open the clip.
clip.open(ais);
clip.close();

This fixes the error but never plays any sound.
If I omit clip.close() the error still occurs. If I move ais.close() to after clip.open the error still occurs.
I've also tried adding a LineListener to the clip as it's created:
@Override
public void update(LineEvent le) {
    if (le.getType() == LineEvent.Type.STOP) {
        if (le.getLine() instanceof Clip) {
            System.out.println("draining");
            ((Clip)le.getLine()).drain();
        }
    }
}

I get a "draining" message each time the clip finishes or is stopped (i.e., 30+ times/second after it starts to happen), but still get the same error. Replacing drain with flush has no effect either. Using close makes the line unopenable later on (even when listening for START and calling open and start).

A: I suspect that the problem is that you are not explicitly closing the audio streams.  You should not rely on the garbage collector to close them.
The allocations seem to be failing in native allocations not in normal Java allocations, and I suspect that the normal behaviour of "the GC runs before throwing an OOME" applies in this case.
Either way, it is best practice to close your streams explicitly (using finally or the Java 7 try with resources).  This applies to any kind of stream that involves external resources or off-heap memory buffers.

A: Please excuse me if this is totally off, but I want to check on two fundamentals that I can't discern from a casual reading of your code.
1) How long are your sound files? Given a specific number of files, lengths in milliseconds, sample rate and encoding (e.g., 16-bit, stereo) you should be able to calculate the expected amount of memory to be consumed. What is that amount?
2) A really common error with Clips is to recreate them every time you play them instead of reusing existing Clips. I see in the comments the line: "sounds.get("zap.wav").start()" and that makes me wonder if you are making this fundamental error. You should only make a Clip once, and then reset the frame position to 0 when you wish to play it again. If you are recreating Clips at a furious rate, you WILL fill up memory very quickly, as each playback will create an additional object with its own copy of the PCM data.
Also, as one commenter states, it IS important to close the various streams. Not doing so will cause memory leaks.

A: Another approach: abandon the use of Java's Clip and write your own. I did this. I made an object that stores the data in memory and two other objects that provide "cursors" into the storage for two different type of playback. One is for looping and the other is for overlapping playback. Both can be set to run at different playback speeds, so you can get different effects by speeding up or slowing down the playback. Both direct their output to a mixer I wrote, where the data is consolidated into a single SourceDataLine.
The code is presented here, included in the jar linked in the first post:
http://www.java-gaming.org/topics/simple-audio-mixer-2nd-pass/27943/view.html
I'm looking forward to getting back to working on it some more, possibly putting it on GitHub.
Also, TinySound is a very capable sound manager. You can learn about it here. The approach is very similar to what I do, mixing down to a single output. TinySound provides support for Ogg and such. I don't think it provides vari-speed playback.
http://www.java-gaming.org/topics/need-a-really-simple-library-for-playing-sounds-and-music-try-tinysound/25974/view.html


text:
Q: QT GUI thread stuck when reading from /dev/input/event* I am running a QT embedded application(4.8.5) on arm, and found an issue that causes the GUI thread hung.
Below is the push button code.
const char* PushButtonService::m_eventfile = "/dev/input/event1";
PushButtonService::PushButtonService(QObject *parent): m_stop(false), m_pressed(false)
{
    m_sockfd = open(m_eventfile, O_RDONLY);
    m_notifier = new QSocketNotifier(m_sockfd, QSocketNotifier::Read, this);
    connect(m_notifier, SIGNAL(activated(int)), this, SLOT(readBtnEvts()));
    m_notifier->setEnabled(true);
}
void PushButtonService::readBtnEvts()
{
    QLOG_TRACE() << "read evts";
    struct input_event events[64];

QMutexLocker locker(&m_mutex);
int bytes = read(m_sockfd, events, sizeof(struct input_event));
if (bytes < (int) sizeof(struct input_event)) {
    QLOG_TRACE() << "no evts";
    return;
}

for (int i = 0; i < bytes / sizeof(struct input_event); i++){
    if (events[i].type == EV_KEY ) {
        if (events[i].value == 2) {
            if ( ! m_pressed ) {
                QLOG_TRACE() << "Emergency Pressed";
                emit emergencyPressed();
                m_pressed = true;
            }
        }else if (events[i].value == 0){
            if (m_pressed){
                QLOG_TRACE() << "Emergency Released";
                emit emergencyReleased();
                m_pressed = false;
            }
        }
    }
}
}
PushButtonService::~PushButtonService()
{
    close(m_sockfd);
    delete m_notifier;
}

Here is the GUI frame:
m_emergency_frame = new EmergencyFrame(this, m_language);
m_emergency_frame->hide();

m_push_button = new PushButtonService(this);
connect(m_push_button, SIGNAL(emergencyPressed()), this,    SLOT(emergencyPressed()));
connect(m_push_button, SIGNAL(emergencyReleased()), this, SLOT(emergencyReleased()));

void MainFerryFrame::emergencyPressed(){
QLOG_TRACE() << "Button pressed";
m_emergency_frame->show();
m_emergency_frame->raise();
}

 void MainFerryFrame::emergencyReleased()
{
    QLOG_TRACE() << "Button released";
    m_emergency_frame->hide();
}

I can get the push button event at the beginning, but after some repeats, the GUI application hung , and the backtrace when the application is :
(gdb) bt
#0  0xb650a378 in read () from /lib/arm-linux-gnueabihf/libpthread.so.0
#1  0xb69c81c0 in ?? () from /usr/lib/libQtGui.so.4
#2  0xb6632bf4 in QMetaObject::activate(QObject*, QMetaObject const*, int, void**) () from /usr/lib/libQtCore.so.4
#3  0xb6667f2a in QSocketNotifier::activated(int) () from /usr/lib/libQtCore.so.4
#4  0xb6638106 in QSocketNotifier::event(QEvent*) () from /usr/lib/libQtCore.so.4
#5  0xb69cf818 in QApplicationPrivate::notify_helper(QObject*, QEvent*) () from /usr/lib/libQtGui.so.4
#6  0xb69d123a in QApplication::notify(QObject*, QEvent*) () from /usr/lib/libQtGui.so.4
#7  0x000d7028 in ?? ()
Cannot access memory at address 0x2044
#8  0x000d7028 in ?? ()
Cannot access memory at address 0x2044
Backtrace stopped: previous frame identical to this frame (corrupt stack?)

Any clues?

A: m_sockfd = open(m_eventfile, O_RDONLY);

I believe this will perform blocking reads unless O_NONBLOCK is set. This is due to the fact that when you are notified, nothing guarantee that 64 events are available.
You should probably execute PushButtonService objects in their own Qthread.
m_push_button = new PushButtonService(0);
m_service_thread = new QThread();

m_push_button->moveToThread(m_service_thread);

You will have to move all setup of the PushButtonService constructor in a slot (ie bootstrap), and connect it to the start signal of the QThread.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Compiling embedded linux drivers This might have passed to the unix and linux stack exchange, but since it involves compiling, i am posting it here.
I want to compile usbserial, usb-wwan, and/or qcserial drivers for 2.6.35-9 Debian for ARMv7.
First problem, there is no 2.6.35-9 driver in the apt-get repos. I tried to compile with 2.6.32-kirkwood, while compilation works, insmod / modprobe, including -f, respectively --force switch fails, with the message :

insmod: error inserting 'usbserial.ko': -1 Invalid module format

I have looked up this and this. In this question, I was pointed to Debian 2.6.35-9 headers, but they did not install, for some dependency problem (Error message : Couldn't resolve dependency, without a list of missing dependencies). So I opened the .deb with ar, but it does not contain anything besides under data.tar.gz a /usr/share/doc ... etc - so no usable header files (or am I missing something?)
I am doing the compilation on the target machine (A Mirabox from Marvell) itself.
So, my question is,

*

*Can I download the Ubuntu 2.6.35 headers? Ubuntu uses Debian core, and the linux kernel is the same, with adaptions to the distro, or it is a fatal error? Is there any Armv7 header for a 2.6.35-9 at all?

*If not, then what do I do? Where do I get the correct header files?

*Also, 2.6.35 code for usbserial / qcserial is buggy anyway. I was using the code from the 3.2 kernel, thinking the errors might have been fixed. Was it a bad choice? If so, what to do


text:
Q: unrecognized selector sent to instance 0x7fb8bf50b3c0' (Swift/Xcode) I am trying to learn a new language (Swift/Xcode) and I don't seem too be able to run the following example:
import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var test: UIBarButtonItem!

    func processTimer(){
        print("a second has passed")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        var timer = Timer()    // Create timer object
        timer = Timer.scheduledTimer(timeInterval: 1,
                                     target: self,
                                     selector: Selector("processTimer"),
                                     userInfo: nil,
                                     repeats: true)
    }
}

I am getting:

Thread 1 :signal SIGABRT ????

A: Please, don't forget to ask a question next time. I think you should change your code into:
import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var test: UIBarButtonItem!

    @objc func processTimer(){
        print("a second has passed")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        var timer = Timer()    // Create timer object
        timer = Timer.scheduledTimer(timeInterval: 1,
                                     target: self,
                                     selector: Selector(processTimer),
                                     userInfo: nil,
                                     repeats: true)
    }
}

And then everything should work.


text:
Q: r count cells with missing values across each row I have a dataframe as shown below
    Id         Date         Col1       Col2     Col3        Col4
    30         2012-03-31              A42.2    20.46        NA
    36         1996-11-15   NA                  V73          55
    96         2010-02-07   X48        Z16      13
    40         2010-03-18   AD14                20.12        36
    69         2012-02-21              22.45
    11         2013-07-03   81         V017                  TCG11
    22         2001-06-01                       67
    83         2005-03-16   80.45      V22.15   46.52        X29.11
    92         2012-02-12
    34         2014-03-10   82.12      N72.22   V45.44

I am trying to count the number of NA or Empty cells across each row and the final expected output is as follows
    Id         Date         Col1       Col2     Col3        Col4       MissCount
    30         2012-03-31              A42.2    20.46        NA        2
    36         1996-11-15   NA                  V73          55        2
    96         2010-02-07   X48        Z16      13                     1
    40         2010-03-18   AD14                20.12        36        1
    69         2012-02-21              22.45                           3
    11         2013-07-03   81         V017                  TCG11     1
    22         2001-06-01                       67                     3
    83         2005-03-16   80.45      V22.15   46.52        X29.11    0
    92         2012-02-12                                              4
    34         2014-03-10   82.12      N72.22   V45.44                 1

The last column MissCount will store the number of NAs or empty cells for each row. Any help is much appreciated.

A: The one-liner
rowSums(is.na(df) | df == "")

given by @DavidArenburg in his comment is definitely the way to go, assuming that you don't mind checking every column in the data frame.  If you really only want to check Col1 through Col4, then using an apply function might make more sense.
apply(df, 1, function(x) {
                sum(is.na(x[c("Col1", "Col2", "Col3", "Col4")])) +
                sum(x[c("Col1", "Col2", "Col3", "Col4")] == "", na.rm=TRUE)
             })

Edit: Shortened code
apply(df[c("Col1", "Col2", "Col3", "Col4")], 1, function(x) {
                    sum(is.na(x)) +
                    sum(x == "", na.rm=TRUE)
                 })

or if data columns are exactly like the example data:
apply(df[3:6], 1, function(x) {
                        sum(is.na(x)) +
                        sum(x == "", na.rm=TRUE)
                     })

A: This should do it.
yourframe$MissCount = rowSums(is.na(yourframe) | yourframe == "" | yourframe == " "))

A: You can use by_row from library purrr:
library(purrr)

#sample data frame
x <- data.frame(A1=c(1,NA,3,NA),
                A2=c("A","B"," ","C"),
                A3=c(" "," ",NA,"t"))

Here you apply a function on each row, you can edit it according to your condition. And you can use whatever function you want.
In the following example, I counted empty or NA entries in each row by using sum(...):
by_row(x, function(y) sum(y==" "| (is.na(y))),
       .to="MissCount",
       .collate = "cols"
       )

You will get:
# A tibble: 4 x 4
     A1     A2     A3 MissCount
  <dbl> <fctr> <fctr>     <int>
1     1      A                1
2    NA      B                2
3     3            NA         2
4    NA      C      t         1

A: We can use
Reduce(`+`, lapply(df, function(x) is.na(x)|!nzchar(as.character(x))))


text:
Q: Access other fragment data I'm having some trouble, and I have done research on the problem but it did not help me.
I have a Main.java class, which is template made pager view of fragments.
I did not modify it in any way, except for getItem() method which now returns my own fragments.
My fragment A is collecting accelerometer data, saving last 120 records in an ArrayList.
It also has graph plots, with Series objects, which I would like to access from fragment B.
This is what I want to do:
In fragment B user presses a button "record data"
This results in fragment A boolean field "recordingOn" changing to true
Now in fragmentA onSensorChange method, after checking for "recordingOn", if it's true it will pass data to an ArrayList that is a field in fragment B
How do I access these fields?

A: from fragment call
Fragment frag = getActivity().getFragmentManager()..findFragmentByTag("fragment to find tag");

A: Greensy answer is a valid option (I upvoted him) but you can also refrain from doing so much DataPassing between fragments and let the Activity be a manager for all that.
For that you can create public methods and interfaces in the fragments and let/force the activity implement the interfaces.
Simple example:
public class Act extends Activity implements OnClickListener{
     @Override
     OnClick(View v){
        if(v.getId()==R.id.btn_recordData){
           fragA.startRecording();
        }
     }
}

then FragA you must create that method:
 public class FragA extends Fragment{
    private boolean isRecording
    public void startRecording(){ isRecording = true; // also init the sensor stuff }
    public void stopRecording() { isRecording = false; // also stop the sensor stuff }
 }

then on FragB you can:
 public class FragB extends Fragment{
      onCreateView(...){
          // initialise all the views and find the button, let's call it Button btn;
          btn.setOnClickListener((OnClickListener)getActivity());
      }
 }

does that make sense?

A: A way to do that is to use your own Application class and store your ArrayList in there
You can then access it in any point of your application, if you got a Context :
ArrayList<AccelerometerData> myAccelerometerData = ((MyApplication) mContext.getApplicationContext()).getAccelerometerData();

Be carefull about this solution since your ArrayList will be alive during all the application run


text:
Q: Refer generic without type parameter in Scala I am creating a tree structure in Scala, trying to implement the following type restrictions:

*

*Non-root nodes are one of three types - Time Node, Start Node or End Node

*Root node only has children of type Time Node

*Time Nodes only have children of type Start Node

*Start Nodes only have children of type End Node

*End nodes may have children of type Start Node or Time Node

These are my type definitions:
trait TreeNode[U] {
val children:HashSet[NonRootNode[U]]
  def addChild(c:NonRootNode[U])
}

class NonRootNode[T <: TreeNode[T]] extends TreeNode[T] {
  var passengers:Set[Passenger] = Set()
  val children:HashSet[T] = new HashSet[T]
  def addChild(c:T) = {
    children.add(c)
  }
}

case class RootNode extends TreeNode[TimeNode] {
    val children:HashSet[TimeNode] = new HashSet[TimeNode]
    def addChild(c:TimeNode) = {
      children.add(c)
    }
}

case class TimeNode(time:Int) extends NonRootNode[StartNode] {

}

case class StartNode(l:Option[String]) extends NonRootNode[EndNode] {

}

case class EndNode(l:Option[String]) extends NonRootNode {

}

First, does this implement requirements 1-4 correctly?
Second, is there a way to implement requirement 5 here in the definition? Is there ANY way to implement this requirement, as this would require a heterogeneous set to store children references.
EDIT: Types RootNode and EndNode would need a method like the following:
trait ParentOfTimeNode extends TreeNode{
  //type ChildType = TimeNode
  def addTimeNodes(startTime:Int, maxTime:Int) = {
      for(i <- startTime to maxTime) {
        this.addChild(new TimeNode(i))
      }
    }
}

Without that line commented, the line that screams is:
case class EndNode(l:Option[String]) extends NonRootNode with ParentOfTimeNode{ type ChildType = NonRootNode with IntervalMarker }

because of an obvious type match.
With the line commented, this.addChild screams since it is bound by ChildType which is undefined.

A: I believe I can achieve your aim, but using type members rather than type parameters.
Also, this meant I could move the implementation of addChild into the trait and not re-implement it in the subclasses.
Finally, I added a marker trait, IntervalMarker, to label the two node types that EndNode can accept as children.
trait TreeNode {
  type ChildType <: NonRootNode
  val children:HashSet[ChildType] = new HashSet[ChildType]
  def addChild(c:ChildType) = {
    children.add(c)
  }
}

abstract class NonRootNode extends TreeNode {
  var passengers:Set[Passenger] = Set()
}

case object RootNode extends TreeNode { type ChildType = TimeNode }

trait IntervalMarker

case class TimeNode(time:Int) extends NonRootNode with IntervalMarker { type ChildType = StartNode }

case class StartNode(l:Option[String]) extends NonRootNode with IntervalMarker { type ChildType = EndNode }

case class EndNode(l:Option[String]) extends NonRootNode { type ChildType = NonRootNode with IntervalMarker }


text:
Q: SSL Handshake with PrivateKey Clarification i think i have an error on my understanding on the SSL handshake, but do i?
My application cant verify itself on the api. After some digging with wireshark i noticed that theres no "certificate verify" step and my private key certificate is not signed with one of the trusted authorities so my first thought was that.
The catch is: If i add the same certificate to my browser(firefox) and call the API i get a popup for the certificate selection and it actually works.
Isnt it supposed to only accept certificates that are listed under the  Distinguished Names? Or is this only required for the public key and the private not necessarily?
What does firefox actually do in background when the popup comes, create a custom certificate chain?
Setup is as followed:

*

*API is under https:somerandomurl

*API-Server integrated a certificate of ours for auth (for all i know)
(this cert is actually a cert for https:someotherurl)

*Client has truststore with cert for somerandomurl

*Client has keystore with PKCS#12 cert
My guess is that my application has wrong/no certificate chain because as far as i know the PKCS#12 cert contains a pub and a private key BUT the pub is not for "somerandomurl" but "someotherurl". But thats just a guess, maybe its just the trusted auths


text:
Q: Can't resolve tsx modules even with .tsx in webpack.config resolve extensions array I have the following component:
import { useAuth } from './Auth';

export function Home() {
    const { user } = useAuth();
    const location = useLocation();
    // if (location.pathname == "/") {
    //     return <Navigate to={`/sessions/`} />
    // }
    return (
        <Container>
            <Row>
                <Col>
Welcome, {user.email}!
</Col>
            </Row>
        </Container>
    )
}

I used to have .tsx after auth but VS code would yell at me for it
("An import path cannot end with a '.tsx' extension. Consider importing './Auth' instead.ts(2691)")
I added .tsx and .jsx to webpage.config.js:
//@ts-check

'use strict';

const path = require('path');

//@ts-check
/** @typedef {import('webpack').Configuration} WebpackConfig **/

/** @type WebpackConfig */
const extensionConfig = {
  target: 'node', // vscode extensions run in a Node.js-context  -> https://webpack.js.org/configuration/node/
    mode: 'none', // this leaves the source code as close as possible to the original (when packaging we set this to 'production')

  entry: './src/extension.ts', // the entry point of this extension,  -> https://webpack.js.org/configuration/entry-context/
  output: {
    // the bundle is stored in the 'dist' folder (check package.json),  -> https://webpack.js.org/configuration/output/
    path: path.resolve(__dirname, 'dist'),
    filename: 'extension.js',
    libraryTarget: 'commonjs2'
  },
  externals: {
    vscode: 'commonjs vscode' // the vscode-module is created on-the-fly and must be excluded. Add other modules that cannot be webpack'ed,  -> https://webpack.js.org/configuration/externals/
    // modules added here also need to be added in the .vscodeignore file
  },
  resolve: {
    // support reading TypeScript and JavaScript files,  -> https://github.com/TypeStrong/ts-loader
      extensions: ['.ts', '.tsx', '.js','.jsx']
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'ts-loader'
          }
        ]
      }
    ]
  },
  devtool: 'nosources-source-map',
  infrastructureLogging: {
    level: "log", // enables logging required for problem matchers
  },
};
module.exports = [ extensionConfig ];

Still getting a  Module not found: Error: Can't resolve './Auth' in '/home/app/web/src' when webpack tries to compile.
I know I can just ignore the error but it seems like importing modules like this is the correct way to do things in TSX. Why does this method not work for me?


text:
Q: Stripping span tag from simple html dom parser HI i dont want to parse the span tag which is a child tag of  from where i am extracting my data.....
Ex:-
     Some data 1 2 3

      Unwanted Data

Code i am using:-
  foreach($html->find(a.imp) as $value)
   {
          echo $value->innertext;
   }

Output:-
Some data 1 2 3
Unwanted Data...

 Desired output:-
 Some data 1 2 3

I really dont knw is there any function or way so that i cant include the child tags ???

A: I believe you would have to loop through your first set of results, find all span elements and set each span element's outertext to an empty string, thus removing the entire HTML for that element.
foreach($html->find('a.imp') as $value)
{
    foreach($value->find('span') as $e)
    {
        $e->outertext = '';
    }

    echo $value->innertext;
}

A: Simple HTML DOM Parser will work:
$content = file_get_html($link);
$stuffiwant = $content->find("//a/text()");
var_dump($stuffiwant);

A: I don't believe simple has a clean way to remove elements. In phpquery you can:
$doc->find('a.imp span')->remove();
echo $doc->find('a.imp')->text();


text:
Q: strpos not working for first string among comma separated strings See this demo
I have two lists of comma separated strings, and want to look for strings and return a message. I noticed that in the particular case that I look for the first string of the first list, it will not find it. If I move that string to another placement, it will. Can't understand why.
$dynamic_list = "AZ, CA, CO";
$static_list = "MN,WA,IA";

$search = "AZ";

if ( strpos($dynamic_list . ',' . $static_list, $search) == false && !empty($search) ) { // check string is not empty + that it is not on any of the lists
    echo 'not found: String '.$search.' was not found in lists';
} else {
    echo 'found';
}

A:     $dynamic_list = "AZ, CA, CO";
    $static_list = "MN,WA,IA";

    $search = "AZ";

    if ( strpos($dynamic_list . ',' . $static_list, $search) === false && !empty($search) ) { // check string is not empty + that it is not on any of the lists
        echo 'not found: String '.$search.' was not found in lists';
    } else {
        echo 'found';
    }

add === and then try

A:
You just need to replace === with ==, So it will check variable type to, here your strpos() is returning 0 which will read as false as in your if will get

$dynamic_list = "AZ, CA, CO";
$static_list = "MN,WA,IA";
$search = "AZ";
if ( strpos($dynamic_list . ',' . $static_list, $search) === false && !empty($search) ) {
        echo 'not found: String '.$search.' was not found in lists';
} else {
        echo 'found';
}

A: Note our use of ===.  Simply == would not work as expected because the position of 'A' in 'AZ' is the 0th (first) character. So === will do the job
for you here. Let's try with ===
See examples here: https://www.php.net/manual/en/function.strpos.php
Warning

This function may return Boolean FALSE, but may also return a
  non-Boolean value which evaluates to FALSE. Please read the section on
  Booleans for more information. Use the === operator for testing the
  return value of this function.

<?php

$dynamic_list = "AZ, CA, CO";
$static_list = "MN,WA,IA";
$search = "AZ";

if (strpos($dynamic_list . ',' . $static_list, $search) === false) {
    echo 'not found: String '.$search.' was not found in lists';
} else {
    echo 'found';
}

DEMO: https://3v4l.org/bo4Yjr


text:
Q: switch the positions of date and author \documentclass[letterpaper,11pt]{article}

\usepackage{titling}
\usepackage[margin=4cm]{geometry}

\newcommand{\subtitle}[1]{%
  \posttitle{%
    \par\end{center}
    \begin{center}\large#1\end{center}
    \vskip0.5em}%
}

\setlength{\parindent}{0mm}
\setlength{\parskip}{1.5mm}

\begin{document}
\title{Title}
\subtitle{Subtitle}
\author{Dimitrios Anagnostou}
\date{mydate}
\maketitle

\end{document}

How can I reverse the positions of the \date and \author fields?
Thanks.

A: Something like this?
\documentclass{article}
\usepackage{titling,parskip}
\usepackage[margin=4cm]{geometry}

\makeatletter
\def\@maketitle{% modified from titling.sty
  \newpage
  \null
  \vskip 2em%
  \vspace*{\droptitle}
  \maketitlehooka
  {\@bspretitle \@title \@bsposttitle}
  \maketitlehookb
  {\@bspredate \@date \@bspostdate}
  \maketitlehookc
  {\@bspreauthor \@author \@bspostauthor}
  \maketitlehookd
  \par
  \vskip 1.5em}
\makeatother
\newcommand{\subtitle}[1]{%
  \posttitle{%
    \par\end{center}
    \begin{center}\large#1\end{center}
    \vskip0.5em}%
}

\begin{document}
\title{Title}
\subtitle{Subtitle}
\author{Dimitrios Anagnostou}
\date{mydate}
\maketitle
\end{document}

A: May be too obvious, but as \author and \date have the same format in this case, there are a quick and dirty way:
% for your eyes only ⚉
\author{\today}
\date{Dimitrios Anagnostou}

And yes, conceptually is a sacrilege. Nobody should know what you have done. Destroy your source code after the PDF compilation.


text:
Q: A question about homogeneous distribution A distribution in $\mathscr{S}^{\prime}\left(\mathbb{R}^{n}\right)$ is called homogeneous of degree $\gamma \in \mathbb{C}$ if for all $\lambda>0$ and for all $\varphi \in \mathscr{S}\left(\mathbb{R}^{n}\right),$ we have
$$
\left\langle u, \delta^{\lambda} \varphi\right\rangle=\lambda^{-n-\gamma}\langle u, \varphi\rangle.
$$
where $\delta^{\lambda} \varphi(x)=\varphi(\lambda x)$. Now suppose that $u \in C^{\infty}\left(\mathbb{R}^{n} \backslash\{0\}\right)$ is homogeneous of degree $-n+i \tau, \tau \in \mathbb{R} .$ How to prove that the operator given by convolution with $u$ maps $L^{2}\left(\mathbb{R}^{n}\right)$ to $L^{2}\left(\mathbb{R}^{n}\right)$.

A: Let $u$ be a smooth function on $\mathbb R^n\backslash\{0\}$ homogeneous with degree $\lambda$ (on $\mathbb R^n\backslash\{0\}$). If $\lambda$ is not an integer $\le -n$, then $u$ can be uniquely extended to a tempered distribution homogeneous with degree $\lambda$. Moreover, the Fourier transform of  an homogeneous distribution with degree $\lambda$ is an homogeneous distribution of degree $-\lambda-n$.
As a result, the Fourier transform of your $u$ is homogeneous with degree $n-i\tau-n=-i\tau$ when $\tau\in \mathbb R^*$, so is in one dimension a linear combination of $\xi_\pm^{-i\tau}$ which is thus bounded, proving the sought $L^2$ boundedness.
If $\tau =0$, then $u$ is homogeneous of degree $-1$ in one dimension. You need $u$ to be odd for the $L^2$ boundedness to hold. Take for instance (still in one dimension)
$u(x)=1/\vert x\vert$, obviously homogeneous with degree $-1$ and smooth on $\mathbb R^*$. The singular integral with kernel $1/\vert x-y\vert$ is not bounded on $L^2$, but the Hilbert transform with kernel $1/(x-y)$ is bounded on $L^2$ (with norm π).

A: By the Proposition 2.4.8. of L. Grafakos(GTM249), we have $\hat{u}\in C^{\infty}\left(\mathbb{R}^{n} \backslash\{0\}\right)$. It follows from $u$ is homogeneous of degree $-n+i\tau$ that $\hat{u}$ is a homogeneous distribution of degree $-i\tau$.Then,
$$\hat{u}(\xi)=|\xi|^{-i\tau}\hat{u}(\frac{\xi}{|\xi|}),$$
which implies that $|\hat{u}(\xi)|=\sup_{|x|=1}|\hat{u}(x)|<\infty$, i.e. $\hat{u}\in L^{\infty}(\mathbb{R}^{n})$. Thus,
$$\|u*f\|_{L^{2}}=\|\hat{u}\hat{f}\|_{L^{2}}\leq \|\hat{u}\|_{L^{\infty}}\|\hat{f}\|_{L^{2}}=\|\hat{u}\|_{L^{\infty}}\|f\|_{L^{2}}$$
for all $f \in L^{2}(\mathbb{R}^{n})$.


text:
Q: Difference between LG default calendar and Google calendars On my LG-G3 there is a default calendar named "Phone". It's not Google's.
I build an application which syncs events with the user's Google Calendars, but when I select all the calendars with a query - I get the "Phone" calendar too. Since it's not a Google calendar, I can't use it with the Google Calendar functions (insert, delete, etc.).
I can't see any different between "Phone" calendar and Google canledars except of its name. Is there any way to know if a calendar is Google's or not?
This is my query:
        String[] l_projection = new String[] { Calendars._ID, Calendars.CALENDAR_DISPLAY_NAME, Calendars.CALENDAR_ACCESS_LEVEL, Calendars.ALLOWED_REMINDERS, Calendars.SYNC_EVENTS };
        Uri l_calendars;
        if (Build.VERSION.SDK_INT >= 8) {
            l_calendars = Uri.parse("content://com.android.calendar/calendars");
        } else {
            l_calendars = Uri.parse("content://calendar/calendars");
        }

        try {
            Cursor l_managedCursor = activity.getContentResolver().query(l_calendars, l_projection, null, null, null);
            if (l_managedCursor.moveToFirst()) {
                String l_methodAllow;
                String l_accessPermission;
                String l_calName;
                String l_calId;
                String l_syncEvents;
                int l_cnt = 0;
                int l_syncEventsCol = l_managedCursor.getColumnIndex(l_projection[4]);
                int l_methodAllowCol = l_managedCursor.getColumnIndex(l_projection[3]);
                int l_accessPermissionCol = l_managedCursor.getColumnIndex(l_projection[2]);
                int l_nameCol = l_managedCursor.getColumnIndex(l_projection[1]);
                int l_idCol = l_managedCursor.getColumnIndex(l_projection[0]);
                do {
                    String access = l_managedCursor.getString(l_accessPermissionCol);
                    if (access.equals("500") || access.equals("600") || access.equals("700") || access.equals("800")) {
                        l_syncEvents = l_managedCursor.getString(l_syncEventsCol);
                        l_methodAllow = l_managedCursor.getString(l_methodAllowCol);
                        l_accessPermission = l_managedCursor.getString(l_accessPermissionCol);
                        l_calName = l_managedCursor.getString(l_nameCol);
                        l_calId = l_managedCursor.getString(l_idCol);

                        calNames.add(l_calName);
                        // ....

                        ++l_cnt;
                    }
                } while (l_managedCursor.moveToNext());
            }
        } catch (Exception e) {
            // ...
        }

A: Google calendar can be identified by looking at the domain name of the Calendar ID. For primary calendar, calendar ID domain name is @gmail.com. If its secondary calendar, calendar ID domain name is group.calendar.google.com


text:
Q: How to run doxygen in clion from cmake how should I set up the clion debugger to run the doxygen.cfg?
I tried to start it but I get the following error:

Scanning dependencies of target docs [100%] Generate documentation
CMakeFiles\docs.dir\build.make:76: recipe for target 'CMakeFiles/docs' failed CMakeFiles\Makefile2:153: recipe for target
'CMakeFiles/docs.dir/all' failed CMakeFiles\Makefile2:160: recipe for
target 'CMakeFiles/docs.dir/rule' failed Makefile:220: recipe for
target 'docs' failed process_begin: CreateProcess(NULL, rm -rf ../doc/html, ...) failed. make (e=2): Impossibile trovare il file
specificato. mingw32-make.exe[3]: *** [CMakeFiles/docs] Error 2
mingw32-make.exe[2]: *** [CMakeFiles/docs.dir/all] Error 2
mingw32-make.exe[1]: *** [CMakeFiles/docs.dir/rule] Error 2
mingw32-make.exe: *** [docs] Error 2

while to follow, respectively, the cmake and the doxygen:
cmake_minimum_required(VERSION 3.10)
project(Data-Master)

set(CMAKE_CXX_STANDARD 17)

include_directories(${PROJECT_SOURCE_DIR}/include)

add_library(data
        src/data.cpp
        include/data.h
        include/BST/bst.h
        deps/rapidcsv.h
        include/List/List.h)

set_target_properties(data PROPERTIES LINKER_LANGUAGE CXX)

add_executable(example examples/example.cpp include/data.h)

add_executable(tests tests/tests.cpp deps/catch.hpp include/data.h tests/tests.cpp)

add_compile_options(-Wall -Wextra -Wpedantic -Werror)

add_custom_target(docs
        COMMAND rm -rf ../doc/html
        COMMAND doxygen ../doxyconfig.cfg
        COMMAND mv html ../doc
        COMMENT "Generate documentation")

install(TARGETS example DESTINATION ${PROJECT_SOURCE_DIR}/bin)

enable_testing()

add_test(NAME bstint
        COMMAND tests [bstint])

add_test(NAME bstchars
        COMMAND tests [bstchars])

add_test(NAME bstint-dupp
        COMMAND tests [bstint-dupp])

add_test(NAME ListInteger
        COMMAND tests [ListInteger])

add_test(NAME Size
        COMMAND tests [Size])

add_test(NAME pushback
        COMMAND tests [pushback])

add_test(NAME listErase
        COMMAND tests [listErase])

add_test(NAME listPlus
        COMMAND tests [listPlus])

add_test(NAME listBracket
        COMMAND tests [listBracket])

add_test(NAME ListTransform
        COMMAND tests [listTransform])

add_test(NAME valgrind
        COMMAND valgrind ./example)

doxygen:
# Doxyfile 1.8.18

#---------------------------------------------------------------------------
# Project related configuration options
#---------------------------------------------------------------------------
DOXYFILE_ENCODING      = UTF-8
PROJECT_NAME           = "Data"
PROJECT_NUMBER         =
PROJECT_BRIEF          =
PROJECT_LOGO           =
OUTPUT_DIRECTORY       = docs
CREATE_SUBDIRS         = NO
ALLOW_UNICODE_NAMES    = NO
OUTPUT_LANGUAGE        = English
OUTPUT_TEXT_DIRECTION  = None
BRIEF_MEMBER_DESC      = YES
REPEAT_BRIEF           = YES
ABBREVIATE_BRIEF       = "The $name class" \
                         "The $name widget" \
                         "The $name file" \
                         is \
                         provides \
                         specifies \
                         contains \
                         represents \
                         a \
                         an \
                         the
ALWAYS_DETAILED_SEC    = NO
INLINE_INHERITED_MEMB  = NO
FULL_PATH_NAMES        = YES
STRIP_FROM_PATH        =
STRIP_FROM_INC_PATH    =
SHORT_NAMES            = NO
JAVADOC_AUTOBRIEF      = NO
JAVADOC_BANNER         = NO
QT_AUTOBRIEF           = NO
MULTILINE_CPP_IS_BRIEF = NO
INHERIT_DOCS           = YES
SEPARATE_MEMBER_PAGES  = NO
TAB_SIZE               = 4
ALIASES                =
OPTIMIZE_OUTPUT_FOR_C  = NO
OPTIMIZE_OUTPUT_JAVA   = NO
OPTIMIZE_FOR_FORTRAN   = NO
OPTIMIZE_OUTPUT_VHDL   = NO
OPTIMIZE_OUTPUT_SLICE  = NO
EXTENSION_MAPPING      =
MARKDOWN_SUPPORT       = YES
TOC_INCLUDE_HEADINGS   = 5
AUTOLINK_SUPPORT       = YES
BUILTIN_STL_SUPPORT    = NO
CPP_CLI_SUPPORT        = NO
SIP_SUPPORT            = NO
IDL_PROPERTY_SUPPORT   = YES
DISTRIBUTE_GROUP_DOC   = NO
GROUP_NESTED_COMPOUNDS = NO
SUBGROUPING            = YES
INLINE_GROUPED_CLASSES = NO
INLINE_SIMPLE_STRUCTS  = NO
TYPEDEF_HIDES_STRUCT   = NO
LOOKUP_CACHE_SIZE      = 0
#---------------------------------------------------------------------------
# Build related configuration options
#---------------------------------------------------------------------------
EXTRACT_ALL            = NO
EXTRACT_PRIVATE        = NO
EXTRACT_PRIV_VIRTUAL   = NO
EXTRACT_PACKAGE        = NO
EXTRACT_STATIC         = NO
EXTRACT_LOCAL_CLASSES  = YES
EXTRACT_LOCAL_METHODS  = NO
EXTRACT_ANON_NSPACES   = NO
HIDE_UNDOC_MEMBERS     = NO
HIDE_UNDOC_CLASSES     = NO
HIDE_FRIEND_COMPOUNDS  = NO
HIDE_IN_BODY_DOCS      = NO
INTERNAL_DOCS          = NO
CASE_SENSE_NAMES       = YES
HIDE_SCOPE_NAMES       = NO
HIDE_COMPOUND_REFERENCE= NO
SHOW_INCLUDE_FILES     = YES
SHOW_GROUPED_MEMB_INC  = NO
FORCE_LOCAL_INCLUDES   = NO
INLINE_INFO            = YES
SORT_MEMBER_DOCS       = YES
SORT_BRIEF_DOCS        = NO
SORT_MEMBERS_CTORS_1ST = NO
SORT_GROUP_NAMES       = NO
SORT_BY_SCOPE_NAME     = NO
STRICT_PROTO_MATCHING  = NO
GENERATE_TODOLIST      = YES
GENERATE_TESTLIST      = YES
GENERATE_BUGLIST       = YES
GENERATE_DEPRECATEDLIST= YES
ENABLED_SECTIONS       =
MAX_INITIALIZER_LINES  = 30
SHOW_USED_FILES        = YES
SHOW_FILES             = YES
SHOW_NAMESPACES        = YES
FILE_VERSION_FILTER    =
LAYOUT_FILE            =
CITE_BIB_FILES         =
#---------------------------------------------------------------------------
# Configuration options related to warning and progress messages
#---------------------------------------------------------------------------
QUIET                  = NO
WARNINGS               = YES
WARN_IF_UNDOCUMENTED   = YES
WARN_IF_DOC_ERROR      = YES
WARN_NO_PARAMDOC       = NO
WARN_AS_ERROR          = NO
WARN_FORMAT            = "$file:$line: $text"
WARN_LOGFILE           =
#---------------------------------------------------------------------------
# Configuration options related to the input files
#---------------------------------------------------------------------------
INPUT                  = "../include"
INPUT_ENCODING         = UTF-8
FILE_PATTERNS          = *.c \
                         *.cc \
                         *.cxx \
                         *.cpp \
                         *.c++ \
                         *.java \
                         *.ii \
                         *.ixx \
                         *.ipp \
                         *.i++ \
                         *.inl \
                         *.idl \
                         *.ddl \
                         *.odl \
                         *.h \
                         *.hh \
                         *.hxx \
                         *.hpp \
                         *.h++ \
                         *.cs \
                         *.d \
                         *.php \
                         *.php4 \
                         *.php5 \
                         *.phtml \
                         *.inc \
                         *.m \
                         *.markdown \
                         *.md \
                         *.mm \
                         *.dox \
                         *.doc \
                         *.txt \
                         *.py \
                         *.pyw \
                         *.f90 \
                         *.f95 \
                         *.f03 \
                         *.f08 \
                         *.f18 \
                         *.f \
                         *.for \
                         *.vhd \
                         *.vhdl \
                         *.ucf \
                         *.qsf \
                         *.ice
RECURSIVE              = YES
EXCLUDE                =
EXCLUDE_SYMLINKS       = NO
EXCLUDE_PATTERNS       =
EXCLUDE_SYMBOLS        =
EXAMPLE_PATH           =
EXAMPLE_PATTERNS       = *
EXAMPLE_RECURSIVE      = NO
IMAGE_PATH             =
INPUT_FILTER           =
FILTER_PATTERNS        =
FILTER_SOURCE_FILES    = NO
FILTER_SOURCE_PATTERNS =
USE_MDFILE_AS_MAINPAGE =
#---------------------------------------------------------------------------
# Configuration options related to source browsing
#---------------------------------------------------------------------------
SOURCE_BROWSER         = NO
INLINE_SOURCES         = NO
STRIP_CODE_COMMENTS    = YES
REFERENCED_BY_RELATION = NO
REFERENCES_RELATION    = NO
REFERENCES_LINK_SOURCE = YES
SOURCE_TOOLTIPS        = YES
USE_HTAGS              = NO
VERBATIM_HEADERS       = YES
CLANG_ASSISTED_PARSING = NO
CLANG_OPTIONS          =
CLANG_DATABASE_PATH    =
#---------------------------------------------------------------------------
# Configuration options related to the alphabetical class index
#---------------------------------------------------------------------------
ALPHABETICAL_INDEX     = YES
COLS_IN_ALPHA_INDEX    = 5
IGNORE_PREFIX          =
#---------------------------------------------------------------------------
# Configuration options related to the HTML output
#---------------------------------------------------------------------------
GENERATE_HTML          = YES
HTML_OUTPUT            = html
HTML_FILE_EXTENSION    = .html
HTML_HEADER            =
HTML_FOOTER            =
HTML_STYLESHEET        =
HTML_EXTRA_STYLESHEET  =
HTML_EXTRA_FILES       =
HTML_COLORSTYLE_HUE    = 220
HTML_COLORSTYLE_SAT    = 100
HTML_COLORSTYLE_GAMMA  = 80
HTML_TIMESTAMP         = NO
HTML_DYNAMIC_MENUS     = YES
HTML_DYNAMIC_SECTIONS  = NO
HTML_INDEX_NUM_ENTRIES = 100
GENERATE_DOCSET        = NO
DOCSET_FEEDNAME        = "Doxygen generated docs"
DOCSET_BUNDLE_ID       = org.doxygen.Project
DOCSET_PUBLISHER_ID    = org.doxygen.Publisher
DOCSET_PUBLISHER_NAME  = Publisher
GENERATE_HTMLHELP      = NO
CHM_FILE               =
HHC_LOCATION           =
GENERATE_CHI           = NO
CHM_INDEX_ENCODING     =
BINARY_TOC             = NO
TOC_EXPAND             = NO
GENERATE_QHP           = NO
QCH_FILE               =
QHP_NAMESPACE          = org.doxygen.Project
QHP_VIRTUAL_FOLDER     = doc
QHP_CUST_FILTER_NAME   =
QHP_CUST_FILTER_ATTRS  =
QHP_SECT_FILTER_ATTRS  =
QHG_LOCATION           =
GENERATE_ECLIPSEHELP   = NO
ECLIPSE_DOC_ID         = org.doxygen.Project
DISABLE_INDEX          = NO
GENERATE_TREEVIEW      = NO
ENUM_VALUES_PER_LINE   = 4
TREEVIEW_WIDTH         = 250
EXT_LINKS_IN_WINDOW    = NO
HTML_FORMULA_FORMAT    = png
FORMULA_FONTSIZE       = 10
FORMULA_TRANSPARENT    = YES
FORMULA_MACROFILE      =
USE_MATHJAX            = NO
MATHJAX_FORMAT         = HTML-CSS
MATHJAX_RELPATH        = https://cdn.jsdelivr.net/npm/mathjax@2
MATHJAX_EXTENSIONS     =
MATHJAX_CODEFILE       =
SEARCHENGINE           = YES
SERVER_BASED_SEARCH    = NO
EXTERNAL_SEARCH        = NO
SEARCHENGINE_URL       =
SEARCHDATA_FILE        = searchdata.xml
EXTERNAL_SEARCH_ID     =
EXTRA_SEARCH_MAPPINGS  =
#---------------------------------------------------------------------------
# Configuration options related to the LaTeX output
#---------------------------------------------------------------------------
GENERATE_LATEX         = NO
LATEX_OUTPUT           = latex
LATEX_CMD_NAME         =
MAKEINDEX_CMD_NAME     = makeindex
LATEX_MAKEINDEX_CMD    = makeindex
COMPACT_LATEX          = NO
PAPER_TYPE             = a4
EXTRA_PACKAGES         =
LATEX_HEADER           =
LATEX_FOOTER           =
LATEX_EXTRA_STYLESHEET =
LATEX_EXTRA_FILES      =
PDF_HYPERLINKS         = YES
USE_PDFLATEX           = YES
LATEX_BATCHMODE        = NO
LATEX_HIDE_INDICES     = NO
LATEX_SOURCE_CODE      = NO
LATEX_BIB_STYLE        = plain
LATEX_TIMESTAMP        = NO
LATEX_EMOJI_DIRECTORY  =
#---------------------------------------------------------------------------
# Configuration options related to the RTF output
#---------------------------------------------------------------------------
GENERATE_RTF           = NO
RTF_OUTPUT             = rtf
COMPACT_RTF            = NO
RTF_HYPERLINKS         = NO
RTF_STYLESHEET_FILE    =
RTF_EXTENSIONS_FILE    =
RTF_SOURCE_CODE        = NO
#---------------------------------------------------------------------------
# Configuration options related to the man page output
#---------------------------------------------------------------------------
GENERATE_MAN           = NO
MAN_OUTPUT             = man
MAN_EXTENSION          = .3
MAN_SUBDIR             =
MAN_LINKS              = NO
#---------------------------------------------------------------------------
# Configuration options related to the XML output
#---------------------------------------------------------------------------
GENERATE_XML           = NO
XML_OUTPUT             = xml
XML_PROGRAMLISTING     = YES
XML_NS_MEMB_FILE_SCOPE = NO
#---------------------------------------------------------------------------
# Configuration options related to the DOCBOOK output
#---------------------------------------------------------------------------
GENERATE_DOCBOOK       = NO
DOCBOOK_OUTPUT         = docbook
DOCBOOK_PROGRAMLISTING = NO
#---------------------------------------------------------------------------
# Configuration options for the AutoGen Definitions output
#---------------------------------------------------------------------------
GENERATE_AUTOGEN_DEF   = NO
#---------------------------------------------------------------------------
# Configuration options related to the Perl module output
#---------------------------------------------------------------------------
GENERATE_PERLMOD       = NO
PERLMOD_LATEX          = NO
PERLMOD_PRETTY         = YES
PERLMOD_MAKEVAR_PREFIX =
#---------------------------------------------------------------------------
# Configuration options related to the preprocessor
#---------------------------------------------------------------------------
ENABLE_PREPROCESSING   = YES
MACRO_EXPANSION        = NO
EXPAND_ONLY_PREDEF     = NO
SEARCH_INCLUDES        = YES
INCLUDE_PATH           =
INCLUDE_FILE_PATTERNS  =
PREDEFINED             =
EXPAND_AS_DEFINED      =
SKIP_FUNCTION_MACROS   = YES
#---------------------------------------------------------------------------
# Configuration options related to external references
#---------------------------------------------------------------------------
TAGFILES               =
GENERATE_TAGFILE       =
ALLEXTERNALS           = NO
EXTERNAL_GROUPS        = YES
EXTERNAL_PAGES         = YES
#---------------------------------------------------------------------------
# Configuration options related to the dot tool
#---------------------------------------------------------------------------
CLASS_DIAGRAMS         = YES
DIA_PATH               =
HIDE_UNDOC_RELATIONS   = YES
HAVE_DOT               = NO
DOT_NUM_THREADS        = 0
DOT_FONTNAME           = Helvetica
DOT_FONTSIZE           = 10
DOT_FONTPATH           =
CLASS_GRAPH            = YES
COLLABORATION_GRAPH    = YES
GROUP_GRAPHS           = YES
UML_LOOK               = NO
UML_LIMIT_NUM_FIELDS   = 10
TEMPLATE_RELATIONS     = NO
INCLUDE_GRAPH          = YES
INCLUDED_BY_GRAPH      = YES
CALL_GRAPH             = NO
CALLER_GRAPH           = NO
GRAPHICAL_HIERARCHY    = YES
DIRECTORY_GRAPH        = YES
DOT_IMAGE_FORMAT       = png
INTERACTIVE_SVG        = NO
DOT_PATH               =
DOTFILE_DIRS           =
MSCFILE_DIRS           =
DIAFILE_DIRS           =
PLANTUML_JAR_PATH      =
PLANTUML_CFG_FILE      =
PLANTUML_INCLUDE_PATH  =
DOT_GRAPH_MAX_NODES    = 50
MAX_DOT_GRAPH_DEPTH    = 0
DOT_TRANSPARENT        = NO
DOT_MULTI_TARGETS      = NO
GENERATE_LEGEND        = YES
DOT_CLEANUP            = YES

thanks for help

A: Try COMMAND rm -rf ../doc/html || true.  This is a quick work-around, as it does not guarantee that the directory will not exist after running this command.  But that anomaly should be rare and it should be caught by mv if you use a better syntax: COMMAND mv -t../doc html.


text:
Q: How to transform image opencv in android I am only a android beginner for Opencv. here is the simple code to tranform image. but I have tried to do a image tansformation for few days. but I cannot figure out what is problem. I think that the part blow comment (src,dst) is wrong asertation.
I need you guys help right now.
(something like Android OpenCV getPerspectiveTransform and warpPerspective).
here is my logcat.
E/AndroidRuntime(9880): CvException [org.opencv.core.CvException: /home/reports/ci/slave_desktop/50-SDK/opencv/modules/java/generator/src/cpp/utils.cpp:97: error: (-215) src.dims == 2 && info.height == (uint32_t)src.rows && info.width == (uint32_t)src.cols in function void Java_org_opencv_android_Utils_nMatToBitmap2(JNIEnv*, jclass, jlong, jobject, jboolean)
public class MainActivity extends Activity implements OnClickListener{
private Button btnProc;
 private ImageView imageView;
 private Bitmap bmp,bmp1;

 private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
     @Override
     public void onManagerConnected(int status) {
         switch (status) {
            case LoaderCallbackInterface.SUCCESS:{
            } break;
            default:{
             super.onManagerConnected(status);
             } break;
         }
     }
 };

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btnProc = (Button) findViewById(R.id.btn_gray_process);
    imageView = (ImageView) findViewById(R.id.image_view);
    btnProc.setOnClickListener(this);
}

public void onClick(View v) {

    bmp = BitmapFactory.decodeResource(getResources(),R.drawable.a2);
    Mat original_image = new Mat();
    Utils.bitmapToMat(bmp, original_image);

    Mat dst = new Mat(4,1,CvType.CV_32FC2);
    Mat src = new Mat(4,1,CvType.CV_32FC2);
    src.put(0,0,407.0,74.0,1606.0,74.0,420.0,2589.0,1698.0,2589.0);
        dst.put(0,0,0.0,0.0,1600.0,0.0, 0.0,2500.0,1600.0,2500.0);
    Mat perspectiveTransform = Imgproc.getPerspectiveTransform(src, dst);
    Mat cropped_image = original_image.clone();
    Imgproc.warpPerspective(src, cropped_image, perspectiveTransform, new Size(512,512));
    bmp1 = Bitmap.createBitmap(400, 400, Config.RGB_565);
    Utils.matToBitmap(dst, bmp1);

    imageView.setImageBitmap(bmp1);
}

public void onResume(){
     super.onResume();
     OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_9, this,mLoaderCallback);
}

}

A: You need to be careful that the parameters to the various functions are of the right type and dimensions. For example, this call here:
   Imgproc.warpPerspective(src, cropped_image, perspectiveTransform, new Size(512,512));

I suspect you don't really want src here as it's a 4x1 CV_32FC2. This should probably be original_image.
Also, here:
  Utils.matToBitmap(dst, bmp1);

again, dst is a 4x1 CV_32FC2. I suspect you should try cropped_image instead.


text:
Q: Permission denied when creating text file in asp I have the following code:
<%
dim deviceid
dim fso
dim outFile

deviceid=Request.QueryString("deviceid")

If deviceid<>"" Then
    Response.Write("Hello " & deviceid & "!<br>")

    Set fso = Server.CreateObject("Scripting.FileSystemObject")
    Set outFile = fso.CreateTextFile("C:\Users\Victor\Desktop\respTank.txt")
    outFile.WriteLine("Hello World!")
    outFile.close

    set outFile = nothing
    set fso = nothing

End If
%>

I get the following error:
Microsoft VBScript runtime error '800a0046'
Permission denied
I gave all permissions to IIS_IUSRS but it didn't help. Can anyone help me here?

A: It sounds like the ApplicationPoolIdentity is not the user context being used by the Web Application.
Depending on the IIS Version, you want to check (using the Manager)

IIS 4-6
Web Site / Application Properties -> Document Security
IIS 7+
Web Site / Application -> Authentication

and check the Anonymous Account which can be set differently to the ApplicationPoolIdentity.
Based on this value apply the permissions (at least Modify) to the folder C:\Users\Victor\Desktop\ and you are good to go.

A: I just had the same thing happening on a delete file, have you tried removing the parenthesis?
Set outFile = fso.CreateTextFile("C:\Users\Victor\Desktop\respTank.txt")

to
Set outFile = fso.CreateTextFile "C:\Users\Victor\Desktop\respTank.txt"


text:
Q: Are there Unicode Letters which are neither upper- nor lower-case? Are there Unicode-codepoints which represent letters but which are neither upper- nor lower-case?
In particular are there characters for which the Java-Function java.lang.Character.isLetter will return true, but java.lang.Character.isUpperCase and java.lang.Character.isLowerCase will return false?

A: It's trivial to test this for yourself:
public class Test {
  public static void main(String[] args) {
    for (int i = Character.MIN_CODE_POINT;
         i <= Character.MAX_CODE_POINT;
         i++) {
      if (Character.isLetter(i) &&
          !Character.isUpperCase(i) &&
          !Character.isLowerCase(i)) {
        System.out.printf("%04x %c%n", i, i);
      }
    }
  }
}

You'll find that writes out lots of entries.

A: Not all scripts have the concept of upper and lower case letters, for example Thai. You should find that the Java API mirrors the Unicode data defined in the standard. For example, look at the Thai letter kho rakhang at http://www.fileformat.info/info/unicode/char/e06/index.htm

A: Most of them. Chinese characters for instance. And if you check http://docs.oracle.com/javase/tutorial/i18n/text/charintro.html isLetter returns true, but they are neither lowercase or uppercase.


text:
Q: Sketch.js pageX undefined error I am using sketch.js by intridea in my phonegap application.It works allright with the modification
 case 'touchstart':
            if (this.painting) {//add
                this.stopPainting();
                //add
            }//add
            this.startPainting();
            break;

by adding the above lines to the code.But I am getting a pageX undefined error which is crashing my app.
01-23 19:53:59.342: E/Web Console(31932): Uncaught TypeError: Cannot read property 'pageX' of undefined at file:///android_asset/www/js/external_libs/sketch.js:107

How to overcome this issue,any help would be appreciated.Thanks

A: It seems as if everyone has swtiched over to jqscribbel.js, but to directly answer this question with sketch.js, you need to check if e.originalEvent.targetTouches[0] is defined.  I haven't dug into sketch.js too much yet, but it seems that when a touchup event is triggered, e.originalEvent.targetTouches[0] is no longer defined, so trying to find .pageX of undefined gives an error.  This error causes the entire canvas to be re-drawn, so you cannot draw more than 1 sketch on the canvas.  To fix this error, simply add find the following two lines of code (around line 100/101):
e.pageX = e.originalEvent.targetTouches[0].pageX;
e.pageY = e.originalEvent.targetTouches[0].pageY;

and replace with
if (e.originalEvent.targetTouches[0] !== undefined && e.originalEvent.targetTouches[0].pageX !== undefined){
    e.pageX = e.originalEvent.targetTouches[0].pageX;
}
if (e.originalEvent.targetTouches[0] !== undefined && e.originalEvent.targetTouches[0].pageY !==undefined){
    e.pageY = e.originalEvent.targetTouches[0].pageY;
}


text:
Q: Making squares disappear - iOS I am planing to make an app for iPhone
I want to include some squares and assign a number to each square.
when a user taps on a square, it should disappear along with some other squares, for example:
If there are squares (1,2,3,4,5,6,7,8,9,10), the user selects 7 for example, so square number
7 should disappear along with all squares (square > 7) so the remaining squares must be
(1,2,3,4,5,6).
What is the best way to do this ?

A: You can create an NSArray of all the buttons and simply set the Alpha of the squares you wish to disappear.
Something like that:
-(void)removeSquersAfterSelection:(NSInteger)selectedSqure
{
  for(NSInteger i=0;i<squersArray;i++){
    if(i<=selectedSqure){
        [squersArray objectAtIndex:i].alpha = 0;
    }

  }
}

Good luck

A: [theSquare removeFromSuperview];

If you subclass a UIButton you can override this method and do some working out in it:
MyCustomButton *theSquare1 = [[MyCustomButton alloc] initWithSquareNumber:1];
[theSquare1 addTarget:self action:@selector(removeFromSuperview) forControlEvents:UIControlEventTouchUpInside];

Then in MyCustomButton.m:
- (void)removeFromSuperview {
    [super removeFromSuperview];
    // you can delete the button from the database or something here...
    // or keep score in the game or similar.
}

Then if you do what shani said and keep an array of these buttons you can iterate through them and find any higher than the one you've got.


text:
Q: Refreshing UserDefaults Variable not working I have a navigation view that uses User defaults, when I am on a different page I have a button that adds += 1 to the userDefualts variable. When I go back there, it doesn't refresh unless I swipe the app. That is super weird, what I want to happen is it automatically refreshes when I enter that page.
Nav View that I need refreshed:
struct Analytics: View {

@ObservedObject var viewModel = VariableViewModel()

 HStack {
                    // Problems compleated
                    Text(" Amount of problems compleated:")
                        .font(.system(size: 20))
                        .foregroundColor(.black)

                    Spacer()

                    Text(String(viewModel.problemsCompleated))
                        .font(.system(size: 20))
                        .foregroundColor(.yellow)
                        .bold()
                        .offset(x: -5, y: 0)
                }.offset(x: 0, y: 5)
}

Nav View were the variables sit and are being changed:
class VariableViewModel: ObservableObject {
    // analytics
    @Published var problemsCompleated = UserDefaults.standard.integer(forKey: "problemsCompleated")

problemsCompleated += 1
UserDefaults.standard.set(problemsCompleated, forKey: "problemsCompleated")
}

A: With your current code, if you're using different instances of VariableViewModel, you won't see it refresh because it only ever pulls from UserDefaults on instantiation. So, when you go 'back' to the other page, it has no way of knowing that variable has been updated.
If you were just within your view, I'd recommend using @AppStorage, since it does all the lifting of checking and updating UserDefaults for you. In the ObservableObject, it's slightly more complicated, because @AppStorage won't trigger an update like @Published. But, it looks like by manually calling objectWillChange when the @AppStorage is set, we can get the best of both worlds:
class VariableViewModel: ObservableObject {
    @AppStorage("problemsCompleted") var problemsCompleted = 0 {
        didSet {
            self.objectWillChange.send()
        }
    }

    func increment() {
        problemsCompleted += 1
    }
}


text:
Q: Force UWP app to run always with 100% screen scale factor My UWP application layout is working as expected when screen scale is 100%. But when I change it from "Display Settings > Change the size of text, apps, and other items" to any value larger than 100% like 125% or 150% the layout is damaged.
So I need to know how to force it run always on 100% scale factor, even if use changed it from Display Settings.
This is available and easy in WPF, but I need to do the same in UWP windows apps.

A: I think you should fix your Layout to be able to scale correctly instead of trying to force a 100% scale factor. Some devices (e.g. Surface Book) use a scale factor of 200% as default, so your application would be scaled wrong if you force it to 100%. Use VisualStates to change the layout when resized/scaled.


text:
Q: Python 2.5 and lists in function arguments I'm trying to accomplish something in Python2.5
So I have my function
def f(a,b,c,d,e):
    pass

and now I'd like to call that function: (in python2.7 I would do)
my_tuple = (1,2,3)
f(0, *my_tuple, e=4)

But there is no way to do it in python2.5. I'm thinking about apply()
apply(f, something magical here)

#this doesn't work - multiple value for 'a'. But it's the only thing I came up with
apply(f, my_tuple, {"a":0, "e":4})

How would you do it? I'd like to do it inline, without putting things in list before.

A: If you're willing to swap the order of arguments then you could use something like this:
>>> def f(a,b,c,d,e):
...  print a,b,c,d,e
...
>>> my_tuple = (1,2,3)
>>> def apply(f, mid, *args, **kwargs):
...  return f(*args+mid, **kwargs)
...
>>> apply(f, my_tuple, 0, e=4)
0 1 2 3 4
>>>
>>> apply(f, ('a', 'b'), '_', d='c', e='d')
_ a b c d
>>>


text:
Q: How to Customise the Alert OK / Cancel buttons using this aritchie/userdialogs in Xamarin Forms Hi I am new to Xamarin Forms and am from native iOS development.
For showing alerts / action sheets I am using this https://github.com/aritchie/userdialogs.
For implementing this I followed this How to use Acr.UserDialogs.
I am getting alert successfully by following this, but now I need to customise the OK / Cancel Button's background color, alignment, frame values, hide and show the buttons..
Thanks in advance.

A:
I need to customise the OK / Cancel Button's background color, alignment, frame values, hide and show the buttons.

As the author said, you could do this by creating a style and apply it in AlertConfig.
For example:
In the style.xml:

And you could find this style Id in the Resource.Designer.cs.
// aapt resource value: 0x7f0b0189
public const int AlertDialogCustom = 2131427721;

Then in the code create a AlertConfig to config the alertdialog:
AlertConfig alertConfig = new AlertConfig();
alertConfig.OkText = "OKOK";
alertConfig.Message = "Message";
alertConfig.Title = "Title";
alertConfig.AndroidStyleId=2131427721;
UserDialogs.Instance.Alert(alertConfig);

A: With Rg.Plugins.Popup Nuget you can customize the popup.

A: Finally I am not using any nugget packages. Now I created my own CustomAlert class. I hope it will helpful for any one.
@Miguel Angel please look at below code
In my CustomAlert.xaml  file
<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="wwww/2009/xaml" x:Class="MY.UserControls.CustomAlert">

<Grid RowSpacing="0" ColumnSpacing="0">

      <Grid BackgroundColor="#656565" Opacity="0.5">
       </Grid>

      <StackLayout  BackgroundColor="{StaticResource WhiteColor}"                     VerticalOptions="Center" Margin="10" Padding="10" >

<Button Text="OK" TextColor="{StaticResource WhiteColor}"
Command="{Binding DismissCustomAlertCommand}"
HorizontalOptions="Center" VerticalOptions="Center"
BackgroundColor="Red" Margin="30,0,30,0" WidthRequest="400" HeightRequest="40"></Button>

        </StackLayout>
    </Grid>
 </ContentView>

Thank you


text:
Q: Force symmetry for a TensorFlow conv2d kernel I'd like to enforce symmetry in the weights within a Variable.  I really want an approximate circular symmetry.  However, I could imagine either row or column enforced symmetry.
The goal is to reduce training time by reducing the number of free variables.  I know my problem would like a symmetric array but I might want to include both symmetric and "free" variables.  I am using conv2d now, so I believe I need to keep using it.

A: Here is a function that creates a kernel symmetric with respect to reflection over its center row:
def SymmetricKernels(height,width,in_channels,out_channels,name=None):
    half_kernels = tf.Variable(initial_value=tf.random_normal([(height+1)//2,width,in_channels,out_channels]))
    half_kernels_reversed = tf.reverse(half_kernels[:(height//2),:,:,:],[0])
    kernels = tf.concat([half_kernels,half_kernels_reversed],axis=0,name=name)
    return kernels

Usage example:
w = SymmetricKernels(5,5,1,1)
sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())
w_ = sess.run(w)
w_[:,:,0,0]
# output:
# [[-1.299 -1.835 -1.188  0.093 -1.736]
#  [-1.426 -2.087  0.434  0.223 -0.65 ]
#  [-0.217 -0.802 -0.892 -0.229  1.383]
#  [-1.426 -2.087  0.434  0.223 -0.65 ]
#  [-1.299 -1.835 -1.188  0.093 -1.736]]

The idea is to use tf.Variable() to create only the upper half variables of the kernels (half_kernels), and then form the symmetric kernels as a concatenation of the upper half and its reflected version.
This idea can be extended to create also kernels with both left-right and up-down symmetries.

A: Another thing you can try is to tie the net's hands by convolving twice, reusing the kernel but flipping it for the second convolution (untested code):
def symmetric_convolution(input_tensor, n_filters, size, name, dilations=[1,1,1,1]):
    with tf.variable_scope("", reuse=tf.AUTO_REUSE):
        kernel = tf.get_variable(shape=[*size, input_tensor.shape[-1], n_filters], name='conv_kernel_' + name, ...)
        lr_flipped_kernel = tf.reverse(kernel, axis=[1], name='conv_kernel_flipped_lr_' + name)

    conv_l = tf.nn.conv2d(input=input_tensor, filter=kernel, strides=[1, 1, 1, 1], padding='SAME', dilations=dilations)
    conv_r = tf.nn.conv2d(input=input_tensor, filter=lr_flipped_kernel, strides=[1, 1, 1, 1], padding='SAME', dilations=dilations)

    return tf.reduce_max(tf.concat([conv_l, conv_r], axis=-1), keepdims=True, axis=[-1])

You can add in biases, activations, etc. as needed. I've used something similar in the past – reduce_max will allow your kernel to take whatever shape, and effectively give you two convolutions for one; if you use reduce_sum instead, any asymmetries will average out quite quickly and your kernel will be symmetric. What works best will depend on your use case.


text:
Q: Matching controls to cases using multiple conditions I want to match 2 controls for every case with two conditions:

*

*the age difference should between ±2;

*the income difference should between ±2.
If there are more than 2 controls for a case, I just need select 2 controls randomly.
There is an example:
EXAMPLE
DATA
dat = structure(list(id = c(1, 2, 3, 4, 111, 222, 333, 444, 555, 666,
                     777, 888, 999, 1000),
              age = c(10, 20, 44, 11, 12, 11, 8, 12,  11, 22, 21, 18, 21, 18),
              income = c(35, 72, 11, 35, 37, 36, 33,  70, 34, 74, 70, 44, 76, 70),
              group = c("case", "case", "case", "case", "control", "control",
                        "control", "control", "control", "control", "control",
                        "control", "control", "control")),
         row.names = c(NA, -14L), class = c("tbl_df", "tbl", "data.frame"))

> dat
# A tibble: 14 x 4
      id   age income group
   <dbl> <dbl>  <dbl> <chr>
 1     1    10     35 case
 2     2    20     72 case
 3     3    44     11 case
 4     4    11     35 case
 5   111    12     37 control
 6   222    11     36 control
 7   333     8     33 control
 8   444    12     70 control
 9   555    11     34 control
10   666    22     74 control
11   777    21     70 control
12   888    18     44 control
13   999    21     76 control
14  1000    18     70 control

EXPECT OUTCOME
For id = 1, the matched controls as below, and I just need select 2 controls randomly in the table below.

id
age
income
group

111
12
37
control

222
11
36
control

333
8
33
control

555
11
34
control

For id = 2,the matched controls as below, and I just need select 2 controls randomly in the table below.

id
age
income
group

666
22
74
control

777
21
70
control

1000
18
70
control

For id = 3,there is no matched controls in dat.
For id = 4, the matched controls as below, and I just need select 2 controls randomly in the table below.

One thing to note here is that we can find that the controls for id = 1 and id = 4 have overlapping parts. I don't want two cases to share a control, what I need is that if id = 1 chooses id = 111 and id = 222 as control, then id = 4 can only choose id = 555 as control, and if id = 1 chooses id = 111 and id = 333 as control, then id = 4 can only choose id = 222 and id = 555 as controls.

id
age
income
group

111
12
37
control

222
11
36
control

555
11
34
control

The final output maybe like this(the id in control group is randomly selected from the id that meets the conditions):

id
age
income
group

1
10
35
case

2
20
72
case

3
44
11
case

4
11
35
case

111
12
37
control

222
11
36
control

333
8
33
control

555
11
34
control

777
21
70
control

1000
18
70
control

NOTE
I've looked up some websites, but they don't meet my needs. I don't know how to implement my requirements using R code.
Any help will be highly appreciated!
Reference:
1.https://stackoverflow.com/questions/56026700/is-there-any-package-for-case-control-matching-individual-1n-matching-in-r-n
2.Case control matching in R (or spss), based on age, sex and ethnicity?
3.Matching case-controls in R using the ccoptimalmatch package
4.Exact Matching in R

A: As per modified requirement, I propose the following for loop
library(dplyr, warn.conflicts = F)

dat %>%
  split(.$group) %>%
  list2env(envir = .GlobalEnv)
#> <environment: R_GlobalEnv>

control$FILTER <- FALSE
control
#> # A tibble: 10 x 5
#>       id   age income group   FILTER
#>    <dbl> <dbl>  <dbl> <chr>   <lgl>
#>  1   111    12     37 control FALSE
#>  2   222    11     36 control FALSE
#>  3   333     8     33 control FALSE
#>  4   444    12     70 control FALSE
#>  5   555    11     34 control FALSE
#>  6   666    22     74 control FALSE
#>  7   777    21     70 control FALSE
#>  8   888    18     44 control FALSE
#>  9   999    21     76 control FALSE
#> 10  1000    18     70 control FALSE

set.seed(123)

for(i in seq_len(nrow(case))){
  x <- which(between(control$age, case$age[i] -2, case$age[i] +2) &
               between(control$income, case$income[i] -2, case$income[i] + 2) &
               !control$FILTER)
  control$FILTER[sample(x, min(2, length(x)))] <- TRUE
}

control
#> # A tibble: 10 x 5
#>       id   age income group   FILTER
#>    <dbl> <dbl>  <dbl> <chr>   <lgl>
#>  1   111    12     37 control TRUE
#>  2   222    11     36 control TRUE
#>  3   333     8     33 control TRUE
#>  4   444    12     70 control FALSE
#>  5   555    11     34 control TRUE
#>  6   666    22     74 control FALSE
#>  7   777    21     70 control TRUE
#>  8   888    18     44 control FALSE
#>  9   999    21     76 control FALSE
#> 10  1000    18     70 control TRUE

bind_rows(case, control) %>% filter(FILTER | is.na(FILTER)) %>% select(-FILTER)
#> # A tibble: 10 x 4
#>       id   age income group
#>    <dbl> <dbl>  <dbl> <chr>
#>  1     1    10     35 case
#>  2     2    20     72 case
#>  3     3    44     11 case
#>  4     4    11     35 case
#>  5   111    12     37 control
#>  6   222    11     36 control
#>  7   333     8     33 control
#>  8   555    11     34 control
#>  9   777    21     70 control
#> 10  1000    18     70 control

Check results for a different seed
set.seed(234)
for(i in seq_len(nrow(case))){
  x <- which(between(control$age, case$age[i] -2, case$age[i] +2) &
               between(control$income, case$income[i] -2, case$income[i] + 2) &
               !control$FILTER)
  control$FILTER[sample(x, min(2, length(x)))] <- TRUE
}
control

bind_rows(case, control) %>% filter(FILTER | is.na(FILTER)) %>% select(-FILTER)

# A tibble: 10 x 4
      id   age income group
   <dbl> <dbl>  <dbl> <chr>
 1     1    10     35 case
 2     2    20     72 case
 3     3    44     11 case
 4     4    11     35 case
 5   111    12     37 control
 6   222    11     36 control
 7   333     8     33 control
 8   555    11     34 control
 9   777    21     70 control
10  1000    18     70 control

dat modified before proceeding for id 3

*

*split the data into two groups case and control using baseR's `split

*save two as separate dfs using list2env

*using purrr::map_df you can take sample 2 rows for each case

*

*once for age

*and once for income

*finally sample 2 rows again from each of these results

*bind_rows again these with case also

library(tidyverse)

dat = structure(list(id = c(1, 2, 3, 111, 222, 333, 444, 555, 666, 777, 888, 999, 1000),
                     age = c(10, 20, 44, 12, 11, 8, 12, 11, 22, 21, 18, 21, 18),
                     income = c(35, 72, 11, 37, 36, 33, 70, 34, 74, 70, 44, 76, 70),
                     group = c("case", "case", "case", "control", "control", "control",
                               "control", "control", "control", "control", "control",
                               "control", "control")),
                row.names = c(NA, -13L), class = c("tbl_df", "tbl", "data.frame"))

dat
#> # A tibble: 13 x 4
#>       id   age income group
#>    <dbl> <dbl>  <dbl> <chr>
#>  1     1    10     35 case
#>  2     2    20     72 case
#>  3     3    44     11 case
#>  4   111    12     37 control
#>  5   222    11     36 control
#>  6   333     8     33 control
#>  7   444    12     70 control
#>  8   555    11     34 control
#>  9   666    22     74 control
#> 10   777    21     70 control
#> 11   888    18     44 control
#> 12   999    21     76 control
#> 13  1000    18     70 control

dat %>%
  split(.$group) %>%
  list2env(envir = .GlobalEnv)
#> <environment: R_GlobalEnv>

set.seed(123)
bind_rows(case, map_dfr(case$age, ~ control %>% filter(between(age, .x -2, .x +2) ) %>%
       sample_n(min(n(),2))) %>% sample_n(min(n(),2)),
       map_dfr(case$income, ~ control %>% filter(between(income, .x -2, .x +2)) %>%
                 sample_n(min(n(),2))) %>% sample_n(min(n(),2)))
#> # A tibble: 7 x 4
#>      id   age income group
#>   <dbl> <dbl>  <dbl> <chr>
#> 1     1    10     35 case
#> 2     2    20     72 case
#> 3     3    44     11 case
#> 4   222    11     36 control
#> 5   777    21     70 control
#> 6   111    12     37 control
#> 7   333     8     33 control

the below code will also do the same without saving individual dfs
dat %>%
  split(.$group) %>%
  {bind_rows(.$case,
             map_dfr(.$case$age, \(.x) .$control %>% filter(between(age, .x -2, .x +2) ) %>%
                       sample_n(min(n(),2))) %>% sample_n(min(n(),2)),
             map_dfr(.$case$income, \(.x) .$control %>% filter(between(income, .x -2, .x +2)) %>%
                       sample_n(min(n(),2))) %>% sample_n(min(n(),2)))}

A: Separate case and control in different dataframes. For each row in case_data find the matching rows in control_data and select 2 random rows from it.
Using map_df we can combine everything in one dataframe.
library(dplyr)
library(purrr)

case_data <- dat %>% filter(group == 'case')
control_data <- dat %>% filter(group == 'control')

case_data %>%
  group_split(row_number(), .keep = FALSE) %>%
  map_df(~bind_rows(.x, control_data %>%
                    filter(between(age, .x$age - 2, .x$age + 2),
                           between(income, .x$income - 2, .x$income + 2)) %>%
        slice_sample(n = 2)))

#     id   age income group
#  <dbl> <dbl>  <dbl> <chr>
#1     1    10     35 case
#2   333     8     33 control
#3   111    12     37 control
#4     2    20     72 case
#5   666    22     74 control
#6   777    21     70 control

A: You could also the following solution. I wrapped map2 function inside curly braces so that I could choose what variables I would like to use for .x and .y, otherwise %>% would've replace the whole data set as the first argument:
library(dplyr)
library(purrr)

dat %>%
  filter(group == "case") %>%
  group_by(id) %>%
  {map2(.$age, .$income, ~ dat %>%
          filter(group == "control" & age >= .x - 2 & age <= .x + 2 &
                   income >= .y - 2 & income <= .y + 2))} %>%
  map_dfr(~ .x %>%
            slice_sample(n = 2)) %>%
  bind_rows(dat %>%
              filter(group == "case")) %>%
  arrange(id)

# A tibble: 7 x 4
     id   age income group
  <dbl> <dbl>  <dbl> <chr>
1     1    10     35 case
2     2    20     72 case
3     3    44     11 case
4   222    11     36 control
5   333     8     33 control
6   777    21     70 control
7  1000    18     70 control


text:
Q: Submit WebSocket request with Nested Arrays in PHP Below I have this WebSocket Request;
{
  "id": 2,
  "command": "submit",
  "tx_json" : {
      "TransactionType" : "TrustSet",
      "Account" : "r████████████████████████████",
      "Amount" : {
         "currency" : "FLX",
         "value" : "100000000",
         "issuer" : "r████████████████████████████"
      }
   },
   "secret" : "s████████████████████████████",
   "offline": false,
   "fee_mult_max": 1000
}

What I have below is a PHP WebSocket Request;
What I am struggling with is you see how tx_json in the above example is like an Array.
How would I replicate this in the below Example ; Also Amount is an Array within an Array.
Then also values like Secret which is outside of the Array.
Thankyou for any help.
<?php
    $server = 'xrpl.ws';
    $submitTransaction = json_encode(array(
        'id' => 2,
        'command' => "submit",

?????

    ));

    if( $sp = websocket_open($server, 443,'',$errstr, 10,true) ) {
      websocket_write($sp,$submitTransaction);
      $result = websocket_read($sp,$errstr);
    }else {
      echo "Failed to connect to server\n";
      echo "Server responed with: $errstr\n";
    }
?>

A: Convert example json to array and send it:
$json = '{
  "id": 2,
  "command": "submit",
  "tx_json" : {
      "TransactionType" : "TrustSet",
      "Account" : "r████████████████████████████",
      "Amount" : {
         "currency" : "FLX",
         "value" : "100000000",
         "issuer" : "r████████████████████████████"
      }
   },
   "secret" : "s████████████████████████████",
   "offline": false,
   "fee_mult_max": 1000
}';
$jsonAsArray = json_decode($json, true);
// arrayAsVariable
var_export($jsonAsArray);


text:
Q: How to update ListBoxItem property I want to update DownloadingSpeed Property which is binded to TextBox in a ListBoxItem. I am generating ListBoxItems in c#. Please guide me how do i update Binding Content of TextBoxes within a ListItemBox in C#.
WPF LisBox Code
 <ListBox Width="Auto"
                 Name="WebsiteList"
                 MouseUp="SelectedListItem"
                 SelectedIndex="0"
                 Grid.Column="1"
                 Grid.Row="2"
                 Grid.RowSpan="2"
                 Margin="0,0,0,0">
            <ListBox.ItemTemplate>
            <DataTemplate>
                    <Grid Width="920">
                    <StackPanel Orientation="Vertical">
                            <StackPanel Orientation="Horizontal">
                                <Grid Width="920">
                                <TextBlock FontWeight="Bold" FontSize="18" Width="Auto">
                                <Hyperlink NavigateUri="http://google.com" FontStyle="Italic">
                                    <Label Content="{Binding WebsiteTitle}" /><Label FontSize="10" Margin="0,0,0,3" Content="{Binding DirectorySize}" />
                                </Hyperlink>
                                </TextBlock>

                                <TextBlock Width="0" TextAlignment="right">
                                    <TextBlock Visibility="Hidden" Text="{Binding DownloadID}"/>
                                    <TextBlock Visibility="Hidden" Text="{Binding DirectoryPath}"/>
                                    <TextBlock Visibility="Hidden" Text="{Binding CurrentTime}"/>
                                    <TextBlock Visibility="Hidden" Text="{Binding CurrentDate}"/>
                                    <TextBlock Visibility="Hidden" Text="{Binding GivenUrl}"/>
                                </TextBlock>
                                </Grid>

                            </StackPanel>

                        <StackPanel Orientation="Horizontal">
                                <Grid Width="920">
                                    <ProgressBar Name="progress1" Maximum="100" Minimum="0" Value="30" Background="#FFF" Width="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Grid}}, Path=Width}" Height="10" />
                                </Grid>
                        </StackPanel>
                        <StackPanel Orientation="Horizontal">
                                <Grid Width="920">
                            <TextBlock HorizontalAlignment="Left" Width="Auto">Status: <TextBlock Text="{Binding Status}"/></TextBlock>
                                    <TextBlock Width="Auto" TextAlignment="right">
                                    <TextBlock Text="Downloading Speed: "/>
                                    <TextBlock Name="DownloadingSpeed" Text="{Binding DownloadingSpeed}"/>
                            </TextBlock>
                                </Grid>
                            </StackPanel>
                    </StackPanel>
                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
         </ListBox>

In MainWindow.xaml.cs
 private void GenerateList()
{
 List<Download> WebsitesList = new List<Download>();

 WebsitesList.Add(new Download() {DownloadID = ID, WebsiteTitle = WebTitle, Status = WebStatus, CurrentTime = CurrentTime,CurrentDate = CurrentDate, DownloadingSpeed = DownloadSpeed, DirectoryPath = path, DirectorySize = helper.GetDirectorySize(path),GivenUrl = url });

 WebsiteList.ItemsSource = WebsitesList;
}
//get download speed and update DownloadingSpeed
 private void updateDownloadingSpeed(object sender, EventArgs e)
    {

        interfaceStats = NetworkInterface.GetAllNetworkInterfaces()[0].GetIPv4Statistics();

        downloadspeed = (interfaceStats.BytesReceived - previousbytesreceived) / 1024;

        previousbytesreceived = NetworkInterface.GetAllNetworkInterfaces()[0].GetIPv4Statistics().BytesReceived;

        Download.DownloadingSpeed = Math.Round(downloadspeed, 2) + " KB/s"; //Rounding to 2 decimal places and save in DownloadSpeed Property
}

In Download.cs
 public class Download : INotifyPropertyChanged
    {
          private string _DownloadingSpeed = "0 kb/s";
        public string DownloadingSpeed
        {
            get { return _DownloadingSpeed; }
            set
            {
                if (_DownloadingSpeed == value)
                    return;

                _DownloadingSpeed = value;
                this.OnPropertyChanged("DownloadingSpeed");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

}

A: Add UpdateSourceTrigger for TextBlock.
<TextBlock Name="DownloadingSpeed" Text="{Binding DownloadingSpeed, UpdateSourceTrigger=PropertyChanged}"/>

A: You might find that your code works if you use WPF properly by defining properties and declaring XAML correctly. It is customary to have an ObservableCollection<T> property that you data bind to the UI collection control. You would then data bind it to the ItemsSource property of the control:
<ListBox ItemsSource="{Binding Items}" ... />

Then, when you want to update any properties of the items, you need to set the properties of the items. This:
Download.DownloadingSpeed = Math.Round(downloadspeed, 2) + " KB/s";

... is not setting the property of an item from the collection. To do that, you'd need to do something like this:
// Use whatever filter you want to find the correct item from the collection
Download downloadInstance = Items.Where(d => d.Name == "SomeName").First();
downloadInstance.DownloadingSpeed = Math.Round(downloadspeed, 2) + " KB/s";


text:
Q: Add 'Active' class to URL Hash Navigation button https://owlcarousel2.github.io/OwlCarousel2/demos/urlhashnav.html
How can I add 'active' class to the buttons?
Currently buttons have a button.secondary:hover & button.secondary:focus
to create a button background color change.
This is fine, except whenever clicking anywhere in the slider the focus is changed and so the background color is removed from the button.
I need the buttons to have a dedicated active state, so that clicking within the slider is possible.
Thanks

A: You can solve this with javascript or jQuery, here's a jQuery example:
$(document).ready(function() {
    $('.button').on('click', function(){
        $('.button').removeClass('active');
        $(this).addClass('active');
    });
});

This removes the 'active' class for all buttons when you click any element with the class 'button' and adds it to the one you're clicking.

A: After playing around for a long time, I came up with the solution.

*

*Add #link as class in hash navigations, and one more additional class in this case "slidetabs" e.g. NIGHT TUBING

*Get the current slide item and then its data-hash

*Feed that data hash as a class in on changed function for adding class to navigation button

*Then repeat same for change event to remove active class

*Add a css to .slidetabs.active

$('.owl-carousel').on('changed.owl.carousel', function(event) {
  var current = event.item.index;
  var hash = $(event.target).find(".owl-item").eq(current).find(".item").attr('data-hash');
  $('.'+hash).addClass('active');
});
$('.owl-carousel').on('change.owl.carousel', function(event) {
  var current = event.item.index;
  var hash = $(event.target).find(".owl-item").eq(current).find(".item").attr('data-hash');
  $('.'+hash).removeClass('active');
});
Note: this is works as expected so I have not worked any further on it, there may be better solutions with good coding out there.
following is the full code:
Slider HTML:

   <button type="button" role="presentation" class="owl-prev">

1 / 4

   </button>
   <button type="button" role="presentation" class="owl-next"></button>

         DINING

         NIGHT TUBING

         COWBOY COASTER

         LIFT TICKETS

Javascript:
jQuery(document).ready(function($) {
  $('.owl-carousel').on('initialized.owl.carousel changed.owl.carousel', function(e) {
    if (!e.namespace)  {
      return;
    }
    var carousel = e.relatedTarget;
    $('.slider-counter').text(carousel.relative(carousel.current()) + 1 + ' / ' + carousel.items().length);
    }).owlCarousel({
      nav:true,
      navText: ["
1 / 3
",""],
      loop:true,
      slideSpeed : 300,
      paginationSpeed : 400,
      items:1,
      dots:false,
      URLhashListener:true,
      startPosition: 'URLHash',
      autoplay:true,
      autoplayTimeout:9000,
      autoplayHoverPause:true,
      animateOut: 'fadeOut',
      animateIn: 'fadeIn',
    responsiveClass:true,
    responsive:{
        0:{
            items:1,
            nav:true
        },
        600:{
            items:1,
            nav:true
        },
        1000:{
            items:1,
            nav:true
        }
    }
  });

    $('.owl-carousel').on('changed.owl.carousel', function(event) {
      var current = event.item.index;
      var hash = $(event.target).find(".owl-item").eq(current).find(".item").attr('data-hash');
      $('.'+hash).addClass('active');
    });

    $('.owl-carousel').on('change.owl.carousel', function(event) {
      var current = event.item.index;
      var hash = $(event.target).find(".owl-item").eq(current).find(".item").attr('data-hash');
      $('.'+hash).removeClass('active');
    });

});

CSS:
.slidetabs.active {
    color: #ce2d27;
    text-decoration: underline;
}