text:
Q: Create an Incident and Notifications in Stackdriver when a GKE Workload has Issues I have a gke cluster with some workloads that can have boot issues. is it possible to create a stackdriver notification when a workload runs into an issue.
For example: create an incident when CrashLoopBackOff is triggered, pods are unshedulable or the Workload Status is anything other than OK for 5 minutes.

A: You can use log-based metrics to track all the CrashLoopBackOff states in your pods, using the following advanced query:
https://cloud.google.com/logging/docs/view/advanced-queries
resource.type="k8s_pod"
resource.labels.location="us-central1-a"
resource.labels.cluster_name="standard-cluster-1"
"myproject"
jsonPayload.message="Back-off restarting failed container"
resource.labels.pod_name:"myproject"

Pods unschedulable might go into crashloopbackoff or not be deployed, which is only traceable at the API server.
We need to consider that to make the log based metrics, it's necessary to adapt the labels depending on the monitoring version (whether you have legacy or non-legacy) - "non-legacy" monitoring & metrics are used in this example
Create the metric via log-based metrics and you'll find them in Monitoring as logging/user/xxxx
https://cloud.google.com/logging/docs/logs-based-metrics/
When you have a metric created you can create an alert policy to notify you when the issue occurs.


text:
Q: Add -f parameter when running Docker Toolbox I would like to run a docker container using Docker Compose. The docker-compose up command works fine but I want to specify the location of the docker-compose.yml file.
This is the command that is working. In this case the location of the docker-compose.yml file is C:\Users\USERNAME\docker-compose.yml
"C:\Program Files\Git\bin\bash.exe" --login -i "C:\Program Files\Docker Toolbox\start.sh" docker-compose up

Now when I add the -f parameter, the Docker Toolbox just crashes. Say I want to put the file under C:\docker-compose.yml
"C:\Program Files\Git\bin\bash.exe" --login -i "C:\Program Files\Docker Toolbox\start.sh" docker-compose -f "C:\docker-compose.yml" up

Why I need this is because I would dock a Neo4j image using C# code and I am trying to make this string work.

A: You're using BASH so you need to use Linux-style paths - c:\app becomes /c/app. Try:
...docker-compose -f /c/docker-compose.yml

The start script in Docker Toolbox just passes through your arguments to BASH, it doesn't do any syntax conversion from Windows.

redpajama_set_name: RedPajamaStackExchange


text:
Q: alternative for module.exports I've got a question that might sound strange.
We are using node.js, but the way we are writing javascript code is in a functional style. We have a lint tool that reports illegal use of the assignment expression. We can eleminate them all except for the 'module.exports = xxx' statement.
Is there an other way to load modules in node.js?
for example; the following statement would be fine as a solution as it is not an assignment expression but a variable declaration:
var exports = xxx;
if there is a way that nodejs would pick up this 'exports' variable, then we're done.
gr,
Coen

A: the following did the trick for me:
vm.runInThisContext

A: Looks like changing lint tool is the best way. :)
However you can use different module loader (there are some AMD implementations for node.js out there) that's pure functional.


text:
Q: How to mock POST on Karma test I dont know how to normal mock POST in Karma tests.How to check is post correct in test? How about to create a mock object and push him this pushData? Is it normal practice?
   it('POST', function () {
        expect(serv.addNew).toBeDefined();

        $httpBackend.when('POST', '/addnew').respond(200);

        $httpBackend.flush();

    });

A: You can use $httpBackend.expectPOST('/addnew').respond(200) which should fail if the post isn't satisfied (see here)


text:
Q: Are there any other penalties for dying? Having found myself in a few arena-type fights in Hyper Light Drifter, I've found myself running out of med kits fairly quickly due to my fear of dying. I've heard the game called "Zelda meets Dark Souls," and that has me worried about losing what little I have to lose upon death.
Are there any penalties for dying, aside from lost time?

A: I played the game for a while and died quite a few times myself. I didn't notice any major losses from death, so far it looks like you only loose the time, the drawback of that however, anything you picked up in between your last save point and death, you loose.
This includes the gearbits which means you have to obtain them again. I found this when trying to get a gear bit  where you need to take large amounts of fire damage to obtain the gear bit, I have yet to bring it back without dying and loosing it.
There is one benefit to dying, your med-kits get reset to the previous point which means you can plan out your attack much more effectively by not using them until you know you need to.


text:
Q: Electronics to select every third pulse from Ti-sapphire laser I'm currently building an optical imaging system and have run into some difficulty. The optical source is a Ti-sapphire laser which outputs pulses at 80 MHz and I'm using a photomultipler tube as a detector. I would like to trigger my sampling based on every third pulse from the Ti-sapphire (in other words I would like to sample at 80/3 MHz). I have already setup a fast photodiode that can detect each pulse. Is there a way I can easily pick off every third pulse?
Thanks for any help.

A: If you have a photodiode detector that can output a digital 1 or 0 on every pulse then creating a trigger that outputs on every 3rd pulse is not that hard.
Make a state machine that essentially counts to 3 and then resets.
Let there be a clock signal that is the output of your photodiode detector.
Let there be a 2 bit state variable that counts the pulses (lets call it C).
Let there be a trigger output.  Lets call it T.

An HDL description for the state machine would look like...

if rising_edge(clock) then
    if C = "00" then C <= "01";
    elsif C = "01" then C <= "10";
    else C <= "00";
end if;
T <= C = 00;

You could of course synthesize that HDL code on a CPLD directly.  Alternatively you could use a few 74-series logic chips to implement the logic.

C(0) <= C(0) NOR C(1)
C(1) <= (C(0) NOR C(0)) NOR C(1)

T = C(0) NOR C(1)

So you would need a quad NOR gate, and two D-Flip-Flops.

Also, as some have suggested, you could use the pulse detector to clock a 3 stage shift register arranged in a circle.  Your trigger would be the output of one of the three register stages.

The shift register would need to be preloaded with the value "100".  After the first pulse the value would shift to "010", after the second "001", and then after the third it would go back to "100".  So you would have a 1 on your trigger every third pulse.


text:
Q: How do you build a docker image and use it as the container for the next job in GitHub actions? On my CI, I want to build a docker image once and then use the same image twice (or multiple times) for any following jobs, such as "test" and "lint".
  ╭─────────────╮
  │ build-image │
  ╰─────────────╯
        ⬇
 ╭──────╮ ╭──────╮
 │ test │ │ lint │
 ╰──────╯ ╰──────╯

It is possible to use a custom container using the container attribute. However, I'm unsure of how to make the image built in the "build-image" step accessible to that property.
What's the best approach to building an image and using it in the following jobs?

A: I was able to build the image in the first step and tag that image with the commit sha. Then, in the next step, load the container with the sha tag.
build-image:
  runs-on: ubuntu-latest
  steps:
    - uses: actions/checkout@v2
    - uses: docker/build-push-action@v1
      with:
        registry: registry
        repository: user/repo/image-name
        tags: ${{ github.sha }}
test:
  needs: [build-image]
  runs-on: ubuntu-latest
  container:
    image: registry/user/repo/image-name:${{ github.sha }}


text:
Q: retrieve the id PDO if a value already exists I have two tables which are linked with many many relationship,Normally I work with Mysqli for querying,but now for some reasons I have to use PDO,So my problem is 1st to check if a value doesn't exists, to add it in a table tag,and if not to take the id of the value and add the related data in the join data.
tag-tagmap-post a tag can belong to many posts,and a post can have many tags I try this but when a tag name already exists I can't retrieve the id of the tag.
 $sql = "
    INSERT INTO tag (name)
    SELECT * FROM (SELECT :name) AS tmp
    WHERE NOT EXISTS (
    SELECT name FROM tag WHERE name =:name
    ) LIMIT 1";

    try {
        $db = getConnection();
        $stmt = $db->prepare($sql);
        $stmt->bindParam(":name", $post->name);
        $stmt->execute();
        $test=$post->id = $db->lastInsertId();
        $db = null;
        //echo json_encode($post);
    } catch(PDOException $e) {
        //error_log($e->getMessage(), 3, '/tmp/php.log');
        echo '{"error":{"text":'. $e->getMessage() .'}}';
    }

    $sql2="INSERT INTO tagmap (tag_id,post_id,user_id) VALUES(:id2,:post_id,:id)";//
    try {
        $db = getConnection();
        $stmt = $db->prepare($sql2);
        $stmt->bindParam("id2", $test);//tag id
        $stmt->bindParam("post_id", $post->post_id);//post_id
        $stmt->bindParam("id", $id);
        $stmt->execute();
        //$post2->id = $db->lastInsertId();
        $db = null;
        echo json_encode(array("result"=>$test));
    } catch(PDOException $e) {
        //error_log($e->getMessage(), 3, '/tmp/php.log');
        echo '{"error":{"text":'. $e->getMessage() .'}}';
    }

Thank you for your help!!!

A: As documented under PDO::prepare():

You cannot use a named parameter marker of the same name more than once in a prepared statement, unless emulation mode is on.

That said, the insertion query itself is over-complicated (and contains syntax errors: there is no LIMIT clause in the INSERT syntax).  You could instead:

*

*define a UNIQUE key over (name) in the tag table:
ALTER TABLE tag ADD UNIQUE (name);

*use INSERT ... ON DUPLICATE KEY UPDATE:
INSERT INTO tag (name) VALUES (?)
ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID(id);

This will ensure that $db->lastInsertId() returns the ID of the relevant record whether it has been newly inserted or it already existed.


text:
Q: MySQL create row error with php/laravel 8 I am trying to create a new row in 'my_groups' table, but am getting this error:
SQLSTATE[23000]: Integrity constraint violation:
1452 Cannot add or update a child row: a foreign key constraint fails
(mefirst.my_groups, CONSTRAINT my_groups_owner_id_foreign FOREIGN KEY (owner_id) REFERENCES users (id)
ON DELETE CASCADE)
(SQL: insert into my_groups (updated_at, created_at) values (2021-05-17 19:07:54, 2021-05-17 19:07:54))

Here is my schema:
Schema::create('my_groups', function (Blueprint $table) {
    $table->id();
    $table->string('groupName')->default('group');
    $table->unsignedBigInteger('owner_id');
    $table->timestamps();

    $table->foreign('owner_id')->references('id')->on('users')->onDelete('cascade');
});

Here is my MyGroup model where I am creating the row and getting the error:
protected $fillable = [
    'groupName',
    'owner_id'
];

public static function add(User $user) {
    $groupData = array('my group', $user->id);
    Self::create($groupData);
    return "success";
}

