text:
Q: Execution priority of threads in waiting queue and entry queue when calling notifyAll I'm struggling a bit to understand the order in which waiting threads get executed once I call notifyAll on a certain object. There is a code example added later, which I will be referencing.
In short, can I be sure that if I have 100 threads named "ABC" in the waiting queue and 100 threads named "GHI" in the entry queue, all "ABC" threads will be executed before "GHI" threads?
When I'm running the short program, it seems that's always the case since "GHI" threads always print out "0", which denotes all "ABC" threads have finished execution by then. I'm just wondering - is this my system/implementation specific or can I be sure this will always be the case? From Java documentation I could not find guarantees about this - but maybe I didn't search in the right place.
Here is the short sample code I was referencing and which always gives consistent results for me:
public class Main {
    private volatile int count = 0;

    public static void main(String[] args) throws InterruptedException {
        Main main = new Main();
        // add 100 threads that will all go to wait
        main.addThreads("ABC");

        // wait for 100 threads to be created and then notify all after sleeping 10s
        main.waitForThreads();

        // make sure thread has managed to start and is holding the lock and slpeeping
        Thread.sleep(1000);

        // add a lot more consumers to entry queue
        main.addThreads("GHI");

        //wait for threads to finish
        Thread.sleep(15000);
    }

    private void waitForThreads() throws InterruptedException {
        while (this.count < 99) {
            System.out.println("Not enough waiting threads yet");
            Thread.sleep(1000);
        }
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Main.this.syncMethod();
                } catch (InterruptedException e) {

                }
            }
        }, "DEF");
        t.start();
    }

    private void addThreads(String threadName) {
        for(int i = 0; i < 100; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Main.this.syncMethod();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }}, threadName).start();;
        }
    }

    private synchronized void syncMethod() throws InterruptedException {
        String name = Thread.currentThread().getName();
        if (name.equals("ABC")) {
            this.count++;
            this.wait();
            this.count--;
        } else if (name.equals("DEF")) {
            Thread.sleep(10000);
            this.notifyAll();
            System.out.println("Waiting threads notified");
        } else {
            System.out.println(this.count);
        }
    }
}


text:
Q: 2 threads performing myAtomicReference.compareAndSet(expected,new Date()) static boolean unsynchronizedSetter(Date expected){
    Date newDate = new Date();
    AtomicReference<Date> myAtomicReference = Lookup.getAtomicRef();
    boolean myStatus = myAtomicReference.compareAndSet(expected, newDate); //CAS
    return myStatus;
}

Q: If 2 threads executes it, which object will get stored in the atomic reference?
In a multi-processor machine, 2 threads could be performing the CAS in the same clock cycle. Suppose they both use the same myAtomicReference object to do the CAS, both use the correct value of "expected", but they try to put in 2 distinct objects ie the 2 newDate. One of them must fail, but will myStatus be false in that thread?
I guess one hardware implementation of CompareAndSwap would make the threads queue up to do their updates. I guess even if the 2 processors are executing the CAS instruction in the same clock cycle, one of them is probably delayed.

A: Q: If 2 threads executes it, which object will get stored in the atomic reference?

Nobody can know. According to the javadoc, one of them.
In a multi-processor machine, 2 threads could be performing the CAS in the same clock cycle.

AFAIK, there's no global clock for current Intel/AMD multicore CPUs.
One of them must fail, but will myStatus be false in that thread?

It must be, otherwise it'd mean that it succeeded and the whole java.util.concurrent would fall to pieces. I'm quite sure, that myStatus in one thread must be false even if both tried to put there the same object.
I guess one hardware implementation of CompareAndSwap would make the threads queue up to do their updates.

I wouldn't say "queue up" (this sounds like something done by the OS), the CAS instruction will be delayed by the hardware.

A: Thanks for the input. As the original questioner, I now feel it's possible that myStatus == true in both threads -- this is my tentative answer to my own question below
"One of them must fail, but will myStatus be false in that thread?"

It is conceivable, IMHO, that both threads "think" they succeeded in putting in their respective newDate object. However, the first thread should know that its variable myStatus is hopelessly unreliable the whole time, right after the CAS operation. It's unreliable because myStatus could be true but when you read the AtomicReference the value in it could have changed. The shared AtomicReference is subject to change any time by any thread. This AtomicReference instance is not guarded by any synchronization construct.
myStatus==true only means that this thread had a correct guess for the value of expected so JVM must give it the promised prize for the correct guess. However, JVM won't keep the newDate inside the AtomicReference. So winning that "prize" means nothing.
I hope this makes some sense.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Property does not exist on type 'never' in Ngrx effect I'm using Angular 8 and NGRX 8. I have an action:
export const loadEnvironment = createAction(
  LicencingActionTypes.LoadEnvironment,
  props<{environment: Environment}>()
);

and corresponding effect:
 loadEnvironment = createEffect(() => this.actions$.pipe(
    ofType(LicencingActionTypes.LoadEnvironment),
    exhaustMap((action) =>
      this.authService.
      getToken(LicencingEffects.getAuthDetailsForEnvironment(action.environment))
        .pipe(
          switchMap((token) => [
            AuthActions.onLogin({token: token}),
            LicencingActions.onLoadEnvironment({environment: action.environment})
          ]),
          catchError(error => of(AuthActions.onLoginError({error: error})))
        )
    )
  ));

