text:
Q: Can I get compilation or runtime error while inserting primitive into List? The following code is valid:
List list = new ArrayList();
list.add(1);

This is because compiler make boxing/unboxing automatically.
My question is: can I somehow get compilation (or runtime) error in such situation?
I already try:
1) method that return primitive:
int foo(){
    return 2;
}

list.add(method());

2) anonymous class from java 8:
list.add(((Function) (ignored) -> 3).apply(""));

UPD:
We can parametrize List to List<Object> or even to List<Integer> the result will be the same - it's work. My question is "how can I fool autoboxing mechanism?"

A: You won't fool typing system, but you can always fool the reader of your code (don't try this at home)
class MyList implements List<Integer> {

    // ...

    @Override
    public void add(Integer value) {
        // Call actual implementation
    }

    // Overload
    public void add(int value) {
        throw new RuntimeException("No autoboxing allowed!");
    }

}

Another way to achieve similar effect would be by creating your own wrapper-type and using it as list parameter instead:
public class IntValue {

    public final int value;

    public IntValue(int value) {
        this.value = value;
    }

}

// ...

List<IntValue> list = new ArrayList<>();
list.add(new IntValue(1)); // will compile
list.add(1); // won't compile

A: You cannot fool compiler, it is in Java Language Spec. Apparently it's possible to use some code check-tools such as PMD or findbugs, e.g.: http://findbugs.sourceforge.net/bugDescriptions.html#BX_BOXING_IMMEDIATELY_UNBOXED and probably you could write additional custom rule for it to check your specific situations.


text:
Q: Why is this a right angle in the mach cone?
This and similar depictions are used when deriving the equation for the Mach cone angle $\theta$.
It is usually stated that using algebra we can conclude that
$$\sin\theta=\frac{ct}{vt},$$
and thus
$$θ=\arcsin \left(\frac{c}{v}\right).$$
However, I noticed that that assumes a right angle between $ct$ and the wavefront, which is never mathematically proven.
So, can someone explain why there is a right angle between $ct$ and the wavefront?

A: This is a standard theorem in Euclidean geometry: the tangent to a circle is perpendicular to the radius at the point of tangency. The proof is a simple proof by contradiction.
Given: a circle $C$, a line tangent to the circle $T$, and a radius, $R$, from the center of the circle to the point of tangency.
Assume: $R$ is NOT perpendicular to $T$
Then there is some other line segment, $S$, from the center of $C$ which is perpendicular to $T$. Since $S$ is perpendicular to $T$ that makes $R$ the hypotenuse of a right triangle. Therefore the length of $R$ is greater than the length of $S$, so $|R|>|S|$.
Now, except for the point of tangency all other points on $T$ are outside of $C$. Since $C$ is defined as all points a distance of $|R|$ away from the center, all points outside of $C$ are a distance $x>|R|$ away from the center. Since $S$ connects the center to such a point we have $|S|>|R|$.
But $|S|>|R|$ contradicts $|R|>|S|$ so our assumption is false. Therefore $R$ is perpendicular to $T$. QED

redpajama_set_name: RedPajamaStackExchange


text:
Q: search text in beginning of word I want to select rows which hold certain text('one') only in a beginning of a word in a certain field (name).
Example:
1)name : name one check
2)name : name anotherone check
I only need row number 1.
I am currently using LIKE %one% ,get those results(rows 1 and 2, more then I need), I then check if the text is located in the beginning of a word or not and keep the results I need.
is there a way to run a query which will break the values in name field according to specific chars (lets say: " "), and then check each Piece if the text is located in the beginning of it?