I have no idea why this is happening and I have confirmed the value of 'owner_id' does exist in my users table as many other solutions have suggested.

A: The line $groupData = array('my group', $user->id); is the problem.
array('my group', $user->id); is the same as ['my group', $user->id]. There are no keys here. If you dumped $groupData you'd get something like this.
array (
  0 => 'my group',
  1 => $user->id
)

When using create(), eloquent uses the keys to know which columns to fill. In this case, it's trying to fill the column '0' with the 'my group' value and the column '1' with $user->id.
'0' and '1' are not in your $fillable properties, which is why the resulting SQL (last line in your error) only seems to be inserting timestamps.
But even if '0' and '1' were in your $fillable properties, SQL would throw another error about the table my_groups having no such columns.

To fix this, simply add keys to your $groupData array.
$groupData = [
    'groupName' => 'my group',
    'owner_id'  => $user->id
];


text:
Q: About the "GetBytes" implementation in BitConverter I've found that the implementation of the GetBytes function in .net framework is something like:
public unsafe static byte[] GetBytes(int value)
{
   byte[] bytes = new byte[4];
   fixed(byte* b = bytes)
     *((int*)b) = value;
   return bytes;
}

I'm not so sure I understand the full details of these two lines:
   fixed(byte* b = bytes)
     *((int*)b) = value;

Could someone provide a more detailed explanation here? And how should I implement this function in standard C++?

A:
Could someone provide a more detailed explanation here?

The MSDN documentation for fixed comes with numerous examples and explanation -- if that's not sufficient, then you'll need to clarify which specific part you don't understand.

And how should I implement this function in standard C++?

#include <cstring>
#include <vector>

std::vector<unsigned char> GetBytes(int value)
{
    std::vector<unsigned char> bytes(sizeof(int));
    std::memcpy(&bytes[0], &value, sizeof(int));
    return bytes;
}

A: Fixed tells the garbage collector not to move a managed type so that you can access that type with standard pointers.
In C++, if you're not using C++/CLI (i.e. not using .NET) then you can just use a byte-sized pointer (char) and loop through the bytes in whatever you're trying to convert.
Just be aware of endianness...

A: First fixed has to be used because we want to assign a pointer to a managed variable:

The fixed statement prevents the garbage collector from relocating a
  movable variable. The fixed statement is only permitted in an unsafe
  context. Fixed can also be used to create fixed size buffers.
The fixed statement sets a pointer to a managed variable and "pins"
  that variable during the execution of the statement. Without fixed,
  pointers to movable managed variables would be of little use since
  garbage collection could relocate the variables unpredictably. The
  C# compiler only lets you assign a pointer to a managed variable in a
  fixed statement. Ref.

Then we declare a pointer to byte and assign to the start of the byte array.
Then, we cast the pointer to byte to a pointer to int, dereference it and assign it to the int passed in.

A: The function creates a byte array that contains the same binary data as your platform's representation of the integer value. In C++, this can be achieved (for any type really) like so:
int value; // or any type!
unsigned char b[sizeof(int)];
unsigned char const * const p = reinterpret_cast<unsigned char const *>(&value);
std::copy(p, p + sizeof(int), b);

Now b is an array of as many bytes as the size of the type int (or whichever type you used).
In C# you need to say fixed to obtain a raw pointer, since usually you do not have raw pointers in C# on account of objects not having a fixed location in memory -- the garbage collector can move them around at any time. fixed prevents this and fixes the object in place so a raw pointer can make sense.

A: You can implement GetBytes() for any POD type with a simple function template.
#include <vector>

template <typename T>
std::vector<unsigned char> GetBytes(T value)
{
    return std::vector<unsigned char>(reinterpret_cast<unsigned char*>(&value),
                                      reinterpret_cast<unsigned char*>(&value) + sizeof(value));
}

A: Here is a C++ header-only library that may be of help.
BitConverter
The idea of implementing the GetBytes function in C++ is straight-forward: compute each byte of the value according to specified layout. For example, let's say we need to get the bytes of an unsigned 16-bit integer in big endian. We can divide the value by 256 to get the first byte, and take the remainder as the second byte.
For floating-point numbers, the algorithm is a little bit more complicated. We need to get the sign, exponent, and mantissa of the number, and encode them as bytes. See https://en.wikipedia.org/wiki/Double-precision_floating-point_format


text:
Q: coverage percentage using a complex sql query...? Ok, i've been trying to solve this for about 2 hours now... Please advise:
Tables:
PROFILE [id (int), name (varchar), ...]
SKILL   [id (int), id_profile (int), id_app (int), lvl (int), ...]
APP     [id (int), ...]

The lvl can basically go from 0 to 3.
I'm trying to get this particular stat:
"What is the percentage of apps that is covered by at least two people having a skill of 2 or higher?"
Thanks a lot

A: SELECT AVG(covered)
FROM (
  SELECT CASE WHEN COUNT(*) >= 2 THEN 1 ELSE 0 END AS covered
  FROM app a
  LEFT JOIN skill s ON (s.id_app = a.id AND s.lvl >= 2)
  GROUP BY a.id
)

More efficient way for MySQL:
SELECT AVG
       (
         IFNULL
         (
           (
           SELECT 1
           FROM skill s
           WHERE s.id_app = a.id
           AND s.lvl >= 2
           LIMIT 1, 1
           ), 0
         )
       )
FROM app a

This will stop counting as soon as it finds the second skilled person for each app.
Efficient if you have a few app's but lots of person's.

A: Untested
select convert(float,count(*)) / (select count(*) from app) as percentage
from (
    select count(*) as number
    from skill
    where lvl >= 2
    group by id_app ) t
where t.number >= 2