I've been reading the documentation on NGRX 8 (https://ngrx.io/guide/effects#incorporating-state).
Their example shows that you can just use the action property without casting the type of the action:
...
exhaustMap(action =>
        this.authService.login(action.credentials)
...

Webpack won't compile, and I get the following error:
ERROR in src/app/licencing/effects/licencing.effects.ts(20,69): error TS2339: Property 'environment' does not exist on type 'never'.

Screenshot of code with errors highlighted
Where am I going wrong?

A: Actions must be declared in a type union at the bottom of the actions file:
const all = union({
  info,
  appError
});

export type CoreActionsUnion = typeof all;

and then in the Effects class constructor injected in with that type as the type parameter of Actions:
constructor(private actions$: Actions<CoreActionsUnion>) { }

A: Instead of passing the Enum of the action, just pass the function instead. At least it works for me. (Angular 14.x, TS 4.7 and NgrxEffects 13.x, RxJS 7.5.x )
This is what my code looks like where I'm updating a spare part
readonly updatePart$ = createEffect(() =>
    this.actions$.pipe(
      ofType(updatePart),
      concatMap(action =>
        this.partService
          .updatePart(action.part)

Action itself
export const updatePart = createAction(
  PartActions.update,
  props<{ part: Required<Part> }>()
);

A: Try changing your effect as below -
loadEnvironment = createEffect(() => this.actions$.pipe(
    ofType(loadEnvironment), //<-- this is your action
    exhaustMap(action => //<-- getting rid of extra parenthesis
      this.authService.
      getToken(LicencingEffects.getAuthDetailsForEnvironment(action.environment))
        .pipe(
          switchMap((token) => [
            AuthActions.onLogin({token: token}),
            LicencingActions.onLoadEnvironment({environment: action.environment})
          ]),
          catchError(error => of(AuthActions.onLoginError({error: error})))
        )
    )
  ));

Sample reference implementation


text:
Q: How to save daily changes in a virtualbox to a live USB I have been successful in installing, booting and using Ubuntu into my 64gb USB flash drive.
What I plan is to do is to convert a copy of my USB key to a virtual image and boot it using virtualbox. (No problem there either!)
My question is: Is there a way for me to save daily changes from my virtual machine to my Ubuntu installed (unlike liveCD) USB pendrive so I can use that to boot and continue where I left off on my Virtualbox?
Note: I installed Ubuntu 14.04 on a 64gb pendrive with 4 partitions. One 8gb fat32, the 2nd is /home, the 3rd is Linux Swap and the last 5.3gb is just an empty parition.

A: If I understand you correctly, what you want to do, is use your flash drive as the 'harddrive' in Virtualbox. This way all your changes will be reflected on the flash drive.
In order to do this, you will need to make a virtual hard drive that points to the physical device, then use the virtual hard drive with Virtualbox.
Use the following command, replacing /dev/sda with the device that is your flash drive
sudo VBoxManage internalcommands createrawvmdk -filename /path/to/file.vmdk -rawdisk /dev/sda
See https://superuser.com/questions/495025/use-physical-harddisk-in-virtual-box for more details.
If what you're trying to do, is run two individual systems in Virtualbox and on the Flash Drive, and then 'synchronise' the changes back and forth, you can use rsync to synchronise the files, if both systems are running at the same time.
But you can't synchronise all the files, as that'd definitely cause problems unless the two systems are identical, so you will have to settle for something like your home directory for instance. Seeing as you have /home on a separate partition, you can also use my above instructions to make a virtual hard drive that points to that single partition, and mount it with Virtualbox.

A: After running some test and actually using it, here's the command for rsync that I am happy with:
rsync -aAXv –exclude={"/dev/*","/proc/*","/sys/*","/tmp/*","/run/*","/mnt/*","/media/*","/lost+found", "/boot/*"} /media/sda1/* /media/sdb1/ –delete -u --dry-run

If I am satisfied, I remove --dry-run to make the changes.


text:
Q: Client-side validation of US currency I have an ASP.Net MVC 5 web application and I need to accept user input of US currency. Some valid inputs might be:
100
$100.21
$ 1,234
$1,234.56

Invalid inputs might be:
10,12
1o0.21

My (simplified) model looks like:
public class Claim {
  [DisplayName("$ Amount)]
  [DataType(DataType.Currency)]
  [Required]
  [Range(0.0, 200000.0)]
  public decimal? DollarAmount { get; set; }
}

My cshtml markup looks like:
  @Html.LabelFor(model => model.DollarAmount, htmlAttributes: new { @class = "control-label col-md-3" })

    @Html.EditorFor(model => model.DollarAmount, new { htmlAttributes = new { @class = "form-control margin-bottom" } })
    @Html.ValidationMessageFor(model => model.DollarAmount, "", new { @class = "text-danger" })

I used this advice this advice to build a binder that converts user input to a decimal, but client-side validation won't let the user enter a dollar-sign or commas. What do I need to do to allow the user to enter valid currency values, but warns her if she enters an invalid value? I'd prefer to do as much validation on the client-side as possible.

A: You Might want to look at https://github.com/globalizejs/globalize#currency-module. Helps allot with this kind of stuff.  As for your Question to be able to use the Dollar Symbol you would not be able to store this Value as a decimal format in the database, only as a string.
There are a few things you can do, Use bootstrap to place a Dollar symbol in front of your TextBox using input-group-addon. Not sure if it will work properly as i see you have set Margin-bottom on your Textbox, telling me you might not be using bootstrap form tags above.
You may want to look into AutoNumeric jQuery plugin, It's well-maintained and they've basically "thought of everything" I could want for currency.
// View

@Html.LabelFor(model => model.DollarAmount, htmlAttributes: new { @class = "control-label col-md-3" })

        $
        @Html.EditorFor(model => model.DollarAmount, new { htmlAttributes = new { @class = "form-control margin-bottom" } })
        @Html.ValidationMessageFor(model => model.DollarAmount, "", new { @class = "text-danger" })

// Class

public class Claim {
  [DisplayName("$ Amount")]
  [DataType(DataType.Currency)]
   // {0:C} Will show as currency {0:N} to show Numbers
  [DisplayFormat(DataFormatString = "{0:C}", ApplyFormatInEditMode = true))]
  [Required]
  [Range(0.0, 200000.0)]
  public decimal? DollarAmount { get; set; }
}

Another option is to have a hidden field with javascript that will duplicate the field from a string to decimal and that can be the one you submit like below.
// MODEL
public class Claim {
  [DisplayName("$ Amount")]
  [DataType(DataType.Currency)]
  [Required]
  [Range(0.0, 200000.0)]
  public decimal? DollarAmount { get; set; }
}

// View

@Html.HiddenFor(model => model.DollarAmount, new { @id = "DollarAmount" })

@Html.LabelFor(model => model.DollarAmount, htmlAttributes: new { @class = "control-label col-md-3" })

        $
        <input id="DollarSave" type="text" name="DollarSave" pattern="^\$?([0-9]{1,3},([0-9]{3},)*[0-9]{3}|[0-9]+)(.[0-9][0-9])?$" title="You must enter in proper currency">
        @Html.ValidationMessageFor(model => model.DollarAmount, "", new { @class = "text-danger" })

A: Pool pro's answer was a great help in solving my problem but I couldn't get his input tag pattern to display a message. It worked in JSFiddles, but not in my Asp.Net view template. So, I did the pattern validation and message update in javascript. I also used a different regex. For completeness, I'm posting my solution here:
@Html.HiddenFor(model => model.DollarAmount, new { @id = "DollarAmount" })

@Html.LabelFor(model => model.DollarAmount, htmlAttributes: new { @class = "control-label col-md-3" })

    <input id="DollarSave" type="text" name="DollarSave" class="form-control text-box single-line">


text:
Q: Topic deletion from Zookeeper I have deleted topic directly from Zookeeper using the below command and did not execute deletion from Kafka before:
zookeeper-shell.sh localhost:2181 rmr /brokers/topics/<topic_name>

Now what I see is that the topic shows up in the log.dirs of at least one broker in the cluster. Is there a way that can be deleted as well.
When i attempt to delete from kafka now it throws the below error
Error while executing topic command : Topic <topic_name> does not exist on ZK path <zookeeper_server_list:2181>

A: I think you have missed a couple of steps. In order to manually delete a topic you need to follow these steps:
1) Stop Kafka server
2) On each broker, you have you have to delete all the topic's log files under logs.dirs:
rm -rf path/to/logs/topic_name/

3) Remove topic directory from Zookeeper:
> zookeeper-shell.sh localhost:2181
> ls /brokers/topics
> rmr /brokers/topics/topic_name

4) Restart Kafka server

Note that the suggested way for deleting a topic is
/bin/kafka-topics.sh --zookeeper localhost:2181 --delete --topic topic_name

assuming that delete.topic.enable=true.


text:
Q: C# generic type in a base class I'm writing a system that has a set of protocol buffers (using protobuf-net), I want to define something like this in an abstract class they all inherit off:
public byte[] GetBytes()

however, the protocol buffer serealiser requires a type argument, is there some efficient way to get the type of the inheriting class?
Example:
public byte[] GetBytes()
    {
        using (MemoryStream stream = new MemoryStream())
        {
            Serializer.Serialize<T /* what goes here? */>(stream, this);
            return stream.ToArray();
        }
    }

A: Just write "T" right?
and then in your class declaration:
public class M<T>

?
-- Edit
And then when you inherit it:
public class Foo : M<Apple>

A: Define your base class as BaseClass<T> and then your derived classes replace T with the serializer type DerivedClass<SerializerType>.
You can also specify constraints on the type argument e.g.
BaseClass<T> where T : SerializerBase

Here is a description of the types of constraints you can apply.

A: You can do this via reflection, but protobuf-net did it for you.
Just change your call to:
Serializer.NonGeneric.Serialize(stream, this /* Takes an object here */);

This works by building the generic method at runtime via reflection.  For details, check the code (second method here).

A: You don't actually need anything special here... since protobuf-net respects inheritance. If you have:
[ProtoInclude(typeof(Foo), 20)]
[ProtoInclude(typeof(Bar), 21)]
public abstract class MyBase {
    /* other members */

    public byte[] GetBytes()
    {
        using(MemoryStream ms = new MemoryStream())
        {
            Serializer.Serialize<MyBase>(ms, this); // MyBase can be implicit
            return ms.ToArray();
        }
    }
}
[ProtoContract]
class Foo : MyBase { /* snip */ }
[ProtoContract]
class Bar : MyBase { /* snip */ }

then it will work. To serialize the data, it always starts at the base (contract) type; so even if you did Serializer.Serialize<Foo>(stream, obj) the first thing it will do is detect that it has a base class that is a contract, and switch to MyBase. During deserialization it will identify the correct derived (concrete) type and use that, so you can use Deserialize with MyBase too, and it will construct a Foo or Bar depending on what the original data was.
Thus the following are largely identical:
Serializer.Serialize<BaseType>(dest, obj);
...
BaseType obj = Serializer.Deserialize<BaseType>(source);

and
Serializer.Serialize<DerivedType>(dest, obj);
...
DerivedType obj = Serializer.Deserialize<DerivedType>(source);

The main difference here is how the variables are typed.


text:
Q: Unable to escape quote in dynamic SQL where file name hold quote in it declare @Path varchar(max) = 'E:\test\PS\Document\159203\Driver''s License and Insurance Card';

EXEC ('INSERT INTO table
        SELECT ''' + @id+ ''', BulkColumn FROM OpenRowSet ( Bulk ''' + @path + ''', Single_Blob) AS table')

Here path has file names which has quotes and I am unable to escape it and getting an error:

Msg 105, Level 15, State 1, Line 36
  Unclosed quotation mark after the character string ', Single_Clob) AS [NOTE_CONTENT]'

A: You just need to escape the single quote again e.g.
declare @Path varchar(max) = 'E:\test\PS\Document\159203\Driver''s License and Insurance Card', @Id varchar(38) = '', @Sql varchar(max);

set @Sql = 'SELECT ''' + @id + ''', ''' + replace(@path,'''','''''') + '''';

print (@Sql);
exec (@Sql);

Note: Using SQL I can execute without access to the file, just adjust to suit.


text:
Q: Mysql Group Concat Range I have a query like this :
SELECT GROUP_CONCAT(urut SEPARATOR '; ') AS urut
   FROM pipe a
GROUP BY a.seal;

Then I get :
Record 1 :
+-------------------------------------+
| 1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11;  |
| 12; 13; 14; 15; 16; 17; 18; 19; 20; |
| 21; 22; 23; 24; 25; 26; 27; 28; 29; |
| 30; 31; 32; 33; 34; 35; 36; 37; 38; |
| 39; 40; 41; 42; 43; 44              |
+-------------------------------------+

Record 2 :
+-----------------------------------------+
| 45; 46; 47; 48; 49; 50; 51; 52; 53; 54; |
| 55; 56; 57; 58; 59; 60; 61; 62; 63; 64; |
| 65; 66; 67; 68; 69; 70; 71; 72; 73; 74; |
| 75; 76; 77; 78; 79; 80; 81; 82; 83; 84; |
| 85; 86; 87; 88                          |
+-----------------------------------------+

Is there a function to make this output to be short like
+------+
| 1-44 |
|45-88 |
+------+

Please advise

A: You can build it yourself with
SELECT CONCAT(MIN(urut), '-', MAX(urut)) AS urut
   FROM pipe a
GROUP BY a.seal;


text:
Q: Manipulating Large JSON with Python I have a fairly large file of data of .json form, which I would like to manipulate, of the following form, which is like many json objects together:
[
{
    "_id" : "...",
    "idSession" : "...",
    "createdAt" : "1526894989268",
    "status" : "COMPLETE",
    "raw" : "Bobsguide,Marketing Assistant,Sales / Marketing79642,Baitshepi,,etc",
    "updatedAt" : "...",
    "graphResults" : [

        [
            "lastName",
            "stock"
        ],
        [
            "country",
            "Botswana"
        ],
        [
            "location",
            "Botswana  "
        ],
        [
            "city",
            "-"
        ],
        [
            "state",
            "-"
        ],
        [
            "school",
            "Heriot-Watt University"
        ],
        [
            "skills",
            "Budgeting,Business Process Improvement,Business Planning"
        ],

    ],

    "eid" : {
        "###" : "12020653-1889-35be-8009-b1c9d43768ac"
    }
}

{
    "_id" : "...",
    "idSession" : "...",
    "createdAt" : "1526894989268",
    "status" : "COMPLETE",
    "raw" : "Bobsguide,79619,Steven,example,steven.jones@example.com,Marketing Assistant,Sales,,etc",
    "updatedAt" : "...",
    "graphResults" : [
        [
            "country",
            "United Kingdom"
        ],
        [
            "location",
            "United Kingdom London London"
        ],
        [
            "city",
            "London"
        ],
        [
            "state",
            "London"
        ],
        [
            "skills",
            "Solvency II,Liquidity Risk,Screening,etc"
        ]
    ],

    "eid" : {
        "###" : "..."
    }
}

...

]

Is there a straightforward way for me to read this into a python script for manipulation/analysis. The main parts of interest are under labelling of graph results and raw. I'm inexperienced with this form of raw data so any help is much appreciated.

A: First of all, the data you posted in not proper, it should be something like the below and to access the elements you mentioned you can try the below
{
    "test":[
    {
        "_id" : "...",
        "idSession" : "...",
        "createdAt" : "1526894989268",
        "status" : "COMPLETE",
        "raw" : "Bobsguide,Marketing Assistant,Sales /             Marketing79642,Baitshepi,,etc",
        "updatedAt" : "...",
        "graphResults" : [

            [
                "lastName",
                "stock"
            ],
            [
                "country",
                "Botswana"
            ],
            [
                "location",
                "Botswana  "
            ],
            [
                "city",
                "-"
            ],
            [
                "state",
                "-"
            ],
            [
                "school",
                "Heriot-Watt University"
            ],
            [
                "skills",
                "Budgeting,Business Process Improvement,Business Planning"
            ]
        ],
        "eid" : {
            "###" : "12020653-1889-35be-8009-b1c9d43768ac"
        }
        },
        {
            "_id" : "...",
            "idSession" : "...",
            "createdAt" : "1526894989268",
            "status" : "COMPLETE",
            "raw" : "Bobsguide,79619,Steven,example,steven.jones@example.com,Marketing     Assistant,Sales,,etc",
            "updatedAt" : "...",
            "graphResults" : [
                [
                    "country",
                    "United Kingdom"
                ],
                [
                    "location",
                    "United Kingdom London London"
                ],
                [
                    "city",
                    "London"
                ],
                [
                    "state",
                    "London"
                ],
                [
                    "skills",
                    "Solvency II,Liquidity Risk,Screening,etc"
                ]
            ],

            "eid" : {
                "###" : "..."
            }
        }
    ]
}

// Answer
import json

data_file = open('data.json', 'r')
information = json.load(data_file) // this will give you a json obj

print(information['test'][1]['raw']) // would pick element 1 from array then

pick and print value in raw key
print(information['test'][1]['graphResults']) // would pick element 1 from array then pick and print value in raw key


text:
Q: Special Woodbury identity I wish to understand linear transformations of the type $M = \left(\alpha I_n+ D^TD\right)^{-1}$
where $\alpha \neq 0$ and $D$ is a (full-rank) $k$ by $n$ matrix. ($k<n$)
My understanding is that though $D^TD$ is singular and thus does not have an inverse, $\left(\alpha I_n+ D^TD\right)^{-1}$ for $\alpha \ll 1$ could be a "good" approximation for it. (or am I mistaken?)
Ideally I would like to relate the eigenvectors of $M$ to my original $D$ (probably dependent also on $\alpha$) (see footnote [1])
So my question is: Is it possible to compute the eigenvalues and eigenvectors of this matrix $M$?
Is there any interesting fact that you know about these types of matrices (thinking them of linear transformations)
I tried to use Woodbury identity to arrive at an expression
$$M = \left(\alpha I_n+ D^TD\right)^{-1}\\
=\alpha^{-1}I_n - \alpha^{-1}D^T\left(I_k+\alpha^{-1}DD^T\right)^{-1}D\alpha^{-1}\\
=\alpha^{-1}I_n - \alpha^{-1}D^T\left(\alpha I_k+DD^T\right)^{-1}D\\
= \alpha^{-1}I_n - \alpha^{-1}D^T\left(\alpha^{-1}I_k - \alpha^{-1}D\left(\alpha I_n+D^TD\right)^{-1}D^T\right)D\\
= \alpha^{-1}I_n - \alpha^{-2}D^TD + \alpha^{-2}D^TD\left(\alpha I_n+D^TD\right)^{-1}D^TD\\
= \alpha^{-1}I_n - \alpha^{-2}D^TD + \alpha^{-2}D^TDMD^TD$$
and got to an implicit equation for $M$ but could not solve it.
Any help is appreciated either in finding a closed-form solution or geometrical interpretations of the effect of $M$
[1] Some initial experimentation with simple $D$ lead me to believe that the rows of $D$ are eigenvectors for $M$ is this possible?

A: The eigenvalues of $\alpha I + D^TD$ can be written as $\alpha + \lambda_j$,
where $\lambda_j$ are the eigenvalues of $D^TD$, of which at least $n-k$ are zero. The eigenvectors of $D^TD$ and $\alpha I+ D^TD$ can be computed by the right-singular vectors of $D$.
The matrix $(\alpha I+D^TD)^{-1}D^T$ is an approximation of the inverse $D$ in the following sense:
$\lim_{\alpha \searrow0}(\alpha I+D^TD)^{-1}D^T =D^\dagger$, where $D^\dagger$ is the Moore-Penrose pseudo-inverse of $D$, see Moore-Penrose pseudo-inverse.
The matrix $(\alpha I+D^TD)^{-1}D^T$ also appears if you want to solve a least-square problem $\|Dx -y\|_2\to 0$ by Tikhonov regularization, where for $\alpha>0$ the problem
$$
\min \frac12\|Dx-y\|_2^2 + \frac\alpha2\|x\|_2^2
$$
is solved. Then $x$ solves this problem if and only if
$$
(\alpha I + D^TD)x = D^Ty \quad \Leftrightarrow \quad x = (\alpha I + D^TD)^{-1}D^Ty.
$$

A: To get the eigenvalues of $M$ we have to evaluate $\det(M-\lambda I)=0$ and can therefore use $M(\alpha I+D^TD)=I$ . Multiplicated $\det(M-\lambda I)=0$ with $(-1)^n\det(\alpha I+D^TD)$ we get $\det(-I+\lambda (\alpha I+D^TD))=\det((\lambda\alpha-1)I+\lambda D^TD)=\lambda^n\det((\alpha-\lambda^{-1})I+D^TD)=0$ . If we define $\overline{\lambda}$ as the eigenvalues of $D^TD$ and if  $\lambda\neq 0$ then the eigenvalues of $M$ are $\lambda=\frac{1}{\alpha+\overline{\lambda}}$ .


text:
Q: DOM Elements loaded from ajax and (probably) not ready in time I'm using sorting/filtering jQuery plugin Isotope and also jQuery $.ajax() to dynamically load some new elements to the page that need to be sorted with Isotope. That library seems to set all the new sorted elements with absolute position and with fixed (left, top) position in order to perform sorting.
The problem is that when you load the first set of elements with clear cache the the element positions in that absolute grid are incorrect (they are overlapping). This is caused by Isotope initialization. My (inexperienced) guess would be that the all the new DOM elements are not fully loaded by the time Isotope starts to calculate the future positions of the elements and there's where the in-accuracy comes in. If I do the exact same ajax request again it manages to calculate the positions correctly.
EDIT #1 ajax reuqest
var $isocont = $('#page-content-result');
var isoActive = false;

$.ajax({
   url: actionUrl + 'ajax',
   type: 'POST',
   data: searchData,
   success:function (data) {
       if(data.trim().length > 0) {
            $('#page-content-result').hide().empty().html(data).fadeIn(600);
            initIsotope();
        } else {
            var visible = $('#page-content-result').is(':visible');
            if(visible === true)
            {
                $('#page-content-result').empty();
            }
            $('#result-notif').show();
        }
    }
});

var initIsotope = function() {
    if(isoActive === true) {
        $isocont.isotope('destroy');
        console.log('iso stop');
        isoActive = false;
    }
    if(isoActive === false) {
        $isocont.isotope({
            getSortData: {
                name: '.iso-docname',
            }
        });
        console.log('iso start');
        isoActive = true;
    }
}

Can someone explain the nature of this problem and give few hints for solution?
Thnx!

A: Seems that once again the "morning is smarter than the night" (it's a saying in Estonian :P).
I placed a piece of test-code after part where the new data was inserted to the DOM.
if (/complete/.test(document.readyState)) {
    alert('loaded');
}

The alert kind of pauses the loading of the page and I realized that the containers where quite a lot shorter because of the not-yet-loaded images. Meaning the DOM doesn't have the information how high the containers are going to be when we initialize the Isotope and that's why the Isotope fails to calculate the correct positions.
FIX: After understanding the problem the fix is really simple just tell the DOM how high the image is going to be in CSS with min-height: 122px; and that is all. I guess if the image height varies then I believe setting an interval checker for document.readyState == 'loaded' would help.
Idea came from that blog http://callmenick.com/2014/06/04/check-everything-loaded-javascript/
So my general js file now looks something like that:
var $isocont;

$(document)(function() {
    //When DOM create a var of selector.
    $isocont = $('#page-content-result');
    //One time aka first init of Isotope with basic options.
    $isocont.isotope({
        getSortData: {
            name: '.iso-docname',
        }
    });

    $.ajax({
       url: actionUrl,
       type: 'POST',
       data: searchData,
       success:function (data) {
           if(data.trim().length > 0) {
                //Set HTML data from ajax request
                $('#page-content-result').hide().empty().html(data).fadeIn(600);
                //Reload isotope items and re-arrange the items according to config.
                reloadIsotope();
            } else {
                //DO SMTH
            }
        }
    });
});

var reloadIsotope = function() {
    $isocont.isotope('reloadItems');
    //We are resetting sorting since we might not want same ordering as on last result.
    $isocont.isotope({sortBy: null, sortAscending: true});
}

Thanx TimSPQR for looking into!


text:
Q: How to get multiple values from a function? So i have this code here, it should read multiple numbers until the user types one between 0 and 10.
int i_want_to_return_those(){
int x,z,y;
do{
scanf("%d", &x);
getchar();
}while (x < 0 || x > 10);

do{
scanf("%i", &y);
getchar();
}while (x < 0 || x > 10);

do{
scanf("%i", &z);
getchar();
}while (z < 0 || z > 10);

return???;

}

I want to return x, y and z. but i have no idea how to do this.


text:
Q: Partially bold colunm headers with gt I want to use the R package gt and have the table output ONE and TWO in bold. It looks like you can use markdown syntax inside gt but this doesn't quite work as I'd expect. Any tips?
dummy <- tibble(
  `**ONE**, N = 1` = 1,
  `**TWO**, N = 2` = 2
)

dummy %>%
  gt()

A: Couldn't see anyway to do exactly what you want but this accomplishes it by having a list that maps column names to label name with formatting.
library(tibble)
library(gt)
dummy <- tibble(
"one" = 1,
"two" = 2
)

col_for_list <- list(one = md("**ONE**, N = 1"), two = md("**TWO**, N = 2"))

dummy %>%
gt::gt() %>%
cols_label(.list = col_for_list)


text:
Q: Implementing interface by templates I have this interface:
struct I
{
    virtual void f(int) = 0;
    virtual void f(float) = 0;
};

May I implemnt I using something similar to next class?
struct C : public I
{
    template<typename T>
    void f(T);
};

A: No, you can't do that. The template method overloads the original two methods (i.e. it's a different method with the same name). C still has two pure virtual functions.

A: As properly pointed out by NPE, you can't do this directly. However, you still can avoid code duplication by delegation:
struct C : public I
{
    void f(int x) { f_internal(x); }
    void f(float x) { f_internal(x); }

private:
    template<typename T>
    void f_internal(T x) { do stuff with x; }
};


text:
Q: Solutions for sum in Prolog I'm an absolute beginner to prolog. I've just read a basic tutorial and tried to solve a quick problem on my own. The problem is this, find possible number combinations that lead to a sum. I'm expecting something like this:
sum(A,B,11).

This should result in values for A and B that would sum them upto 10.
My initial code was this:
sum(A,B,C):-
    C is A + B.

But I do not get any results with this. I get the following.
ERROR: Arguments are not sufficiently instantiated
ERROR: In:
ERROR:    [9] 11 is _3302+_3304
ERROR:    [7] <user>
ERROR:
ERROR: Note: some frames are missing due to last-call optimization.
ERROR: Re-run your program in debug mode (:- debug.) to get more detail.

What am I missing in my understanding of Prolog?

A: The standard is/2 predicate requires an evaluable arithmetic expression for second argument. Thus, in your case, you will need to generate possible values for A and B so that A + B can be computed. To make it practical, you will need to restrict the range of possible values. For example:
?- between(1,7,A), between(1,7,B), sum(A,B,11).
A = 4,
B = 7 ;
A = 5,
B = 6 ;
A = 6,
B = 5 ;
A = 7,
B = 4 ;
false.

As you progress on your learning of Prolog, you may eventually be interested in learning about constraint solvers.

A:
This should result in values for A and B that would sum them upto 10.

If you consider negative numbers as well, there are infinite possible results: .. -100+111, -2+13, -1+12, 0+11, 1+10, 2+9, 150+-139 ...
Your program will confirm the sum, and perform the calculation given the inputs for A and B:
?- sum(2,9,11).
true

?- sum(2,9,C).
C = 11

but even if you leave out one of them, it can't solve it.
?- sum(A,9,11).
is/2: Arguments are not sufficiently instantiated

You are hoping Prolog will intuit that you mean "numbers between 0 and 11 which sum to 11" but Prolog sees a potentially infinite search space, and nowhere to start searching, and no way to narrow it down.
Paulo Moura's answer will generate the numbers in the range, and test them all, and show which pairs satisfy A + B = C. He mentions constraint solvers, which are libraries available for popular Prolog implementations and they have a more general way of solving problems like this. Constrain the solution space in some way ("A and B are positive integers"), as many constraints as you know, and then they apply those rules to reason about numbers, apply more techniques to find the answers without searching every imaginable number:
% load the 'clpfd' code
:- use_module(library(clpfd)).

% define a sum using the imported #= instead of "is"
mysum(A, B, C) :-
    C #= A + B.

% declare that A and B are positive,
% and solve for A and B values.
?- mysum(A, B, 11), A in 0..sup, B in 0..sup, label([A,B]).

In this case it ends up being more code, but if you're generally hoping for Prolog to solve numeric calculations for you, you will likely have to go in this direction rather than using between() and making all the number lists yourself.


text:
Q: How to hide seek bar in Javascript I am doing a video player using JavaScript with basic playback features and have listeners for Ad starts and Ad ended. I hide seekbar when Ad is playing and make visible after Ad end. Now my problem is if I call a play function or pause method from console when Ad is playing the seekbar get visible instead of hide.
// Ad start event
this.onAdStartedEvent = function(data) {
  isAdPlaying = true;
  // code for hide seekbar
  OO.$(".oo-control-bar").hide();
}
// Ad end event
this.onAdCompletedEvent = function(data) {
  isAdPlaying = false;
  OO.$(".oo-control-bar").show();
}
// pause method
this.pause = function(data){
 if(isAdPlaying){
   OO.$(".oo-control-bar").hide(); // It does not hide the seekbar
  }
}

I call the pause() method from console the seek bar code get executed but its not hidden.
Please let me know how to get hide the seekbar from pause method


text:
Q: SQL Query - Finding a difference between 2 values in same table I need help with a specific query involving one of my databases.
Name           Elev    Difficulty  Map         Region
----------------------------------------------------------
Pilot Knob(S)   6200    2       Oynx          Southern Sierra
Spanish Needle  12322   3       Lament Peak   Southern Sierra
Lamont Peak     7429    2       Lament Peak   Southern Sierra
South Guard     13232   2       Mt Brewer     Great Western Divide
Mount Brewer    13570   2       Mt Brewer     Great Western Divide
North Guard     13327   4       Mt Brewer     Great Western Divide
Midway Mountain 11284   2       Mt Brewer     Great Western Divide

I need to find which maps have more than 2000 foot difference between the highest and lowest peaks?
Not to sure on I would use the MIN() and MAX() functions to figure this out.
Help is much appreciated!

A: You're on the right track with MIN and MAX. You just need to apply them over a grouping of the maps. Something like this:
SELECT Map
FROM
    Table
GROUP BY
    Map
HAVING
    MAX(Elev) - MIN(Elev) > 2000
ORDER BY
    MAX(Elev) - MIN(Elev)

A: Depending on your implementation (I've demonstrated writing in T-SQL below. You need to aggregate the maps into groups, then evaluate these based on the maximum and minimum values within these groupings.
--//We're grouping by map and demonstrating the max and min values returned
select Map, max (elev) as MaxElev, min (elev) as MinElev
from targettable
group by map;

--//We then need to filter the group and only return when the difference is
--//Greater than 2000
select map,  max (elev) as MaxElev, min (elev) as MinElev
from targettable
group by map
having (Max (elev) - 2000) > min (Elev);

--//Or alternatively you can use subtract values and compare

select map,  max (elev) as MaxElev, min (elev) as MinElev
from targettable
group by map
having (max (elev) - min (elev)) > 2000;

--//We can then tidy up and add an order if required (descending shown)

select map
from targettable
group by map
having (max (elev) - min (elev)) > 2000
order by max(elev);


text:
Q: Azure Machine Learning Studio - Input port Dataset is unconnected
I want to get the input file as a web service input. But it says gives the error "Input port dataset is unconnected". I want to take the input file from the user and send the model results back to ASP.NET web page. Please help on how to do that. Above is the screenshot of the experiment


text:
Q: Checkbox uncheck when submit form I am not sure is this a bugs in jQuery when using .click() function instead of .change() function for checkbox. It's working well on jsfiddle
1: http://jsfiddle.net/fadlisaad/tSgbZ/16/ but not on the live page http://webcollect.viewscast.com/canonrepairmobile
You may test it with this sequence:

*

*Language > English

*Country > United Kingdom

*Click 'Continue'

*Choose any option and click 'Continue' for the next 3 question until you found question 'Prior to having your product repaired which steps did you take to try and resolve the problem?'

*try to choose the last option 'None of the above' and click continue. During the loading to the next question, the checked option is mysteriously unchecked itself, so if you view the source on the next page, you will find <INPUT TYPE="Hidden" ID="__OUTP__ResolveWay_7" NAME="__OUTP__ResolveWay_7" VALUE=""> which should be <INPUT TYPE="Hidden" ID="__OUTP__ResolveWay_7" NAME="__OUTP__ResolveWay_7" VALUE="1">
It's just working fine with the others checkboxes. Could someone figure it out why?

A: With this code:
$('input[name!="ResolveWay_7"]').click(function() {
    $('input[name="ResolveWay_7"]').removeAttr('checked');
});

you make it so that each time there's a click on an input, the checkbox is deactivated. So when you click on the submit button (yes, that's also an input) it unchecks the checkbox.
I believe you only need to change the selector to $('input[type="checkbox"][name!="ResolveWay_7"]') and it should work.

A: The problem is this piece of code:
$('input[name!="ResolveWay_7"]').click(function() {
    $('input[name="ResolveWay_7"]').removeAttr('checked');
});

Your Continue button is also going to satisfy that jQuery selector as it is of type <input> and is not called ResolveWay_7.  Therefore when the Continue button is clicked, it will deselect the checkbox.

A: Look at the bottom of the source code of the page where you select "None of the above".
<script type="text/javascript">
/* <![CDATA[ */
$(document).ready(function() {
    $('#comment').hide();
    $('#specify').click(function() {
        $('#comment').toggle();
        $('textarea').val('');
    });
    $('input[name="ResolveWay_7"]').change(function() {
        $('input[name!="ResolveWay_7"]').removeAttr('checked');
        $('textarea').val('');
        $('#comment').hide();
    });
    $('input[name!="ResolveWay_7"]').click(function() {
        $('input[name="ResolveWay_7"]').removeAttr('checked');
    });
});
/* ]]> */
</script>

There are 2 places there where it says:
$('input[name="ResolveWay_7"]').removeAttr('checked');

A: check this:
$('input[name!="ResolveWay_7"]').click(function() {
    $('input[name="ResolveWay_7"]').removeAttr('checked');
});

when you click on any input except ResolveWay_7 it clears checked property of it (Resolveway_7) and submit button (continue) is also an input so clicking it clears checkbox.
You need to exclude button from selection like:
$('input[name!="ResolveWay_7"]').not("input.myButton").click(.......);


text:
Q: Order Extension Attribute I have added a custom extension attribute following this guide.
However, I am struggling to understand it's purpose. By what I can see they are setting their extension attribute on the order every time the order is requested. However, they are also saving the data to a custom table using their own custom model.
So what is the point in adding an extension attribute? If you can just get that data using the model/repository?

A: From https://devdocs.magento.com/guides/v2.3/extension-dev-guide/extension_attributes/adding-attributes.html

Third-party developers cannot change the API Data interfaces defined in the Magento Core code. However, most of these entities have a feature called extension attributes. Check the interface for the methods getExtensionAttributes() and setExtensionAttributes() to determine if they are available for the entity.

In other words... you as a developer cannot change the API Interfaces (and you shouldn't) but using extension attributes you can add your own meta data to the entities you need without changing how the API looks and works.
In other other words.... the extension attributes, provide a separation between what's core data and what's custom data.


text:
Q: Use Gremlin to find the shortest path in a graph avoiding a given list of vertices? I need to use Gremlin find the shortest path between two nodes (vertices) while avoiding a list of given vertices.
I already have:
v.bothE.bothV.loop(2){!it.object.equals(y)}.paths>>1
To get my shortest path.
I was attempting something like:
v.bothE.bothV.filter{it.name!="ignored"}.loop(3){!it.object.equals(y)}.paths>>1
but it does not seem to work.
Please HELP!!!

A: The second solution you have looks correct. However, to be clear on what you are trying to accomplish. If x and y are the vertices that you want to find the shortest path between and a vertex to ignore during the traversal if it has the property name:"ignored", then the query is:
x.both.filter{it.name!="ignored"}.loop(2){!it.object.equals(y)}.paths>>1

If the "list of given vertices" you want filtered is actually a list, then the traversal is described as such:
list = [ ... ] // construct some list
x.both.except(list).loop(2){!it.object.equals(y)}.paths>>1

Moreover, I tend to use a range filter just to be safe as this will go into an infinite loop if you forget the >>1 :)
x.both.except(list).loop(2){!it.object.equals(y)}[1].paths>>1

Also, if there is a potential for no path, then to avoid an infinitely long search, you can do a loop limit (e.g. no more than 4 steps):
x.both.except(list).loop(2){!it.object.equals(y) & it.loop < 5}.filter{it.object.equals(y)}.paths>>1

Note why the last filter step before paths is needed. There are two reasons the loop is broken out of. Thus, you might not be at y when you break out of the loop (instead, you broke out of the loop because it.loops < 5).
Here is you solution implemented over the Grateful Dead graph distributed with Gremlin. First some set up code, where we load the graph and define two vertices x and y:
gremlin> g = new TinkerGraph()
==>tinkergraph[vertices:0 edges:0]
gremlin> g.loadGraphML('data/graph-example-2.xml')
==>null
gremlin> x = g.v(89)
==>v[89]
gremlin> y = g.v(100)
==>v[100]
gremlin> x.name
==>DARK STAR
gremlin> y.name
==>BROWN EYED WOMEN

Now your traversal. Note that there is not name:"ignored" property, so instead, I altered it to account for the number of performances of each song along the path. Thus, shortest path of songs played more than 10 times in concert:
gremlin> x.both.filter{it.performances > 10}.loop(2){!it.object.equals(y)}.paths>>1
==>v[89]
==>v[26]
==>v[100]

If you use Gremlin 1.2+, then you can use a path closure to provide the names of those vertices (for example) instead of just the raw vertex objects:
gremlin> x.both.filter{it.performances > 10}.loop(2){!it.object.equals(y)}.paths{it.name}>>1
==>DARK STAR
==>PROMISED LAND
==>BROWN EYED WOMEN

I hope that helps.
Good luck!
Marko.


text:
Q: unittest runs in terminal but not in pycharm I have the following project structure and I am working with remote deployment with Pycharm.
source/
+- src/
   +- __init__.py
   +- abcd.py
+- test/
   +- __init__.py
   +- tests.py

In tests.py, I import src.abcd.
Running unittest in terminal with python -m unittest test.tests in the source folder is OK. But when I run the unittest in Pycharm, it says No module named 'src.abcd'.
If I remove the __init__.py in source/test folder, Pycharm is OK but terminal reports error No module named 'test/tests'.
Is there anyway to run unittest with both the commandline and Pycharm?


text:
Q: Find lines from points We have build a laser scanner scanning a room, which works pretty well.
Now we drew our points to a simple JPanel and it looks like this:
I connectet the blue points already, but it's not smooth and it doesn't look like a room :)
So is there an algorithm, which draw the lines where are many points and average them, so it looks smooth? Or are there any suggestions, how to develop an algorithm for that?
Our testprogram is written in Java, but later it should be written in Vala(C).


text:
Q: Using \includegraphics before my new line of text, but on pdf image is after the text
Possible Duplicate:
How to influence the position of float environments like figure and table in LaTeX?

sometimes im in trouble with my images. Because if there is no space on one page, the images is getting printed on the next page. Thats fine, but if I write a text after the image on the pdf the text is before the image.
Something like this:
\begin{figure}[htb]
\centering
\includegraphics*[width=1\textwidth]{myimage.pdf}
\caption{\em Description}
\label{fig:myimage}
\end{figure}

\hspace{0pt}
\\

MyText. But this text appears sometimes before the image and not after how it should be.

I saw this question. People are explaining h,t,b but its not helping me. How can I solve this problem? Thank you
Edit: I could solve this problem with adding a lot of new lines, something like this:
\begin{figure}[htb]
\centering
\includegraphics*[width=1\textwidth]{myimage.pdf}
\caption{\em Description}
\label{fig:myimage}
\end{figure}

\hspace{0pt}
\\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\

Now its fine.

But this cannot be the solution...

A: Summing up the comments.
If you really need to stop LaTeX moving the figure then use the float package and
\begin{figure}[H]

Note that using H is more or less equivalent to not using a figure at all and just placing the graphic and caption in a full width minipage. (The caption-of package will allow you to caption such non-floating environments).
However it is almost always better to allow the figure to move and use the \label \ref mechanism to refer to it by number in the text, that allows LaTeX to find much better page breaks.  To achieve this do not use an optional argument at all, or if you want to allow figures mid-page if they will fit then use
\begin{figure}[htbp]

Always include at least p in such an optional argument otherwise you increase the chance that LaTeX can not find anywhere to place the figure. The full details of the figure placement (perhaps more details than you want initially) are in Frank Mittelbach's description.


text:
Q: why is the image in my ireport generating an extra blank page? I´ve a report that generates a pdf files with images only.
When the image has the size 800x1054; the image fits perfectly (1 image per page).
But for example if the image size is (667x1054) the image fits the page and it generates an extra blank page above the 667x1054 image.
Here is my ireport code:
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="ReporteExpediente" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="d978dab3-2ee3-486f-b62c-7e6817ee39da">
    <property name="ireport.zoom" value="1.0"/>
    <property name="ireport.x" value="0"/>
    <property name="ireport.y" value="0"/>
    <queryString>
        <![CDATA[]]>
    </queryString>
    <field name="imagen" class="java.io.InputStream">
        <fieldDescription><![CDATA[imagen]]></fieldDescription>
    </field>
    <background>
        <band splitType="Stretch"/>
    </background>
    <detail>
        <band height="166" splitType="Stretch">
            <image scaleImage="RealHeight">
                <reportElement x="0" y="0" width="555" height="166" uuid="9b2798da-ca28-4aeb-a8de-8299718c3e40"/>
                <imageExpression><![CDATA[$F{imagen}]]></imageExpression>
            </image>
        </band>
    </detail>
</jasperReport>

A: If your format is width x height  (800,667 is width and 1054 is height)
Your attribute scaleImage on image:

RealHeight - the image can be stretched vertically to match the actual
  image height, while preserving the declared width of the image
  element.

since it needs to preserve your width 555px an image with width 667 can stretch its height more then an image with width 800. This will result in that an image with width 667 will use more height and therefore you may see the overflow.
Solutions

*

*Decrease the width of your reportElement (so that 667x1054 fits as well)

*Set the height and width of your reportElement to fill the page and use scaleImage="RetainShape"


text:
Q: Destruction of an object when erasing it from std::map I was curios if default destructor is called, when I'm removing an element from an std::map. Here is an example which I have made:
class CTestMap{
public:
    CTestMap() {
        std::cout << "default constructor called" << std::endl;
    }
    CTestMap(int id) {
        std::cout << "created object: " << id << std::endl;
        m_id = id;

    }
    ~CTestMap() {
            std::cout << "destroyed object: " << this->m_id << std::endl;
    }
    int get_id(){
        return m_id;
    }
    int m_id;
};

int main(void){

    std::map<int, CTestMap>m;
    std::map<int, CTestMap>::iterator m_it;

    std::cout << "created map " << std::endl;

    CTestMap t1(1);
    std::cout << "created test object: " << t1.get_id() << std::endl;
    CTestMap t2(2);
    std::cout << "created test object: " << t2.get_id() << std::endl;
    CTestMap t3(3);
    std::cout << "created test object: " << t3.get_id() << std::endl;

    m[1] = t1;
    m_it = m.find(1);
    std::cout << "inserted test object: " <<  m_it->second.get_id() << std::endl;

    m[2] = t2;
    m_it = m.find(2);
    std::cout << "inserted test object: " <<  m_it->second.get_id() << std::endl;

    m[3] = t3;
    m_it = m.find(3);
    std::cout << "inserted test object: " <<  m_it->second.get_id() << std::endl;

    m_it = m.find(1);
    std::cout << "will now erased test object: " << m_it->second.get_id() << std::endl;
    m.erase(m.find(1));
    std::cout << "erased test object: " << m[1].get_id() << std::endl;

    m_it = m.find(1);
    std::cout << "object shall no longer exist: " << m_it->second.get_id() << std::endl;

    while(1);
return 0;
}

An here is the output:
./htest
created map
created object: 1
created test object: 1
created object: 2
created test object: 2
created object: 3
created test object: 3
default constructor called
destroyed object: 9377935
destroyed object: 9377935
inserted test object: 1
default constructor called
destroyed object: 9377935
destroyed object: 9377935
inserted test object: 2
default constructor called
destroyed object: 9377935
destroyed object: 9377935
inserted test object: 3
will now erased test object: 1
destroyed object: 1
default constructor called
destroyed object: 158830600
destroyed object: 158830600
erased test object: 158830600
object shall no longer exist: 158830600

Questions are:

*

*Why so many times default constructor is called, when I'm only
creating 3 objects using my own constructor ?

*Can I, based on
this example say, that each time I'm erasing any object from the
std::map, its destructor is called ? Is this general behavior of a
std::map ? I could not find this information.

*What if I'm storing pointers to objects (I'm creating them using 'new' operator) ? When then delete shall be called ?

A: std::map stores a copy of the object you insert.  When the
object is removed, it is this copy which is destructed.  So
after m[1] = t1;, there are two identical instances of
CTestMap: t1 and the one in the map.
Also: m[1] = t1; will first create a new entry in the map,
using the default constructor, and later assign t1 to it.
In general, if you want to trace instance lifetime like this,
you need provide a user defined copy constructor and assignment
operator which trace as well.  And you probably want to output
the this pointer in all of the traces.  (Another technique
would be to dote each object with an immutable unique
identifier:
#define TRACE(m) std::cout << #m << '(' << m_objectId << ')' << std::endl
static int currentObjectId = 0;

class TestMap
{
    int m_id;
    int const m_objectId;
public:
    TestMap()
        : m_id( 0 )
        , m_objectId( ++ currentObjectId )
    {
        TRACE(DFLT);
    }
    TestMap( int id )
        : m_id( id )
        , m_objectId( ++ currentObjectId )
    {
        TRACE(CTOR);
    }
    TestMap( TestMap const& other )
        : m_id( other.m_id )
        , m_objectId( ++ currentObjectId )
    {
        TRACE(COPY);
    }
    ~TestMap()
    {
        TRACE(DTOR);
    }
    TestMap& operator=( TestMap const& other )
    {
        m_id = other.m_id;
        TRACE(ASGN);
        return *this;
    }
};

You might want to add additional information (like m_id) to
the trace as well.
Also: your last output invokes undefined behavior.  After
m.find(i), you should check first that the iterator hasn't
returned m.end().  If it has, dereferencing isn't allowed.  So
your test output should be something like:
void
testOutput( std::map<int, TestMap> const& m, int i )
{
    std::map<int, TestMap>::const_iterator entry = m.find( i );
    if ( entry == m.end() ) {
        std::cout << "no object at " << i << std::endl;
    } else {
        std::out << "object " << entry->second.m_id << " at " << i << std::endl;
    }
}

(Finally: I think Microsoft has preempted the C prefix for
classes, so you should avoid it.  If you want a prefix, choose
something else, to avoid confusion.)

A: If you store an actual object (rather than a reference or pointer), yes, the object gets destroyed when you erase it.
If you store pointers or references, then the object is not destroyed, and delete is not called on a pointer. If you want that to happen automatically, you should use a smart pointer (e.g. unique_ptr or shared_ptr depending on what behaviour you want).
If you don't use smart pointers, then you will need to take pointer stored, and delete the object yourself (after using erase to remove the element from the map).

A: Your default constructor is called a fourth time, because m[1] in
std::cout << "erased test object: " << m[1].get_id() << std::endl;

will construct a new object with key "1". This is because such an element doesn't exist in the map yet – otherwise it would just return that already existing object. (It did exist before, but you erased it in the line above! ;])


text:
Q: arbitrary data shared between plugins I'm making a program that supports plugins.  The program is being written in F#.
The program maintains a single object that represents the state of the program.  When a plugin is invoked, it takes the state and returns a new state which replaces the old one.
Example:
The filereader plugin takes an empty state and puts the contents of a specified file into the state.
The textviewer plugin takes this state, checks if it contains a "text" object; if it does, it displays the text on the screen.
In this way, a filereader can be implemented seperately from the textviewer.  The textviewer only cares if there is a "text" object in the state; it does not care how the object got there.
My question is of implementation.  I could represent the state as a big JSON object.  But this is rather clumsy (but it isn't too bad).  I could also use System.Object to hold arbitrary data, but is this a good approach?

A: First, you probably want to use Event Driven architecture in this case, or something similar to decouple all the modules. Once module is done doing what it's doing, it triggers an event on the main program that all other modules are subscribed to.
Now, to your question:
I would only store the references to resources provided by the modules in the state - not the whole text file as you described.

*

*Text Reader Module is attached to main program.

*Module is updating the state with new reference to the text file that it stores somewhere.

*Text loaded event is dispatched.

*Text Viewer is subscribed to the event, and thus pulls the file by reference from the state.

Your state object should represent a collection of assets probably utilizing Decorator pattern and potentially Composite pattern to treat collections of collections as just assets if required.
That's roughly what I would do. Of course, this would change a bit as you design and implement as I am making a lot of assumptions here.

A: Plugin architectures is quite a well-known problem in Object-Oriented Design, where it's usually addressed by defining a set of interfaces that the host program expects the plugins to implement.
On .NET, the Managed Extensibility Framework was explicitly designed to address this problem. Not only does it support interfaces that are defined in advance by the host program, but it can also discover and compose interfaces that one plugin requires (imports), and another plugin implements (exports).
Other mature DI Containers that support convention-based Auto-registration can be configured to supply the same features.
In F#, substitutability and composition is usually achieved with functions instead of interfaces, but I'm not aware of any DI Containers or other composition engines that work on F# functions instead of .NET interfaces. Since I mostly favour Pure DI these days, I also hope never to see this happen.
You may wonder why this is relevant in an F# context, but once you realise that there's a strong relationship between objects and closures, the relevancy may become more apparent.
In any case, the architecture suggested here isn't how plugin architectures are normally implemented. As explained above, plugin architectures are usually defined around a set of predefined behaviours, rather than data. Well-designed interfaces define behaviours, just as functions do. These are strongly typed and substitutable (polymorphic).
Weakly typed data is likely to become a maintenance headache over time, so I wouldn't go with that design.
You can read more about (Object-Oriented) loosely coupled architectures in my book.
You don't write about your root cause for writing an application with a plug-in architecture, but unless you're writing a big shrink-wrapped application like Visual Studio, a browser, a general-purpose web server, or the like, this sort of architecture is most likely overkill.
One of the best features of F# is that it prohibits cycles. In Object-Oriented languages like C# and Java, people often utilise component-based architectures like Ports and Adapters, Onion architecture, layers, etc because at the module level, cycles are prevented (you can't easily create cycles with hard dependencies). However, in F#, you get this assistance from the language itself, so there's much less reason to address coupling with architecture; coupling is already addressed by the language.


text:
Q: push to array within javascript object function v1 executes w/o error, and console log shows the expected array populated w/ the response data.  However, I'm trying to make life simpler down the road by returning 2 arrays within nysQueryReturn as an object:
function v2 also executes without errors, but console logs show nysQueryReturn {sldlBills: Array(0), slduBills: Array(0)}...empty arrays.

Function v1: works as expected
function getBillData() {
  return getBills().
  then(function(response) {
    // save retrieved bill numbers
    var billData = response;
    var nysQueryReturn = [];

    // get NY State Leg data for each bill number
    billData.forEach(function(p) {

      // Assembly bill
      nysBillQuery(p.gsx$sessionyear.$t, p.gsx$assemblynum.$t).
      then(function(response){
        nysQueryReturn.push(response);
      });

      // Senate bill
      nysBillQuery(p.gsx$sessionyear.$t, p.gsx$senatenum.$t).
      then(function(response){
        nysQueryReturn.push(response);
      });
    });
    console.log('nysQueryReturn', nysQueryReturn);
    return nysQueryReturn;
  });
} // end of getBillData()

function v2:  empty arrays :(
function getBillData() {
  return getBills().
  then(function(response) {
    // save retrieved bill numbers
    var billData = response;
    var nysQueryReturn = {
      sldlBills: [],
      slduBills: []
    };

    // get NY State Leg data for each bill number
    billData.forEach(function(p) {

      // Assembly bill
      nysBillQuery(p.gsx$sessionyear.$t, p.gsx$assemblynum.$t).
      then(function(response){
        nysQueryReturn.sldlBills.push(response);
      });

      // Senate bill
      nysBillQuery(p.gsx$sessionyear.$t, p.gsx$senatenum.$t).
      then(function(response){
        nysQueryReturn.slduBills.push(response);
      });
    });
    console.log('nysQueryReturn', nysQueryReturn);
    return nysQueryReturn;
  });
} // end of getBillData()

i've found several examples of "array of arrays" and "array of objects" on stackoverflow, but i can't see how to re-purpose those answers to fit my "object of arrays" scenario.  any thoughts/pointers/explanations of what i'm missing would be warmly welcomed.
Thank you for your time.
edit:
k, I found this question & answer, which seems to suggest I was "doing it right". Taking another look, Chrome Dev Tools console reports that the two arrays are "empty", but when expanded they contain the expected info.  Still, I can't actually access the array elements w/ nysQueryReturn.sldlBills[0].basePrintNo without getting TypeError: Cannot read property 'basePrintNo' of undefined, and I can't for the life of me figure out why.
What am I not getting?

A: I will assume you know about arrow functions and how to use them appropriately.  I will also assume you know about let and const.  None of these are required, they just make things a little prettier.  You can replace all arrow functions (in the example below) with normal functions and all let and const declarations with var declarations.
Your end result should look something like the following:
function getBillData() {
  return getBills().then((billData) => {
    const nysQueryReturn = {
      sldlBills: [],
      slduBills: []
    };

    // This should look familiar, it returns a Promise.  This
    // Promise first loads the Assembly bill then adds the result
    // to the appropriate array in nysQueryReturn object.
    const loadAssemblyBill = (bill) => {
      return nysBillQuery(bill.gsx$sessionyear.$t, bill.gsx$assemblynum.$t).then((sldlBill) => {
        nysQueryReturn.sldlBills.push(sldlBill);
      });
    };

    // This should look familiar, it returns a Promise.  This
    // Promise first loads the Senate bill then adds the result to
    // the appropriate array in nysQueryReturn object.
    const loadSenateBill = (bill) => {
      return nysBillQuery(bill.gsx$sessionyear.$t, bill.gsx$senatenum.$t).then((slduBill) => {
        nysQueryReturn.slduBills.push(slduBill);
      });
    };

    // First exciting thing: Let's map each bill to a 2 workers
    // that will load the important information that we will add to
    // nysQueryReturn.
    const workers = [];

    billData.forEach((bill) => {
      workers.push(loadAssemblyBill(bill));
      workers.push(loadSenateBill(bill));
    });

    // Return a Promise that will wait for all the workers to
    // finish.
    return Promise.all(workers).then(() => nysQueryReturn);
  });
}

You weren't seeing the results you expected because you weren't waiting for the results to load.  In fact, if you set a timeout and examine the result sometime later, you would have seen the arrays populate.
Let's think of nysQueryReturn as a box that holds all the sldlBills and slduBills, Promises as workers, and the code that called getBillData() as your customer.  With v2 of getBillData(), you

*

*Found all the bills.

*Created the nysQueryReturn box

*Hired some workers and told them what to do.

*Gave the box to your customer.

Unfortunately, you did not wait for your workers to finish their job before you gave the box to your customer.  Needless to say, your customer was quite confused and just pretended like they got what they wanted.
With the new implementation, you

*

*Found all the bills.

*Created the nysQueryReturn box

*Hired some workers and told them what to do.

*Wait for your workers to give you what they found.

*Gave the box to your customer.

You wait for your workers to finish by maintaining a list of the workers and then waiting for all() (Promise.all()) of them to  tell you they have finished and added their results to the nysQueryReturn box.  After they have all finished, you give your customer all of the results (.then(() => nysQueryReturn)).
Remember, every time you use a Promise (anything that has a .then() method), you are executing something outside of the flow of the normal program.  JS will not wait for that flow to finish before continuing with it's original flow.  Pictorially, this would look something like:
___________                     ____________                                ____________
|  Flow 1 |                     |  Flow 2  |                                |  Flow 3  |
-----------                     ------------                                ------------

billData.forEach(/* ... */);
console.log(/*...*/);
return nysQueryReturn;
                                nysQueryReturn.sldlBills.push(/*...*/);
                                                                            nysQueryReturn.slduBills.push(/*...*/)

To wait for the new flow to finish, you have to explicitly wait for it by passing a callback to .then().

A: Promises are async functions, so not run line by line.I recommend that you read https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise, to understand how promises work.
You can try this code: use map to returns the promises, then use Promise.all to wait for completion of all.
function getBillData() {
    return getBills()
    .then(function (response) {
        var billData = response;
        var nysQueryReturn = {
            sldlBills: [],
            slduBills: []
        };

        prs = billData.map(function (p) {
            return nysBillQuery(p.gsx$sessionyear.$t, p.gsx$assemblynum.$t)
                .then(function (res) {
                    nysQueryReturn.sldlBills.push(res);
                    return nysBillQuery(p.gsx$sessionyear.$t, p.gsx$senatenum.$t);
                })
                .then(function (res) {
                    nysQueryReturn.slduBills.push(res);
                });
            });

        return Promise.all(prs).then(function () {
            return nysQueryReturn
        });

    });
} // end of getBillData()


text:
Q: Visual SVN and Visual Studio 2010 Beta 2 won't play nice I can't seem to get Visual SVN and Visual Studio Beta 2 to work together, anyone know of a workaround???

A: This is known problem. We're working on it and provide fix soon.
As workaround you may copy file "C:\Program Files\[Prev Visual studio]\Common7\IDE\PrivateAssemblies\microsoft.visualstudio.dll" to C:\Program Files\VisualSVN\bin directory.

A: The latest generation VisualSVN in reporting Visual Studio 2010 compatibility: http://www.visualsvn.com/visualsvn/download/
There's also a post about getting it to work with the first beta here: http://mikeownage.com/wordpress/?p=336

A: The workaround solved the problem for me. Look in C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\PrivateAssemblies for the dll.

A: I know ankhsvn is working on it. Might you give them a try?
Have you updated to a recent build?
VisualSVN change log

A: Ivan: The workaround to copy a DLL describes a DLL that I am unable to locate. I don't have a "microsoft.visualstudio.dll".
Can you please elaborate?
EDIT:
Ahhh ... I think my browser had left out the ..\[Prev Visual studio]\.. part. I just read an empty segment ..\\.., and so I was looking for it in the Microsoft Visual Studio 10.0 folder. Found it!
Thanks.


text:
Q: Provide metrics for Business Discovery insights in Instagram Graph API I was creating an application to get insights into business and creator accounts. But when I was trying out to get insights of an account using business discovery, I was receiving the error
{
  "error": {
    "message": "(#100) For field 'insights': The parameter metric is required",
    "type": "OAuthException",
    "code": 100,
    "fbtrace_id": "A_VNXOMovZwvUpzUFVF5y87"
  }
}

The query I fetched was ?fields=business_discovery.username(google){insights{impressions}}
I know how can I fetch insights data for my account /insights?metric=impressions&period=day. But I cannot understand, how can I give the period argument in that previous query?

A: Business discovery cannot get insight data.
You should use insight api instead.
Here's a simple account insight fyr
17841403823915540/insights/?metric=follower_count,reach,impressions&period=day&since2021-01-11&until=2021-01-18
And you will get sth like:
{
  "data": [
    {
      "name": "follower_count",
      "period": "day",
      "values": [
        {
          "value": 0,
          "end_time": "2021-01-16T08:00:00+0000"
},


text:
Q: UIViewController removeFromSuperview error I have a UIViewController then when I longpress to self.view it will push a popup (MenuViewController). But when I try to remove popup by removeFromSuperview it still appears
You can see more detail of my problem with this http://www.youtube.com/watch?v=nVVgmeJEnnY
ViewController.m
#import "MenuViewController.h"
@interface ViewController () {
    MenuViewController *menu;
}
....
- (void)viewDidLoad
{
    ....
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(albumButtonPressed : ) name:@"albumButtonPressed" object:nil];
    ....
}

....

-(void)albumButtonPressed : (NSNotification*) notification {
    UIImagePickerController *photoPicker = [[UIImagePickerController alloc] init];
    photoPicker.delegate = self;
    photoPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

    [self presentModalViewController:photoPicker animated:YES];
}

...

-(void)handleLongPress:(UILongPressGestureRecognizer*)recognizer {
    menu = [[MenuViewController alloc] initWithNibName:@"MenuViewController" bundle:nil];
    if (self.imageView.image != nil) {
        menu.imageAdded = YES;
    }
    [self.view addSubview:menu.view];
}

MenuViewController.m
-(IBAction)albumButtonPressed:(id)sender {
    [self.view removeFromSuperview];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"albumButtonPressed" object:nil];
}

A: Setting aside my reservations about not applying proper view controller containment, the problem is that your handleLongPress will be called multiple times with different recognizer.state values, once as UIGestureRecognizerStateBegan and again as UIGestureRecognizerStateEnded. You should be checking the state of the gesture, e.g.:
-(void)handleLongPress:(UILongPressGestureRecognizer*)recognizer {
    if (recognizer.state == UIGestureRecognizerStateEnded) {
        menu = [[MenuViewController alloc] initWithNibName:@"MenuViewController" bundle:nil];
        if (self.imageView.image != nil) {
            menu.imageAdded = YES;
        }
        [self.view addSubview:menu.view];
    }
}

Original Answer:
I'd suggest putting a NSLog or breakpoint at your code with the removeFromSuperview and see if you're even getting to that piece of code.
There are some clear problems here. Specifically, you're not adding added the view associated MenuViewController in handleLongPress properly. If you want a subview with it's own controller, you have to use containment (and that only works with iOS 5 and later). And in containment, you have critical methods like addChildViewController, etc. See Creating Custom Container View Controllers in the View Controller Programming Guide or see WWDC 2011 - Implementing UIViewController Containment. And, as an aside, you're also maintaining a strong reference to MenuViewController, so even if you succeeded in removing it's view, you'd leak the controller.
Spend a little time going through the containment documentation/video, and I think you'll want to revisit how you're presenting your menu. This is dense reading, but worth really understanding. Containment is powerful, but has to be done right.

A: [self.view removeFromSuperview];

what do you mean by this?????? removing the main view!!!!

A: Instead of directly using
[self.view removeFromSuperview];

use
 [[self.view.superview subviews] makeObjectsPerformSelector:@selector(removeFromSuperview) withObject:self.view];


text:
Q: Windows 7 Symbolic Link - Cannot create a file when that file already exists I'm trying to create a symbolic link between two directories. I have a directory called TestDocs and TestDocs2. I will be doing all my work in TestDocs, but I need it all to be reflected in TestDocs2. So all files that are in TestDocs2 will be replicated in TestDocs, and if I add a file, change a file, etc in TestDocs it should be reflected in TestDocs2.
So I thought it would be as simple as just doing this:
mklink /D TestDocs TestDocs2

But when I do that I get the error:

Cannot create a file when that file already exists

Why am I getting this?
Also, do I have the order of my TestDocs and TestDocs2 wrong in the command?
Thanks for the help, Symbolic Links have always confused me!

A: The correct usage is:
MKLINK [options] {link} {target}

You're creating a link, so the link is the new link you're about to create.
And the target is the link's target, which is the existing directory.

A: Here is how that worked for me.
I wanted to relocate my C:\ProgramData\Package Cache to F: partition.
Steps I had to do:

*

*Physically move "C:\ProgramData\Package Cache" to F:. Now I had "F:\ProgramData\Package Cache" and "C:\ProgramData\Package Cache" is gone since I moved it.

*In cmd run (all in one line, split here for readability)
mklink /J "C:\ProgramData\Package Cache"
          "F:\ProgramData\Package Cache"

*Result:
Junction created for C:\ProgramData\Package Cache <<===>>
                     F:\ProgramData\Package Cache`

A: I did this for Google Picasa so I could access photographs on more than one machine. It works very well as Picasa is not really a netowrk enabled program.
For me I did the following:

*

*Install Picasa

*Run the application. This will create all the necessary database files.

*Close the application.

*Navigate to the directory where the database is - on Windows 7 it will be created in c:\users\\AppData\Local\Google

*There will be two folders Picasa2 and Picasa2Albums
Copy these folders to a network location. In my case I created a folder called o:\PicasaDatabase and copyied these folders into it.

*Next rename the original folders to Picasa2.old and Picasa2Albums.old

Run the following commands from an elevated cmd prompt:
mklink /D "c:\Users\\AppData\Local\Google\Picasa2" "o:\PicasaDatabase\Picasa2"
mklink /D "c:\Users\\AppData\Local\Google\Picasa2Albums" "o:\PicasaDatabase\Picasa2Albums"
Two symbolic links will have been created in the source location and they will point to the network drive.
Obviously using symbolic links like this is a workaround for application that are not networkable and only one user can access the database at once.

A: I had the same issue. You have to make sure the Source folder does not already exist. (if it does , then rename it to something else)
In case of below Backup folder should not exist under MobileSync. Since Apple iTunes looks for Backup folder with that name, just rename the existing folder to something like OriginalBackup to avoid iTunes from finding it. Instead the mklink will synonym Backup to D: folder as below
mklink /J C:\Users\Dell\Apple\MobileSync\Backup D:\Apple\Backup\iPhoneXRBackup

A: I had this error. Two things I did to fix it.

*

*check I was actually in the directory I thought I was and not another one with a very similar path.

*put quotes around the new link name.
First attempt:
mklink /d \shared_files ....\my-app-public\src\shared_files
gave error described.
Second attempt:
mklink /d ".\shared_files" ....\my-app-public\src\shared_files
worked fine.


text:
Q: Angularjs: transclude directive template How to use transclusion in the below case. The intention is to use markup in the html (partials) file, than defining it in template (within the directive).
I found a great tree directive here. (source)
Original: http://jsfiddle.net/n8dPm/
Instead of defining the template in the directive, I was trying to use a transcluded content. I also updated Angular to 1.2.0.rc2.
Updated: http://jsfiddle.net/aZx7B/2/
got below error

TypeError: Property '$transclude' of object [object Object] is not a
  function

code:
module.directive("tree", function($compile) {
    return {
        restrict: "E",
        transclude: true,
        scope: {family: '='},
        template:
            '
' +
                '

' +
                '
' +
                    '<tree family="child"></tree>' +
                '
' +
            '
',
        compile: function(tElement, tAttr) {
            var contents = tElement.contents().remove();
            var compiledContents;
            return function(scope, iElement, iAttr) {
                if(!compiledContents) {
                    compiledContents = $compile(contents);
                }
                compiledContents(scope, function(clone, scope) {
                         iElement.append(clone);
                });
            };
        }
    };
});

        <tree family="family">

{{ family.name }}

        </tree>

Edit:
With David's suggestion, made some changes. http://jsfiddle.net/aZx7B/3/
now, it prints, Parent. changing, family -> treeFamily didn't work though

A: You need to output the name of the family in the template as well:
http://jsfiddle.net/roadprophet/DsvX6/
module.directive("tree", function($compile) {
    return {
        restrict: "E",
        transclude: true,
        scope: {family: '='},
        template:
            '
' +
                '

' +
                '
' +
                    '<tree family="child">{{family.name}}</tree>' +
                '
' +
            '
',
        compile: function(tElement, tAttr, transclude) {
            var contents = tElement.contents().remove();
            var compiledContents;
            return function(scope, iElement, iAttr) {
                if(!compiledContents) {
                    compiledContents = $compile(contents, transclude);
                }
                compiledContents(scope, function(clone, scope) {
                         iElement.append(clone);
                });
            };
        }
    };
});

EDIT
You could also simplify by doing this: http://jsfiddle.net/roadprophet/DsvX6/2/

        <tree family="treeFamily">
        </tree>

module.directive("tree", function($compile) {
    return {
        restrict: "E",
        transclude: true,
        scope: {family: '='},
        template:
            '
' +
                '

' +
                '
{{ family.name }}
' +
                '
' +
                    '<tree family="child"></tree>' +
                '
' +
            '
',
        compile: function(tElement, tAttr, transclude) {
            var contents = tElement.contents().remove();
            var compiledContents;
            return function(scope, iElement, iAttr) {
                if(!compiledContents) {
                    compiledContents = $compile(contents, transclude);
                }
                compiledContents(scope, function(clone, scope) {
                         iElement.append(clone);
                });
            };
        }
    };
});

EDIT
Same source of the problem though.  No template being passed to the inner tree directive.
http://jsfiddle.net/roadprophet/DsvX6/3/

        <tree family="treeFamily">

{{ family.name }}

        </tree>

 template:
            '
' +
                '

' +
                '
' +
                    '<tree family="child">

</tree>' +
                '
' +
            '
'

A: You want to compile the transcluded DOM against the parent scope; you can do this automatically with the injectable $transclude function in a directive's controller definition:
module.directive("tree", function($compile) {
  return {
    restrict: "E",
    transclude: true,
    scope: { family: '=' },
    template: '
' +
                '
' +
                  '<tree family="child">' +
                    '
{{ child.name }}
' +
                  '</tree>' +
                '
' +
              '
',
    controller: function($element, $transclude) {
      $transclude(function(e) {
        $element.append(e);
      });
    },
    compile: function(tElement, tAttr, transclude) {
      var contents = tElement.contents().remove();
      var compiledContents;
      return function(scope, iElement, iAttr) {
        if(!compiledContents) {
          compiledContents = $compile(contents);
        }
        compiledContents(scope, function(clone) {
          iElement.append(clone);
        });
      };
    }
  };
});

This allows you to use the parent scope property treeFamily in your root template (also notice the use of child in the directive's template, above):

    <tree family="treeFamily">

{{ treeFamily.name }}

    </tree>

You can see an example here: http://jsfiddle.net/BinaryMuse/UzHeW/

A: Very very late to the party. I needed this for a project so after dwelling into it and finding other great approaches and directions, finally came up with this:
Same code as the ng-transclude directive, but with small addition of context binding that the directive watch and sets on the transcluded generated scope each time it changes. Same as ng-repeat does, but this allows:

*

*using the customize ng-transclude with ng-repeat without the hassle of rewriting ng-repeat and like angular/2 template outlet.

*Having the transcluded content keep access the grandparent scope while receiving direct context data from the parent. Same as template outlet again.

The augmented ng-transclude function:
return function ngTranscludePostLink(
   ...
  ) {
  let context = null;
  let childScope = null;
  ...
  $scope.$watch($attrs.context, (newVal, oldVal) => {
    context = newVal;
    updateScope(childScope, context);
  });
  ...
  $transclude(ngTranscludeCloneAttachFn, null, slotName);
  ...
  function ngTranscludeCloneAttachFn(clone, transcludedScope) {
     ...
     $element.append(clone);
     childScope = transcludedScope;
     updateScope(childScope, context);
     ...
  }
  ...
  function updateScope(scope, varsHash) {
    if (!scope || !varsHash) {
      return;
    }
    angular.extend(scope, varsHash);
  }
}

And it's usage:
App
<my-list items="$ctrl.movies">

App data: {{ $ctrl.header }}

Name:{{ name }} Year: {{ year }} Rating: {{ rating
          }}

</my-list>

MyList

Ng repeat item scope id: {{ $id }}

   <cr-transclude context="item"></cr-transclude>

Full directive code can be found here on GitHub


text:
Q: Deleting firebase data from a web application Is it possible to delete data from Firebase from within the application. I currently can add, amend and delete data directly from the console which updates in the application using the child_added, child_changed and child_removed.
Also, I can add data to Firebase using .push which also reflects the changes with the application.
However, I cannot find anything within the documentation to suggest how to remove data from Firebase through the application - Something like a bin icon next to each Firebase object which when clicked will remove that piece of data from the Firebase database and update within the application.
Is this possible? I'm going round in circles and still can't crack it. Any help would be greatly appreciated.
Thanks,
G

A: For JS please use this code:
ref = new Firebase("myfirebase.com")
ref.remove();

Hope it helps.

A: You can do it in two ways.
firebase.database().ref(CHILD_TO_DELETE).remove();

or
firebase.database().ref(CHILD_TO_DELETE).set(null);

Something like a bin icon next to each Firebase object which when clicked will remove that piece of data from the Firebase database and update within the application.

The answer to this part is it can be inside a click event function of maybe a delete button.

A: ref.child(key).remove();

In JS you could do it like shown above. Keep in mind, it´s asynchronus.


text:
Q: Four finger swipe not working on Magic Trackpad Even though in the preference pane for Trackpad it says "Swipe between full-screen apps" when I'm using the internal trackpad in my laptop, it will switch desktops even if I'm not using full screen apps. However, when I'm using my Magic Trackpad, the 4-finger swipe does not switch desktops.

A: Solution: Go into settings -> trackpad -> turn off the four finger swipe, and turn it on again.
(Credit to Stiwi for the very efficient Jeopardy Question)


text:
Q: Can't change default .jar opener from Command Prompt to Java SE Binary A while back I changed my default opener for .jar files to cmd, as I was writing a few console applications in java and wanted to be able to run them easily (I now know that you can a similar result via javaw.exe). I am now trying to switch the default opener back to javaw.exe, as I'd done this before. I was unable to change it to javaw.exe or any other program, suggested or otherwise.
I couldn't do it via right clicking and going through Open With --> Choose Default Program... menus. This approach opened the program with javaw.exe, but failed to set it as the default opener. I tried also to do it through Control Panel, but this failed to change the default opener as well. Finally, I followed the tutorial here, but I couldn't find "No File Associate".

A: First try to uninstall and then reinstall Java (in hopes it resets the file associations)
If still not working try pressing Windows Key + R and paste
"Control Panel\Programs\Default Programs\Set Associations"
Set it to java.exe not javaw.exe (Can't remember which one runs java but it's worth a shot.
Even if that doesn't work try a System Restore point from before the associations. (Make one before you restore incase you need to revert)
If that still doesn't work check this article out:
http://www.sevenforums.com/tutorials/19449-default-file-type-associations-restore.html
or other tutorials from the internet. Please backup before making changes if something goes wrong (system restore point)


text:
Q: Linux (Ubuntu Server) / run shell script on startup on a Linux Server (Ubuntu) I have a script to set environment variables and start a python script afterwards.
The script contains the following:
 #!/bin/bash

export IOTHUB_DEVICE_SECURITY_TYPE=connectionString
export IOTHUB_DEVICE_CONNECTION_STRING="HostName=device01;DeviceId=thermostat01;SharedAccessKey=VERYSECRET"
export IOTEDGE_ROOT_CA_CERT_PATH=/home/myuser/certs/mycert.pem

python3 /home/myuser/scripts/simple_thermostat.py

When running the script on the command line it works fine (the script will continuously simulate temperature data until stopped via CTRL-X)
What i did:
Created a service thermostat.service under /etc/systemd/system with the following content:
Environment = /home/myuser/scripts
Type = oneshot
ExecStart = /home/myuser/scripts/startthermo.sh
RemainAfterExit= yes
User = root
Group = root

[Install]
WantedBy = multi-user.target

Afterwards updated with sudo systemctl daemon-reload followed by sudo systemctl start thermostat.service to start the service which fails.
systemctl status thermostat.service is providing the following error:
Aug 19 07:31:26 thermostat01 startthermo.sh[17566]:   File "/home/myuser/scripts/simple_thermostat.py", line 324, in main
Aug 19 07:31:26 thermostat01 startthermo.sh[17566]:     await user_finished
Aug 19 07:31:26 thermostat01 startthermo.sh[17566]:   File "/usr/lib/python3.8/concurrent/futures/thread.py", line 57, in run
Aug 19 07:31:26 thermostat01 startthermo.sh[17566]:     result = self.fn(*self.args, **self.kwargs)
Aug 19 07:31:26 thermostat01 startthermo.sh[17566]:   File "/home/myuser/scripts/simple_thermostat.py", line 189, in stdin_listener
Aug 19 07:31:26 thermostat01-newcoffee startthermo.sh[17566]:     selection = input("Press Q to quit\n")
Aug 19 07:31:26 thermostat01 startthermo.sh[17566]: EOFError: EOF when reading a line
Aug 19 07:31:26 thermostat01 systemd[1]: thermostat.service: Main process exited, code=exited, status=1/FAILURE
Aug 19 07:31:26 thermostat01 systemd[1]: thermostat.service: Failed with result 'exit-code'.
Aug 19 07:31:26 thermostat01 systemd[1]: Failed to start Thermostat01 Service.

I think this must be connected to the fact that the intention of the python script is to run until manually stopped.
Any ideas how I could fix this?
Thanks a lot in advance.


text:
Q: How to judge whether the compound series is convergent Note: The following questions are from the 4th question of the 2009 Chinese Graduate Mathematical Entrance Examination (first set):
There are two series  $\left\{a_{n}\right\}$,$\left\{b_{n}\right\}$. If $ \lim _{n \rightarrow \infty} a_{n}=0$, which of the following conclusions is correct:
$$\begin{array}{c}
&(A)& \text {When the series}\sum_ {n = 1}^{\infty} b_ {n} \text {converges, then}\sum_ {n = 1}^{\infty} a_ {n} b_ {n}\text {also converges.}\\
&(B)& \text {When the series} \sum_{n=1}^{\infty} b_{n}   \text{diverges, then} \sum_{n=1}^{\infty} a_{n} b_{n} \text {also diverges.} \\
&(C)& \text {When the series} \sum_{n=1}^{\infty}\left|b_{n}\right|  \text {converges, then} \sum_{n=1}^{\infty} a_{n}^{2} b_{n}^{2}  \text {also converges.}\\
&(D)& \text {When the series} \sum_{n=1}^{\infty}\left|b_{n}\right|  \text{diverges, then}  \sum_{n=1}^{\infty} a_{n}^{2} b_{n}^{2} \text {also diverges.}
\end{array}$$
I know that enumerating special cases like $a_{n}=b_{n}=(-1)^{n} \frac{1}{\sqrt{n}}$ can solve this question, but I want to know more specific mathematical proofs.


text:
Q: Checking out a file from last commit while having it in index I am a beginner in git.
What I've learned so far is that if I use git checkout -- <file> the file will be checked out from the staging area, if the file was staged, and from the last commit if the file was not staged.
Now, if the file was staged after modification, and I try to replace the file in the working tree with the last committed version using git checkout HEAD -- <file>, it also removes the file from the staging area.
Is it possible to keep the initial modifications in the staging area and get the last committed version of the file in the working tree?

A: To extract a file from a specific revision, we can use
git show $revision:$path

So in your case, you could try
git show HEAD:$path > $path

You could also replace git show with git cat-file -p. git show uses the pager by default, and git cat-file does not at all, even if a valid pager is specified. But the pager doesn't matter here.

A: If is better to consider the newer (Git 2.23, Q3 2022) git restore command  when you want to... restore files.
It allows you to specify:

*

*the source (from which commit you want that file)

*the destination (do you want to restore the file only in your working tree, the index or both?)

That is:
git restore --source $revision -- path/to/file

By default, it affects only the working tree, without impacting the staging area (cache).


text:
Q: Django model design advice I am currently learning Django, specifically DRF to make an API that will be consumed by a web app client. The app is for a teacher who gives extracurricular classes in Mathematics and Science. My basic idea is that there will be two types of User, a Student and a Teacher. Teachers will obviously have more access rights than Students. The problem is, a django User class has the is_admin attribute and, since only Teachers could possibly be admin of the site, I cannot create a single User class that has is_admin and user_type attribute. For instance, the User with is_admin=True and user_type=Student will be an invalid combination. My idea is to make my User class as an Abstract Base Class and then make two seperate classes, Student and Teacher, that inherit from it. This is also ideal in the sense that only Teachers can publish articles, which means the Student class just won't have that permission, but then I face another problem. All Users have a single Profile. The Profile will store a bio, an avatar image of the user, etc. But when setting up the OneToOneField relationship in Profile, the profile must have that relationship with Students and Teachers, thus all User types. How can I set up that relationship? Can I say OneToOneField(User) and due to the inheritance that user could be a Student or a Teacher? If not, what should I do?
If you have experience and you are thinking, why on earth is he (that is me) doing that?, feel free to comment on my design plan and please show me how a better design would look. Thanks in advance.
EDIT: Is there any advantage in having a single profile for each user, storing a bio and image etc? Is there any gain in this over storing that info in the User model?

A: Don't create separate classes. Just that they have different permissions doesn't mean they need to be different classes! They can all be User (or your own subclass of that, but the same).
Then you configure two different groups (docs). You assign each new user to one of the two groups.
Your code can then use some custom permission (say a 'publish' permission on Article) and give that permission to the Teacher group, and check in your code that the current user has that permission.
Typically only one or a few users have "is_admin", is_admin means that you automatically have all existing permissions. It's for user management, configuring the groups, and such.

A: Keep it as one class unless you need each class to have different attributes.  But in your case, you can just make is_staff=True synonymous with being a teacher, and then you could get rid of the user_type attribute.  It's usually better practice to use boolean fields instead of char fields with a finite set of choices that do unknown things in the code.  So staff would be teachers, and non-staff would be students.
Aside: By "is_admin", you meant "is_staff", right?  I am not aware that the django User model has an "is_admin" attribute, only is_staff and is_superuser.


text:
Q: MySql search string that matches at least 2 substrings with regexp I'm trying to create a regexp expression in order to match some strings in my db.
My initial solution was something like this:
SELECT * FROM myTable WHERE myColumn REGEXP 'a1|a2|a3'

but with this solutions it matches every string that contains at least one needle of the haystack. What i'm trying to achieve is to match every needle or at least 2 of them.
Examples:
Wanted string: 'My little foo with bar'

*

*['little', 'foo'] => Matches

*['little', 'foobar'] => Not matches

*['my', 'bar', 'little'] => Matches

A: This is ugly, and slow, but here's a way:
    WHERE (myColumn LIKE '%a1%')
        + (myColumn LIKE '%a2%')
        + (myColumn LIKE '%a3%') >= 2;

Note that a boolean expression (such as the result of LIKE) is 1 for true or 0 for false.
LIKE is faster than REGEXP and LIKE is sufficient for my suggestion, so I switched to it.
If you need to match words, the FULLTEXT is probably a better way to go.  However, doing my >= 2 trick may not be possible.