A: use the Like Operator: SELECT * FROM table WHERE name LIKE 'one%'
(don't use % on both sides as this will find ANYTHINGoneANYTHING.)
However, If the word can appear somewhere in the sentence, you need the double %:
Add a whitespace, like this: LIKE '% one%' to ensure the word STARTS with "one".
If the word needs to be standalone, you can use LIKE '% one %' (this however will not match The start or end of the field. It will fail on one test.)
To bypass this problem, you can concatenate the field with a leading and trailing whitespace:
... WHERE CONCATENATE(" ", CONCATENATE (field, " ")) LIKE '% one %'
This will match Theres one, one goes home and even if there is one that goes home, but not someone is there or hes done.


text:
Q: How to define a function inside a function and call it from outside? I've started learning JavaScript and this problem blocked me. please look at this:
<script>
    $(function () {
        // Start the connection.
        $.connection.hub.start().done(function () {
            // How to define some functions here to call from below script?
        });
    });
</script>

<script type="text/javascript" gwd-events="handlers">
    window.gwd = window.gwd || {};
    gwd.boardSelectionChanged = function(event) {
        var carousel = document.getElementById("mediaCarousel");
        var index = carousel.currentIndex;
        // how to pass this index to a function above?
};
</script>

in the first script I try to connect to the server. in the second script, user can select an image.
I want to pass the index from second script to a function inside the first one to send it to the server.
How can I define a function in first one and how to call it? thanks.

A: You could do something like this:
<script>
    var newFunction = undefined;

    $(function () {
        // Start the connection.
        $.connection.hub.start().done(function () {
            // How to define some functions here to call from below script?
            newFunction = function(index){
                // Your function processing.
            }
        });
    });
</script>

<script type="text/javascript" gwd-events="handlers">
    window.gwd = window.gwd || {};
    gwd.boardSelectionChanged = function(event) {
        var carousel = document.getElementById("mediaCarousel");
        var index = carousel.currentIndex;
        // how to pass this index to a function above?
        if(newFunction) newFunction(index);
};
</script>

A: Consider the example below. Define your function in the connection.done callback function, then call the function when a selection has changed.

$(function() {
  // Start the connection.
  $(window).load(function() {

    // We'll define our function here
    postConnectFunction = function(index) {
      console.log('You selected', index)
    }

  });
});

// When something is changed we'll call the function above
$('select').on('change', function(event) {
  if (postConnectFunction) {
    postConnectFunction(event.target.value);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select>
  <option>Option 1</option>
  <option>Option 2</option>
  <option>Option 3</option>
  <option>Option 4</option>
</select>

A: You could expose the function to an outer-scoped reference, like so:
var functionReference = undefined;
$(function() {
    $.connection.hub.start().done(function() {
        functionReference = function () { /* ... */ };
    });
});

// You could then check if the function is set later, and invoke it:
if (functionReference) {
    functionReference(index);
}

However, a better way to handle this sort of problem that you are presenting would be to set the event handler instead of passing around a function reference:
<script>
$(function () {
    // Obtain a reference to the carousel element:
    var carousel = document.getElementById("mediaCarousel");

    // Start the connection.
    $.connection.hub.start().done(function () {
        window.gwd.boardSelectionChanged = function (event) {
            // Call your handler function
            handleBoardSelectionChange(carousel.currentIndex);
        };
    });

    // We are separating and naming this function so that the logic
    // above remains concise and readable, if we kept all of the
    // functions of this nature anonymous it would have been harder to
    // follow the code due to length and scope depth.
    function handleBoardSelectionChange(index) {
        // Do your work here
    }
});
</script>

<script type="text/javascript" gwd-events="handlers">
window.gwd = window.gwd || {};
gwd.boardSelectionChanged = function(event) {
    // Indicate to the user that we are not ready yet.
    // (Do whatever is sensible here, maybe doing nothing is better?)
    alert('Not connected yet, please wait...');
};
</script>

A: <script>
    var innerfunc;
    $(function () {
        // Start the connection.
        $.connection.hub.start().done(function () {
            // How to define some functions here to call from below script?
              innerfunc = function(index) {
                  console.log('here is my index: ' + index);
              };

        });
    });
</script>

<script type="text/javascript" gwd-events="handlers">
    window.gwd = window.gwd || {};
    gwd.boardSelectionChanged = function(event) {
        var carousel = document.getElementById("mediaCarousel");
        var index = carousel.currentIndex;
        // how to pass this index to a function above?
         if( innerfunc ) innerfunc(index);
};
</script>

Make sure the top code executes first before the bottom one. If racing condition persists, you can check with,

if( innerfunc ) innerfunc(index)

Hope it helps.


text:
Q: Is adding support for another operation system a minor version or a patch? Let's say I use Semantic Versioning for a my project. I'm developing it under FooOS, but the language uses virtual machine(either interpreted language or bytecode based) so any operation system can run it. The thing is, the project interacts heavily with OS-managed things(e.g. pipes, processes, the file system) so if you try running it under a different operation system - BarOS - it gets so buggy and so many things don't work that the project is practically useless.
Now, at some point I want to make my project work for BarOS, and I want to release a version just to add that support. The question is - does that count as a minor version or as a patch?
It seems like it's a patch:

*

*All I do is fixing all the bugs that appear when running the project under BarOS.

*Users of my project shouldn't notice any change in functionality, since they are using FooOS in the first place.

*For BarOS users my whole project is new - but getting new users is not something that should result in a version increment.
But even with all that reasoning, it just doesn't seem right to label a release as big as new OS support as a patch...

A: If you already officially supported BarOS, but there were so many issues with it that nobody would use it, then providing proper support for BarOS would be a set of bug fixes and thus a patch release.
On the other hand, if you never officially supported BarOS, then adding official support for BarOS (regardless of how well it worked previously) is a new (backwards compatible) feature and therefor a minor release.
So, the answer to your question is that it depends on the official status of BarOS within your project so far.


text:
Q: Node.js - Sending form data to hapi I'm trying to send a variable from html form to hapi but i think i did somethings wrong.
addword.html :
    <form id="messages" action="/addword" method="POST">
  Your variable:

  <input  type="text" name="your_variable" value="your_value">

  <input type="submit" value="Submit">
</form>

server.coffee
server.route
    method: 'GET'
    path: '/addword'
    handler: (request, reply) ->
        reply.file './public/addword.html'

###
ADD WORD
###

server.route
  method: 'POST'
  path: '/addword'
  config: payload: output: 'data'
  handler: (request, response) ->
    your_variable = request.payload.your_variable
    console.log your_variable
    return

/server.js
/public/addword.html
what should i change to make it work?


text:
Q: WebGL mixes colors on pixel level I want to write a small program that calculates for example prime numbers. My idea was to use webgl/threejs to color all pixels that represent prime numbers (based on coordinates) white and the rest black. My problem is that webgl somehow mixes the colors on pixel level (if you have a white pixel in the middle of a black canvas it mixes with the environment and the pixels around that one white pixel become gray). With this problem, I can't identify white and black pixels properly.
My Question: How can I tell webgl or canvas to use the correct color for each pixel without mixing things?
Here is a demo where I colored every 2nd pixel white:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ProjectLaGPU</title>

/* main.js */
async function init() {
    const scene = new THREE.Scene();
    const camera = new THREE.OrthographicCamera(-.5, .5, .5, -.5, -1, 1);
    const renderer = new THREE.WebGLRenderer({
        preserveDrawingBuffer: true,
        powerPreference: "high-performance",
        depth: false,
        stencil: false
    });

    const geometry = new THREE.PlaneGeometry();
    const material = new THREE.ShaderMaterial({
        uniforms: {
            u_start: { value: 0.5 },
        },
        vertexShader: document.getElementById("vertex-shader").innerText,
        fragmentShader: document.getElementById("fragment-shader").innerText,
      });
    const mesh = new THREE.Mesh(geometry, material);
    renderer.setSize(1000, 1000);
    document.body.appendChild(renderer.domElement);
    scene.add(mesh)
    renderer.render(scene, camera);
}

init();

A: The previously accepted answer is not correct and only worked via luck... In other words if it worked for you you were lucky that your machine/browser/OS/current-settings happened to appear to work. Change a setting, switch to another browser/os/machine and it will not work.
There are many issues being conflated here
1. Getting non-blurry canvas
There 2 things you have to do to get a non-blurry canvas
turn off the browser's filtering
In Chrome/Edge/Safari you can do this with canvas { image-rendering: pixelated; } on firefox canvas { image-rendering: crisp-edges; }
Note that pixelated is more correct for this situation than crisp-edges. From the spec, given this original image

And displaying it 3x the size the default algorithm is up to the browser but a typical example might look something like this

pixelated would look something like this

IMPORTANT: See update at bottom
crisp-edges would look something like this

But note that the actual algorithm used to draw the image is not defined by the spec  so at the moment firefox happens to use nearest-neighbor filtering for crisp-edges and does not support pixelated. Therefore you should specify pixelated last so it overrides crisp-edges if it exists
A canvas has 2 sizes. Its drawingbuffer size (the number of pixels in the canvas) and it's display size (defined by CSS). But CSS sizes are computed in CSS pixels which are then scaled by the current devicePixelRatio. This means if you're not zoomed in or out and your on a device with a devicePixelRatio that's not 1.0 and your drawingbuffer size matches your display size then the canvas will be scaled to what it needs to be to match the devicePixelRatio. So, the image-rendering CSS style will be used to decide how that scaling happens.
Example

const scene = new THREE.Scene();
const camera = new THREE.OrthographicCamera(-.5, .5, .5, -.5, -1, 1);
const renderer = new THREE.WebGLRenderer();

const geometry = new THREE.PlaneBufferGeometry();
const material = new THREE.ShaderMaterial({
  vertexShader: document.getElementById("vertex-shader").innerText,
  fragmentShader: document.getElementById("fragment-shader").innerText,
});
const mesh = new THREE.Mesh(geometry, material);
document.body.appendChild(renderer.domElement);
scene.add(mesh)
renderer.render(scene, camera);
canvas {
  image-rendering: crisp-edges;
  image-rendering: pixelated;  /* pixelated is more correct so put that last */
}

turn off antialiasing.
Three.js does this for you
2. Getting 1 pixel in the canvas = to 1 pixel on the screen
This is what calling setPixelRatio was trying to do. That it appeared to work for you was just luck. In other words when you try to run your code on a different machine or different browser it may not work.
The issue is in order to set the size of the canvas's drawing buffer so that it matches 1 to 1 how many pixels will be used to display the canvas you have to ask the browser "how many pixels did you use".
The reason is for example, let's say you have a device with device pixel ratio (dpr) of 3. Let's say the window is 100 device pixels wide. That's 33.3333 CSS pixels wide. If you look at window.innerWidth (which you should never do anyway) it will report 33 CSS pixels. If you then multiply by your dpr of 3 you get 99 but in reality the browser may/will draw 100.
To ask what size was actually used you have to use ResizeObserver and have it report the exact size used via devicePixelContentBoxSize

const scene = new THREE.Scene();
const camera = new THREE.OrthographicCamera(-.5, .5, .5, -.5, -1, 1);
const renderer = new THREE.WebGLRenderer();

const geometry = new THREE.PlaneBufferGeometry();
const material = new THREE.ShaderMaterial({
  vertexShader: document.getElementById("vertex-shader").innerText,
  fragmentShader: document.getElementById("fragment-shader").innerText,
});

const mesh = new THREE.Mesh(geometry, material);

function onResize(entries) {
  for (const entry of entries) {
    let width;
    let height;
    let dpr = window.devicePixelRatio;
    if (entry.devicePixelContentBoxSize) {
      // NOTE: Only this path gives the correct answer
      // The other 2 paths are an imperfect fallback
      // for browsers that don't provide anyway to do this
      width = entry.devicePixelContentBoxSize[0].inlineSize;
      height = entry.devicePixelContentBoxSize[0].blockSize;
      dpr = 1; // it's already in width and height
    } else if (entry.contentBoxSize) {
      if (entry.contentBoxSize[0]) {
        width = entry.contentBoxSize[0].inlineSize;
        height = entry.contentBoxSize[0].blockSize;
      } else {
        width = entry.contentBoxSize.inlineSize;
        height = entry.contentBoxSize.blockSize;
      }
    } else {
      width = entry.contentRect.width;
      height = entry.contentRect.height;
    }
    // IMPORTANT! You must pass false here otherwise three.js
    // will mess up the CSS!
    renderer.setSize(Math.round(width * dpr), Math.round(height * dpr), false);
    renderer.render(scene, camera);
  }
}

const canvas = renderer.domElement;
const resizeObserver = new ResizeObserver(onResize);
try {
  // because some browers don't support this yet
  resizeObserver.observe(canvas, {box: 'device-pixel-content-box'});
} catch (e) {
  resizeObserver.observe(canvas, {box: 'content-box'});
}
document.body.appendChild(renderer.domElement);
scene.add(mesh)
renderer.render(scene, camera);
html, body, canvas {
  margin: 0;
  width: 100%;
  height: 100%;
  display: block;
}

Any other method will only work sometimes.
To prove it here's the method from using setPixelRatio and window.innerWidth vs using ResizeObserver

function test(parent, fn) {
  const scene = new THREE.Scene();
  const camera = new THREE.OrthographicCamera(-.5, .5, .5, -.5, -1, 1);
  const renderer = new THREE.WebGLRenderer();

  const geometry = new THREE.PlaneBufferGeometry();
  const material = new THREE.ShaderMaterial({
    vertexShader: document.getElementById("vertex-shader").innerText,
    fragmentShader: document.getElementById("fragment-shader").innerText,
  });

  const mesh = new THREE.Mesh(geometry, material);
  fn(renderer, scene, camera);
  parent.appendChild(renderer.domElement);
  scene.add(mesh)
  renderer.render(scene, camera);
}

function resizeOberserverInit(renderer, scene, camera) {
  function onResize(entries) {
    for (const entry of entries) {
      let width;
      let height;
      let dpr = window.devicePixelRatio;
      if (entry.devicePixelContentBoxSize) {
      // NOTE: Only this path gives the correct answer
      // The other 2 paths are an imperfect fallback
      // for browsers that don't provide anyway to do this
        width = entry.devicePixelContentBoxSize[0].inlineSize;
        height = entry.devicePixelContentBoxSize[0].blockSize;
        dpr = 1; // it's already in width and height
      } else if (entry.contentBoxSize) {
        if (entry.contentBoxSize[0]) {
          width = entry.contentBoxSize[0].inlineSize;
          height = entry.contentBoxSize[0].blockSize;
        } else {
          width = entry.contentBoxSize.inlineSize;
          height = entry.contentBoxSize.blockSize;
        }
      } else {
        width = entry.contentRect.width;
        height = entry.contentRect.height;
      }
      // IMPORTANT! You must pass false here otherwise three.js
      // will mess up the CSS!
      renderer.setSize(Math.round(width * dpr), Math.round(height * dpr), false);
      renderer.render(scene, camera);
    }
  }

  const canvas = renderer.domElement;
  const resizeObserver = new ResizeObserver(onResize);
  try {
    // because some browers don't support this yet
    resizeObserver.observe(canvas, {box: 'device-pixel-content-box'});
  } catch (e) {
    resizeObserver.observe(canvas, {box: 'content-box'});
  }
}

function innerWidthDPRInit(renderer, scene, camera) {
  renderer.setPixelRatio(window.deivcePixelRatio);
  renderer.setSize(window.innerWidth, 70);
  window.addEventListener('resize', () => {
    renderer.setPixelRatio(window.deivcePixelRatio);
    renderer.setSize(window.innerWidth, 70);
    renderer.render(scene, camera);
  });
}

test(document.querySelector('#innerWidth-dpr'), innerWidthDPRInit);
test(document.querySelector('#resizeObserver'), resizeOberserverInit);
body {
  margin: 0;
}
canvas {
  height: 70px;
  display: block;
}
#resizeObserver,
#resizeObserver>canvas {
  width: 100%;
}

via window.innerWidth and setPixelRatio

via ResizeObserver

Try zooming in the browser or try different devices.
Update
The spec changed in Feb 2021. crisp-edges now means "use nearest neighbor" and pixelated means "keep it looking pixelated" which can be translated as "if you want to then do something better than nearest neighbor that keeps the image pixelated". See this answer

A: This is typical side effect for not configuring the device pixel ratio. Meaning your app does not necessarily run in a native solution. The following produces the expected result (I've made a screenshot and checked the color values in Gimp).

const scene = new THREE.Scene();
const camera = new THREE.OrthographicCamera(-.5, .5, .5, -.5, -1, 1);
const renderer = new THREE.WebGLRenderer();

const geometry = new THREE.PlaneBufferGeometry();
const material = new THREE.ShaderMaterial({
  vertexShader: document.getElementById("vertex-shader").innerText,
  fragmentShader: document.getElementById("fragment-shader").innerText,
});
const mesh = new THREE.Mesh(geometry, material);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
scene.add(mesh)
renderer.render(scene, camera);
body {
      margin: 0;
}


text:
Q: How to define two FK in the same table? I have a table called User which inherit the properties from IdentityUser, inside that table I added a reference to the UserFriendship table which need to store all the user friendship:
public class User : IdentityUser
{
    public string FirstName { get; set; }
    public DateTime BirthDate { get; set; }

    public virtual ICollection<UserFriendship> UserFriendship { get; set; }
}

Essentially the UserFriendship contains two users, who are those who have a common friendship, this is the model definition:
public class UserFriendship
{
    public int Id { get; set; }

    [Key, ForeignKey("UserA")]
    public string UserAId { get; set; }
    public User UserA { get; set; }

    [Key, ForeignKey("UserB")]
    public string UserBId { get; set; }
    public User UserB { get; set; }

    [Required]
    public DateTime DateTime { get; set; }
}

I defined the UserA and the UserB which are two FK of a User that are contained inside AspNetUsers table.
Now inside the FluentAPI I declared the following:
builder.Entity<UserFriendship>(entity =>
{
    entity.HasKey(f => f.Id);

    entity.HasOne(u => u.UserA)
          .WithMany(n => n.UserFriendships)
          .HasForeignKey(u => u.UserAId)
          .IsRequired();

    entity.HasOne(u => u.UserB)
          .WithMany(n => n.UserFriendships)
          .HasForeignKey(u => u.UserBId)
          .IsRequired();
 });

when I execute this command:
add-migration InitialMigration -context MyAppContext

I'll get:

Cannot create a relationship between 'User.UserFriendships' and 'UserFriendship.UserB', because there already is a relationship between 'User.UserFriendships' and 'UserFriendship.UserA'. Navigation properties can only participate in a single relationship.

I'm not an expert of EnityFramework, but based on that error I think that I cannot define two FK in the same table?
Sorry for any mistake, thanks.

A: You can define more than one FK in table.
The problem here is you are pointing two times to one navigation property - UserFriendships. The solution would be to create two navigation properties.
Navigation properties are used to browse the related data for specified foreign-key (you have one-to-many relationship) of entity.
Try this:
public class User
{
    public string FirstName { get; set; }
    public DateTime BirthDate { get; set; }

    public ICollection<UserFriendship> UserAFriendships { get; set; }
    public ICollection<UserFriendship> UserBFriendships { get; set; }
}

public class UserFriendship
{
    public int Id { get; set; }

    public string UserAId { get; set; }
    public User UserA { get; set; }

    public string UserBId { get; set; }
    public User UserB { get; set; }
    public DateTime DateTime { get; set; }
 }

And define the relationship through fluent api as following:
modelBuilder.Entity<UserFriendship>(entity =>
{
     entity.HasKey(f => f.Id);

     entity.HasOne(u => u.UserA)
         .WithMany(n => n.UserAFriendships)
         .HasForeignKey(u => u.UserAId)
         .IsRequired();

     entity.HasOne(u => u.UserB)
          .WithMany(n => n.UserBFriendships)
          .HasForeignKey(u => u.UserBId)
          .IsRequired();
});

What is more - you don't need to specify attributes Key, ForeignKey if you use Fluent API.


text:
Q: Calling Permalinks With PHP I'm developing a theme which supports WordPress' post formats.  As a result I am using a big if statement, which can be found below.

*

*I would like to link my post titles to the posts while maintaining my theme as XHTML valid.

*I would like to call images (with classes) in the if statement while maintaining my theme as XHTML valid.

*I would appreciate if somebody could add the appropriate code to the following code to do so

_
if ( has_post_format( 'video' )) {
                echo the_title();
                echo the_excerpt();
}

EDIT: Basically, the most important thing I'm looking for is that it calls the post name as a link which links to the actual post.

A: I don't know what you mean by "call images", but this will display the title as a link.
if ( has_post_format( 'video' )) {
   ?><a href="<?php the_permalink(); ?>"><?php the_title(); ?><?php
   the_excerpt();
}

A: You only need to add in the <a href="<?php the_permalink();?>"><?php the_title();?> to link the post and also add the title as the visible part of the link. Also you can replace <?php the_title();?> for a thumbnail (with the correct funct.) or an image, a video, a button, etc. and another kind of php stament as well <?php your_function(your args);?>.
As far as your other question goes, I think that you'll need to add a category for videos and make an special CSS for that. I'll leave two posts, they are in spanish but they are really useful and they work very well: first how to add a different structure How to: different structure per category and then how to style it How to: style each category differently
Hope you find this response helpful ^^

A: So:
<?php if ( has_post_format( 'video' )) { ?>
    <a href="<?php the_permalink();?>"><?php the_title();?>
    <?php the_excerpt();?>
<?php } else {;?> If you plan on adding something else. otherwise just delete this line and close with the next one only

<?php } ;?>

And that's it, hope you find this helpful!!


text:
Q: EditorTemplate + Model not being returned on POST I can't seem to figure this out, it is driving me crazy!
Essentially, I have a list of rows I need to display with one drop down list per row.
I have a view model:
public class UserMembershipViewModel:BaseViewModel
{
    public List<ProgramMembership> ProgramMembership { get; set; }
}

In my parent view I have, as you can see I am using an editor template which is located in "/Views/Shared/EditorTemplates/ProgramMembership.cshtml":
@using AcnCS.Model
@model AcnCS.Model.ViewModels.User.UserMembershipViewModel
@{
    ViewBag.PageHeader = "Membership for " + Model.User.FullName;
    ViewBag.PageTitle = "Membership for " + @Model.User.FullName;
    ViewBag.HideNav = true;
}

    @if (Model.ProgramMembership != null)
    {

                    @using (Html.BeginForm())
                    {

                                    Program
                                    Effective Membership?
                                    Permission Type

                             @Html.EditorFor(m => Model.ProgramMembership, "ProgramMembership")

                        <input type="submit" class="btn btn-primary" value="Save Changes"/>
                    }

    }

My Editor template (ProgramMembership.cshtml) is:
@using AcnCS.Model
@model List<AcnCS.Model.ProgramMembership>

@foreach(ProgramMembership membership in Model)
{

        @membership.ProgramName

            @if (membership.IsMember)
            {
                @membership.IsMember
            }
            else
            {
                @membership.IsMember
            }

        @Html.DropDownListFor(x => membership.PermissionType, membership.PermissionTypes)

}

Everything is being displayed properly, but when I submit, my model object is null, even the ProgramMembership property in the model is null:
    [HttpPost]
    public ActionResult Membership(UserMembershipViewModel model)
    {

        // model IS NULL!!

        return View(model);
    }

Any help would be greatly appreciated!

A: I would pluralize the Property name since it is a collection, for better readability
public class UserMembershipViewModel:BaseViewModel
{
    public List<ProgramMembership> ProgramMemberships { get; set; }
}

and you dont need a Loop inside your EditorTemplate file
@model AcnCS.Model.ProgramMembership

    @membership.ProgramName

      @if (membership.IsMember)
      {
         @membership.IsMember
      }
      else
      {
         @membership.IsMember
      }

    @Html.DropDownListFor(x => membership.PermissionType, membership.PermissionTypes)

In your main view,call your EditorTemplate like this
@Html.EditorFor(m=>m.ProgramMemberships)


text:
Q: How to align multiple equation with numbereing each equation I've tried the answer of similar question but doesn't work.
\begin{equation}\label{pertama0}
\begin{aligned}
\frac{\partial E}{\partial L^0_{10}}&= \frac{\partial E}{\partial \hat{x}_{n+1}}\\
&=-2(x-\hat{x})\\
&=2(\hat{x}-x)
\end{aligned}
\end{equation}

\begin{equation}
\begin{aligned}
\frac{\partial L^o_{10}}{\partial L^i_{10}}&= \frac{\partial f(L^i_{10})}{\partial L^i_{10}}\\
&=\frac{\partial L^i_{10}}{\partial L^i_{10}}\\
&=1
\end{aligned}
\end{equation}

\begin{equation}
\begin{aligned}
\frac{\partial L_{10}^{i}}{\partial a_{21}} &=\frac{\partial\left(x_{n}+h\left(b_{1} k_{1x}+b_{2}k_{2x}\right)\right.}{\partial a_{21}} \\
&=\frac{\partial\left(h b_{2} k_{2 x}\right)}{\partial a_{21}} \\
&=h b_{2}\frac{ \partial\left(x_{n}^{\prime}+h a_{21} k_{1x^{\prime}})\right.}{\partial a_{21}} \\
&=h^{2} b_{2} k_{1 x^{\prime}}
\end{aligned}
\end{equation}
%
\begin{equation}
\begin{aligned}
\frac{\partial E}{\partial L^0_{11}}&= \frac{\partial E}{\partial \hat{y}_{n+1}}\\
&=-2(y-\hat{y})\\
&=2(\hat{y}-y)
\end{aligned}
\end{equation}

\begin{equation}
\begin{aligned}
\frac{\partial L^o_{11}}{\partial L^i_{11}}&= \frac{\partial f(L^i_{11})}{\partial L^i_{11}}\\
&=\frac{\partial L^i_{11}}{\partial L^i_{11}}\\
&=1
\end{aligned}
\end{equation}

\begin{equation}
\begin{aligned}
\frac{\partial L_{11}^{i}}{\partial a_{21}} &=\frac{\partial\left(y_{n}+h\left(b_{1} k_{1y}+b_{2}k_{2y}\right)\right.}{\partial a_{21}} \\
&=\frac{\partial\left(h b_{2} k_{2 y}\right)}{\partial a_{21}} \\
&=h b_{2}\frac{ \partial\left(y_{n}^{\prime}+h a_{21} k_{1y^{\prime}})\right.}{\partial a_{21}} \\
&=h^{2} b_{2} k_{1 y^{\prime}}
\end{aligned}
\end{equation}
%
\begin{equation}
\begin{aligned}
\frac{\partial E}{\partial L^0_{12}}&= \frac{\partial E}{\partial \hat{x}^{\prime}_{n+1}}\\
&=-2({x}^{\prime}-\hat{x}^{\prime})\\
&=2(\hat{x}^{\prime}-{x}^{\prime})
\end{aligned}
\end{equation}

\begin{equation}
\begin{aligned}
\frac{\partial L^o_{12}}{\partial L^i_{12}}&= \frac{\partial f(L^i_{12})}{\partial L^i_{12}}\\
&=\frac{\partial L^i_{12}}{\partial L^i_{12}}\\
&=1
\end{aligned}
\end{equation}

\begin{equation}
\begin{aligned}
\frac{\partial L_{12}^{i}}{\partial a_{21}} &=\frac{\partial\left(x_{n}^{\prime}+h\left(b_{1} k_{1x^{\prime}}+b_{2}k_{2 x^{\prime}}\right)\right)}{\partial a_{21}} \\
&=\frac{\partial\left(h b_{2} k_{2 x^{\prime}}\right)}{\partial a_{21}} \\
&=h b_{2} \frac{\partial f_{x^\prime}\left(x_{n}+h a_{21} k_{1 x^{\prime}}, y_{n}+h a_{21} k_{1 y^{\prime}}\right)}{\partial a_{21}} \\
&=h b_{2}\left(f_{x^{\prime}_{1}} h k_{1x^{\prime}} +f_{x^{\prime}_{2}} h k_{1 y^{\prime}}\right)
\end{aligned}
\end{equation}
%
\begin{equation}
\begin{aligned}
\frac{\partial E}{\partial L^0_{13}}&= \frac{\partial E}{\partial \hat{y}^{\prime}_{n+1}}\\
&=-2({y}^{\prime}-\hat{y}^{\prime})\\
&=2(\hat{y}^{\prime}-{y}^{\prime})
\end{aligned}
\end{equation}

\begin{equation}
\begin{aligned}
\frac{\partial L^o_{13}}{\partial L^i_{13}}&= \frac{\partial f(L^i_{13})}{\partial L^i_{13}}\\
&=\frac{\partial L^i_{13}}{\partial L^i_{13}}\\
&=1
\end{aligned}
\end{equation}
\begin{equation}\label{terakhhir0}
\begin{aligned}
\frac{\partial L_{13}^{i}}{\partial a_{21}} &=\frac{\partial\left(y_{n}^{\prime}+h\left(b_{1} k_{1y^{\prime}}+b_{2}k_{2 y^{\prime}}\right)\right)}{\partial a_{21}} \\
&=\frac{\partial\left(h b_{2} k_{2 y^{\prime}}\right)}{\partial a_{21}} \\
&=h b_{2} \frac{\partial f_{y^\prime}\left(x_{n}+h a_{21} k_{1 x^{\prime}}, y_{n}+h a_{21} k_{1 y^{\prime}}\right)}{\partial a_{21}} \\
&=h b_{2}\left(f_{y^{\prime}_{1}} h k_{1x^{\prime}} +f_{y^{\prime}_{2}} h k_{1 y^{\prime}}\right)
\end{aligned}
\end{equation}
\frac{\partial E}{\partial L^0_{13}}&= \frac{\partial E}{\partial \hat{y}^{\prime}_{n+1}}\\
&=-2({y}^{\prime}-\hat{y}^{\prime})\\
&=2(\hat{y}^{\prime}-{y}^{\prime})
\end{aligned}
\end{equation}

\begin{equation}
\begin{aligned}
\frac{\partial L^o_{13}}{\partial L^i_{13}}&= \frac{\partial f(L^i_{13})}{\partial L^i_{13}}\\
&=\frac{\partial L^i_{13}}{\partial L^i_{13}}\\
&=1
\end{aligned}
\end{equation}
\begin{equation}\label{terakhhir0}
\begin{aligned}
\frac{\partial L_{13}^{i}}{\partial a_{21}} &=\frac{\partial\left(y_{n}^{\prime}+h\left(b_{1} k_{1y^{\prime}}+b_{2}k_{2 y^{\prime}}\right)\right)}{\partial a_{21}} \\
&=\frac{\partial\left(h b_{2} k_{2 y^{\prime}}\right)}{\partial a_{21}} \\
&=h b_{2} \frac{\partial f_{y^\prime}\left(x_{n}+h a_{21} k_{1 x^{\prime}}, y_{n}+h a_{21} k_{1 y^{\prime}}\right)}{\partial a_{21}} \\
&=h b_{2}\left(f_{y^{\prime}_{1}} h k_{1x^{\prime}} +f_{y^{\prime}_{2}} h k_{1 y^{\prime}}\right)
\end{aligned}
\end{equation}

\begin{equation}\label{pertama0}
\begin{aligned}
\frac{\partial E}{\partial L^0_{10}}&= \frac{\partial E}{\partial \hat{x}_{n+1}}\\
&=-2(x-\hat{x})\\
&=2(\hat{x}-x)
\end{aligned}
\end{equation}

\begin{equation}
\begin{aligned}
\frac{\partial L^o_{10}}{\partial L^i_{10}}&= \frac{\partial f(L^i_{10})}{\partial L^i_{10}}\\
&=\frac{\partial L^i_{10}}{\partial L^i_{10}}\\
&=1
\end{aligned}
\end{equation}

\begin{equation}
\begin{aligned}
\frac{\partial L_{10}^{i}}{\partial a_{21}} &=\frac{\partial\left(x_{n}+h\left(b_{1} k_{1x}+b_{2}k_{2x}\right)\right.}{\partial a_{21}} \\
&=\frac{\partial\left(h b_{2} k_{2 x}\right)}{\partial a_{21}} \\
&=h b_{2}\frac{ \partial\left(x_{n}^{\prime}+h a_{21} k_{1x^{\prime}})\right.}{\partial a_{21}} \\
&=h^{2} b_{2} k_{1 x^{\prime}}
\end{aligned}
\end{equation}
%
\begin{equation}
\begin{aligned}
\frac{\partial E}{\partial L^0_{11}}&= \frac{\partial E}{\partial \hat{y}_{n+1}}\\
&=-2(y-\hat{y})\\
&=2(\hat{y}-y)
\end{aligned}
\end{equation}

\begin{equation}
\begin{aligned}
\frac{\partial L^o_{11}}{\partial L^i_{11}}&= \frac{\partial f(L^i_{11})}{\partial L^i_{11}}\\
&=\frac{\partial L^i_{11}}{\partial L^i_{11}}\\
&=1
\end{aligned}
\end{equation}

Wondering like this

A: Use align with split.
\documentclass{article}
\usepackage{amsmath}

\begin{document}

\begin{align}
\begin{split}\label{first}
\frac{\partial E}{\partial L^0_{10}}&= \frac{\partial E}{\partial \hat{x}_{n+1}}\\
&=-2(x-\hat{x})\\
&=2(\hat{x}-x)
\end{split}
\\[1ex]
\begin{split}\label{second}
\frac{\partial L^o_{10}}{\partial L^i_{10}}&= \frac{\partial f(L^i_{10})}{\partial L^i_{10}}\\
&=\frac{\partial L^i_{10}}{\partial L^i_{10}}\\
&=1
\end{split}
\\[1ex]
\begin{split}\label{third}
\frac{\partial L_{10}^{i}}{\partial a_{21}} &=\frac{\partial(x_{n}+h(b_{1} k_{1x}+b_{2}k_{2x}))}{\partial a_{21}} \\
&=\frac{\partial(h b_{2} k_{2 x})}{\partial a_{21}} \\
&=h b_{2}\frac{ \partial(x_{n}'+h a_{21} k_{1x'})}{\partial a_{21}} \\
&=h^{2} b_{2} k_{1 x'}
\end{split}
\\[1ex]
\begin{split}\label{fourth}
\frac{\partial E}{\partial L^0_{11}}&= \frac{\partial E}{\partial \hat{y}_{n+1}}\\
&=-2(y-\hat{y})\\
&=2(\hat{y}-y)
\end{split}
\end{align}

\end{document}

Between blocks I used \\[1ex] that adds some vertical space that helps the  reader in better seeing the block boundaries.
I removed the useless \left and \right instructions: in those cases they just added unwanted space. I also changed ^{\prime} into the simpler '.
Check the suspicious ^o that should probably be ^0.


text:
Q: Using a paintComponent with layout How do I convert a paintComponent to something that I can manipulate with a layout in a JFrame?
So, I'm running into an issue. I haven't really been taught (and don't have access to a book) how to use layouts/GUI stuff in my courses yet.
My issue is this: I have a program that the user inputs a number. Based on this number, the program calculates a circle and draws it out with a paintComponent method that has a for loop inside of it. The "pixels" that the circle is drawn with are actually fillRect methods. The current method of getting a user-input that I am using is a JOptionPane showInputDialog. This is MOSTLY fine, but I want the user to be able to select from a set of pre-defined numbers. Somebody suggested that I use a JComboBox, but I don't know how I would convert the paintComponent to something that would be usable by a layout manager (which a JComboBox must use, as far as I've learned). I know the dimensions of the paintComponent (805px by 805px) and there is no situation where it will change. If I could get some help with this bit, I am confident that I can figure out using a layout manager myself.

A: Another way to paint (besides custom painting) is to paint to a BufferedImage.  The image can then be displayed in a JLabel.
Examples:

*

*Painting in a BufferedImage inside Swing  A fairly complicated one.

*Dynamic Graphics Object Painting  Another one.

*Yet another one.

A: You don't know the dimensions of paintComponent because it's a method, and methods don't have dimensions. You probably know the dimensions of a JPanel or a JFrame or whatever your component is.
You should separate the panel where you do the painting, and a different panel which would contain any comboboxes or other inputs you decide to put in. That way you can keep your drawing panel as is, and they won't interfere with each other. You'll want to search for the tutorial on LayoutManagers.


text:
Q: Infinite Series $\left(\frac12+\frac14-\frac23\right)+\left(\frac15+\frac17-\frac26\right)+\left(\frac18+\frac{1}{10}-\frac29\right)+\cdots$ How do I find the sum of the following infinite series:
$$\left(\frac12+\frac14-\frac23\right)+\left(\frac15+\frac17-\frac26\right)+\left(\frac18+\frac{1}{10}-\frac29\right)+\cdots$$
The series definitely seems to be convergent.

A: Here's $\let\leq\leqslant\let\geq\geqslant$a complex analysis approach. (It may look a bit tedious, but that's because of some issues with convergence. After all, the concept is beautiful.)
Let $\zeta=e^{2\pi i/3}$, we have $\zeta^k+\zeta^{2k}=-1$ if $3\nmid k$ and $\zeta^k+\zeta^{2k}=2$ if $3\mid k$.
Hence
$$\sum_{n=1}^\infty\left(\frac1{3n-1}+\frac1{3n+1}-\frac2{3n}\right)=-\sum_{k=2}^\infty\frac{\zeta^k+\zeta^{2k}}k.$$
Let $f(z)=\sum_{k=2}^\infty\frac{z^k+z^{2k}}k$. Note that $f(\zeta)$ exists because from the original formula we have
$$f(\zeta)=\sum_{n=1}^\infty\frac2{3n(3n+1)(3n-1)}=O\left(\sum_{n=1}^\infty\frac1{n^3}\right)=O(1).$$
For $|z|<1$,
$$\begin{align*}f(z)
&=\sum_{k=2}^\infty\int_0^z\left(t^{k-1}+2t^{2k-1}\right)dt\end{align*}.$$
Because the series $\sum_{n\geq1}t^n$ converges uniformly for $|t|\leq z$, we can write
$$\begin{align*}f(z)
&=\int_0^z\sum_{k=2}^\infty\left(t^{k-1}+2t^{2k-1}\right)dt\\
&=\int_0^z\left(\frac t{1-t}+2\frac{t^3}{1-t^2}\right)dt.\end{align*}$$
Finally, by Abel's theorem,
$$\begin{align*}f(\zeta)
&=\int_0^\zeta\left(\frac t{1-t}+2\frac{t^3}{1-t^2}\right)dt\\
&=\left[t^2+t+\log(t^3-t^2-t+1)\right]_0^\zeta\\
&=-1+\log3.\end{align*}$$
Because we had our initial sum with a minus sign, the answer is $1-\log3$.

A: Your sum is equal to:
\begin{align}
\sum_{i=1}^{\infty} \left ( \frac{1}{3i-1}+\frac{1}{3i+1}-\frac{2}{3i}\right )  &=\sum_{i=1}^{\infty} \frac{(3i+1) \cdot 3i+3i \cdot (3i-1)-2(3i-1) \cdot (3i+1)}{(3i-1) \cdot 3i \cdot (3i+1)} \\
&=\sum_{i=1}^{\infty}\frac{9i^2+3i+9i^2-3i-2(9i^2-1)}{(3i-1) \cdot 3i \cdot (3i+1)} \\
&=\sum_{i=1}^{\infty}\frac{18i^2-18i^2+2}{(3i-1) \cdot 3i \cdot (3i+1)} \\
&=\sum_{i=1}^{\infty}\frac{2}{(3i-1) \cdot 3i \cdot (3i+1)} \\
&= 2 \sum_{i=1}^{\infty} \frac{1}{(3i-1) \cdot 3i \cdot (3i+1)}
\end{align}

A: Let
$$S_m=\sum_{k=1}^m\left(\frac{1}{3k-1}+\frac{1}{3k+1}-\frac{2}{3k}\right)$$
this can be written as follows
$$S_m=\sum_{k=1}^m\left(\frac{1}{3k-1}+\frac{1}{3k}+\frac{1}{3k+1}-\frac{1}{k}\right)
=H_{3m+1}-1-H_m=\frac{1}{3m+1}-1+H_{3m}-H_m$$
where $H_n=\sum_{k=1}^n1/k=\ln n+\gamma+o(1)$, is the $n$th harmonic number. Using this asymptotic expansion we see that
$$S_m=\ln 3-1+o(1)$$
Hence $\lim\limits_{m\to\infty}S_m=-1+\ln3$.

A: Hint:
$$S=\left(\frac12+\frac14-\frac23\right)+\left(\frac15+\frac17-\frac26\right)+\left(\frac18+\frac{1}{10}-\frac29\right)+\cdots\infty$$
$$S
=\sum_{k=0}^{\infty}\left(\frac1{2+3k}+\frac1{4+3k}-\frac2{3+3k}\right)\\
=\sum_{k=0}^{\infty}\left(\frac1{2+3k}+\frac1{4+3k}-\frac2{3+3k}\right)\\
$$

A: \begin{array}{l}
 s_0 \left( x \right) = \sum\limits_{x = 0}^{ + \infty } {\frac{{x^{3k + 3} }}{{3k + 3}}}  \Rightarrow s'_0 \left( x \right) = \sum\limits_{x = 0}^{ + \infty } {x^{3k + 2} }  = \frac{{x^2 }}{{1 - x^3 }} \\
 s_1 \left( x \right) = \sum\limits_{x = 0}^{ + \infty } {\frac{{x^{3k + 4} }}{{3k + 4}}}  \Rightarrow s'_1 \left( x \right) = \sum\limits_{x = 0}^{ + \infty } {x^{3k + 3} }  = \frac{{x^3 }}{{1 - x^3 }} \\
 s_2 \left( x \right) = \sum\limits_{x = 0}^{ + \infty } {\frac{{x^{3k + 2} }}{{3k + 2}}}  \Rightarrow s_2 ^\prime  \left( x \right) = \sum\limits_{x = 0}^{ + \infty } {x^{3k + 1} }  = \frac{x}{{1 - x^3 }} \\
 s_0 \left( x \right) + s_1 \left( x \right) + s_2 \left( x \right) = \sum\limits_{x = 0}^{ + \infty } {\left( {\frac{{x^{3k + 3} }}{{3k + 3}} + \frac{{x^{3k + 4} }}{{3k + 4}} + \frac{{x^{3k + 2} }}{{3k + 2}}} \right)}  \\
 \frac{x}{{1 - x^3 }} + \frac{{x^3 }}{{1 - x^3 }} - \frac{{2x^2 }}{{1 - x^3 }} = \frac{{x^3  + x - 2x^2 }}{{1 - x^3 }} = \frac{{x\left( {x - 1} \right)}}{{1 + x + x^2 }} \\
 \end{array}


text:
Q: Loading AJAX calls one after the other I have the following 3 AJAX function, and the problem is that it loads sessionAllCoursePage3 first then sessionAllCoursePage2 then sessionAllCoursePage1, I wanted to be inverse. I want to ensure that page1 is loaded first, then page 2, page 3, etc.
// Retrieve last 9 session
$.ajax({
    type: "POST",
    data: { run: true, providerName: $('#providerName').val() },
    url: '/app/functions/sessionAllCoursePage1.php',
    cache: false,
    success: function(response) {
        // Response is value returned from php
        $('#contentPage1').html(response);
        return false;
    }
});

// Retrieve the next 9 session

$.ajax({
    type: "POST",
    data: { run: true, providerName: $('#providerName').val() },
    url: '/app/functions/sessionAllCoursePage2.php',
    cache: false,
    success: function(response) {
        // Response is value returned from php
        $('#contentPage2').html(response);
        return false;
    }
});

// Retrieve the next 9 session

$.ajax({
    type: "POST",
    data: { run: true, providerName: $('#providerName').val() },
    url: '/app/functions/sessionAllCoursePage3.php',
    cache: false,
    success: function(response) {
        // Response is value returned from php
        $('#contentPage3').html(response);
        return false;
    }
});

A: I'd suggest you chain them with promises:
// Retrieve last 9 session
$.ajax({
    type: "POST",
    data: {
        run: true,
        providerName: $('#providerName').val()
    },
    url: '/app/functions/sessionAllCoursePage1.php',
    cache: false
}).then(function(response) {

    $('#contentPage1').html(response);

    return $.ajax({
        type: "POST",
        data: {
            run: true,
            providerName: $('#providerName').val()
        },
        url: '/app/functions/sessionAllCoursePage2.php',
        cache: false
}).then(function(response) {

    $('#contentPage2').html(response);

    return $.ajax({
        type: "POST",
        data: {
            run: true,
            providerName: $('#providerName').val()
        },
        url: '/app/functions/sessionAllCoursePage3.php',
        cache: false
    });
}).then(function(response) {
    $('#contentPage3').html(response);
});

Or, using a little more shared code:
function ajaxCommon(url, resultId) {
    return $.ajax({
        type: "POST",
        url: url,
        data: {
            run: true,
            providerName: $('#providerName').val()
        },
        cache: false
    }).then(function(result) {
        $("#" + resultId).html(result);
    });
}

ajaxCommon('/app/functions/sessionAllCoursePage1.php', 'contentPage1').then(function() {
    return ajaxCommon('/app/functions/sessionAllCoursePage2.php', 'contentPage2');
}).then(function() {
    return ajaxCommon('/app/functions/sessionAllCoursePage3.php', 'contentPage3');
});

Or, a little more table/loop driven:
function ajaxCommon(url, resultId) {
    return $.ajax({
        type: "POST",
        url: url,
        data: {run: true, providerName: $('#providerName').val()},
        cache: false
    }).then(function(result) {
        $("#" + resultId).html(result);
    });
}

[1,2,3].reduce(function(p, item) {
    return p.then(function() {
        return ajaxCommon('/app/functions/sessionAllCoursePage' + item + '.php', 'contentPage' + item);
    });
}, Promise.resolve());

A: You can use Array.prototype.shift(), String.prototype.match() with Regexp /\d/ to match digit character in url, .then()
    function request(url) {
      return $.ajax({
              type: "POST",
              data: {run: true, providerName: $('#providerName').val()},
              url: url,
              cache:false,
              success: function (response) {
                $('#contentPage' + url.match(/\d/)[0]).html(response);
              }
            });
    }

    var urls = ['/app/functions/sessionAllCoursePage1.php'
               , '/app/functions/sessionAllCoursePage2.php'
               , '/app/functions/sessionAllCoursePage3.php'];

    request(urls.shift())
    .then(function re() {
      if (urls.length) {
        request(urls.shift()).then(re)
      }
    })
    // can use `.catch()` here at jQuery 3.0+
    .fail(function(jqxhr, textStatus, errorThrown) {
      // handle error
      console.log(errorThrown);
    });

plnkr http://plnkr.co/edit/fREO6Jzw65gq2s3jrwjp?p=preview

A: Just place your asynchronous code inside some request callback (e.g. success). Didactically:
var firstRequestOptions = {
  success: function () {
    secondRequest();
  }
};
var secondRequestOptions = {
  success: function () {
    thirdRequest();
  }
};
var thirdRequestOptions = {
  success: function () {
    firstRequest();
  }
};
var firstRequest = function () {
  console.log('request 1');
  $.ajax(firstRequestOptions);
};
var secondRequest = function () {
  console.log('request 2');
  $.ajax(secondRequestOptions);
};
var thirdRequest = function () {
  console.log('request 3');
  $.ajax(thirdRequestOptions);
};

Then:
firstRequest();

The log should be:
> request 1
> request 2
> request 3
> request 1
> request 2
...


text:
Q: Why Spring Data JPA / Hibernate is not binding `Pageable` values to generated query? I am using spring-data-jpa (2.1.7.RELEASE) with hibernate (5.6.9.Final) as ORM implementation.
I am creating Pageable object in service layer and passing it to repo layer -
Service Layer Code:
Pageable pg = PageRequest.of(4, 2);
Page<Tuple> packagesList = packageRepository.getPackageByAccountIdAndPackageId(accountId, packageId, pg);

Repository Layer Code:
public interface PackageRepository extends JpaRepository<Packages, PackageId> { ...

and
@Query(value = "SELECT p.package_id FROM packages p WHERE p.account_id=:accountId AND (CASE WHEN :packageId IS NULL THEN TRUE WHEN  p.package_id LIKE :packageId THEN TRUE ELSE FALSE END)",
            countQuery = "SELECT count(*) FROM packages", nativeQuery = true)
Page<Tuple> getPackageByAccountIdAndPackageId(String accountId, String packageId, Pageable pg);

In the generated SQL - the limit restriction is getting added but no binding values are getting generated. Below should clarify that -
Query and Binding Params
Hibernate:
    SELECT
        p.package_id
    FROM
        packages p
    WHERE
        p.account_id=?
        AND (
            CASE
                WHEN ? IS NULL THEN TRUE
                WHEN  p.package_id LIKE ? THEN TRUE
                ELSE FALSE
            END
        ) limit ?, ?
2022-10-15 18:43:46.285 TRACE 68021 --- [nio-8095-exec-1] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [VARCHAR] - [40955353-d2c3-4377-8c95-6b403b7570ef]
2022-10-15 18:43:46.286 TRACE 68021 --- [nio-8095-exec-1] o.h.type.descriptor.sql.BasicBinder      : binding parameter [2] as [VARCHAR] - [%2]
2022-10-15 18:43:46.286 TRACE 68021 --- [nio-8095-exec-1] o.h.type.descriptor.sql.BasicBinder      : binding parameter [3] as [VARCHAR] - [%2]
2022-10-15 18:43:46.328 TRACE 68021 --- [nio-8095-exec-1] .s.t.s.TransactionSynchronizationManager : Retrieved value [org.springframework.orm.jpa.EntityManagerHolder@41baa13] for key [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean@7317fb] bound to thread [http-nio-8095-exec-1]
2022-10-15 18:43:46.329 TRACE 68021 --- [nio-8095-exec-1] .s.t.s.TransactionSynchronizationManager : Retrieved value [org.springframework.orm.jpa.EntityManagerHolder@41baa13] for key [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean@7317fb] bound to thread [http-nio-8095-exec-1]

Why binding parameters 4 and 5 corresponding to offset and limit are not getting generated even though the query is expecting them.
Note: The query is succeeding and I am not getting any exception.
Note: plz ignore the count query. It is intentionally incorrect. I added it to see if count query makes any difference. But it did not.
Q2 - Is count query mandatory for Pageable to work?

A: JPA handles limit and offset separately from the rest of the query.
What Spring Data does for you is:

*

*Create a query object from your SQL statement.

*Bind parameters to it (excluding the pageable)

*Call special methods for limit and offset
So these values get some special treatment in you JPA implementation and I guess this is why they don't get printed with normal bind parameters.
Also I seem to remember that some database doesn't allow setting these as bind parameters at all.
Which might actually be the original reason for the special treatment.


text:
Q: Many php-fpm: pool www processes running but Apache isn't I'm using CentOS 6.4 (x86) VPS with Nginx.
In Webmin Running processes table I found up to 8 "php-fpm: pool www" running processes that "Apache" is the owner, but Apache isn't running!
This consumes a lot of RAM memory.
It is necessary for the nginx jobs or not? Sorry for this (stupid?) question but I'm newbie about Server management.
Thank you in advance.

A: The processing running will be needed and won't be being wasted.
One of the first things that should be defined in your PHP-FPM config file is what user and group PHP-FPM should be running under.
Presumably your config file says to run PHP-FPM under the user 'Apache'. You can change this to whatever you like, so long as you get the file permission right for PHP-FPM to access your php files.
However if PHP-FPM is taking up a lot of memory then you should tweak the values for the number of pools and how much memory each one can use. In particular you could reduce the settings:
pm.start_servers = 4
pm.min_spare_servers = 2

To not have as many PHP-FPM processes sitting around idle when there is no load.

A: PHP-FPM has it's own separate process manager and really isn't connected to anything other than itself. Other software will connect to it, IE: nginx / apache. You probably see the "Apache" user running the process because of the pool configuration you have. You can easily change the configuration and then restart the FPM Process.
If you do not wish to have stale processes running while they are not used, then I would recommend that you change the PM option in the pool configuration from Static/Dynamic to ondemand. This way, FPM will only spool up when it is needed.
Many people use the Static/Dynamic options when they need specific variations for the processes they are running, IE: a site that receives a lot of constant traffic.
Depending on your FPM installation you'll normally find the configurations in /etc/php. I keep my configurations in /usr/local/etc/php-fpm/ or /usr/local/etc/fpm.d/


text:
Q: Using regular expressions in python to determine C++ functions and their parameters So I'm doing something wrong in this python script, but it's becoming convoluted and I'm losing sight of what I'm doing wrong.
I want a script to go through a file, find all the function definitions, and then pull out the name, return type, and parameters of the function, and output a "doxygen" style comment like this:
/******************************************************************************/
  /*!
    \brief
      Main function for the file

    \return
      The exit code for the program
  */
/******************************************************************************/

But I'm doing something wrong with the regular expression in trying to parse the parameters... Here is the script so far:
import re
import sys

f = open(sys.argv[1])

functions = []

for line in f:
  match = re.search(r'([\w]+)\s+([\S]+)\(([\w+\s+\w+])+\)',line)
  if line.find("\\fn") < 0:
    if match:
      returntype = match.group(1)
      funcname = match.group(2)
      print '/********************************************************************'
      print "  \\fn " + match.group()
      print ''
      print '  \\brief'
      print '    Function description for ' + funcname
      print ''
      if len(match.groups()) > 2:
        params = []
        count = len(match.groups()) - 2
        while count > 0:
          matchingstring = match.group(count + 2)
          if matchingstring.find("void") < 0:
            params.append(matchingstring)
          count -= 1
        for parameter in params:
          print "  \\param " + parameter
          print '    Description of ' + parameter
          print ''
      print '  \\return'
      print '    ' + returntype
      print '********************************************************************/'
      print ''

Any help would be appreciated. Thanks

A: The grammar of C++ is far too complex to be handled by simple
regular expressions.  You'll need at least a minimal parser.
I've found that for restricted cases, where I'm not concerned
with C++ in general, but only my own style, I can often get away
with a flex based tokenizer and a simple state machine.  This
will fail in many cases of legal C++—for starters, of
course, if someone uses the pre-processor to modify the syntax;
but also because < can have different meanings, depending on
what precedes it names a template or not.  But it's often
adequate for a specific job.

A: I've used a PEG parser with great success when trying to do simple format parsing.  pyPeg is a very simple implementation of such a parser written in Python.
Example Python code for C++ function parser:
EDIT: Address template parameters.  Tested with input from SK-logic and output is correct.
import pyPEG
from pyPEG import parseLine
import re

def symbol(): return re.compile(r"[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ&*][\w:]+")
def type(): return symbol
def functionName(): return symbol
def templatedType(): return symbol, "<", -1, [templatedType, symbol, ","], ">"
def parameter(): return [templatedType, type], symbol
def template(): return "<", -1, [symbol, template], ">"
def function(): return [type, templatedType], functionName, -1, template, "(", -1, [",", parameter], ")" # -1 -> zero or more repetitions.

sourceCode = "std::string foobar(std::vector<int> &A, std::map<std::string, std::vector<std::string> > &B)"
results = parseLine(sourceCode, function(), [], packrat=True)

When this is executed results is:
([(u'type', [(u'symbol', 'std::string')]), (u'functionName', [(u'symbol', 'foobar')]), (u'parameter', [(u'templatedType', [(u'symbol', 'std::vector'), (u'symbol', 'int')]), (u'symbol', '&A')]), (u'parameter', [(u'templatedType', [(u'symbol', 'std::map'), (u'symbol', 'std::string'), (u'templatedType', [(u'symbol', 'std::vector'), (u'symbol', 'std::string')])]), (u'symbol', '&B')])], '')

A: C++ cannot really be parsed by a (sane) regular expression: they are a nightmare as soon as nesting is concerned.
There is another concern too, determining when to parse and when not to. A function may be declared:

*

*at file scope

*in a namespace

*in a class

And the two last can be nested at arbitrary depths.
I would propose to use CLang here. It's a real C++ front-end with a full-featured parser and there are:

*

*a C API, with (notably) an API to the Indexing Library

*Python bindings on top of the C API

The C API and Python bindings are far from fully exposing the underlying C++ model, but for a task as simple as listing functions it should be enough.

That said, I would question the usefulness of the project: if the documentation can be generated by a simple parser, then it is redundant with the code. And redundancy is at best, useless, and worst dangerous: it introduces the potential threat of desynchronization...
If the function is tricky enough that its use requires documentation, then a developer, who knows the limitations and al, has to write this documentation.


text:
Q: Nothing shows up when i run Jupyter notebook When i run jupyter notebook it just shows up blank
I checked Console for errors and it showed me this:
Console error message
This is the line that the above Error message is referring to:
Error message line
Here is the URL bar if you need it (this is what the URL bar shows when i launch Jupyter notebook):
URL

A: used
jupyter nbconvert --to script object_detection_tutorial.ipynb

to convert .ipynb to .txt, then copied the code to a .py file


text:
Q: Specify Framework Version for CSharpCompilation.Emit Does anyone know whether it is possible to specify the Framework-Version when Emitting assemblies using CSharpCompilation's extensionmethod Emit?
We need to target 4.5.1 apparently since otherwise we get a nasty runtime error:
MissingMethodException
Method not found: '!!0[] System.Array.Empty()'.

Or do we have to wait till clients are upgraded to Framework 4.6 before we can make use of Roslyn?

A: The compiler doesn't (and has never) had a concept of "framework version". All the compiler understands is what set of references are included. It sounds like you are creating your compilation with references to 4.6 versions of the framework (possibly because you are using running assembly locations, and are running on 4.6).
Instead, you'll need to ensure that you have the 4.5.1 targeting pack installed (VS install does this automatically, but other machines may not have it), and add its references to your compilation from out of C:\Program Files (x86)\Reference Assemblies.
The compiler will emit references to Array.Empty if it exists in the referenced assemblies, but has fallback logic if it doesn't.


text:
Q: WordPress archive page for multiple taxonomies I want to ask if it is possible to make WP archives page that arranges the custom posts in specific way. Let me explain.
The CPT is "Products". All the products have several custom taxonomies. Ex.
Product>Fall 2014>Shampoo     (there is only one shampoo from this Fall 2014 collection)
Product>Fall 2014>Conditioner (there is only one conditioner from this Fall 2014 collection)
I want to add the corresponding Winter 2014> Shampoo and Winter 2014 > Conditioner but I want to be able to display them in the following order (masonry style):
     Fall 2014:

Shampoo           Conditioner
    Winter 2014:

Shampoo           Conditioner
Also I want to be able to categorize them by product type like:
    Shampoos

Fall 2014   Winter 2014
    Conditioners

Fall 2014   Winter 2014
In the end to explain the relation between the taxonomies and CPT.
Shampoo1( Custom post type - Products) which has the taxonomies Shampoo (parent taxonomy) and Fall 2014 (child taxonomy).
Is something like this possible to be made so the process of sorting will be made by wordpress with each new product, and if it is possible can someone point me in the right direction because I am lost :)

A: Yes, you can. By creating custom taxonomy templates for all your taxonomies and so your posts relevant to certain taxonomies will be showing up in your taxonomy template. For example if your custom taxonomy is Shampoo, then your taxonomy page will become taxonomy-shampoo.php  in this way you can create templates for all other taxonomies to show your products according to your needs, for reference check https://developer.wordpress.org/themes/template-files-section/taxonomy-templates/


text: Q: Any way to validate pig script before running in hdfs cluster? I'm new to pig script. The problem I'm facing is inability to validate how syntactically correct my script is. I have to upload it to hdfs cluster and run there just to realize I missed ';' in the end of the line. Big waste of time. I use IntelliJ IDEA with pig script plugin, but while it helps to highlight pig statements it does not validate it.  Apache Pig does not seem to have any compiler, you can only run it, but I can't run it locally, data is not available from my laptop. So I wonder it there is any sophisticated pig script syntax validator, so I can run it and check if my script syntactically correct before uploading to the server.


text:
Q: vc code audible prompts in Chinese, I'm not Chinese VS Code v1.65.0 (and prior versions)
Commit: b5205cc8eb4fbaa726835538cd82372cc0222d43
Date: 2022-03-02T11:12:08.962Z
Whilst entering code, or sometimes changing focus, I get a very long and LOUD audible message in Chinese (or some similar dialect). How do I disable it or perhaps, change it to English?
Yes, I've looked over the available options and have not been able to find it.
Helpful comments would be appreciated.
Thankyou


text:
Q: parameter complex object is coming into JavaScript function as undefined On Page 1 I get the object I need:
ProjectSearchCriteria = (GBLProjectSearchCriteria)Session[GblConstants.SESSION_PROJECT_SEARCH_CRITERIA];

I'm trying to pass this to an API on a page load of Page 2.
Page 2:
<!DOCTYPE HTML>
<html>
    <head>
        <title></title>
        <link href="../x.css" type="text/css" rel="stylesheet">
        <link href="../Content/kendo.common.min.css" rel="stylesheet" />
        <link href="../Content/kendo.default.min.css" rel="stylesheet" />
    </head>
    <body>
        <form id="frmProjectSearchResults" runat="server">
        </form>
        <script src="../Scripts/ProjectsTreeView.js"> </script>
        <script type="text/javascript">
            CreateProjectTree(<%= ProjectSearchCriteria %>);
        </script>
    </body>
</html>

And this is the JavaScript function:
function CreateProjectTree(searchCriteria)
{
    debugger;
    var projects = new kendo.data.HierarchicalDataSource({
        transport: {
            read: {
                url: "../api/projects?searchcriteria =" + searchCriteria,
                contentType: "application/json"
            },
            parameterMap: function (data, operation) {
                return JSON.stringify(data);
            }
        },
        schema: {
            model: {
                children: "seasons"
            }
        }
    });

    $("#treeview").kendoTreeView({
        dataSource: projects,
        loadOnDemand: true,
        dataUrlField: "LinksTo",
        checkboxes: {
            checkChildren: true
        },
        dataTextField: ["Title"],
        select: treeviewSelect
    });

    function treeviewSelect(e) {
        var node = this.dataItem(e.node);
        window.open(node.NotificationLink, "_self");
    }
}

Can anyone help me understand what I'm doing wrong?

A: Maybe this:
<script type="text/javascript">
    CreateProjectTree("\"" + <%= ProjectSearchCriteria %> + "\"");
</script>


text:
Q: Calculated fields in database - Laravel What is the best practice to store calculated fields in database.
For example, lets say a table has fields height, weight, bmi
A user enters height weight values and bmi field is automatically filled. How to achieve this with a form.
Formula for bmi
$bmi = weight / (height * height)
Tried the following
Profile Model
protected $table = 'profiles';

protected $fillable = ['user_id', 'weight', 'height', 'dob', 'age', 'bmi'];

public function user(){
  return $this->belongsTo(User::class, 'user_id');
}

protected static function boot() {
  parent::boot();

  static::saving(function($model){
      $model->bmi = $model->weight / ($model->height * $model->height);
      $model->age = (date('Y') - date('Y',strtotime($model->dob)));
  });
}

Profile Controller
public function store(Request $request)
  {
      $profile = new Profile();
      $profile->weight = $request->get('weight');
      $profile->height = $request->get('height');
      $profile->dob = $request->get('dob');
      $profile->age;
      $profile->bmi;
      $profile->save();
      return back()->with('success', 'Your profile has been updated.');
  }

But im receiving an error
Illuminate \ Database \ QueryException (42S22)
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'weight' in 'field list' (SQL: insert into `users` (`weight`, `height`, `dob`, `bmi`, `age`, `created_by`, `updated_by`, `updated_at`, `created_at`) values (60, 175, 1988-04-03, 0.0019591836734694, 30, 2, 2, 2018-03-08 20:06:02, 2018-03-08 20:06:02))

A:
What is the best practice to store calculated fields in database.

In general, don't. It's redundant - your database already has all the information needed to compute it, so why store redundant data?
Instead, put an accessor on the model:
public function getBmiAttribute() {
    return ($this->weight / ($this->height * $this->height));
}

You can then do $this->bmi to get the computed value.
If you must have it in the database, use an Eloquent event. You'd probably want to hook into the saving event.

A: You could do this in the boot method of the model:
protected static function boot() {
    parent::boot();

    static::saving(function($model){
        $model->bmi = $model->weight / ($model->height * $model->height);
    });
}

A: As of Laravel 5.3 & MySQL 5.7, you can use Column Modifiers virtualAs and storedAs to create a VIRTUAL (evaluated when rows are read) or STORED (evaluated and stored when rows are inserted or updated) generated column for MySQL.
I've made use of virtualAs in the example below...
    Schema::create('results', function (Blueprint $table) {
        $table->bigIncrements('id');
        ...
        $table->time('predicted_time')->nullable()->default(NULL);
        $table->time('handicap')->nullable()->default(NULL);
        $table->time('finish_time')->nullable()->default(NULL);
        $table->time('actual_time')->virtualAs('TIMEDIFF(finish_time, handicap)');
        $table->time('offset')->virtualAs('TIMEDIFF(actual_time, predicted_time)');
        ...
    });

A:
What is the best practice to store calculated fields in database.

It depends on your use case. If you're using a relational database, and your use case does not involve big data (in terms of volume, variety or velocity), the best practice is to not store calculated fields and calculate them on the fly.
If you're using a noSQL database (such as MongoDB, which is supported by Laravel) or Hadoop, the best practice is to store calculated fields to avoid computational time.
In A Nutshell

It's a tradeoff between time complexity and space/storage complexity.
  For big data / noSQL systems, store calculated fields especially if
  they are computationally complex. For a relational database, calculate
  them on the fly and keep your data non-redundant

Laravel Solution for RDBMS:
Use accessors like so:
public function getBmiAttribute($value)
{
    return ($this->weight / ($this->height * $this->height));
}

Laravel Solution for NoSql
Use model events like so:
protected static function boot() {
    parent::boot();

    static::saving(function($model){
        $model->bmi = $model->weight / ($model->height * $model->height);
    });
}

A: If your DBMS supports computed columns (aka generated columns), you might consider utilizing them.
Highlights:

*

*Computed columns don't persist the data to the database (or if they do technically they'll be managed by the DBMS), so you're not duplicating any data or making anything redundant

*The calculation is then available outside of the application's code base for anything to use. For example, if there is a need to develop reporting with raw SQL queries then the calculation will be available there.

*Eloquent (Laravel's default ORM) will pick up the column without you necessarily needing to define it anywhere.

You could execute code to create it during a migration. For example, I had a use case where I wanted to simplify determining if something was currently published and I did it like this:
Schema::table('article', function (Blueprint $table) {
    $table->dateTime('published_at')->nullable();
    $table->dateTime('unpublished_at')->nullable();
});

$sql = "ALTER TABLE article ADD is_published AS CAST(CASE WHEN GETUTCDATE() BETWEEN ISNULL(published_at, '2050-01-01') AND ISNULL(unpublished_at, '2050-01-01') THEN 1 ELSE 0 END AS BIT);";
DB::connection()->getPdo()->exec($sql);

Then after retrieving a record from the database I can determine if it's published by simply checking...
if ($article->is_published) ...

And if I want to query it from the database I can easily do...
SELECT * FROM article WHERE is_published = 1

Note, this syntax is for T-SQL since the RDBMS for my project is MS SQL Server. However, other popular DBMS have similar features.

*

*MS SQL Server: Computed Columns
ALTER TABLE dbo.Products ADD RetailValue AS (QtyAvailable * UnitPrice * 1.35);

*MySQL: Generated Columns
ALTER TABLE t1 ADD COLUMN c2 INT GENERATED ALWAYS AS (c1 + 1) STORED;

*Oracle: Virtual Columns
ALTER TABLE emp2 ADD (income AS (salary + (salary*commission_pct)));
PostgreSQL doesn't seem to support it (yet), but this SO answer provides a decent workaround.

A: another way to make this
making a computed column in the migration
this working with all DB:-
 $table->computed ('tax','price * 0.27');

but this working with MySQL DB:-
 $table->integer('tax')->virtualAs('price * 0.27')->nullable();
 $table->integer('discount')->storedAs('price - 100')->nullable();


text:
Q: Larevel 9 error forgot password "Class "Ramsey\Uuid\Converter\Time\UnixTimeConverter" not found" I'm having a problem with laravel nine password recovery with jetstream/fortify.
I have pulled it to a modal, but I keep pointing to the URL route('password.email') with the post method.
But I get this error, attached image:

Error Class "Ramsey\Uuid\Converter\Time\UnixTimeConverter" not
found

I have checked that I have "ramsey/uuid": "^4.5".
In the database, I see that password_resets changes the token.
I am at a loss as to what the error could be.
Recover passwords in Laravel 9 by using a form and sending an email with a link to create a new password.


text:
Q: PHP Scripts not working with Plesk It's the first time that I've worked with Plesk. Before using Plesk, this website and scripts were all fully functional all of the PHP was working without issue although once it was moved to a different host using Plesk, most of the PHP is now showing up as plain text. Some of the includes are working, but a lot of the short MySQLi commands do not work, such as;
$conn->query
$result2->fetch_row()
$result->num_rows

Also, when I try and perform a very simple test, such as;
$test = 'hello';
echo $test;

I get nothing returning? Here is an example of one of the scripts I am using and how it shows up on the website...
<?
if($show == 'All'){
        $sql = mysqli_query($conn, "SELECT * FROM `xWKaiNXU_news` WHERE `news_public` = '1' ORDER BY `news_date` DESC LIMIT 100");
        } else {
        if($show == 'EVENT'){
                $sql = mysqli_query($conn, "SELECT * FROM `xWKaiNXU_news` WHERE (`news_type` = 'EVENT' OR `news_type` = 'PDF') AND `news_public` = '1' ORDER BY `news_date` DESC LIMIT 100");
            } else {
        $sql = mysqli_query($conn, "SELECT * FROM `xWKaiNXU_news` WHERE `news_type` = '$show' AND `news_public` = '1' ORDER BY `news_date` DESC LIMIT 100");
            }
        }
          $result = $sql;
echo $test;
          if (mysqli_num_rows($result) > 0) {

              while($row = mysqli_fetch_assoc($result)) {
                    $news_id = $row['news_id'];
                    $news_type = $row['news_type'];
                    $news_title = $row['news_title'];
                    $news_tagline = $row['news_tagline'];
                    $news_date = date('dS F Y', strtotime($row['news_date']));
                    $news_time = date('H:i', strtotime($row['news_date']));
                    $news_image = $row['news_image'];

                    if($news_type == 'PDF'){
                        $news_text = $row['news_text'];
                    ?>

                    <?
                    if($news_tagline == 'port'){
                    ?>

From:
<? echo $news_date; ?>

<? echo $news_text; ?>

                     <object data="<? echo $news_image; ?>" type="application/pdf" width="80%" height="600px">

Alternative link - <a href="<? echo $news_image; ?>">PDF Viewer

</object>

                    <?
                    } else {
                    ?>

From:
<? echo $news_date; ?>

<? echo $news_text; ?>

                     <object data="<? echo $news_image; ?>" type="application/pdf" width="100%" height="550px">

Alternative link - <a href="<? echo $news_image; ?>">PDF Viewer

</object>
                    <?
                    }
                    ?>

                    <?

                    } else {
                        if($news_image == ''){
                        $news_dp_image = 'assets/images/default.jpg';
                    } else {
                        $news_dp_image = 'news_images/'.$news_image;
                    }
                    ?>

<a href="full_news.php?id=<? echo $news_id; ?>" title="Post" style="background-image: url('<? echo $news_dp_image; ?>'); box-shadow: 0 1px 5px rgba(0, 0, 0, 0.4), 0 1px 5px rgba(130, 130, 130, 0.35);">

<a href="full_news.php?id=<? echo $news_id; ?>"> <? echo $news_title; ?>

<? echo $news_tagline; ?>

 <? echo $news_date; ?> at  <? echo $news_time; ?> <? echo $news_type; ?>

<a href="full_news.php?id=<? echo $news_id; ?>" class="btn btn-primary"> Read More

                    <?
                    }
              }
          } else {
              ?>

              <?
          }
              ?>

How it displays:
0) { while($row = mysqli_fetch_assoc($result)) { $news_id = $row['news_id']; $news_type = $row['news_type']; $news_title = $row['news_title']; $news_tagline = $row['news_tagline']; $news_date = date('dS F Y', strtotime($row['news_date'])); $news_time = date('H:i', strtotime($row['news_date'])); $news_image = $row['news_image']; if($news_type == 'PDF'){ $news_text = $row['news_text']; ?>
From:
From:
Any ideas as to why this might be happening? I've tried different PHP versions and such but I don't get many options...
Performance settings
memory_limit
128M (Default)
max_execution_time
30 (Default)
max_input_time
60 (Default)
post_max_size
8M (Default)
upload_max_filesize
2M (Default)
opcache.enable
on (Default)
Common settings
include_path
.:/usr/share/php (Default)
session.save_path
/var/lib/php/sessions (Default)
mail.force_extra_parameters
open_basedir
{WEBSPACEROOT}{/}{:}{TMP}{/}
error_reporting
E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED
display_errors
off (Default)
log_errors
on (Default)
allow_url_fopen
on (Default)
file_uploads
on (Default)
short_open_tag
off (Default)

A: As suggested in my comment, the issue was that short open tags (<?) were disabled / not interpreted. Changing them to <?php solved the issue.


text:
Q: Displaying a hidden div content using JQuery I am having two div tags. While clicking on the first div tag, an AJAX call takes place and the second div tag replaces the first one.
I am having the Back button in second div tag. While clicking on the Back button, I should be able to see the first div tag replaced by second div tag.
Here is my Razor code:

    View

    Back

Here is my AJAX call:
@using (Ajax.BeginForm("Detail", "Places", new AjaxOptions
    {
        HttpMethod = "POST",
        InsertionMode = InsertionMode.Replace,
        UpdateTargetId = "tag1",
    }, new { name = "PlaceDetailsForm", id = "PlaceDetailsForm" }))
{
    <input type="hidden" name="locationId" id="locationId" />
    <input type="hidden" name="distance" id="distance" />
}

And here is my JQuery:
function show_placedetail() {
    $('#tag1').hide();
    $('#PlaceDetailsForm').submit();
}

function show_placelist() {
    $('#tag2').hide();
    $('#tag1').show();
}

I have checked the .html() content of the first div tag is emptied after the AJAX call.
What should I do in order to display a div tag which had been replaced by another div tag during AJAX? Do I need to call another AJAX call to display the first div content?
Kindly advice.
Thanks in advance.

A: I got fixed my mistake.
Actually, I am replacing my first div by AJAX. Hence, it wont be available if I try to show it again. So I created a parent tag and put both of the tags within it. And I changes my InsertionMode option to InsertAfter.
Now it is working fine.
Here is my updated Razor code:

      View

      Back

And my updated AJAX code:
@using (Ajax.BeginForm("Detail", "Places", new AjaxOptions
    {
        HttpMethod = "POST",
        InsertionMode = InsertionMode.InsertAfter,
        UpdateTargetId = "parent",
    }, new { name = "PlaceDetailsForm", id = "PlaceDetailsForm" }))
{
    <input type="hidden" name="locationId" id="locationId" />
    <input type="hidden" name="distance" id="distance" />
}


text:
Q: How do I parse JSON into an int? I have Parsed some JSON data and its working fine as long as I store it in String variables.
My problem is that I need the ID in an int varibable and not in String.
i have tried to make a cast int id = (int) jsonObj.get("");
But it gives an error message that I cannot convert an object to an int.
So I tried to convert by using:
String id = (String) jsonObj.get("id");
int value = Integer.parseInt(id);

But also that is not working. What is wrong. How is JSON working with int?
My strings are working just fine its only when I try to make them as an int I get problems.
Here is my code :
public void parseJsonData() throws ParseException {

        JSONParser parser = new JSONParser();
        Object obj = parser.parse(jsonData);
        JSONObject topObject = (JSONObject) obj;
        JSONObject locationList = (JSONObject) topObject.get("LocationList");
        JSONArray array = (JSONArray) locationList.get("StopLocation");
        Iterator<JSONObject> iterator = array.iterator();

        while (iterator.hasNext()) {

            JSONObject jsonObj = (JSONObject) iterator.next();
            String name  =(String) jsonObj.get("name");
            String id = (String) jsonObj.get("id");
            Planner.getPlanner().setLocationName(name);
            Planner.getPlanner().setArrayID(id);

        }

    }

A: Its very simple.
Example JSON:
{
   "value":1
}

int z = jsonObject.getInt("value");

A: Non of them worked for me.
I did this and it worked:
To encode as a json:
JSONObject obj = new JSONObject();
obj.put("productId", 100);

To decode:
long temp = (Long) obj.get("productId");

A: You may use parseInt :
int id = Integer.parseInt(jsonObj.get("id"));

or better and more directly the getInt method :
int id = jsonObj.getInt("id");

A: It depends on the property type that you are parsing.
If the json property is a number (e.g. 5) you can cast to Long directly, so you could do:
(long) jsonObj.get("id") // with id = 5, cast `5` to long

After getting the long,you could cast again to int, resulting in:
(int) (long) jsonObj.get("id")

If the json property is a number with quotes (e.g. "5"), is is considered a string, and you need to do something similar to Integer.parseInt() or Long.parseLong();
Integer.parseInt(jsonObj.get("id")) // with id = "5", convert "5" to Long

The only issue is, if you sometimes receive id's a string or as a number (you cant predict your client's format or it does it interchangeably), you might get an exception, especially if you use parseInt/Long on a null json object.
If not using Java Generics, the best way to deal with these runtime exceptions that I use is:
if(jsonObj.get("id") == null) {
   // do something here
}

int id;
try{
    id = Integer.parseInt(jsonObj.get("id").toString());
} catch(NumberFormatException e) {
  // handle here
}

You could also remove that first if and add the exception to the catch.
Hope this helps.

A: I use a combination of json.get() and instanceof to read in values that might be either integers or integer strings.
These three test cases illustrate:
int val;
Object obj;
JSONObject json = new JSONObject();
json.put("number", 1);
json.put("string", "10");
json.put("other", "tree");

obj = json.get("number");
val = (obj instanceof Integer) ? (int) obj : (int) Integer.parseInt((String) obj);
System.out.println(val);

obj = json.get("string");
val = (obj instanceof Integer) ? (int) obj : (int) Integer.parseInt((String) obj);
System.out.println(val);

try {
    obj = json.get("other");
    val = (obj instanceof Integer) ? (int) obj : (int) Integer.parseInt((String) obj);
} catch (Exception e) {
    // throws exception
}

A: The question is kind of old, but I get a good result creating a function to convert an object in a Json string from a string variable to an integer
function getInt(arr, prop) {
    var int;
    for (var i=0 ; i<arr.length ; i++) {
        int = parseInt(arr[i][prop])
            arr[i][prop] = int;
    }
    return arr;
  }

the function just go thru the array and return all elements of the object of your selection as an integer

A: For JsonNode use:Integer.parseInt(String.valueOf())


text:
Q: SpriteKit - Stop Objects Piling-Up I'm wondering what code I should add to stop rocks from piling up at the bottom of the screen and have them removed when resting (not moving).
Here is the code that creates the rocks. If you need any other code please let me know :)
-(void)addRock {

    SKSpriteNode *rock = [SKSpriteNode spriteNodeWithImageNamed:@"asteroid"];
    rock.position = CGPointMake ([self makeRandomXWBetween:0 and:self.size.width], self.size.height);
    rock.name = @"rock";
    rock.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:rock.size];
    rock.physicsBody.usesPreciseCollisionDetection = YES;
    rock.physicsBody.categoryBitMask = rockCategory;
    rock.physicsBody.contactTestBitMask = dodgerCategory;
    [self addChild:rock];
}

-(void)makeRocks {

    SKAction *makeRocks = [SKAction sequence: @[
                                                [SKAction performSelector:@selector(addRock) onTarget:self],
                                                [SKAction waitForDuration:0.3 withRange:0.0]
                                                ]];
    [self runAction: [SKAction repeatActionForever:makeRocks]];
}

Thanks in advance for any help!
Best Regards,
Louis.

A: Since you want the rocks to be removed when they are resting, they can be removed when their velocity property is zero.
You can check so in the -update method.
-(void)update:(CFTimeInterval)currentTime {

    [self enumerateChildNodesWithName:@"rock" usingBlock:^(SKNode *node, BOOL *stop){

        if ((node.physicsBody.velocity.dx == 0) && (node.physicsBody.velocity.dy == 0) && (node.position.y < self.size.height)) {
            [node removeFromParent];
        }
    }];
}


text:
Q: MPI_Bcast gets seg. fault with Signal code: Address not mapped (1) I'm trying to broadcast an array of words. More precisely, I'm trying to bcast a dictionary (an hash_map {string,int} ) but of course I cannot do it the easy way. So I'm storing all keys and all values in two separate arrays (cfKeys and cfValues). MAX_CF_LENGTH is the maximum number of characters of a key.
Here's a code snippet:
char **cfKeys; // this contains all cf keys in the dataset
int *cfValues; // this contains all cf values in the dataset
int num_cf;

[...some preprocessing...]
if(myrank == 0) num_cf = cfDictionary.size(); // this is an hardcoded dictionary in a separate header file

MPI_Bcast(&num_cf, 1, MPI_INT, 0, MPI_COMM_WORLD);
cfValues = new int[num_cf];
cfKeys = new char *[num_cf];
for (int i = 0; i < num_cf; i++)
    cfKeys[i] = new char[MAX_CF_LENGTH];

if (myrank == 0)
{
    int i = 0;
    for (auto cf : cfDictionary)
    {
        strncpy(cfKeys[i], cf.first.c_str(), MAX_CF_LENGTH);
        cfValues[i] = cf.second;
        i++;
    }
}

MPI_Bcast(cfValues, num_cf, MPI_INT, 0, MPI_COMM_WORLD); // no problem here
MPI_Bcast(cfKeys, num_cf * MAX_CF_LENGTH, MPI_CHAR, 0, MPI_COMM_WORLD); // seg. fault here

Besides the error, if you think there's a better way to implement this dictonary transfer please do not hesitate to advise me :) Comment if you need more infos/code snippets. Thanks in advance.


text:
Q: Chrome Extension - Devtools - invoke element selector programatically I want to invoke the "Element selector" to be invoked from dev-tools js or background js. I checked the chrome api documentation and could not find a direct .

I referred to this solution. It is launching an inspect session with the supplied argument ex.

inspect(document.body)

I want to allow user select the element. I want to reuse the element selection facility given by devtools inspect element
Could you please point me to an api or any set of statements by which I can achieve the same?


text:
Q: SVG inside input overlaps pasted long text We have a custom text input component with a limit of 400 characters. When user pastes more than 400 characters we show an svg icon indicating the error inside the input. And we have a problem here in Chrome. It shows the svg icon above the text cursor and overlaps the last three characters of text (so if we had "abcde" at the end then we can see only "ab" on the screenshot below). The issue happens only on Google Chrome. It's fine on Firefox. I've fixed this behavior for the "Ctrl+v" hotkey (by calling onChange twice on input) but I cannot find now what can I do with pasting using context menu.
I need to make the cursor at the end of string to appear before the icon.


text:
Q: Sorting "human readable" file sizes How do we sort by using any Linux core utility (scripts) numerical value of output of du such as:
136K    foo.bar/feed
140K    foo.bar/buy-electronic-components
32K foo.bar/cdn-cgi
88K foo.bar/what-is-ground
344K    foo.bar/ldr-circuit-diagram
64K foo.bar/what-is-an-led
100K    foo.bar/types-of-resistors
516K    foo.bar/wp-includes
60K  foo.bar/author
56K  foo.bar/diy-pcb
112K    foo.bar/how-to-learn-electronics
376K    foo.bar/category
76K  foo.bar/electronic-schematics
84K  foo.bar/how-to-bar
88K foo.bar/bar-tools
20K foo.bar/comments
88K foo.bar/right-bar-temperature
48K foo.bar/contact
44K foo.bar/products
80K foo.bar/types-of-bar
3M foo.bar/
3M total

if in descending way to be:
3M foo.bar/
3M total
516K    foo.bar/wp-includes
376K    foo.bar/category
344K    foo.bar/ldr-circuit-diagram
140K    foo.bar/buy-electronic-components
...

Thank you much

A: sort has an option --human-numeric-sort and --sort=human-numeric to do exactly this.


text:
Q: improve growing cell array in matlab I would like to know how to efficiently run this part of my progam. Basically for a background of what I aim to do, I want to cluster points. There are around 10,000 points. These points have computed "forces" between them that is stored in matrix F. So the force between point 1 and point 2 is F(1,2). I would then like to "cluster points" with sufficient F acting on them (Force setting/threshold), that is 2 points with sufficient F between them belong to the same cluster.
I have a code as seen below. A cell array CLUSTER was made to contain the cluster assignments. So CLUSTER{i} is the cell containing the ith cluster with clustered points in it.
However, for some F settings, the implementation takes forever. I have read about preallocation and parfor (parfor can't be done since there is dependency in iterations). But does preallocation of cell arrays mean that individual cells are not preallocated with memory? Is there any other way around this? Profiling tells me that ismember has the biggest share in computing. I hope to improve the code with your suggestions. Thanks a lot!
CLUSTER = {};

for fi = 1:srow
    for fj = 1:scol
        if fj > fi % to eliminate redundancy, diagonal mirror elements of F !check on this
            if F(fi,fj) >= 2000 % Force setting
                if( (~ismember(1,cellfun(@(x)ismember(fi,x),CLUSTER))) && (~ismember(1,cellfun(@(x)ismember(fj,x),CLUSTER))) ) % fi & fj are not in CLUSTER
                    CLUSTER{end+1} = [fi fj];
                    end
                %%if( (ismember(1,cellfun(@(x)ismember(fi,x),CLUSTER))) && (ismember(1,cellfun(@(x)ismember(fj,x),CLUSTER))) ) % fi & fj are in CLUSTER
                    %do nothing since lfi and fj are in CLUSTER
                %%end
                if( (ismember(1,cellfun(@(x)ismember(fi,x),CLUSTER))) && (~ismember(1,cellfun(@(x)ismember(fj,x),CLUSTER))) ) % fi in CLUSTER, fj not in CLUSTER
                    c = find(cellfun(@(x)ismember(fi,x),CLUSTER));
                    CLUSTER{c} = [CLUSTER{c} fj];
                end
                if( (~ismember(1,cellfun(@(x)ismember(fi,x),CLUSTER))) && (ismember(1,cellfun(@(x)ismember(fj,x),CLUSTER))) ) % fi not in CLUSTER, fj in CLUSTER
                    c = find(cellfun(@(x)ismember(fj,x),CLUSTER));
                    CLUSTER{c} = [CLUSTER{c} fi];
                end
            end
        end
    end
end

A: I am not sure if this is the best way, but my thought is that this should be possible to do by some kind of update algorithm. Begin with looking at node 1. Find all the nodes clustered with node 1 as,
clusteredNbr = find(F(1,:)>=2000); (a)

This will give you the node number for all nodes that are clustered with node 1. Then find all nodes that is clustered with clusteredNbr, by repeting (a) with for all new nodes. These nodes can then be added to the same vector as the old nodes in clusteredNbr. You may have some duplicates here, but they can be removed later. Then check for new unique nodes in this resulting vector. If there are any, repeat (a) for these. Continue until you find all nodes in the first cluster. Then you know that any of the nodes in the first cluster is not clustered with the others.
Repeat this process for the next cluster and so on. The gain with this is that you use find instead of ismember and that the operation can be vectorized, which allows you to run only one for loop.


text:
Q: XPath: как получить содержимое только тех узлов, которые находятся внутри родителей с нужным названием? Разбираю html с такой структурой:

Хочу с помощью XPath забрать одним запросом все ссылки за 2020, 2019 года, а за 2021, допустим, не брать.. Как мне получить ссылки из всех узлов за нужные года...? Пробовал так:
$document = new DOMDocument();
    $document->loadHTML($html);

    $xpath = new DOMXpath($document);

$elements = $xpath->query('//div[contains(@class,"versions")]');

и так:
$document = new DOMDocument();
        $document->loadHTML($html);

        $xpath = new DOMXpath($document);

$experiments = $xpath->query('//div[contains(@data-versions-items,"2020 г.")]');

За 2020 год дает информацию, но мне хотелось бы за несколько лет и обойтись без подстановки нескольких возможных вариантов в цикле, потому что тогда будет несколько xpath зарпосов, а это избыточно..
Можно ли добиться нужного результата и как? Я уже не знаю, что попробовать..

A: Для XPath 2.0 и новее.
Основано на идее последовательностей (sequences).
XPath 2.0 или новее
/div/div[substring(@data-versions-items,1,4)=("2019","2020")]

XPath 1.0
/div/div[substring(@data-versions-items,1,4)="2019" or substring(@data-versions-items,1,4)="2020"]


text:
Q: How to query firebase database by specific value without knowing the parent key
I want to find key (ex: -KYNc6XTtavDtsC-VoqIb) where email is amitabh@gmail.com
I have tried many code, but not working, I am getting full list of data.
this is my code :
database = FirebaseDatabase.getInstance();
myRef = database.getReference("members");
myRef.orderByChild("email").startAt(emailId).endAt(emailId);

this is what I am getting.
DataSnapshot{
  key=members,
  value={
    -KYNYiw5B1d8Brdz5KdR={
      lastname=zxvzxvfsdf44,
      email=fasdfds@rr44,
      firstname=fdafaf44
    },
    -KYNYdX_gZ0tU-AbI1Ab={
      lastname=zxvzxvfsdf,
      email=fasdfds@rr,
      firstname=fdafaf
    },
    -KYNd02QZptRktmR02IH={
      lastname=dfasf,
      email=you@bo.com,
      firstname=amita
    },
    -KYNdlMM4zzlUT9FdSdu={
      lastname=99dfasfs,
      email=99@bos.com,
      firstname=99
    },
    -KYNdBPMqxgSzm1ai92B={
      lastname=dfasfs,
      email=you@bos.com,
      firstname=amitas
    },
    -KYNlYF4OzzCCewJuatt={
      lastname=go2o,
      email=go@to.to,
      firstname=go
    },
    -KYNo7ZvLQeCGm97yUvf={
      lastname=bamio,
      email=samio@ss.com,
      firstname=amio
    },
    -KYNdBRAipnlTYCCUwz6={
      lastname=dfasfs,
      email=you@bos.com,
      firstname=amitas
    },
    -KYNc6XTtavDtsC-VoqI={
      lastname=Sarkar,
      email=amitabh@gmail.com,
      firstname=amitabh
    },
    -KYNcHdlZjUlNSsjKlyW={
      lastname=gjaldga,
      email=ee@ee.com,
      firstname=ami
    }
  }
}

A: I found the solution :
myRef.orderByChild("email").startAt(emailId).endAt(emailId).addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String s) {

        Log.e("onChildAdded", dataSnapshot.toString());
    }
});


text:
Q: How to identify invalid dates in postgres table field? I have a table in PostgreSQL that has two date fields ( start and end ). There are many invalid dates both date fields like 0988-08-11,4987-09-11 etc.. Is there a simple query to identify them? The data type of the field is DATE. Thanks in advance.

A: Values in a date column ARE valid per definition. The year 0988 = 988 is a valid historic date as well as the year 4987 which is far in the future.
To filter out dates which are too historic or too far in the future you simply make this query:
SELECT
    date_col
FROM
    table
WHERE
       date_col < /* <MINIMUM DATE> */
    OR date_col > /* <MAXIMUM DATE> */

For date ranges (your minimum and maximum date) you could use the daterange functionality:

*

*https://www.postgresql.org/docs/current/static/rangetypes.html

*https://www.postgresql.org/docs/current/static/functions-range.html
Example table:
start_date    end_date
2015-01-01    2017-01-01   -- valid
 200-01-01     900-01-01   -- completely too early
3000-01-01    4000-01-01   -- completely too late
0200-01-01    2000-01-01   -- begin too early
2000-01-01    4000-01-01   -- end too late
 200-01-01    4000-01-01   -- begin too early, end too late

Query:
SELECT
    start_date,
    end_date
FROM
    dates
WHERE
    daterange('1900-01-01', '2100-01-01') @> daterange(start_date, end_date)

Result:
start_date    end_date
2015-01-01    2017-01-01

demo:db<>fiddle

A: Those are valid dates, but if you have business rules that state they are not valid for your purpose, you can delete them based on those rules:
For example, if you don't want any dates prior to 1900 or after 2999, this statement would delete the records with those dates:
DELETE FROM mytable
WHERE
    start_date < '1900-01-01'::DATE OR
    start_date >= '2999-01-01'::DATE OR
    end_date < '1900-01-01'::DATE OR
    end_date >= '2999-01-01'::DATE;

If you want to replace the dates with the lowest/highest acceptable dates instead of deleting the entire record, you could do something like this:
UPDATE mytable
SET
    start_date = least('2999-01-01'::DATE, greatest('1900-01-01'::DATE, start_date)),
    end_date = least('2999-01-01'::DATE, greatest('1900-01-01'::DATE, end_date))
WHERE
    start_date < '1900-01-01'::DATE OR
    start_date >= '2999-01-01'::DATE OR
    end_date < '1900-01-01'::DATE OR
    end_date >= '2999-01-01'::DATE;