A: The logic is: percentage = 100 * ( number of apps of interest ) / ( total number of apps )
select 'percentage' =
-- 100 times
  ( cast( 100 as float ) *
-- number of apps of interest
  ( select count(id_app)
    from ( select id_app, count(*) as skilled_count
           from skill
           where lvl >= 2
           group by id_app
           having count(*) >= 2 ) app_counts )
-- divided by total number of apps
  / ( select count(*) from app )

The convert to float is needed so sql doesn't just do integer arithmetic.

A: SELECT SUM( CASE lvl WHEN 3 THEN 1 WHEN 2 THEN 1 ELSE 0 END ) / SUM(1) FROM SKILL

If your database has an if/then function instead of CASE, use that.  For example, in MySQL:
SELECT SUM( IF( lvl >= 2, 1, 0 ) ) / SUM(1) FROM SKILL

A: I'm not sure if this is any better or worse than tvanfosson's answer, but here it is anyway:
SELECT convert(float, count(*)) / (Select COUNT(id) FROM APP) AS percentage
FROM APP INNER JOIN SKILL ON APP.id = SKILL.id
WHERE (
   SELECT COUNT(id)
   FROM SKILL AS Skill2 WHERE Skill2.id_app = APP.id and lvl >= 2
) >= 2


text:
Q: How to resolve special character exception issue in UTF8 byte code conversion in C#? I am converting a string into UTF8 byte code,where as it is not accepting any special character and not converting it. so please help me to know convert these special char also in c#.
byte[] bytes = Encoding.UTF8.GetBytes("<Shipper>A & G VENLO BV</Shipper>");

A: Do not lead people astray. Your code throws a System.Xml.XmlException while parsing the XML.
The fact is that the string <Shipper>A & G VENLO BV</Shipper> is not well formed XML. The & symbol in XML must be escaped.
You have to create XML using the right approach:
XmlDocument xmlDoc = new XmlDocument();
XmlElement shipper = xmlDoc.CreateElement("Shipper");
shipper.InnerText = "A & G VENLO BV";
xmlDoc.AppendChild(shipper);

As a result, you will get the well-formed XML
<Shipper>A & G VENLO BV</Shipper>

Now you can work with it
byte[] bytes = Encoding.UTF8.GetBytes(shipper.OuterXml);


text:
Q: lm function throws an error in terms.formula() in R I am trying to run linear modelling on the training data frame, but it is not giving me the output.
It gives me an error saying
Error in terms.formula(formula, data = data) :
'.' in formula and no 'data' argument

Code
n <- ncol(training)
input <- as.data.frame(training[,-n])
fit <- lm(training[,n] ~.,data = training[,-n])

A: There's no need to remove the column from the data to perform this operation, and it's best to use names.
Say that your last column is called response.  Then run this:
lm(response ~ ., data=training)

It's hard to say that this is the formula that you need.  If you provide a reproducible example, that will become clear.


text:
Q: How to identify which class is calling a specific method? Let's assume that we have an abstract class with a method that prints a WARN log entry (WARNING: Cannot set header. Response already committed), this method is being called by class X lots of times (it is flooding the logs).
Based on the log entry that was generated from the Application Server, I have managed to identify the abstract class and found its jar (using jarscan), the JAR is an OOTB Component of the application server so it is not supposed to be modified in any sense. I have hacked the JAR and introduced a line within the method that generates the log entry:
new Exception().printStackTrace()

This approach should give me the stack trace to identify class X.
However, I don't know how to reproduce this error in my test environment, there are a lot of projects that I don't have in my workspace and I can't just check hundreds of classes to see which one is setting something into the response object, I have tried to find a match between the log entries timestamps and Selenium test reports that are running against the test environment but it is not showing up in the logs.
Question: What would be a good troubleshooting approach to identify Class X without any intrusive changes on the environment that presents the issue?

A: If you cannot use debugger because of your environemnt specific, you can investigate classes loaded into your server's JVM and find classes that inherit from your abstract class.
Run jvisualvm and connect to your server's JVM, then go to OQL console in jvisualvm and run such query:
select heap.findClass("com.xyz.my.AbstractClass").subclasses()

This will find all subclasses of your abstract class currently loaded.

A: public String getMethodName(final int depth) {
    final StackTraceElement[] ste = Thread.currentThread().getStackTrace();
    return ste[depth].getMethodName();
}

Usage:
public void doSysOutTest() {
    String getMetNameFunc = getMethodName(1);
    String callingMethod = getMethodName(2);

    System.out.println(getMetNameFunc);
    System.out.println(callingMethod);
}

Output:
getMethodName
doSysOutTest

To get more information out of the stack you could also use these methods:
ste[depth].getClassName()
ste[depth].getFileName()
ste[depth].getLineNumber()

Take a look here: http://docs.oracle.com/javase/7/docs/api/java/lang/StackTraceElement.html


text:
Q: Magento2 - Wait for checkout page completely loaded and fire JS code The goal is to add a piece of JS to manipulate a date picker on the checkout page. I use an OSC (OneStepCheckout from mageplaza). So far I've followed this documentation and added this mixin:
var config = {
  config: {
    mixins: {
      'Magento_Checkout/js/action/set-shipping-information': {
        'Vendor_Module/js/action/set-shipping-information-mixin': true
      },
    }
  }
}

in this file:
define([
  'jquery',
  'mage/utils/wrapper',
], function ($, wrapper) {
  'use strict';

  // the html is not there so this is empty
  var datepicker = $('#datepicker')

  return function (setShippingInformationAction) {
    return wrapper.wrap(setShippingInformationAction, function (originalAction) {

      // ... some custom code ... //
      return originalAction();
    });
  };
});

When I load the page the date picker var has no HTMLElements, the reason is that the checkout is loading all the checkout components. So how can I tell the mixin to wait until the checkout components are completely done/loaded?
Maybe it shouldn't be a mixin?

A: Try using like below
require([
'jquery',
'Magento_Ui/js/lib/view/utils/dom-observer',
], function ($,$do) {
    $(document).ready(function(){
        $do.get('.class-name', function(elem){
            $(elem).addClass('test-class');
            //your code
        });
    });
});

A: You can wait for the DOM to be ready with this !domReady requireJs utility.
define([
  'jquery',
  'mage/utils/wrapper',
  '!domReady'
], function ($, wrapper) {
  'use strict';

  var datepicker = $('#datepicker')

  return function (setShippingInformationAction) {
    return wrapper.wrap(setShippingInformationAction, function (originalAction) {

      // ... some custom code ... //
      return originalAction();
    });
  };
});

However due to knockout templates loading asynchronously via knockout this may not work.
I would try initializing datepicker in the wrapper itself. Something like so:
define([
  'jquery',
  'mage/utils/wrapper',
  '!domReady'
], function ($, wrapper) {
  'use strict';

  var datePickerFunc = function() {
       var datepicker = $('#datepicker');
       ...do datepicker things....

  };

  return function (setShippingInformationAction) {
    return wrapper.wrap(setShippingInformationAction, function (originalAction) {
       datePickerFunc();
      // ... some custom code ... //
      return originalAction();
    });
  };
});

None of this is tested.


text:
Q: Thunderbolt Bridge Mode: compatible to rtp midi/ multicast udp When a thunderbolt bridge is established as a network with fixed ip's between two Macs, does it supports with its emulation a standard ethernet connection in terms of rtp midi and multicast udp data transmission?

A: The Thunderbolt Bridge is not a standard Ethernet connection, but macOS provides you with an IP interface where you can send IP packets between two computers.
RTP-MIDI is a protocol that encapsulates MIDI messages within RTP packets that are exchanged over the UDP protocol. The UDP protocol runs on top of the IP protocol, and as such RTP-MIDI is fully compatible with Thunderbolt Bridge connections.
Similarly multicast UDP runs on top of the IP protocol and as such is fully compatible with Thunderbolt Bridge connections. Obviously its usefulness is not quite the same here, as you normally use multicasting to send the same data to many hosts on the network at the same time. As a Thunderbolt Bridge connection is always between two computers, and two computers only, the multicast element is not really the same.


text:
Q: Application.EnableVisualStyles doesn't seem to have any effect in Windows 10 I am writing in vb.net (2013). My form looks different in the IDE than in run-time when using Windows 10. I tried using the EnableVisualStyles command with no apparent success.
The first picture shows the form in my IDE, the second shows the form in run-time compared to the form using the EnableVisualStyle command.
I appreciate any help you can give.
Thanks!
Form in IDE
Forms with and without EnableVisualStyles
Below is the code for the form with EnableVisualStyles:
Imports System
Imports System.Drawing
Imports System.Windows.Forms

'Summary description for Form1.
Public Class vsForm

    Inherits System.Windows.Forms.Form

    Private button1 As System.Windows.Forms.Button

    <System.STAThread()> _
    Public Shared Sub Main()

        System.Windows.Forms.Application.EnableVisualStyles()
        System.Windows.Forms.Application.Run(New Form1)
    End Sub 'Main

    Public Sub New()

        Me.button1 = New System.Windows.Forms.Button()
        Me.button1.Location = New System.Drawing.Point(24, 16)
        Me.button1.Size = New System.Drawing.Size(120, 100)
        Me.button1.FlatStyle = FlatStyle.System
        Me.button1.Text = "I am themed."

        ' Sets up how the form should be displayed and adds the controls to the form.
        Me.ClientSize = New System.Drawing.Size(300, 286)
        Me.Controls.Add(Me.button1)

        Me.Text = "Application.EnableVisualStyles Example"
        Me.FormBorderStyle = Windows.Forms.FormBorderStyle.Fixed3D
    End Sub 'New
End Class 'Form1


text:
Q: custom lock with spinlock i can not see the error, maybe someone can help me out here.
I have a custom lock using spinlock (it's a for school)
 public class Spinlock : Locker
{
    Boolean locked = false;
    private SpinLock spinLock = new SpinLock();

    public override void LockIt()
    {
        try
        {
            spinLock.Enter(ref locked);
        }
        finally
        {
            if(locked)
                spinLock.Exit();
        }
    }

    public override void UnlockIt()
    {
    }
}

 public abstract class Locker
{
    abstract public void LockIt();
    abstract public void UnlockIt();
}

The exception i get is the following:
System.ArgumentException was unhandled
Message=The tookLock argument must be set to false before calling this method.

A: Yes, this is not correct code.  It will fail when a second thread also enters the lock and it is already held.  The locked variable must be a local variable to ensure that it has thread affinity.  Fix:
public override void LockIt()
{
    bool locked = false;
    try
    {
        spinLock.Enter(ref locked);
    }
    finally
    {
        if(locked)
            spinLock.Exit();
    }
}

Do note that the code otherwise makes no sense, there is no point in entering a lock and then immediately exit it again.  I assume that's your real homework assignment.

A: The code works fine for me.
You must make sure before you enter the lock (spinLock.Enter) that locked is false.
Otherwise you'll get this exception!
Seems that some other part of your code overwrites that variable.


text:
Q: Java Non-static array I have to find dynamic array using in java. I know I can use ArrayList or List but i cant use them now, I really made an effort about finding this, but i couldn't find how to use non static(dynamic) array without Collections, thanks

A: Arrays have fixed length in Java. There's no way around that.
If you want to add an N:th element to an array, arr with length N-1 then you'll have to

*

*Create a new array.

*Copy over the content of the old array to the new array

*Replace all references to the old array with references to the new on.

In code these steps correspond to
int[] newArr = new int[N];
System.arraycopy(arr, 0, newArr, 0, arr.length);
arr = newArr;

or, slightly shorter by using Arrays.copyOf from Java 6:
int[] newArr = Arrays.copyOf(arr, N);
arr = newArr;

A: Normal arrays in Java are not dynamic, so when you want to change the size of the array, you need to create a new one and copy the content of the previous one into it.
You can do that using Arrays#copyOf method to create and copy it in a simple way:
int[] myNewIntArray = Arrays.copyOf(oldIntArray, newArraySize);

A: You can implement your own dynamic array. Create an array of size 1 (or n if an initial size is provided), then double the size and copy existing elements once it reaches the capacity.
And this is going to have an amortized cost of 3 per operation, 3n for n elements, meaning you can maintain that in o(n) time.
A very simple naive implementation (for int array) would be:
class DynamicIntArray
{
    private int capacity;
    private int[] array;
    private int size = 0;

    public DynamicIntArray()
    {
        this(1);
    }

    public DynamicIntArray(int capacity)
    {
        this.capacity = capacity;
        array = new int[this.capacity];
    }

    public void add(int a)
    {
        if (size == capacity)
            resize();
        array[size] = a;
        size++;
    }

    private void resize()
    {
        capacity *= 2;
        array = Arrays.copyOf(array, capacity);
    }

    // Implement the rest
}

Here is how you would use it:
DynamicIntArray dynamicArray = new DynamicIntArray();
dynamicArray.add(1);
dynamicArray.add(2);
dynamicArray.add(3);

If you change it to use generics you can use it for anything, not just integers.

A: You just allocate them like this:
int[] array = new int[17];

A: You could use a Collection until the type array is needed and then get your array by using Collection.toArray() function.

A: You could mimick dynamic behaviour by creating a new array when it is close to getting full e.g., create a new array with twice the length of the original array, and copy all the elements over.

A: I think you would get even better answers if you explain what you are trying to do and why you can't/won't user Collections. What exactly is the problem you are trying to solve?


text:
Q: Let $X\sim\text{Bin}(n,p)$. if $n = 100$ and $\hat p = X/n = 0.8$, if we want the length of the $95\%$ CI for $p\leq 0.03$, we need at least what $n$?
(b) (2 points). Let $X\sim\operatorname{Bin}(n,p)$. If $n = 100$ and $\hat p = X/n = 0.8$, then the $95\%$ confidence interval for $p$ is _______. If we want the length of the $95\%$ confidence interval for $p$ to be less than or equal to $0.03$, we need $n$ at least ________.

My Work:
a) $0.8 \pm 1.96\sqrt{\frac{(0.8)(0.2)}{100}} = 0.8\pm 0.0784 =(0.7216, 0.8784)$ (This is correct.)
b) $\frac{(2)(1.96)(0.4)}{\sqrt n}\leq \frac{3}{100}$
$n = 2731.1076$
but the answer for this part is $4269$.
Need help with the second part

A: Half the length of the CI is the margin of error $M = 1.96\sqrt{\frac{.8(.2)}{n}}.$ So you want to set $2M = .03$ and solve for $n$. This gives the same
answer you got.
It seems the text is taking a conservative approach. The longest possible CI
results if $p = 1/2.$ So ignoring the current evidence that $p \approx .8,$
the author goes for the worst-case scenario and uses
$M = 1.96\sqrt{\frac{.5(.5)}{n}}.$ Using that, I get 4268.444, and
rounding up to the next larger integer I get 4269. That would ensure that
even the longest possible CI is still as short as .03.
Of course, there is no guarantee that we won't get $p \approx .5$ on the
next survey and need such a large sample. But given the statement of the
problem, I can see why you worked it as you did. You should have another
look at the discussion on lengths of CIs in your text to get a better view of the
author's recommendations for finding sample sizes.
Notes: (1) To see that $p = 1/2$ gives the largest possible value
of $p(1-p)$ under the square root sign, notice that $y = p(1-p)$ is
an inverted parabola with its maximum at $p = 1/2.$
(2) In practice a polling or market research company would probably set
a trial $n \approx 2800.$ Then see if the CI is sufficiently short with that many observations. If not,
revise to $n \approx 4200$ or $4300$ and continue taking data. I worked
briefly for an advertising firm that did market research, and that is the
sort of procedure they followed. (It was a fine job and they're still in business
decades later, but I preferred medical and governmental applications, and teaching.)


text:
Q: plugin doesn't show after deployment in the eclipse I have created an eclipse plugin and it works fine when I'm running it using run as eclipse application.But when I deployed my plugin in the eclipse using File->Export->Deployable plugins and fragments, I cannot see it under new wizard.
I can see my plugin under installed plugins.
Any help why I cannot see it under new wizard list?
UPDATE:
My plugin shows under plugin registry view and when I'm diagnosing it says "no problems detected".
Can anyone help why it's not visible?

A: Quite often this is due to a missing dependency.

*

*Check the "Plug-in Registry" View of your Eclipse installation for your Plug-In.

*Right click on any plugin and check "Show Advanced Options".

*Search your plugin, right click it and clcik on "Diagnose".

It should show you missing dependencies, if there are any.


text:
Q: Collision detection delegate scheme Hey guys!  My physics engine is coming along quite nicely (thanks for asking!) and I'm ready to start working on some even more advanced junk.  Case in point, I'm trying to set up my collision engine so that an arbitrary delegate can be notified when a collision occurs.  Let me set up a scenario for you:
Say we have object A, object B, and object C in the physics simulation.  I want to be able to inform a delegate about a collision between A and B, AND inform a potentially DIFFERENT delegate about a collision between A and C.
A little background information: I have a known interface for the delegate, I have the potential of storing state for my collision detector (but don't atm), and have the ability to store state in the objects themselves.  Similarly, I use this delegate model to handle collision resolution, simply setting the physics engine as the delegate for all objects by default, allowing the user to change the delegate if desired.
Now, I already tried having each object store it's own collision delegate that would be informed when a collision occurred.  This didn't work because when the objects had the same collision delegate, the same collision was handled twice.  When I switched to only using the delegate of the first object (however that was decided), the order of simulation became an issue.  I want to use a dictionary, but that introduces a significant amount of overhead.  However, that seems like the direction I need to be heading.
So here's the question: fight to the death over a suitable solution.  How would YOU solve this problem?

A: I must say that it's a bit odd that two objects can have different delegates (at a collision) and still it would be bad if two identical delegates fired at a collision. I seems like they should both fire all the time or only one of them should. Consistency is what bothers me here.
Explaining that would help some more.
Second, if you use the naive version of holding a delegate for each object and then conditioning activating its functionality ("if (!some boolean indicating this delegate was fired already) {do something}"), this could be solved with a very small overhead.
It works, but I don't like this kind of code.
My suggestion (a bit complex, so think about it before working on it) is to try to focus on a manager object which would go over all the delegates and invoke the two that where relevant to the collision.
For instance, A and B collide, and the manager is invoked with them as parameters. You now can cycle through all the delegates known to the system (assuming they are few) and fire the ones that match "delegate == a.del or delegate == b.del".
This comes at a greater overhead, but if we are talking about a small number of delegates, if will make very little difference. On the other side this will allow you to expend your collision detection engine in this area further more in the future (like the existence of more then one delegate per object).


text:
Q: Failing to compile the zziplib library with MinGW on Windows 10 Good day
I am attempting to compile zziplib-0.13.69 (http://zziplib.sourceforge.net/) with MinGW, as I would like to use LuaZip for Lua 5.3.5. I have installed the dependency zlib 1.2.3. (http://www.zlib.net/), which thankfully has a windows installer. In order to create a UNIX environment and make use of the provided make files I use msys.bat, cd to the source directory and then set up the path to zlib 1.2.3 via:
    export CPATH="C:\Program Files (x86)\GnuWin32\src\zlib\1.2.3\zlib-1.2.3"

As per normal I then run:
    configure && make && make check && make install

The following error is then consistently generated during compiling:
checking CFLAGS for gcc -Wstrict-aliasing... -Wstrict-aliasing
checking CFLAGS for gcc -Warray-bounds... -Warray-bounds
checking CFLAGS making strings readonly... no, unknown
checking CFLAGS for strict prototypes... -Wstrict-prototypes
checking for pkg-config... no
configure: warning: pkgconfigdir=C:/mingw/lib/pkgconfig (see config.log)
configure: perhaps: make install pkgconfigdir=/
configure: warning: aclocaldir=C:/mingw/share/aclocal (see config.log)
configure: perhaps: make install aclocaldir=/mingw/share/aclocal
C:\MinGW\bin\sed.exe: -e expression #1, char 1: unknown command: `C'
configure: creating ./config.status
C:\MinGW\bin\sed.exe: -e expression #1, char 1: unknown command: `C'
config.status: creating Makefile
gawk: ./confjLOGyR/subs.awk:73: S["CFLAGS"]="   -fomit-frame-pointer -Wall -Wpointer-arith -Wsign-compare -Wmissing-declarations -Wdeclaration-after-statement -Werror-implicit-function-declarat"\
gawk: ./confjLOGyR/subs.awk:73:                                                                                ^ backslash not last character on line
C:\MinGW\bin\sed.exe: couldn't write 1 item to stdout: Invalid argument
config.status: error: could not create Makefile
C:\MinGW\bin\sed.exe: -e expression #1, char 1: unknown command: `C'
C:\MinGW\bin\sed.exe: -e expression #1, char 1: unknown command: `C'

I have tried the guide "Compiling zziplib with MinGW" from: http://itsacleanmachine.blogspot.com/2012/03/compiling-zziplib-with-mingw.html
But unfortunately the error persists. New to compiling in general so excuse my ignorance.
Thanks in advance.


text:
Q: How to debug a managed BHO from Visual Studio 2010 I've a managed Explorer Bar (working in Internet Explorer) that is working reasonably well. Currently, the only way to debug it:

*

*Start IE outside VS

*From VS (Debug => Attach) Attach to the process "iexplore.exe"

Trying to do the following:

*

*Go to Project Properties => Debug tab

*Start External Program: c:\program files (x86)\internet explorer\iexplore.exe

*Command line argument: about:blank

*Hit F5
The first method is very cumbersome. With the second method, iexplore starts, but the debugger doesn't recognize the breakpoints, don't know why.
Any tip?

A: So ... 3 months after I opened this question, here is the answer.
In Visual Studio, open an EXE as a new project:

*

*File -> Open -> Project/Solution

*Change type to exe file

*Open c:\program files\internet explorer\iexplore.exe

then, open project property:

*

*There is only one 'General' tab

*Change Debugger Type to 'Managed v4.0'

That's it. F5 will now work. You can add this EXE project to the solution that contains your managed bho, and set the EXE project to be the Startup project.


text:
Q: Bootstrap 3 not loading all class's when called by Ajax URL request, but some are executed I asked a question yesterday, not knowing exactly how to ask the question.  So here is my revised question.
I am using Bootstrap 3 and It is not loading all the classes completely when the Ajax function calls "LEADS_2020_CARD.PHP".  One of the comments on my previous question indicated that bootstrap 3 has a lot of class overrides.  I have searched and searched and there is not much on this topic.  If my issue is with class overrides, I just don't understand why it reads most classes, but ignores others on the "LEADS_2020_CARD.PHP" page, as the only CSS I have in "PHP_LOADER.PHP" is only related to my spinner ring.  Please help me understand, Thank You.
    php_loader.php

    <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Lato" />

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" >

And Here is my CSS for this loader page

    body {
      margin: 0;
      padding: 0;
      font-family: 'Montserrat';
      background: black;
      color: #fff;
    }
    .center {
      display: flex;
      text-align: center;
      justify-content: center;
      align-items: center;
      min-height: 100vh;
    }

    .ring {
      position: absolute;
      width: 200px;
      height: 200px;
      border-radius: 50%;
      animation: ring 2s linear infinite;
    }
    @keyframes ring {
      0% {
        transform: rotate(0deg);
        box-shadow: 1px 5px 2px #e65c00;
      }
      50% {
        transform: rotate(180deg);
        box-shadow: 1px 5px 2px #18b201;
      }
      100% {
        transform: rotate(0360deg);
        box-shadow: 1px 5px 2px #0456c8;
      }
    }
    .ring::before {
      position: absolute;
      left: 0;
      content: "";
      top: 0;
      height: 100%;
      width: 100%;
      border-radius: 50%;
      box-shadow: 0 0 5px rgba(255, 255, 255, 0.3);
    }
    span {
      color: #737373;
      font-size: 20px;
      text-transform: uppercase;
      letter-spacing: 1px;
      line-height: 200px;
      animation: text 3s ease-in-out infinite;
    }
    @keyframes text {
      50% {
        color: black;
      }
    }
    </style>


text:
Q: OnRequestPermissionsResultCallback not triggering in PreferenceFragment import android.preference.PreferenceFragment;
import android.support.v13.app.FragmentCompat;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;

public class Preferences extends PreferenceFragment implements OnPreferenceClickListener, FragmentCompat.OnRequestPermissionsResultCallback {
if (ContextCompat.checkSelfPermission(activity, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
   != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity,
      new String[]{ android.Manifest.permission.WRITE_EXTERNAL_STORAGE },
      Constant.WRITE_STORAGE_PERMISSION);

}

public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grants) { }

I'm trying to get the new permissions. The dialog shows up requesting the permission when it should, but onRequestPermissionResult it's never called, be it rejection or acceptance.
Any idea? The examples are all using Activity and not a Fragment, so that might be the problem. Also, I'm not sure which Compat I should be using (v4 vs v13). Min SDK is 14.

A: full code for you:
public interface PermissionResultListener {
        public void onPermissionResult(int requestCode,
                                       String permissions[], int[] grantResults);
    }

  public class Preferences extends PreferenceFragment implements Preference.OnPreferenceClickListener,
        PermissionResultListener {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    public void requestPermission() {

        Activity activity = getActivity();
        if (activity != null && activity instanceof MainActivity) {
            MainActivity mainActivity = (MainActivity) activity;
            mainActivity.requestPermissionStorage();
            mainActivity.setPermissionResultListener(this);
        }

    }

    @Override
    public boolean onPreferenceClick(Preference preference) {
        return false;
    }

    @Override
    public void onPermissionResult(int requestCode, String[] permissions, int[] grantResults) {
        // request permission result here
    }
}

public class MainActivity extends AppCompatActivity {

    private PermissionResultListener mPermissionResultListener;

    public void setPermissionResultListener(PermissionResultListener mPermissionResultListener) {
        this.mPermissionResultListener = mPermissionResultListener;
    }

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

        // Check that the activity is using the layout version with
        // the fragment_container FrameLayout
        if (findViewById(R.id.fragment_container) != null) {

            // However, if we're being restored from a previous state,
            // then we don't need to do anything and should return or else
            // we could end up with overlapping fragments.
            if (savedInstanceState != null) {
                return;
            }

            // Create a new Fragment to be placed in the activity layout
            Preferences preferences = new Preferences();

            // In case this activity was started with special instructions from an
            // Intent, pass the Intent's extras to the fragment as arguments
            preferences.setArguments(getIntent().getExtras());

            // Add the fragment to the 'fragment_container' FrameLayout
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_container, preferences).commit();
        }

    }

    public void requestPermissionStorage() {

        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    Constant.WRITE_STORAGE_PERMISSION);
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (mPermissionResultListener != null) {
            mPermissionResultListener.onPermissionResult(requestCode, permissions, grantResults);
        }

    }
}


text:
Q: Stored Procedure does not use available index on table (Oracle) A SELECT query in my stored procedure takes 3 seconds to execute when the table queried has no indexes. This is true in both when executing the query in Toad Editor and when calling the stored procedure. The Explain Plan shows that a full table scan is done.
When an index is added, the same query in Toad Editor returns results instantaneously (just a few milliseconds). The Explain Plan shows that the index is used. However, even when the index is present, the query still takes 3 seconds in the stored procedure. It looks like the query uses a full table scan when executed in stored procedure despite having an index that can speed it up. Why?
I have tried with indexes on different columns with different orders. The same results persist in all cases.
In the stored procedure, the results of the query are collected using BULK COLLECT INTO. Does this make a difference? Also, The stored procedure is inside a package.
The query is a very simple SELECT statement, like this:
  SELECT MY_COL, COUNT (MY_COL)
    /* this line is only in stored proc */ BULK COLLECT INTO mycollection
    FROM MY_TABLE
   WHERE ANOTHER_COL = '123' /* or ANOTHER_COL = filterval (which is type NUMBER) */
GROUP BY MY_COL
ORDER BY MY_COL

A: Without source code we can only guess...
So I suspect it's because in Toad you get just first 500 rows (500 is default buffer size in Toad) but in stored proc you fetch ALL rows into collection. So fetching probably takes most of 3 sec time. Especially if there are nested loops iny our query.
Update: It might also be implicit type conversion in where condition


text: Q: Loadrunner monitoring of VMWare ESX host Looking into setting up a Loadrunner monitor for a ESX host running my test virtual machines. Some quick searching is not finding any native ESX monitors. Can i use some Linux kind of thing? I have seen some doco which suggests Sitescope does this. Thoughts?


text:
Q: fread(); problema na implementação Estou com um problema simples. Consigo utilizar a função fread normalmente para trabalhar com processamento de áudio em C. No caso tenho 2 códigos. O primeiro lê um arquivo .WAV (com fread) e salva em um arquivo .CSV. Esta etapa está funcionando corretamente, pois já verifiquei o .csv com o matlab. Porém, no segundo código quando tento abrir o arquivo .CSV só retorna lixo da memória. Então criei um arquivo .txt com apenas 1 numero e tentei acessá-lo através da função fread e mesmo assim retorna lixo.
Segue o código:
#include<stdio.h>
#include<stdlib.h>

int main(){

    FILE *fp;
    //Este arquivo contem apenas o digito 1.
    fp = fopen("ex.txt","r");
    int text[100];

    fread(text, sizeof(text),1,fp);

    printf("%d",text[0]);

    fclose(fp);

    return 0;
}

Qual seria o problema principal? Conheço os outros métodos como fgets e fscanf porém gostaria de utilizar o fread.

A: Seu programa possui vários pequenos problemas e você parece ter a ideia correta, mas com problemas na implementação para uma linguagem de nível mais baixo como C.
Inicialmente, vamos deixar claro que a função fread lê bytes consecutivos do stream que você especificou e, daí, coloca esses bytes lidos de forma "binária" na memória que você especificar.
Note-se que, aqui, fread não faz interpretação/conversão da representação textual de números (por exemplo, a sequência de caracteres 1) para a forma "interna" do computador (a representação binária dele, que pode ser big ou little-endian).
Se o seu arquivo ex.txt tiver única e exclusivamente o dígito 1 na forma de texto, o que estará no arquivo será (muito provavelmente, codificado em latin1 ou UTF-8) um único byte e a função fread lerá esse byte (para o caractere 1 a representação interna, com essas codificações que eu falei, será 49 (o valor "ASCII" do 1)) e colocará o conteúdo desse byte na memória de endereço &text (não é erro o &).
Em computadores "populares" (ARMs, PowerPCs, i386, amd64 etc.), um inteiro possui tamanho de 4 bytes e, portanto, quando você lê a posição de memória text[0] para imprimir com printf, você estará lendo o número 1 e mais 3 outros bytes que podem ser algum lixo.
(Além disso, a maioria dos computadores que temos à nossa disposição é little-endian).
No meu computador (rodando Debian GNU/Linux testing, com GCC 8.2.1 e biblioteca C glibc 2.28), se eu colocar um arquivo ex.txt com o dígito 1 seguido de new-line (isto é, '\n', que possui código ASCII 10) e eu executar o seu programa, eu obtenho o número 2609, que faz completo sentido, já que 2609 = 49 + 10 * 256 e isso é consistente com o computador ser little-endian:

*

*primeiro, o byte de número 49 está na memória

*depois, o byte de número 10 está na memória

(Provavelmente, zeros foram colocados no restante da memória reservada para text no meu sistema, mas não se deve contar com isso).
Seu código ainda possui alguns outros problemas (além de indentação/espaçamento), mas um dos principais é que você declara o vetor text como vetor de ints, mas parece querer colocar dados arbitrários (binários), se você insiste em usar fgets (fscanf ou fgets fariam a interpretação das sequências de caracteres para a representação interna do computador).
Supondo-se que você queira ainda usar a sequência binária nas suas manipulações, você deveria, depois de fazer a leitura dos dados como você já fez:

*

*fazer a leitura da região de memória text com um ponteiro para chars

*usar a string de formatação %c no printf

*declarar o vetor text como apenas de chars (não é estritamente necessário, mas evita uma grande quantidade de "sambadas" com ponteiros)

Honestamente, é mais simples usar fgets (geralmente, mais seguro do que outras opções) e deixar fread apenas para quando você quiser os dados binários do arquivo.


text:
Q: How to remove the last child of element in DOM? var rightSide=document.getElementById("rightSide");
var leftsidecopy = leftSide.cloneNode(true);
document.getElementById("leftsidecopy").removeChild();
document.getElementById("rightSide").appendChild(leftsidecopy);

I have a original copy of data in leftside.I make a copy of leftside .I remove the lastchild of leftside and initialise to rightside.This code doesnt work!

A: Try this type of thing. I try on ol if you need on other tag you can try.

List item 1

List item 2

List item 3

List item 4

List item 5

List item 6

List item 7

 $('ol#myTestList li:last-child').remove();


text:
Q: How to assign dynamically value in @Meta comment in Spring I want to add a comment log in db.system.profile of mongodb, and it works in a constant variable, such as following.
@Query(value="{'field1':?0, 'field2': ?1}")
@Meta(comment="staticComment")
Mono<Quota> findByField1AndField2(String value1, String value2, Sort sort);

My question is if there's any way to assign comment in running time? or such as @Query to carry parameter in? I tried following, but it show up "{?2}" in comment of db.system.profile.
@Query(value="{'field1':?0, 'field2': ?1}")
@Meta(comment="{?2}")
Mono<Quota> findByField1AndField2(String value1, String value2, String dynamicalComment, Sort sort);


text:
Q: NiFi Registry Access Denied I am trying to dockerise the 3 services Zookeeper, NiFi and NiFi Registry below is the docker-compose.yml file
version: "3.7"
services:
    # configuration manager for NiFi
    zookeeper:
        hostname: myzookeeper
        container_name: zookeeper_container_persistent
        image: zookeeper:latest
        restart: on-failure
        environment:
            - ALLOW_ANONYMOUS_LOGIN=no
        networks:
            - my_persistent_network
# version control for nifi flows
    registry:
        build:
            context: .
        user: nifi
        hostname: myregistry
        container_name: registry_container_persistent
        image: apache/nifi-registry:latest
        restart: on-failure
        ports:
            - "18080:18080"
        environment:
            - LOG_LEVEL=INFO
            - NIFI_REGISTRY_DB_DIR=/opt/nifi-registry/nifi-registry-current/database
            - NIFI_REGISTRY_FLOW_PROVIDER=file
            - NIFI_REGISTRY_FLOW_STORAGE_DIR=/opt/nifi-registry/nifi-registry-current/flow_storage
        volumes:
            - nifi_registry_database:/opt/nifi-registry/nifi-registry-current/database
            - nifi_registry_flow_storage:/opt/nifi-registry/nifi-registry-current/flow_storage
        networks:
            - my_persistent_network
    nifi:
        build:
            context: .
        user: nifi
        hostname: mynifi
        container_name: nifi_container_persistent
        image: apache/nifi:latest
        restart: on-failure
        ports:
            - '8091:8080'
        environment:
            - NIFI_WEB_HTTP_PORT=8080
            - NIFI_CLUSTER_IS_NODE=true
            - SINGLE_USER_CREDENTIALS_USERNAME=admin
            - SINGLE_USER_CREDENTIALS_PASSWORD=ctsBtRBKHRAx69EqUghvvgEvjnaLjFEB
            - NIFI_CLUSTER_NODE_PROTOCOL_PORT=8082
            - NIFI_ZK_CONNECT_STRING=myzookeeper:2181
            - NIFI_ELECTION_MAX_WAIT=30 sec
            - NIFI_SENSITIVE_PROPS_KEY='12345678901234567890A'
        # healthcheck:
        #     test: "${DOCKER_HEALTHCHECK_TEST:-curl localhost:8091/nifi/}"
        #     interval: "60s"
        #     timeout: "3s"
        #     start_period: "5s"
        #     retries: 5
        volumes:
            - nifi_database_repository:/opt/nifi/nifi-current/database_repository
            - nifi_flowfile_repository:/opt/nifi/nifi-current/flowfile_repository
            - nifi_content_repository:/opt/nifi/nifi-current/content_repository
            - nifi_provenance_repository:/opt/nifi/nifi-current/provenance_repository
            - nifi_state:/opt/nifi/nifi-current/state
            - nifi_logs:/opt/nifi/nifi-current/logs
            - nifi_conf:/opt/nifi/nifi-current/conf
        networks:
            - my_persistent_network
networks:
  my_persistent_network:

volumes:
  nifi_conf: {external: true}
  nifi_database_repository: {external: true}
  nifi_flowfile_repository: {external: true}
  nifi_content_repository: {external: true}
  nifi_provenance_repository: {external: true}
  nifi_state: {external: true}
  nifi_logs: {external: true}
  nifi_registry_database: {external: true}
  nifi_registry_flow_storage: {external: true}
  # nifi_database_repository:
  #   external: true

while running docker stack deploy -c docker-compose.local.yml nifi_docker the NiFi Registry is not running and its getting exited. The error that is thrown is
Caused by: org.h2.mvstore.MVStoreException: Could not open file /opt/nifi-registry/nifi-registry-current/database/nifi-registry-primary.mv.db

Log File
I have also tried to specify the user tag also within the docker compose file not sure what is causing the issue.
When I change the following lines from
volumes:
            - nifi_registry_database:/opt/nifi-registry/nifi-registry-current/database
            - nifi_registry_flow_storage:/opt/nifi-registry/nifi-registry-current/flow_storage

to
volumes:
            - ./nifi_registry_database:/opt/nifi-registry/nifi-registry-current/database
            - ./nifi_registry_flow_storage:/opt/nifi-registry/nifi-registry-current/flow_storage

the registry seems to be up all the time but this would be creating the volumes locally, I want to be able to deploy the stack via GitLab on a Docker Server.

A: adding user: root to the docker-compose file will solve the issue.


text:
Q: Which seeds does the `getAssociatedTokenAddress` function use to determine the associated token account public key? The @solana/spl-token package contains the getAssociatedTokenAddress function which can be used to obtain the address (public key) of an associated token account. Here's an example:
const programATAPublicKey = await getAssociatedTokenAddress(
  mintPublicKey,
  programPDAPublicKey,
  true,
  program.programId
);

I am trying to achieve the same result using the findProgramAddress function from the @project-serum/anchor package. My problem is that I can't figure out which seeds are used inside getAssociatedTokenAddress. For example, I expected the following code to return the associated token account public key:
const [programATAPublicKey] =
      await anchor.web3.PublicKey.findProgramAddress(
        [mintPublicKey.toBuffer(), programPDAPublicKey.toBuffer()],
        program.programId
      );

The result is, however, different. Which seed combination would yield an identical result to whatever is returned from getAssociatedTokenAddress?

A: The best is to use the source!  Here's the exact code that generates the associated token account address:
export async function getAssociatedTokenAddress(
    mint: PublicKey,
    owner: PublicKey,
    allowOwnerOffCurve = false,
    programId = TOKEN_PROGRAM_ID,
    associatedTokenProgramId = ASSOCIATED_TOKEN_PROGRAM_ID
): Promise<PublicKey> {
    if (!allowOwnerOffCurve && !PublicKey.isOnCurve(owner.toBuffer())) throw new TokenOwnerOffCurveError();

    const [address] = await PublicKey.findProgramAddress(
        [owner.toBuffer(), programId.toBuffer(), mint.toBuffer()],
        associatedTokenProgramId
    );

    return address;
}

where ASSOCIATED_TOKEN_PROGRAM_ID is "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL".
Taken from https://github.com/solana-labs/solana-program-library/blob/ad97543192e05e6ecba88fff3b1da08ca523a5b6/token/js/src/state/mint.ts#L156

A: The Associated Token Account uses the following structure:
[
    walletAddress.toBuffer(),
    TOKEN_PROGRAM_ID.toBuffer(),
    tokenMintAddress.toBuffer(),
],
SPL_ASSOCIATED_TOKEN_ACCOUNT_PROGRAM_ID

Where TOKEN_PROGRAM_ID = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"
and SPL_ASSOCIATED_TOKEN_ACCOUNT_PROGRAM_ID = "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL".


text:
Q: Getting Gmail messages via cURL using PHP There's tons of info on logging in to Gmail and displaying the inbox and getting contacts etc, but I cannot figure out how to get the email itself into a variable so I can do stuff with it in PHP.
Here's what I have:
function inbox($username, $password){
    $url = "https://mail.google.com/mail/feed/atom";
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_USERPWD, $username . ":" . $password);
    curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($curl, CURLOPT_ENCODING, "");
    $curlData = curl_exec($curl);
    curl_close($curl);
    return $curlData;
}
//calling the function
$em = "email@gmail.com";
$pw = "pass";
$feed = inbox($em, $pw);
    $x = new SimpleXmlElement($feed);
    echo "
";
        foreach($x->entry as $msg){
            //extracting the link to the message from xml
            $href = $msg->link->attributes()->href;
            //create a link to the message and display title, summary
            echo "
".$msg->title."
".$msg->summary."
";
        }
    echo "
";

Now when I click on the link I just created it just opens the message in gmail. I want to access the html of the message in a string/variable. I've tried all kinds of things. I've tried forwarding the message link to another page to open in curl but instead of showing me the message google sends some html with yet another link to the message. If the link is clicked in the browser it again, opens in gmail, but if I try to curl a third time to this link it shows me a blank page.
The point is, my work server doesn't have imap/pop enabled and cURL is the last think I know of that can accomplish this.

A: I ended up using imap remotely then cURLing it back to the server in question. I've determined that gmail doesn't allow messages to be sent via cURL, it's one of those google things, like where they don't allow frames, etc


text:
Q: Rails 3 - including JavaScript on a View? here's what I'm trying to do right.... When a user signs in and is redirect to the landing page, I want to run a bit of jquery ajax to grab and inject some content.
I originally had it in my application.js file but the problem with that is that the code is there for user's that aren't logged in, which means I have to add logic to account for that which doesn't seem clean.
What I'd like is for when the view is called to be able to include JavaScript.... I tried pasting it in the view file itself but that failed because it is loaded before JQUERY which is at the bottom of the page...
How do Rails 3 gurus handle this? Thanks!

A: Well, you could include the jQuery file at the top.
If that's not an option, add <%= yield :javascript %> in the layout below the jQuery include, and do:
<% content_for :javascript do %>
    <script type="text/javascript">
        // code goes here
    </script>
<% end %>

It will be placed in the proper location in your layout. (However, I'd recommend, for caching's sake, that you write the Javascript in an external file and include it where necessary instead of using inline Javascript. Just good practice.)

A: Load jQuery from Google CDN and load your view specific JS after. If you are worried about Landing Page speed for non signed in users, have it Page Cached.
If you still want to optimize it further, use a reverse proxy like Sqiud. You can also use Jammit or Asset Packager(http://synthesis.sbecker.net/pages/asset_packager) to minimize your javascript and CSS.
A word of advise, you should focus your performance efforts after you finish writing your app, it's easy to get caught up in lower priority issues which will hinder your development efforts.

A: You'll make it a lot easier on yourself if you just load jQuery earlier in the document. If you load it from Google APIs, chances are it's cached in your client's browser anyway and so the otherwise negligible increase in page load time becomes none at all.


text:
Q: Pokemon GO with Hotspot My smartphone isn't powerful enough to play Pokemon GO, or doesn't have GPS. However, my tablet does.
If I were to activate the WiFi Hotspot feature on my phone, would I be able to play the game on my tablet?

A: Pokemon Go needs a GPS-derived position to work, and internet access.  The type of internet connection (cell or wifi) should not matter.

A: The problem is that your tablet probably doesn't have GPS which is required to play the game.
So unless your tablet has GPS (unlikely as it has no 3G or 4G) then you will not be able to play.

A: You can log in and everything, but when I tired to use my mobile hotspot for my sons tablet so we could walk together it did not work well for him.
It showed the gyms but no PokeStops no Pokemon ever popped up and his character just ran back and forth between blocks as the loading icon constantly showed. My guess is that it knew the general area he was in because of the tower reference from my cell signal, but it could not use gps for a precise location.
Just try it... Maybe you will have better luck.


text:
Q: Can we calculate the point on Earth nearest to the Moon? We have the ability to calculate the Moon's orbit in order to predict Lunar and Solar eclipses precisely.
Using our known calculations of the Moon's orbits, can we calculate the closest point (city or coordinate) on Earth to the Moon for any future or past date and time?
If so, how?


text:
Q: A Set That Is "Precisely" Measure-Dense This question asks for a set of real numbers that is measure-dense, whose complement is also measure dense. In terms of $[0,1]$, the question asks for an $S$ such that for every open interval $I$ we have $0 < \mu(I \cap S) < 1$.
This question can be made a little more precise: is there a set of real numbers $S$ such that for every open interval $I$, we have $\mu(I \cap S) = \frac{1}{2} \mu(I)$? The Cantor-set construction referenced above doesn't really lend itself to finding the volume of $I$ contained in $S$, just guaranteeing that it isn't zero. You can modify that construction to get a set that has measure $1/2$, but it's not clear at all that it satisfies the property mentioned here.

A: I remember seeing this question here, but I can't find it now. Here's the proof that no such $S$ exists:
Suppose such $S$ existed. Define the ($\sigma$-finite) Borel measure $\lambda(A)=\mu(A\cap S)$. Since $\lambda$ and $\mu/2$ are equal on the open intervals, which generate the Borel $\sigma$-algebra, then $\lambda=\mu/2$. Let $\chi_S$ be the characteristic function of $S$. Then for every $f\in L^1(\mathbb{R},\mu)$,
$$\int_\mathbb{R} f\chi_Sd\mu=\int_{\mathbb{R}\cap S} fd\mu=\int_\mathbb{R}fd\lambda=\int_\mathbb{R} fd\frac{\mu}{2}=\int_\mathbb{R}\frac{1}{2}fd\mu$$
so $\int(\chi_S-\frac{1}{2})fd\mu=0$ for every $f\in L^1(\mathbb{R},\mu)$, so this means that $\chi_S-1/2=0$ a.e., that is, $\chi_S=1/2$ a.e. (with respect to $\mu$). But $\chi_S$ is either $0$ or $1$, an absurd.
Therefore, no such $S$ exists.


text:
Q: Navigate from an area to a page with no area in ASP.NET I set up my routing to load /AreaName/Home/Indexby default and when adding this
<a asp-area="" asp-controller="Application" asp-action="Index",
to Index.cshtml I would expect it to go to /Application/Index, but when hovering over the link the url looks like this localhost:######/AreaName/Application/ instead of localhost:######/Application/.
I think my routing is a bit off. Here's what I tried:
app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "Default",
        template: "{area}/{controller}/{action}/{id?}",
        defaults: new { area = "AreaName", controller = "Home", action = "Index" }
    );

    routes.MapRoute(
        name: "SomeName",
        template: "{area}/{controller}/{action}/{id?}",
        defaults: new { area = string.Empty, controller = "Application", action = "Index" }
    );
}

What am I doing wrong?

A: Your routing table should have a default route without an area, your current configuration will always lead to a route with area name = AreaName because you defaulted it to "AreaName" in your first route.
Copy the first route and remove the area section from it and remove the second one.


text:
Q: Received error when trying to setChecked on Checkbox from different fragment My app has one Main Activity and is just composed of different fragments. In one fragment, after I got the JSON values from the server and try to set the check mark on the checkbox, the app crashes and I receive a

java.lang.NullPointerException: Attempt to invoke virtual method 'void
  android.widget.CheckBox.setChecked(boolean)' on a null object
  reference

error I'm trying to set the checkbox value from a different fragment of where the checkbox value is.
Main Activity:
if(v == findViewById(R.id.login)){     //between fragments: from login screen to home page

        username_text = (EditText) findViewById(R.id.username_text);
        password_text = (EditText) findViewById(R.id.password_text);
        RequestQueue requestQueue = Volley.newRequestQueue(this);;
        String signin = "http://acarjsystem.herokuapp.com/auth/";
        StringRequest request;

        uname = username_text.getText().toString();
        pword = password_text.getText().toString();

        final ProgressDialog loading = new ProgressDialog(MainActivity.this);
        loading.setTitle("Loading");
        loading.setMessage("Attempting to Log In");
        loading.show();
        ////////////////////
        request = new StringRequest(Request.Method.POST, signin, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                final Fragment nextFrag;
                final CheckBox check_locateCar, check_carOff,check_getImg, check_tase, check_carOn;
                try {
                    check_locateCar = (CheckBox)findViewById(R.id.check_locateCar);
                    check_carOff = (CheckBox)findViewById(R.id.check_carOff);
                    check_getImg = (CheckBox)findViewById(R.id.check_getImg);
                    check_tase = (CheckBox)findViewById(R.id.check_tase);
                    check_carOn = (CheckBox)findViewById(R.id.check_carOn);

                    JSONObject jsonObject = new JSONObject(response);
                    if(jsonObject.getString("user").equals("logined")){
                        Toast.makeText(getApplicationContext(),"SUCCESS "+jsonObject.getString("user"),Toast.LENGTH_SHORT).show();
                        //startActivity(new Intent(getApplicationContext(),Welcome.class));
                        if(!jsonObject.getString("car_plate").equals("0")){
                            loading.hide();

                            if(jsonObject.getString("car_stat").equalsIgnoreCase("true")){
                                //////////////HERE//////////////////////////////////
                                if(jsonObject.getString("loc_stat").equalsIgnoreCase("true")){
                                         /*THE ERROR IS AROUND THIS LINE*/
                                        check_locateCar.setChecked(true);
                                    }else{
                                        check_locateCar.setChecked(false);
                                    }
                                    if(jsonObject.getString("ignition").equalsIgnoreCase("true")){
                                        check_carOff.setChecked(true);
                                    }else{
                                        check_carOff.setChecked(false);
                                    }
                                    if(jsonObject.getString("taser").equalsIgnoreCase("true")){
                                        check_tase.setChecked(true);
                                    }else{
                                        check_tase.setChecked(false);
                                    }
                                    if(jsonObject.getString("photo_stat").equalsIgnoreCase("true")){
                                        check_getImg.setChecked(true);
                                    }else{
                                        check_getImg.setChecked(false);
                                    }

                                    //check_carOn.setChecked(false);
                                    nextFrag = new locate_updatedstatus();

                                    ////////////////////////////////////////////////////
                                }
                                else{

                                    loading.hide();
                                    nextFrag = new locate_before();
                                }
                            }
                            else{
                                loading.hide();
                                nextFrag = new locate_car_reg();
                            }

                            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                            transaction.replace(R.id.fragment_container, nextFrag);
                            transaction.addToBackStack(null);
                            transaction.commit();

                        }else {

                            Toast.makeText(getApplicationContext(), "Error" +jsonObject.getString("user"), Toast.LENGTH_SHORT).show();
                            loading.hide();

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }){
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    HashMap<String,String> hashMap = new HashMap<String, String>();
                    hashMap.put("username",username_text.getText().toString());
                    hashMap.put("password",password_text.getText().toString());

                    return hashMap;
                }
            };

            requestQueue.add(request);

            ///////////////////////////
            //Toast.makeText(MainActivity.this,uname+"\n"+pword, Toast.LENGTH_LONG).show();
            //newFragment = new locate_login();
        }

fragment_locate_updatedstatus's XML file:
<CheckBox
        android:id="@+id/check_locateCar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/updates"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:text="Locate Car using Gmaps" />

    <CheckBox
        android:id="@+id/check_carOff"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignStart="@+id/check_locateCar"
        android:layout_below="@+id/check_locateCar"
        android:layout_marginTop="10dp"
        android:text="Turn car off" />

    <CheckBox
        android:id="@+id/check_getImg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_below="@+id/check_carOff"
        android:layout_alignStart="@+id/check_carOff"
        android:text="Capture images" />

    <CheckBox
        android:id="@+id/check_tase"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_below="@+id/check_getImg"
        android:layout_alignStart="@+id/check_getImg"
        android:text="Tase Culprit" />

    <CheckBox
        android:id="@+id/check_carOn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignStart="@+id/check_tase"
        android:layout_below="@+id/check_tase"
        android:layout_marginTop="10dp"
        android:text="Turn system off" />

Error
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.CheckBox.setChecked(boolean)' on a null object reference

A: Try moving your fragment transaction for `nextFrag':
if(v == findViewById(R.id.login)){     //between fragments: from login screen to home page

    username_text = (EditText) findViewById(R.id.username_text);
    password_text = (EditText) findViewById(R.id.password_text);
    RequestQueue requestQueue = Volley.newRequestQueue(this);;
    String signin = "http://acarjsystem.herokuapp.com/auth/";
    StringRequest request;

    uname = username_text.getText().toString();
    pword = password_text.getText().toString();

    final ProgressDialog loading = new ProgressDialog(MainActivity.this);
    loading.setTitle("Loading");
    loading.setMessage("Attempting to Log In");
    loading.show();
    ////////////////////
    request = new StringRequest(Request.Method.POST, signin, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            final Fragment nextFrag;
            final CheckBox check_locateCar, check_carOff,check_getImg, check_tase, check_carOn;
            try {

                JSONObject jsonObject = new JSONObject(response);
                if(jsonObject.getString("user").equals("logined")){
                    Toast.makeText(getApplicationContext(),"SUCCESS "+jsonObject.getString("user"),Toast.LENGTH_SHORT).show();
                    //startActivity(new Intent(getApplicationContext(),Welcome.class));
                    if(!jsonObject.getString("car_plate").equals("0")){
                        loading.hide();

                        if(jsonObject.getString("car_stat").equalsIgnoreCase("true")){
                            //////////////HERE//////////////////////////////////

                                //check_carOn.setChecked(false);
                                nextFrag = new locate_updatedstatus();

                                ////////////////////////////////////////////////////
                            }
                            else{

                                loading.hide();
                                nextFrag = new locate_before();
                            }
                        }
                        else{
                            loading.hide();
                            nextFrag = new locate_car_reg();
                        }

                        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                        transaction.replace(R.id.fragment_container, nextFrag);
                        transaction.addToBackStack(null);
                        transaction.commit();

                        check_locateCar = (CheckBox)findViewById(R.id.check_locateCar);
                        check_carOff = (CheckBox)findViewById(R.id.check_carOff);
                        check_getImg = (CheckBox)findViewById(R.id.check_getImg);
                        check_tase = (CheckBox)findViewById(R.id.check_tase);
                        check_carOn = (CheckBox)findViewById(R.id.check_carOn);

                        if(jsonObject.getString("loc_stat").equalsIgnoreCase("true")){
                             /*THE ERROR IS AROUND THIS LINE*/
                            check_locateCar.setChecked(true);
                        }else{
                            check_locateCar.setChecked(false);
                        }
                        if(jsonObject.getString("ignition").equalsIgnoreCase("true")){
                            check_carOff.setChecked(true);
                        }else{
                            check_carOff.setChecked(false);
                        }
                        if(jsonObject.getString("taser").equalsIgnoreCase("true")){
                            check_tase.setChecked(true);
                        }else{
                            check_tase.setChecked(false);
                        }
                        if(jsonObject.getString("photo_stat").equalsIgnoreCase("true")){
                            check_getImg.setChecked(true);
                        }else{
                            check_getImg.setChecked(false);
                        }

                    }else {

                        Toast.makeText(getApplicationContext(), "Error" +jsonObject.getString("user"), Toast.LENGTH_SHORT).show();
                        loading.hide();

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String,String> hashMap = new HashMap<String, String>();
                hashMap.put("username",username_text.getText().toString());
                hashMap.put("password",password_text.getText().toString());

                return hashMap;
            }
        };

        requestQueue.add(request);

        ///////////////////////////
        //Toast.makeText(MainActivity.this,uname+"\n"+pword, Toast.LENGTH_LONG).show();
        //newFragment = new locate_login();
    }

A:
I'm trying to set the checkbox value from a different fragment of where the checkbox value is.

Fragments need to communicate through the main/parent Activity via proxy. To do this

*

*Define an interface for the listener method needed (in your case an OnCheckBoxSelectedListener listener).

*Have the main Activity implement OnCheckBoxSelectedListener

*Declare a private member of OnCheckBoxSelectedListener in your fragment(s)

*In your Fragment's onAttach override set the OnCheckBoxSelectedListener member to the Activity argument.

1) Define an interface for the listener method needed (in your case an OnCheckBoxSelectedListener listener).
interface OnCheckBoxSelectedListener
{
    public void SetChecked(bool checked);
}

2) Have the main Activity implement OnCheckBoxSelectedListener
public class Activity implements OnCheckBoxSelectedListener
{
    public void SetCheck(bool checked)
    {
        check_locateCar = (CheckBox)findViewById(R.id.check_locateCar);
        check_locateCar.setChecked(true);
    }
}

3) Declare a private member of OnCheckBoxSelectedListener in your fragment(s)
4) In your Fragment's onAttach override set the OnCheckBoxSelectedListener member to the Activity argument.
public static class FragmentA extends ListFragment {
    OnCheckBoxSelectedListener mListener;
    ...
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnArticleSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement OnArticleSelectedListener");
        }
    }
    ...
}

Then from onResponse call the listener
      @Override
        public void onResponse(String response) {
            final Fragment nextFrag;
            final CheckBox check_locateCar, check_carOff,check_getImg, check_tase, check_carOn;
            try {
                check_locateCar = (CheckBox)findViewById(R.id.check_locateCar);
                check_carOff = (CheckBox)findViewById(R.id.check_carOff);
                check_getImg = (CheckBox)findViewById(R.id.check_getImg);
                check_tase = (CheckBox)findViewById(R.id.check_tase);
                check_carOn = (CheckBox)findViewById(R.id.check_carOn);

                JSONObject jsonObject = new JSONObject(response);
                if(jsonObject.getString("user").equals("logined")){
                    Toast.makeText(getApplicationContext(),"SUCCESS "+jsonObject.getString("user"),Toast.LENGTH_SHORT).show();
                    //startActivity(new Intent(getApplicationContext(),Welcome.class));
                    if(!jsonObject.getString("car_plate").equals("0")){
                        loading.hide();

                        if(jsonObject.getString("car_stat").equalsIgnoreCase("true")){
                            //////////////HERE//////////////////////////////////
                            if(jsonObject.getString("loc_stat").equalsIgnoreCase("true")){
                                     /*THE ERROR IS AROUND THIS LINE*/
                                    //check_locateCar.setChecked(true);
                                    mListener.SetChecked(true)
                                }else{
                                    check_locateCar.setChecked(false);
                                }
                                // ...
                            }
                        }
                    }
                }
            }
        }

Note: The above establishes communication in the direction of Fragment to Activity. To go the other way (a "callback" from the listener), I define a callback interface, implement it in the Fragment, and call it from the listener using a reference to the Fragment passed in as an argument (via the this pointer). For example
interface OnCheckBoxSelectedListener
{
    public void SetCheck(OnCheckBoxSelectedCallback callingFragment, attachmentDialog2EventListener, bool checked);
}

interface OnCheckBoxSelectedCallback
{
    SetCheckedCallback();
}

public class Activity implements OnCheckBoxSelectedListener
{
    public void SetCheck(OnCheckBoxSelectedCallback callingFragment, bool checked)
    {
        check_locateCar = (CheckBox)findViewById(R.id.check_locateCar);
        check_locateCar.setChecked(true);

        callingFragment.SetCheckedCallback();
    }
}

public static class FragmentA extends ListFragment implements OnCheckBoxSelectedCallback {
    OnCheckBoxSelectedListener mListener;
    ...
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnCheckBoxSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement OnCheckBoxSelectedListener");
        }
    }
    ...

    public void SetCheckedCallback()
    {
        // ...
    }
}

It would then be called from onRequest as follows (you may not need a callback in this case, but at some point you probably will, like when startActivityForRequest/onActivityRequest are called from Main Activity, since they run on separate thread)
      @Override
        public void onResponse(String response) {
                            // ...
                            if(jsonObject.getString("loc_stat").equalsIgnoreCase("true")){
                                     /*THE ERROR IS AROUND THIS LINE*/
                                    //check_locateCar.setChecked(true);
                                    mListener.SetChecked(this, true)
                                }else{
                                    check_locateCar.setChecked(false);
                                }
                                // ...
                            }
                        }
                    }
                }
            }
        }


text:
Q: É seguro criar ponteiro para objeto no stack indiretamente? A minha classe possui um método que retorna um ponteiro pra si mesma, e em algum momento eu uso o seguinte :
void classequalquer::metodo() {
    ClasseA * ponteiro = ClasseA().getThis();
    //usa o ponteiro nesse método sem usar delete
}

//Para referências
ClasseA* ClasseA::getThis() {
    return this;
}

A: O trecho postado não é seguro:
void classequalquer::metodo() {
  ClasseA * ponteiro = ClasseA().getThis();
  //deferenciar o ponteiro aqui é comportamento indefinido
  //o objeto não existe mais
}

ponteiro pega o endereço de um objeto criado como temporário para a operação de atribuição. O objeto não está disponível ao fim do ponto sequencial que encerra a operação, e ponteiro referencia endereço invalidado. É ilegal pegar o endereço de um rvalue.

Retornar o ponteiro através de um método é seguro:
Apesar do trecho postado, retornar o ponteiro através de um método é seguro, e o trecho deveria ser adaptado para a seguinte forma:
void classequalquer::metodo() {
  ClasseA A;
  ClasseA * ponteiro = A.getThis();
  //usa o ponteiro nesse método sem usar delete
  //o objeto ainda existe
}

Mas o método é desnecessário (e eu pessoalmente o desencorajo), qualquer escopo de código que tenha acesso a ClasseA::getThis() tem também acesso ao operador &, que tem função de retornar endereço:
void classequalquer::metodo() {
  ClasseA A;
  ClasseA * ponteiro = &A;
}

Algo semelhante, retornar uma referência a si, é bem comum:
Algo muito semelhante a retornar um ponteiro para si é bastante usado, como no overload de operadores de atribuição, onde retorna-se uma referência ao próprio objeto (criada através da desreferenciação do this), por exemplo:
ClasseA& ClasseA::operator = (ClasseA const & outra) {
  //..(algumas operações de atribuição)..
  return *this; //semelhante a retornar ponteiro, (refere-se a este objeto)
                //mas a referência é mais transparente.
                //assim como o ponteiro,
                //  a referência será invalidada quando o objeto for destruído
}

A: Exemplo mostrando o comportamento indefinido ao se utilizar o recurso usado pelo OP.
// arquivo ptrtest.cpp

#include <iostream>
using namespace std;

class A
{
   public:
      int x;
      A();
      A* getThis() { return this; }
};

A::A()
{
   cout << "* this=" << (void*)this << '\n';
   x = 42;
   cout << "* &A::x=" << (void*)&x << '\n';
}

int main()
{
   A* aPtr;
   aPtr = A().getThis();
   int z = 1;
   cout << "* &aPtr= " << (void*)&aPtr << '\n';
   cout << "* &z=    " << (void*)&z << '\n';
   cout << "* A::x=  " << aPtr->x << '\n';
}

Compilando o código acima no gcc 6.3.1 com a linha de comando
g++ -O3 -o ptrtest ptrtest.cpp

(Opção -O3 otimiza o código gerado).
Ao executar, o resultado é:
* this=0x7ffdd82e7550
* &A::x=0x7ffdd82e7550
* &aPtr= 0x7ffdd82e7558
* &z=    0x7ffdd82e7550
* A::x=  1

Notar que a variável A::x foi sobrescrita pelo valor de z.
Compilando sem otimização:
g++ -o ptrtest ptrtest.cpp

Ao executar, o resultado agora é:
* this=0x7ffdd82e7550
* &A::x=0x7ffdd82e7550
* &aPtr= 0x7ffdd82e7558
* &z=    0x7ffdd82e7550
* A::x=  42

Notar que a variável A::x agora não foi sobrescrita pelo valor de z.
Isso demonstra que utilizar endereços de valores temporários possui comportamento indefinido. Neste caso, dependendo das opções de compilação o programa apresenta comportamentos diferentes. Os efeitos poderiam ser mais drásticos, como o programa apresentar exceção de endereçamento, ou ficar em loop, etc, qualquer comportamento poderia acontecer (de acordo com a definição da linguagem), porque esta é a definição de comportamento indefinidio: em princípio, qualquer coisa pode acontecer.

A: Depende o que faz com o ponteiro.
O objeto está sendo criado no stack, isto você já sabe. Portanto o ponteiro referenciará uma posição no stack. Quando esta função acabar, o objeto deixa de existir, não pode mais haver uma referência para ele. Mas a referência criada aí também se vai, então ok. Mas e se você escapou a referência para algum objeto, jogando o ponteiro nele e esse objeto sobrevive mais que esta função? Você estará acessando um objeto que não existe mais. E não sei o que é pior, dar um erro, ou parecer que funciona em vários cenários, mas não em todos.
Não teria porque usar o delete se não usou um new.
Agora se por acaso o getThis() retornar um outro objeto criado no heap, aí tem que gerenciar isto, mas não parece ser o caso.


text:
Q: Big Numbers, Common Algorithms? I was wondering what big numbers are, and what are some common algorithms used to handle them.  I heard this term mentioned in Coders at Work, where one was asked in an interview to create a library to work with big numbers.

A: Big numbers are usually full-precision integers or decimals, as opposed to floating point numbers (which can also store very large numbers, but with a very limited precision). They are mostly used in cryptography. Take for example RSA keys: Those are integers with 1024 or 2048 bits (roughly 300 or 600 decimal digits). They need to be long to make it unfeasible to break the encryption using brute-force calculations.
What a library needs to provide is support to store these numbers and perform calculations on them (e.g. addition, multiplication, integer division with rest)

A: There are bignum libraries like gmp - some provide arbitrary precision (...as much as your memory can handle), some have simply ridiculous limits - floating point variables of 256 bytes base, 256 bytes mantissa.
The methods are very similar to normal software emulation of FPU, simply iterating over way more bytes of data for each calculation, operations resembling how you calculate it on paper. If you have 256-byte integer, it can be treated as a normal 256 base256 digits number...
simple 256-byte integer addition (totally unoptimized... the numbers should keep lengths etc)
unsigned char x[256];
unsigned char y[256];
unsigned char sum[256];
int overflow=0,tmp;
for(unsigned char i=0;i<256;i++)
{
  tmp = x[i] + y[i] + ovr;
  sum[i] = tmp % 256;
  overflow = tmp / 256;
}

A: These are numbers with variable bit-length, unlike numbers with predefined size (e.g. 4-bit integer type).
An example of a fast C++ library working with big numbers is NTL, also used especially for number theory and cryptography application. Another well-known tool is the unix bc calculator that by default works with unlimited precision. Some functional languages like Haskell use this type of numbers as well.
Example of approaches used for dealing with large number arithmetics is Karatsuba algorithm used for multiplication. In the docs of NTL you can find much more if you're interested ;)


text:
Q: Remove all traces of wordpress while using wordpress "plugin" I just purchased cornerstone page builder which is a drag and drop website builder. The problem I have right now is that it works as a wordpress plugin making me access it through the wordpress admin panel.
Is there a way for me to remove everything "wordpress related" to basically hide everything that has to do with wordpress and just let me access the plugin without signing in to wordpress, maybe using my own log in function?