text:
Q: Can you put a magnetic ball into a hollow magnetic sphere? if all magnets have to have two poles(one north one south), is it possible to construct a hollow sphere where the inside face of the sphere was one pole, and the outside face another pole?
is it also possible to make a magnetic sphere (not hollow) where the outside face is one pole?
If both of these ideas are possible, what would happen if we put a small sphere (non hollow) inside of a hollow sphere, where the polarity of the hollower sphere's inside face was the same as the polarity of the smaller ball? the ball would levitate theoretically, but what if the magnets were so strong that they pushed the ball more and more into the center until it had nowhere else to move?

A: The answer is that you can build such a sphere.
Assuming the sphere is built perfectly, then the magnetic field will cancel everywhere.

A: Conventional magnetic fields are observed to be loops. Where a magnetic field exists, it is impossible to carve out a volume of space such that more magnetic lines enter that region, than leave.  Although a bar magnet has identifiable north and south poles, the imaginary lines of the field actually continue inside the magnet, forming complete circuits.
If you had a sphere which was all north all over, there would be no way for the lines emanating from that pole to meet with the interior south pole. That sphere would effectively be a magnetic monopole, as far as what we can tell from its exterior. If we contain that sphere in a region of space, that region of space has magnetic field lines emanating all over, without any such lines re-entering it.
http://en.wikipedia.org/wiki/Magnetic_monopole
If the search for magnetic monopoles ever turns up something, then it will confirm that such a sphere can exist.
http://en.wikipedia.org/wiki/Magnetic_monopole#Searches_for_magnetic_monopoles
Now of course could have a sphere such that most of its surface is a magnetic pole, like north, but such that it has some small region (or regions) where the magnetic lines emanating from this north re-enter into the sphere.  These regions would then be de-facto south poles, though, making this different from a sphere which is north all over.  If you make an object by tiling a sphere with magnets, I suspect you will get this kind of animal. The inner field lines will "escape" somewhere.

A: For the most part, See Above.
All I have to add is that from a simple geometric perspective, you would be forced to leave gaps in between magnets on the outside of the sphere. Magnetic poles can be thought of as straight lines, and so the number of ends on the inside of your sphere would have to equal the number of ends on the outside. The outside of a hollow sphere has more surface area of course, and so you would always have gaps in between. These would be the de-facto south poles, as noted above.

A: Possibly by using a nonmagnetic sphere as your center and pressing a neodynium cobalt alloy around it sealing the outside sphere shut. I have thought about it for a bit but have no opportunity to attempt such thing.

A: I believe if you start with a flat magnet then press it into a semi sphere, I say semi because you want a hole in it, the hole you will role in on itself to form an inner lip creating a third semi sphere effect.  As long as you have that hole I figure it will weaken the inner pole enough to give you a mono pole effect.  The effect would be sufficient enough to make a mono magnet wheel to spin a generator.


text:
Q: How to lag row number in R I have three columns and in fourth column i want a lag of third column. How to do this in R
For example
uid       timestamp    operation
 1         24-04-12    logged-in
 2         25-06-13    view content
 1         31-05-10    delete

But i want to use lag function as we do in SAS and want output as below
uid        timestamp    operation     lag
 1         24-04-12     logged-in
 2         25-06-13     view content  logged-in
 3         31-05-10     delete        view content

I have lag function using zoo package ,but it is not happening , how to do this in R??
Any guidance will be much appreciated.

A: When using functions specific to the zoo package (e.g. ?lag.zoo), you need to make sure the data you are operating on is a zoo object:
operation <- c("logged-in","view current", "delete")
lag(zoo(operation),-1,na.pad=TRUE)
#         1            2            3
#      <NA>    logged-in view current

lag(zoo(operation),1,na.pad=TRUE)
#           1            2            3
#view current       delete         <NA>

Otherwise, using base R, head (and tail) can get you there:
# match the 1 and -1 to how big you want your lag:
c(rep(NA,1),head(operation,-1))
#[1] NA             "logged-in"    "view current"

c(tail(operation,-1),rep(NA,1))
#[1] "view current" "delete"       NA

redpajama_set_name: RedPajamaStackExchange


text:
Q: Need a collection view remaining the same in landscape orientation as it is in the portrait enter image description hereI'm currently working on a project in my class for App Game Development. So I'm basically using an Connect 4 app, and implementing the code to make an app where you can play this classic version along with two extra versions. However, I am struggling with some auto layout issues. I am required to make an app usable on iPad and iPhones. My app runs perfectly on the iPhone because I only am required to use portrait mode due to the small screen size. I have to use portrait and Landscape for the iPad however. I was wondering if you knew how to make it playable on landscape and portrait orientation for the iPad. The game board is all messed up whenever I switch to landscape mode, but in portrait it is perfectly fine.This is my final project of my senior year and it is due by Friday. Could you please help me out with this issue?

A: Put a width constraint on your collection view to make it narrower.
If you are using leading and trailing constraints, then use their constants to add side padding so the view is narrower. You can change the constant based on the device and orientation.
Neither of these are really the "right way", but they are something you can get working quickly. Unfortunately, the right way is probably not using UIKit and collection view for games. It's possible, but they aren't made for that and therefore sometimes don't act in the way you expect.


text:
Q: How to find if I have the same domain name but using a with different extension I have a problem that I was thinking it was going to be simple to solve but I cannot figure it out.
I have a database full of URLs like:

*

*http://www.domain.com/page.html

*http://domain.com/page.html

*http://sub.domain.co.in/page.html

*http://sub.sub.domain.it/page.html

*http://other.domain.net/page.html

*http://ok.domain.com/ok.html

*etc...

now, given http://www.domain.co.uk/page.html
I need to figure out if such page it is already in the database assuming that the different extension does not change the content.
The final goal is simple, I am building a site where people can submit pages, those pages needs to be unique to avoid duplication of content.  Users are submitting google maps .com and google maps .co.in creating a duplication of the same page, what I need  to do is to figure out if the page submitted is already been submitted with a different domain extension.  I will also do a check on title and content if found, just in case the domain extension DOES change the content ( like www.wyska.net and www.wyska.com )
in other words:

*

*maps.google.com === maps.google.it === maps.google.co.in === maps.google.co.uk .....

only if content is "similar" (I will have to work on figure out what "similar" means too)
so far I have (but it doesn't work):
<?php
$url = 'http://www.domain.com/text.html';  //works with this domain
$parse = parse_url($url);
var_dump($parse);
var_dump(pathinfo($parse['host']));

$url = 'http://sub.sub.domain.co.in/text.html';  //does not work with this domain
$parse = parse_url($url);
var_dump($parse);
var_dump(pathinfo($parse['host']));
?>

if necessary I can even break the domain in different parts and store those parts instead than the full domain.
I as thinking to do a search replace on the domain extension, but I haven't been able to find a full list of domain extension to use.  Something like: if it ends with any of those strings, then remove that part from the domain


text:
Q: Parse PFAnonymousUtils logInWithBlock not returning completion block when no internet connection I use Parse SDK 1.6.2 in my app. I'm trying to create an anonymous user using:
[PFAnonymousUtils logInWithBlock:^(PFUser *user, NSError *error) {
    if (error) {
      NSLog(@"Anonymous login failed.");
    } else {
      NSLog(@"Anonymous user logged in.");
    }
}];

If there is internet everything works fine, the completion block gets called and one of the NSLogs will be called. HOWEVER if there is no internet, the completion block NEVER gets called, the debugger will break somewhere in the Parse library but not crash. The console outputs "+[PFObject parseClassName]: unrecognized selector sent to class" but doesn't crash and instead just never calls the completion block and continues running. I think a workaround would be to check internet connection first but wondering if I'm missing something. Hector Ramos are you out there?

A: There is a difference between users created by [PFAnonymousUtils logInWithBlock...] and [PFUser enableAutomaticUser]. If you need unconditionally created anonymous user (including "no internet" conditions), use the second method. You can read details here: http://blog.parse.com/2012/04/02/protect-user-data-with-new-parse-features/


text:
Q: continuous integration - build separated projects or build all in one? I'm working on a project that will have these applications:
- backend api   (nodejs)
- ios app       (objective-c)
- android app   (java)
- web site      (php)
- admin site    (php)
- client site   (php)

My question is about versioning and managing all this projects.
I'm thinking about two options:
1) build each app saparately

*

*Harder to test apps integrations

*If I change something in one app, I need to be careful with all other apps

*I need merge all apps changelogs to a single document

2) put all apps into one single build

*

*This seems good to generate a single changelog

*Maybe write tests to apps integrations?

--
So, what is some good practices for this case? Maybe option 2?

A: My vote goes to option 2. Much easier to 'carry' development across all its phases with a monolithic approach:

*

*simpler integration - all pieces are already integrated, everyone working on any piece of the overall project is on the same page, not in their own sandbox (true continuous integration, if you want) - very important if you also plan to use agile methodologies

*integration testing no longer has to be a separate activity, you can do it
part of the regular CI process since you can test all pieces together (possibly with a single combo testbed instead of dedicated testbeds for each piece - lower costs)

*simpler coherent/consistent source code control (even if the pieces have their own
repos, they can be managed together in a monolithic style like I
suggested in this Q&A:
Build dependencies and local builds with continuous integration

*possibly faster overall builds (different builds can use idle cycles
in other builds which is harder to orchestrate when they are
independent - they could potentially be better "packed", leading to
cost reduction on build resources)

A: I would absolutely not go with option 2. Continuous integration was termed by Grady Booch back in the early 90's. Today, they want to use the term Continuous Delivery. I say we should have used Continuous Improvement the whole time. Anyhow, you want to be able to deliver, deploy, put into production an application, a project, "a" deliverable. You absolutely do not want to mix applications. You could have the need to deploy one application to production and something is wrong with another application. Or you just did a very quick fix to a single application and you want to take it through the process to delivery today. I would not choose option 2 for these reasons.


text:
Q: How do I move data from from an api to statehook? I've run into this issue more than once and I could use some advice.  I have an api call.  I want to display the results in another component that is a child of the form.  I've worked out a component that can map state to jsx but I'm having trouble understanding the part where I actually use the new Array from my API response. I have a function that makes this call from a seperate module.
const data = []
const search = (values, loadData) => {

fetch(`/search`, {
    method: 'POST',
    headers: headers,
    body: values
})
    .then(checkStatus)
    .then(parseJSON)
    .then(res => {
               let items = res.response.docs

                for (let i = 0; i < items.length; i++) {
                    console.log(items[i].start)

                    data.push({
                        headline: items[i].title,
                        web_url: items[i].web_url,
                        snippet: items[i].snippet

                    })
                }
                console.log(data)
            }

          )
}
const fetcher ={search, otherthings}
export default fetcher

I want to have a set of methods that I can call that keeps things modular,  But I am kind of hazy when it comes to mapping the api response to state.

A: To display the results in a child of the form you want to do something like this where the search results are set in the form component state and passed down to the component which displays them.
I've simplified the request function to remove a lot of code which just changes a single property name of the docs list and mocked it for the example.
import React, { useState } from "react";

// our search function which will return a promise that resolves to docs
const search = values =>
  // fetch(`/search`, {
  //   method: 'POST',
  //   headers: headers,
  //   body: values
  // })
  //   .then(checkStatus)
  //   .then(parseJSON)
  //   .then(res => res.response.docs);
  Promise.resolve([{ id: 1, name: "doc 1" }, { id: 2, name: "doc 2" }])

// our component to render the results
const Results = ({ docs }) => docs.map(doc =>
{doc.name}
);

// our Search component with the form that passes results to it's child
const Search = () => {
  const [results, setResults] = useState([]);

  // call setResults with the value returned by `search`
  const doSearch = e => search({ query: e.currentTarget.value }).then(setResults);

  return (

      <form>
        <input onChange={doSearch} />
      </form>

        <Results docs={results} />

  )
}

see working example here.. https://codesandbox.io/s/5zrx67k94
Just type a char in the input to trigger the request.
To display the results in any other component you'd want to use either a central data store such as Redux, or use React Context. For the latter you could move the state that holds the results, and the search function into a Context Component and export the function and results, use it from your form to make the call and set the state, and use it from your other component to access the state. You'd also need to render the context provider in the component tree above both components.
Maybe start with the simple solution above for now.


text:
Q: SDL load bmp problems I've been following the lazy foo SDL tutorials and have already hit a road block in lesson 2. My code is exactly what he wants, yet i keep getting the same errors whenever i'm trying to blit the following images:
Unhandled exception at 0x68126030 in SDLtest.exe: 0xC0000005: Access violation reading location 0x00000004.
Here is the following code that is constantly producing such errors:
#include "SDL.h"
#include <string>

const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
const int SCREEN_BPP = 32;

SDL_Surface *message = NULL;
SDL_Surface *background = NULL;
SDL_Surface *screen = NULL;

SDL_Surface *load_image(std::string filename)
{
    SDL_Surface* loadedImage = NULL;
    SDL_Surface* optimizedImage = NULL;
    //load the image
    loadedImage = SDL_LoadBMP( filename.c_str() );

    if (loadedImage != NULL)
    {
        optimizedImage = SDL_DisplayFormat(loadedImage);
        SDL_FreeSurface(loadedImage);
    }
    return optimizedImage;
}

void apply_surface(int x, int y, SDL_Surface* source, SDL_Surface* destination)
{
    SDL_Rect offset;

    offset.x = x;
    offset.y = y;
    //blit the surface
    SDL_BlitSurface(source, NULL, destination, &offset);
}

int main(int argc, char* args[])
{
    if (SDL_Init(SDL_INIT_EVERYTHING) == -1)
    {
        return 1;
    }

    screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE);

    if (screen = NULL)
    {
        return 1;
    }

    SDL_WM_SetCaption("Hello World",NULL);
    //loading images
    message = load_image("hello.bmp");
    background = load_image("background.bmp");
    //image blitting
    apply_surface(0,0,background,screen);
    apply_surface(320,0,background,screen);
    apply_surface(0,240,background,screen);
    apply_surface(320,240,background,screen);
    apply_surface(180,140,message,screen);

    if (SDL_Flip(screen) == -1)
    {
        return 1;
    }

    SDL_Delay(2000);

    SDL_FreeSurface(message);
    SDL_FreeSurface(background);

    SDL_Quit();
    return 0;
}

A: The error Access violation reading location 0x00000004 is saying that you are dereferencing a pointer whose value is 4, instead of something real.
The easiest way to track this down is to run under a debugger, and see what line causes the problem.  Then you can backtrack to figure out where the pointer's value got messed up.  Then you may find an error like Bert pointed out.

A: Replace the line
if(screen = NULL)

with
if(screen == NULL)


text:
Q: MYSQL - How to count the number of occurrences per month I have a table with a varchar column and a datetime column that I want to get some counts from:
CREATE TABLE `appointment` (
  `appointmentId` int(10) NOT NULL AUTO_INCREMENT,
  `cid` int(10) NOT NULL,
  `title` varchar(255) NOT NULL,
  `description` text NOT NULL,
  `location` text NOT NULL,
  `contact` text NOT NULL,
  `start` datetime NOT NULL,
  PRIMARY KEY (`appointmentId`));

Some values:
INSERT INTO `appointment` (`cid`, `title`, `description`, `location`, `contact`, `start`)
VALUES
('1', 'text1', ' ', ' ', ' ', '2017-07-21 16:00'),
('2', 'text1', ' ', ' ', ' ', '2017-08-21 16:00'),
('1', 'text1', ' ', ' ', ' ', '2017-09-21 16:00'),
('1', 'text1', ' ', ' ', ' ', '2017-09-21 16:00'),
('3', 'text2', ' ', ' ', ' ', '2017-07-21 16:00'),
('1', 'text3', ' ', ' ', ' ', '2017-07-21 16:00'),
('1', 'text4', ' ', ' ', ' ', '2017-07-21 16:00'),
('5', 'text5', ' ', ' ', ' ', '2017-07-21 16:00'),
('1', 'text1', ' ', ' ', ' ', '2017-07-21 16:00'),
('1', 'text1', ' ', ' ', ' ', '2017-07-21 16:00'),
('1', 'text3', ' ', ' ', ' ', '2017-07-21 16:00');

What I want to accomplish is to get a count of the occurrences of a 'title' on a monthly basis. Something like this:
Month       | title | count
---------------------------
July        | text1  | 3
August      | text1  | 1
September   | text1  | 2
July        | text2  | 1
etc...

I have gotten as far as
SELECT  MONTHNAME(start) AS 'MONTH',
    title AS 'TITLE',
    count(title) AS 'COUNT'
FROM appointment
GROUP BY TITLE

But, that is grouping all of text1 into a total count on the first month of occurrence. So, for the example above it is showing: 'July | text1 | 6'
I've tried several variations on that query, but I'm clearly missing something.
Can someone explain:
a) why is it aggregating all of those into one month?
and b) how to get the query to produce the results I want?

A: Not sure if you tried this or not but you need to group by month like:
SELECT  MONTH(start) AS MONTH,
    title AS TITLE,
    count(title) AS COUNT
FROM appointment
GROUP BY title,MONTH(start);

Plus why do you need quotes after AS ...?

A: You need to group by monthname(Start) as well  so GROUP BY Title, MonthName(start).
The reason why you're seeing July text1 6 is because all of text1 is being put into July, not just july.  Typically any non-aggregated field int eh select should be in the group by.  mySQL extends the group by to not thow an error when a non-aggregated field isn't in the group by; whereas oracle, db2, SQL Server Postgresql and others would all throw an error.  There is a setting which can be disabled in mySQL which would cause your SQL to error since monthname(start) wasn't in the group by.
https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html


text:
Q: What are switch expressions and how are they different from switch statements? As part of Java SE 12, switch expressions were introduced and since Java SE 14, they have been standardized. How are they different from switch statements?

A: Adding to existing answers: yield can also be used with -> and its main purpose is to allow the use of a block when a single expression is not sufficient for a given case:
var test = switch (value) {
    case A -> 1;
    case B -> 2;
    case C -> {
        System.err.println("neither A nor B"); // or some calculation
        yield -1;
    }
}

I would also mention JEP-354 where the switch expression is proposed and described.
Formal specification can be found, as always in the Java Language Specification.

A: The switch statement:
Unlike the if/else if/else statement, a switch statement can have a number of possible execution paths. A switch works with the primitive types, byte, short, char, and int, their respective wrapper types (Byte, Short, Character, and Integer), enumerated types, and the String type1. While an if-else statement is used to test expressions based on ranges of values or conditions, a switch statement is used to test expressions based only on a single value.
Demo
enum PaymentStatus {
    UNPAID, PARTPAID, PAID, DISPUTED, UNKNOWN;
}

public class Main {
    public static void main(String[] args) {
        String message = "";
        PaymentStatus paymentStatus = PaymentStatus.PARTPAID;

        switch (paymentStatus) {
        case UNPAID:
            message = "The order has not been paid yet. Please make the minimum/full amount to procced.";
            break;
        case PARTPAID:
            message = "The order is partially paid. Some features will not be available. Please check the brochure for details.";
            break;
        case PAID:
            message = "The order is fully paid. Please choose the desired items from the menu.";
            break;
        default:
            throw new IllegalStateException("Invalid payment status: " + paymentStatus);
        }
        System.out.println(message);
    }
}

Output:
The order is partially paid. Some features will not be available. Please check the brochure for details.

The switch expression:
The switch expression was introduced with Java SE 12. However, it remained as a Preview feature in Java SE 12 and 13 and finally got standardized with Java SE 14. Like any expression, switch expressions evaluate to a single value, and can be used in statements. It also introduced "arrow case" labels eliminating the need for break statements to prevent fall through. As of Java SE 15, there is no change in the supported data types (mentioned in the switch statement section above).
Demo
enum PaymentStatus {
    UNPAID, PARTPAID, PAID, DISPUTED, UNKNOWN;
}

public class Main {
    public static void main(String[] args) {
        PaymentStatus paymentStatus = PaymentStatus.PARTPAID;

        String message = switch (paymentStatus) {
        case UNPAID -> "The order has not been paid yet. Please make the minimum/full amount to procced.";
        case PARTPAID -> "The order is partially paid. Some features will not be available. Please check the brochure for details.";
        case PAID -> "The order is fully paid. Please choose the desired items from the menu.";
        default -> throw new IllegalStateException("Invalid payment status: " + paymentStatus);
        };

        System.out.println(message);
    }
}

Output:
The order is partially paid. Some features will not be available. Please check the brochure for details.

The switch expression with yield:
Since Java SE 13, you can use yield statement, instead of the arrow operator (->), to return a value from a switch expression.
Demo
enum PaymentStatus {
    UNPAID, PARTPAID, PAID, DISPUTED, UNKNOWN;
}

public class Main {
    public static void main(String[] args) {
        PaymentStatus paymentStatus = PaymentStatus.PARTPAID;

        String message = switch (paymentStatus) {
        case UNPAID:
            yield "The order has not been paid yet. Please make the minimum/full amount to procced.";
        case PARTPAID:
            yield "The order is partially paid. Some features will not be available. Please check the brochure for details.";
        case PAID:
            yield "The order is fully paid. Please choose the desired items from the menu.";
        default:
            throw new IllegalStateException("Invalid payment status: " + paymentStatus);
        };

        System.out.println(message);
    }
}

Output:
The order is partially paid. Some features will not be available. Please check the brochure for details.

1 The support for String was added with JDK 7

A: Adding to the above answers one can look at the current "shortfalls" with switch statement which switch expression solve:
Switch Statement:

*

*Issue 1: Accidental Fall-through

*Issue 2: Variable scoping

*Issue 3: No return value

Switch expression:

*

*No fallthrough

*Combined constants

*Blocked scope

*Return yield

EXAMPLE:
Switch Statement:
private static void oldSwitchStatement(String month) {

    int i = 0;
    String quarter = "";

    switch (month) {
        case "JAN":
        case "FEB":
        case "MAR":
            i = i + 1;
            quarter = "Q1";
            // break;
        case "APR":
        case "MAY":
        case "JUN":
            i = i + 2;
            quarter = "Q2";
            // break;
        case "JUL":
        case "AUG":
        case "SEP":
            i = i + 3;
            quarter = "Q3";
            // break;
        case "OCT":
        case "NOV":
        case "DEC":
            i = i + 4;
            quarter = "Q4";
        default:
            System.out.println("Unknown case");
    }

    System.out.println("QUARTER: "+ i + " "+ quarter);
}

Switch Expression
private static String newSwitchExpressionYield(String month) {

    return switch (month) {
        case "JAN", "FEB", "MAR" -> "Q1";
        case "APR", "MAY", "JUN" -> {
            System.out.println("Using yield.");
            yield "Q2";
        }
        case "JUL", "AUG", "SEP" -> "Q3";
        case "OCT", "NOV", "DEC" -> "Q4";
        default -> "Unknown case";
    };
}

To test the above pass oldSwitchStatement("APR"); and newSwitchExpressionYield("APR"); and see the resutls.

A: Nice writeup!  But I might also add the ability to have multiple cases for a single case statement.  The following example is very contrived (there are many better ways to achieve it).  It does a simple frequency count of the vowels, digits, consonants, and other characters in a string.
int count[] = new int[4];

String s = "829s2bi9jskj*&@)(so2i2ksso";

for (char c : s.toCharArray()) {
      int i = switch (c) {
                case  'a', 'e', 'i', 'o', 'u' -> 0;
                case  '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' -> 1;
                case  'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l',
                      'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w',
                      'x', 'y', 'z' -> 2;
                default -> 3;
      };
      count[i]++;
}
System.out.printf("vowels  - %d%n", count[0]);
System.out.printf("digits  - %d%n", count[1]);
System.out.printf("consonants - %d%n", count[2]);
System.out.printf("other   - %d%n", count[3]);

Prints
vowels  - 4
digits  - 7
consonants - 10
other   - 5


text:
Q: Ratio between two sets of numbers? I have two sets of numbers. The first set is 1 to 4. The second set is 0 to 190. What is the calculation to get the proportionate number in the second set if a number in the first set is, for example, 1.2? Math is not my forte!

A: It is $\displaystyle\frac{1.2-1}{4-1}\cdot (190-0) +0$.


text:
Q: Define orderby in url is there a way to set the order of posts via the url?
/orderby/date/order/desc/
i have tried several things with add_rewrite_rule whiteout success.
add_action( 'init', 'wpse13483_init' );
function wpse13483_init()
{
    add_rewrite_rule( 'category/(.+?)/orderby/([^/]+)/order/([^/]+)(/page/?([0-9]{1,}))?/?$', 'index.php?category_name=$matches[1]&paged=$matches[5]&orderby=$matches[2]&order=$matches[3]', 'top' );
}

best, Dan.

A: adding this in the functions.php file works. Just remember to re-save your permalinks & empty the cache a few times to see the changes.
add_action( 'init', 'wpse13483_init' );
function wpse13483_init() {
    add_rewrite_rule( 'category/(.+?)/orderby/([^/]+)?/?$', 'index.php?category_name=$matches[1]&orderby=$matches[2]&order=asc', 'top' );
    add_rewrite_rule( 'category/(.+?)/orderby/([^/]+)/order/([^/]+)?/?$', 'index.php?category_name=$matches[1]&orderby=$matches[2]&order=$matches[3]', 'top' );
//  with pagination;
    add_rewrite_rule( 'category/(.+?)/orderby/([^/]+)/order/([^/]+)/page/([0-9]{1,})?/?$', 'index.php?category_name=$matches[1]&orderby=$matches[2]&order=$matches[3]&paged=$matches[4]', 'top' );
}

A: Creating URL rewrite rules is something entirely different from using URL query variables to sort the Loop query.
I would suggest  tackling the latter, before worrying about the former.
First, you need to register your URL query variables, e.g. (in functions.php):
function mytheme_loop_sort_queryvars( $qvars ) {
    $qvars[] = 'loop_orderby';
    $qvars[] = 'loop_order';
    return $qvars;
}
add_filter( 'query_vars', 'mytheme_loop_sort_queryvars' );

So, now that you've registered your query vars, use them to modify the default Loop query.
First, prepare the query variables, e.g. (in the appropriate template files):
<?php

// Orderby Query Filter
$loop_orderby = '';
// Array of valid 'orderby' parameters, for validating the URL query string
$valid_loop_orderbys = array( 'ID', 'author', 'title', 'date', 'modified', 'parent', 'rand', 'comment_count', 'menu_order' ); //note: excluding 'meta_value', for simplicity
// Do something only if the query var is set
if ( isset( $wp_query->query_vars['loop_orderby'] ) ) {
    // Make sure that only a valid 'orderby' parameter is used
    // If URL string value isn't valid, use default 'date'
    $title_filter = ( in_array( $wp_query->query_vars['loop_orderby'], $valid_loop_orderbys ) ? $wp_query->query_vars['loop_orderby'] : 'date' );
}
// Order Query Filter
$loop_order = '';
// Array of valid 'order' paramters, for validating the URL query string
$valid_loop_orders = array( 'ASC', 'DESC' );
// Do something only if the query var is set
if ( isset( $wp_query->query_vars['loop_order'] ) ) {
    // Make sure that only a valid 'order' parameter is used
    // If URL string value isn't valid, use default 'DESC'
    $title_filter = ( in_array( $wp_query->query_vars['loop_order'], $valid_loop_orders ) ? $wp_query->query_vars['loop_order'] : 'DESC' );
}
?>

Now, use the query variables to modify the loop. First, set up your custom argument array:
<?php
$custom_orderby_query_args = array();

if ( '' != $filter_loop_orderby ) {
    $custom_orderby_query_args['orderby'] = $filter_loop_orderby;
}
if ( '' != $filter_loop_order ) {
    $custom_orderby_query_args['order'] = $filter_loop_order;
}
?>

Now, merge your custom argument array with the default loop query args:
<?php
// Globalize the default query
global $wp_query;
// Merge arguments
$customized_query_args = array_merge( $wp_query->query, $custom_orderby_query_args );
// Modify the query output
query_posts( $customized_query_args );
?>

Note: you'll have to determine exactly how you're applying the URL query strings. This code just uses the query strings once they're in place.


text:
Q: How to use Point In Time query using xdmp:eval in Marklogic? I have changed the merge policy for the database. Where I set the merge timestamp as current timesatmp(15181726371585905). After changing the merge policy I updated one docs with same URI and collection. Now when I am trying to fetch the deleted docs I am not getting it. I am getting empty sequence.
xdmp:eval("doc('/docs/test.xml')", (),
<options xmlns="xdmp:eval">
  <timestamp>{xdmp:request-timestamp()-1}</timestamp>
</options>)

How to get the deleted docs using above query.
TIA.

A: Just tried this out and get the newest version, rather than the empty sequence. Here's my understanding of what you're trying to do:
You've set the timestamp to the current time (t), then inserted a document (at time t + m), then inserted a new version of the document at the same URI (at time t + n). You now want to retrieve the document from time t + m.
The problem is the way you're specifying the timestamp for your read request:
<timestamp>{xdmp:request-timestamp()-1}</timestamp>

You're asking MarkLogic to rewind the clock one tick and give you the document that existed at that time. However, timestamps do correlate to clock time; they don't just increment when the database state changes. From MarkLogic's Administrator's Guide:

The ticks are calculated at 10,000,000 ticks per second

So by subtracting one from the current timestamp, you're asking to go back about 1/10,000,000 of a second.
If you know the wall-clock time for when you want to query the database, you can find the corresponding timestamp with xdmp:wallclock-to-timestamp.
As an aside, you've also asked a question on Stack Overflow about how to track multiple versions of a document. I'd like to caution you not to view point-in-time queries as one of them, if that's what you had in mind. For that purpose, document library services or bitemporal documents are a better solution. For more information on why not to use PIT queries for versioning, I'll refer you to the Overview of Merges section of the Administrator's Guide, particularly the "Dangers of Disabling Merges" and "Merges Will Change Scores" parts.

A: Setting the merge-timestamp to the current time tells the server to keep fragments from that point on.  All documents in the system prior to setting the new merge-timestamp value would logically have a fragment timestamp prior to that time. Therefore, when you update the document, the system no longer makes available the previous versions(because you said to only keep documents with fragment timestamps from now on).
Some references:

*

*Merges and point-in-time queries

*Description of Merge Parameters
(See the description of merge-timestamp as it explains the impact of various settings)

*Point in Time Queries

*Set Rolling Window of time


text:
Q: Word Wrap detection in JavaScript I am trying to work out a way to detect wordwrap in a specific span tag inside a banner. If it wraps to 2 lines then increase the overall height of the container by 56px. There is also a sub headline (headline2) which also needs to increase (or decrease) the height by 40px.
I have written some basic JS code here which checks the div height of the span but its not great & also will only work for 3 lines.
   // Variable banner heights
    var hl11sub = 368;
    var hl21sub = 448;
    var hl31sub = 548;

    var hl12sub = 416;
    var hl22sub = 496;
    var hl32sub = 576;

    var hLFontSizeCSS = window.getComputedStyle(headlineText, null).getPropertyValue("font-size");
    var hL2FontSizeCSS = window.getComputedStyle(headline2text, null).getPropertyValue("font-size");
    var bannerHeightCSS = window.getComputedStyle(banner, null).getPropertyValue("height");
    var headlineHeight = headlineText.offsetHeight;
    var hL2HeadHeight = headline2text.offsetHeight;

    var headHeight = headlineText.style.lineHeight = parseInt(hLFontSizeCSS) + 10 + "px";
    var hL2Height = headline2text.style.lineHeight = parseInt(hL2FontSizeCSS) + 10 + "px";

    // Text Height values
    var hL1LineHeight = parseInt(headHeight); // 8 is line height & padding
    var hL2LinesHeight = 140;
    var hL3LinesHeight = 195;

    // HL2 height values
    var hL2TextOver1LineHeight = parseInt(hL2Height); // 8 is line height & padding
    var hL2TextOver2LineHeight = 84;

    if(hL2HeadHeight == hL2TextOver1LineHeight && headlineHeight == hL1LineHeight){
      banner.style.height = hl11sub + "px";
    }
    else if(hL2HeadHeight == hL2TextOver1LineHeight && headlineHeight == hL2LinesHeight){
      banner.style.height = hl21sub + "px";
    }
    else if(hL2HeadHeight == hL2TextOver1LineHeight && headlineHeight >= hL3LinesHeight){
      banner.style.height = hl31sub + "px";
    }
    else if(hL2HeadHeight == hL2TextOver2LineHeight && headlineHeight == hL1LineHeight){
      // Single headline with 2 lines sub
      banner.style.height = hl12sub + "px";
    }
    else if(hL2HeadHeight == hL2TextOver2LineHeight && headlineHeight == hL2LinesHeight){
      // 2 headlines with 2 lines sub
      banner.style.height = hl22sub + "px";
    }
    else {
      banner.style.height = hl32sub + "px";
      // 3 headlines with 2 lines sub

It needs to only change the height of the banner depending on if the span words wrap once, twice, three times etc.
Any suggestions or help with this would be greatly appreciated.

A: Here is a very basic implementation on how to detect when a line is wrapped hopefully this gives you a good idea where to start and integrate it into your app.
Heres the docs for stuff used

https://developer.mozilla.org/en/docs/Web/API/EventTarget/addEventListener
https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle
https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

You mentioned the height changing and you needing to know when its wrapped you can use a mutation observer to check when the style has changed then check if its wrapped.
Resize the demo window to see results
any questions i'll try get to them asap if i've misunderstood i'll happily change :)

const h1 = document.querySelector('h1');
const banner = document.querySelector('.banner');

//handles style changes on banner to check wrapping
const observer = new MutationObserver(mutations =>
  mutations.forEach(mutationRecord => onLineWrapDoSomething())
);
observer.observe(banner, { attributes : true, attributeFilter : ['style'] });

// handles window resize events
window.addEventListener('resize', onLineWrapDoSomething)

function onLineWrapDoSomething() {
  const { lineHeight } = getComputedStyle(h1);
  const lineHeightParsed = parseInt(lineHeight.split('px')[0]);
  const amountOfLinesTilAdjust = 2;

  if (h1.offsetHeight >= (lineHeightParsed * amountOfLinesTilAdjust)) {
    console.log('your h1 now wrapped')
  } else {
    console.log('your h1 on one line')
  }
}

// shows it logs when style changes and it wraps, ignore the disgusting code below
setTimeout(() => {
  banner.style.width = '50%'
  setTimeout(() => {
    banner.style.width = '100%'
  }, 1500)
}, 1500)
.banner {
  width: 100%;
}
h1 {
  line-height: 1.5
}

This is some text that will eventually wrap


text:
Q: windowShouldClose(_:) delegate function not being called in code I am currently trying to learn Cocoa through a Mac Apps book and one of the programs has the windowShouldClose(_:) delegate function. However, when I run the program, the window will still close whenever this function is supposed to be called. The program still runs, but the window closes. Can anyone explain why this happens? Here is my code:
import Cocoa

class MainWindowController: NSWindowController, NSSpeechSynthesizerDelegate, NSWindowDelegate {

@IBOutlet weak var textField: NSTextField!
@IBOutlet weak var speakButton: NSButton!
@IBOutlet weak var stopButton: NSButton!

let speechSynth = NSSpeechSynthesizer()

var isStarted: Bool = false {
    didSet {
        updateButtons()
    }
    }

override var windowNibName: String {
    return "MainWindowController"
}

override func windowDidLoad() {
    super.windowDidLoad()
    updateButtons()
    speechSynth.delegate = self
}

//MARK: - Action methods

//get typed-in text as string
@IBAction func speakIt(sender: NSButton){
    let string = textField.stringValue
    if string.isEmpty {
        print("string from \(textField) is empty")
    } else{
        speechSynth.startSpeakingString(string)
        isStarted = true
        }

    }
@IBAction func stopIt(sender: NSButton){
    speechSynth.stopSpeaking()
}

func updateButtons(){
    if isStarted{
        speakButton.enabled = false
        stopButton.enabled = true
    } else {
        speakButton.enabled = true
        stopButton.enabled = false
    }
}

//Mark: NSSpeechSynthDelegate
func speechSynthesizer(sender: NSSpeechSynthesizer, didFinishSpeaking finishedSpeaking: Bool){
    isStarted = false
    print("finished speaking=\(finishedSpeaking)")
}

//Mark: Window Delegate
func windowShouldClose(sender: AnyObject) -> Bool {
    return !isStarted
}
}

Thanks!

A: You will need to set your main view controller as the delegate of the NSWindow.
In your windowDidLoad, you can set self as the delegate for the window
override func windowDidLoad() {
    super.windowDidLoad()
    updateButtons()
    speechSynth.delegate = self
    self.window.delegate = self
}

A: What Shripada said is correct, but there's also another catch. Don't forget to make a connection from your MainWindowController to the window defined in your xib, otherwise the window outlet won't be referencing anything.
So, the window defined in your File's owner
should reference the window in interface builder

A: windowShouldClose() was not being called in my code either after upgrading to Swift 5. In previous versions, it was sufficient to have the app delegate inherit from NSApplicationDelegate for it to receive the windowShouldClose() notification (building in Xcode). Upgrading to Swift 5, I had to have my app delegate also inherit from NSWindowDelegate to get the notification. This declaration restored the window close notification to my app:
class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate {

A: your method signature has to match exactly.
it has to be
windowShouldClose(_:)
the _ is important.


text:
Q: Rasterio. Pixel value of a point X km away from current point
I have a EPSG:4326 raster file with pixel size of 15 arcseconds, and the longitude and latitude of a point.
dataset = rasterio.open(url)
lat = 5.535456
lon = 7.531536

I know I can retrieve the pixel value of the point with the code below.
row, col = dataset.index(lon, lat)
band = dataset.read(1)
band[row][col]

But how can I retrieve the pixel value of a point X km away to the north of the current point? My ultimate intention is to aggregate over a circle of X km radius, whose center is a given point like the one above.

A: If you're ultimately working toward a polygon (circle) intersection with your raster, there are built-in methods for calculating a numpy mask, given a polygon.
You can use this question to see how Shapely can be used to get a circle of defined radius from a centre point (you will need to convert to a projected coordinate system).
Then, use rasterio.features.geometry_mask to calcualate a numpy mask given a polygon geometry. (Shapely's abstract geometry interface is widely accepted in an ecosystem of spatial Python libraries, which includes Rasterio.)
Once you have the mask for the ndarray, you can calculate various statistics on the masked array using numpy methods, e.g. numpy.ma.mean.


text:
Q: Codeigniter , The upload path does not appear to be valid I'm have a problem uploading a picture using codeigniter. I followed the online upload tutorial, but can't figure out the problem. I keep getting "The upload path does not appear to be valid". So, here's my form structure:
<?php if (isset($error)) {?>

                <?= $error ?>

<?php } ?>

<?php echo form_open_multipart('pages/do_upload');?>

<input type="file" name="userfile" size="20" />

<input type="submit" value="upload" />

</form>

I also checked for my directory to be a valid path and to be writable with this code:
<?php if(is_writable('./uploads') && is_dir('./uploads')){
echo 'valid';
}
else { echo  (base_url('uploads'). ' ' ."is not writable");} ?>

And this returns valid.
The following is my controller structure:
public function do_upload()
    {
            $config['upload_path']          = './uploads/';
            $config['allowed_types']        = 'gif|jpg|jpeg|png';
            $config['max_size']             = 10000000000;
            $config['max_width']            = 1920;
            $config['max_height']           = 1080;

            $this->load->library('upload', $config);

            if ( ! $this->upload->do_upload('userfile'))
            {
                    $error = array('error' => $this->upload->display_errors());

                    $this->load->view('user/profile/profile', $error);
            }
            else
            {
                    $data = array('upload_data' => $this->upload->data());

                    $this->load->view('upload_success', $data);
            }
    }

In construct i loaded the upload library.
With all this being said, I keep getting the error I mentioned before.

A: Try Using
$config["upload_path"] = $_SERVER['DOCUMENT_ROOT']."/your/desired/location/";


text:
Q: Partial update of entity objects with EF 4 I'm implementing DAL and BL layers of application.
It is hosted as WCF service, and EF 4 is used as ORM.
We have role based security layer and business rule that only part of object can be updated by some particular role.
Here is simplified example of problem:
We have such DTOs:
MainType
{
    public Guid ID { get; set; }
    public String DoctorField1 { get; set; }
    public String DoctorField2 { get; set; }
    public String NurseField1 { get; set; }
    public String NurseField2 { get; set; }
    public DateTime Created {get; set;}
    public DateTime Updated {get; set;}
    public Guid LastUpdateBy {get; set;}

    public List<DetailsType> Details { get; set; }
}

DetailsType
{
    public Guid MainTypeID { get; set; }
    public Guid SomeIdentityID { get; set; }

    public String DoctorDetail { get; set; }
    public String NurseDetail { get; set; }
    public DateTime Created {get; set;}
    public DateTime Updated {get; set;}
    public Guid LastUpdateBy {get; set;}
}

This entities are mapped to corresponding DB tables with the same fields.

*

*ID field of MainType is Primary Key;

*MainTypeID of DetailsType is Foreign Key to MainType table.

*SomeIdentityID of DetailsType is FK to some other entity that is not important for this sample.

*MainTypeID SomeIdentityID is complex primary key for DetailsType table.

I have graph of such objects (1 main and list details), and determined role of user who performs update operation.
My task is:

*

*IF current user has role Doctor - update Doctor fields in Main object and all Details objects, insert new details objects.

*IF current user has role Nurse - update Nurse fields in Main object and all Details objects.

*save current date to Updated field

*save current user id to LastUpdateBy field

*do not modify Created field and any other field that are not updated by this role.

So for example if I have user with role Doctor I should do following:

*

*Update DoctorField1, DoctorField2, Updated, LastUpdateBy in MainObject

*Update DoctorDetail, Updated, LastUpdateBy in every details object

*DO NOT modify any other fields.

Currently we have implementation that reads full graph for MainObject, makes necessary modifications and saves in back to DB.
This solution works too slow and I need to find a way to improve it.
Currently I know clearly how to do that by RAW SQL, but this will be my solution in case nothing else will help.
How can I make Entity Framework to update only needed fields and ignore another.
I have some successful results with ApplyOriginalValues and ApplyCurrentValues methods for String fields.
Idea was to assign some fictive value to property in both objects, for example string "@#$%&@#$%&@#$%&@#$%&@#$%&", and EF then treats them as not modified properties during saving changes.
However this trick does not work with Boolean, Int32 and Decimal values.
I should use some simple approach to all objects.
I will appreciate any ideas and thoughts about this problem.

A: If you have such specific requirement you should start by modifying your WCF service to not accept fields which user cannot modify. That leads to two simple DTOs:
public class MainTypeUpdateDto
{
    public Guid ID { get; set; }
    public String Field1 { get; set; }
    public String Field2 { get; set; }
    public List<DetailsTypeUpdateDto> Details { get; set; }
}

public class DetailsTypeUpdateDto
{
    public Guid MainTypeID { get; set; }
    public Guid SomeIdentityID { get; set; }
    public String Detail { get; set; }
}

All other fields either cannot be updated or should be handled by your server side logic.
Now when you receive dtos you can map them back to real entity objects. Based on user role you will know which fields and details you must set. You have two options to force EF to save only fields you want:

*

*First create object graph with MainType and related details. Set only Ids in these entities and attach MainType entity to context. After that set all updatable fields to current values. Do not change state of any entity.

*Create object graph with MainType and all related details and set all Ids and all updatable fields. After that attachMainType` entity to the context and manually set state for each modified property (on each entity).

You can need some additional logic if user can also remove or add details.


text:
Q: Insert the contents of the tag into the get query path How to get content from:

 Samsung Galaxy S8 Dual

and pass it to the param:
 Learn more

The contents of the p tag all change because of ajax queries and I need to transfer the contents that are currently there.

A: You could call a function which takes the value of the parameter when clicked instead when the page loads.

customRedirect = function(param){
  location.href = "/about?param=" + param;
}

 Samsung Galaxy S8 Dual

 Learn more

A better way to do it (in my case using jquery) :

$("[customParam]").click(function(){
  location.href = "/about?param=" + $('#' + $(this).attr('call') ).html()
});

 Samsung Galaxy S8 Dual

 Learn more

Without jquery:

var elems = document.querySelectorAll("[customParam]")
for(var i = 0; i < elems.length; i++){
  elems[i].addEventListener("click", function(){
    location.href = "/about?param=" + document.getElementById(this.getAttribute('call') ).innerHTML
  })
}

 Samsung Galaxy S8 Dual

 Learn more

A: Get the value like this:
var v = document.querySelector('p[id1="p-1-1"]').value;

and set the param like this:
var target = document.getElementsByClassName("btn2")[0];
target.href = target.href.substring(0, target.href.indexOf("=") + 1) + '"' + v + '"';


text:
Q: Error while Running iOS simulator from Xcode on Mac I am unable to open my iOS Simulator. Whenever I run my iOS App on Xcode it displays the following error:-
failed to start launched sim could not bind to session launched_sim may have

Could anyone please let me know how could I resolve this issue? Thanks for the help!

A: *

*Go to Xcode preferences and from tab "Locations", directly open "Derived Data" directory and delete it

or

*

*Go to here and make Device -> Erase All Content and Settings


text:
Q: Create ID variable according to levels of a second variable using R I would like to add an ID variable to a data frame, but I would like it to start over at each level of a second variable in the data.frame (terrible sentence, hopefully an example helps).
So, I know how to create an ID variable that extends the length of the data.frame using mutate
dat <- mutate(dat, id=rownames(dat))
Var1    ID
1        1
1        2
1        3
1        4
1        5
1        6
2        7
2        8
2        9
2       10
2       11

But what I would really like is the ID variable to start over once the Var1 hits 2 (then 3, then 4, etc). I figure you can use some type of apply function, or possibly dplyr, but I'm not sure with one. Below is what I am trying to do.
Var1 ID
1    1
1    2
1    3
1    4
1    5
1    6
1    7
2    1
2    2
2    3
2    4
2    5
2    6
2    7
2    8
2    9
3    1
3    2
3    3
3    4
3    5
3    6
3    7
3    8
3    9


text:
Q: Pass Lat/Long to geolocator New to python, I have a cvs file with lat/long and I am trying to retrieve the addresses, how can I pass my lat/long string to geolocator
with open('try.csv', 'rb') as f:
   reader = csv.DictReader(f)
   for row in reader:
    geolat = row['pickup_latitude']
    geolong = row['pickup_longitude']
    # point = Point(float(row['pickup_latitude']),     float(row['pickup_longitude']))

    val1 = ("\""+geolat+", ")
    val2 = (geolong+"\"")
    val = val1 + val2
    print val
# var returns "40.750912, -73.99102"
location = geolocator.reverse(val)

A: geolocator.reverse accepts a single comma-separated string as its argument.
with open('try.csv', 'rb') as f:
    reader = csv.DictReader(f)
    for row in reader:
        geolat = row['pickup_latitude']     # geolat is a string
        geolong = row['pickup_longitude']   # geolong is a string
        latlong = [geolat, geolong]         # latlong is a list of two strings
        val = ", ".join(latlong)            # val is one comma-separated string

        location = geolocator.reverse(val)
        print(location)

Of course you can cut out all the intermediate steps at the expense of readability.
with open('try.csv', 'rb') as f:
    reader = csv.DictReader(f)
    for row in reader:
        location = geolocator.reverse(", ".join([row['pickup_latitude'], row['pickup_longitude']]))
        print(location)

Rembember, the line indent convention in Python is 4 spaces.


text:
Q: Swing remove JTexField and JLabel I have a JTable 2 columns, column name and check-box. If the user clicks the check box next to the name of the column that creates a new field for data entry. I wish the unclick check box input field has disappeared.
How can I do that?

My code to add a new field:
 headerTable.getModel().addTableModelListener(new TableModelListener() {

                @Override
                public void tableChanged(TableModelEvent e) {
                    if(e.getColumn() >= 0  && e.getFirstRow()>-1){
                        int id =  e.getFirstRow();
                        String colName = (String)headerTable.getValueAt(e.getFirstRow(), 1);
                        boolean colValue = (boolean)headerTable.getValueAt(e.getFirstRow(), 2);

                        System.out.println("Row : " + e.getFirstRow() +
                                   " value :" + headerTable.getValueAt(e.getFirstRow(), 2));
                        appListener.getColumnId(id);
                        //create texfield
                        if(colValue==false){
                            System.out.println("Delete");
                        }
                        jTextField = new JTextField(20);
                        textField.put(id,jTextField);
                        if (textField != null && !textField.isEmpty()) {
                            textField.get(textField.size()-1);
                            System.out.println("Add");
                        }
                        JLabel kolor1name = new JLabel(colName+": ");
                        operationContent.add(kolor1name,"");
                        operationContent.add(jTextField, "growy, wrap");

                        revalidate();
                        repaint();
                    }
                }
            });

A: Quick-n-dirty way:
if(colValue){
    jTextField = new JTextField(20);

    textField.put(id,jTextField);

    if (textField != null && !textField.isEmpty()) {
        textField.get(textField.size()-1);
        System.out.println("Add");
    }

    JLabel kolor1name = new JLabel(colName+": ");
    operationContent.add(kolor1name,"");
    operationContent.add(jTextField, "growy, wrap");

} else {
    System.out.println("Delete");
    Component[] comps = operationContent.getComponents();
    operationContent.remove(comps[comps.length - 2]);
    operationContent.remove(comps[comps.length - 1]);
}
revalidate();
repaint();

But this way may (not always) cause layouting issues (panel looks bad after removal).
Better way: provide full relayout of the panel "operationContent"
operationContent.removeAll();
// add all the components above the kolor1name
if(colValue){
    jTextField = new JTextField(20);

    textField.put(id,jTextField);

    if (textField != null && !textField.isEmpty()) {
        textField.get(textField.size()-1);
        System.out.println("Add");
    }

    JLabel kolor1name = new JLabel(colName+": ");
    operationContent.add(kolor1name,"");
    operationContent.add(jTextField, "growy, wrap");
}
revalidate()
repaint();

This way is ok, but in some cases can also provide layouting issues. But if you want to add more than 1 row (for example when user select 2 checkboxes in table) it's colud be the best way for you.
Another way: use the CardLayout. This only will work when you always add one field (with label) independed on how many comboboxes in the table was selected.

A: You can create a Vector of all the fields that you want. And when the user clicks on the check-box, you can add it to the Vector. for eg:
Vector fields = new Vector();

And when you get the notification, you add the name of the field in the vector, and call the refreshPanel() method, which removes all the fields in it, and add the new fields to it.
// In the tableChanged(...) method
fields.addElement(colname);
refreshPanel();

Then the refreshPanel() method:
public void refreshPanel()
{
     String fNames[] = (String[]) fields.toArray();
     panel.removeAll();
     for(String fname : fNames)
     {
          //add the fields in `newPanel`, the field name is in `fname` variable
     }
     revalidate();
     repaint();
}

And when the user deselects the check-box, then remove the field name from the Vector:
fields.removeElement(colname);
refreshPanel();


text:
Q: No Set-Cookie header in showing in chrome I am making an api call using axios from my react app. The api call returns a Set-Cookie header which appear to be working fine in firefox. However, I don't the Set-Cookie header in chrome at all. I tried googling around this issue but couldn't find any concrete answer. Any help regarding this would be appreciated.
Url in browser
http://localhost:3000/checkout/5423568515
Url for api call
http://localhost:8087/session/loginByUserName
Firefox
Image showing Set-Cookie header in firefox
Cookies are even set in browser
Image showing cookies are set
Chrome: No Set-Cookie header is shown and cookies are not set
Chrome with no Set-Cookie header

A: An ajax library will never drop headers from a response. What you see in the network tab is actually what the server is responding with. I suspect the server is not sending back that header because the cookies are already set. Try clearing the relevant cookies.
The following code will expire the cookie specified in cookieName. By setting it's expiry date to the past.
document.cookie = cookieName + "=something; expires=Thu, 18 Dec 2013 12:00:00 UTC;"

A: I suspect this is a bug (or poorly thought out "feature") in Chrome.  You can verify that the cookie is being set by capturing a NetLog of the transaction.  This gives you access to the exact, un-modified headers on each incoming and outgoing request, including (if you enable the relevant option) cookies and other credentials.
I'm currently running into this from the other end -- Chrome is sending session cookies but not showing the relevant header in the Network tab -- and was planning on putting together a small test case to submit a bug to their tracker.


text:
Q: Erlang server request order I'm trying to understand request order in erlang, but I can't seem to grasp it very well. Here's the example code:
test() ->
    Server  = start(),
    spawn(fun() -> write(Server, 2),
                   io:format("Child 1 read ~p~n", [read(Server)]) end),
    write(Server, 3),
    write2(Server, 5),
    spawn(fun() -> write2(Server, 1),
                   io:format("Child 2 read  ~p~n", [read(Server)]) end),
    io:format("Parent read ~p~n", [read(Server)]).

And here's the server:
start() ->
    spawn(fun() -> init() end).

init() -> loop(0).

loop(N) ->
    receive
        {read, Pid} ->
            Pid ! {value, self(), N},
            loop(N);
        {write, Pid, M} ->
            Pid ! {write_reply, self()},
            loop(M);
        {write2, _Pid, M} -> loop(M)
    end.

read(Serv) ->
    Serv ! {read, self()},
    receive {value, Serv, N} -> N end.

write(Serv, N) ->
    Serv ! {write, self(), N},
    receive {write_reply, Serv} -> ok end.

write2(Serv, N) ->
    Serv ! {write2, self(), N},
    ok.

I understand that different values could be printed by the three different processes created in test/0, but I'm trying to figure out the lowest and highest values that could be printed by those Parent, Child1 and Child2 processes. The answer states:

*

*Parent: lowest 1, highest 5

*Child1: lowest 1, highest 5

*Child2: lowest 1, highest 2

Can somebody explain this?

A: Keep in mind that Erlang guarantees message order only from one process to another. If process A sequentially sends message 1 and then message 2 to process B, then B will receive them in that order. But Erlang guarantees no specific ordering of messages arriving at B if multiple concurrent processes are sending them. In this example, Parent, Child1, and Child2 all run concurrently and all send messages concurrently to Server.
The Parent process performs the following sequential steps:

*

*Spawns the Server process. This eventually sets the initial value in the Server loop to 0.

*Spawns Child1. This eventually writes the value 2 to Server, then reads from Server and prints the result.

*Uses write/2 to send the value 3 to Server. The write case in the loop/1 function first replies to the caller and then installs the value 3 for its next iteration.

*Uses write2/2 to send 5 to Server. The write2/2 function just sends a message to Server and does not await a reply. The write2 case in the loop/1 function just installs the value 5 for its next iteration.

*Spawns Child2, which eventually calls write2/2 with the value 1, and then reads Server and prints the result.

*Reads Server and prints the result.

For Parent, step 3 sends the value 3 to Server, so as far as Parent is concerned, Server now has the value 3. In step 4, Parent calls write2/2 to send 5 to the server, and that message must arrive at Server sometime after the message sent in step 3. In step 6, Parent performs a read, but all we know is that this message has to arrive at Server after the write message in step 4. This message ordering means the highest value Parent can see is 5.
The lowest value Parent can see is 1 because if Child2 gets its write message of 1 to Server after the Parent write message of 5 but before the final Parent read message, then Parent will see the 1.
For Child1, the highest value it can see is 5 because it runs concurrently with Parent and the two messages sent by Parent could arrive at Server before its write message of 2. The lowest Child1 can see is 1 because the Child2 write message of 1 can arrive before the Child1 read message.
For Child2, the lowest value it can see is its own write of 1. The highest value it can see is 2 from the write of Child1 because the Parent writes of 3 and 5 occur before Child2 is spawned, thus Child1 is the only process writing concurrently and so only it has a chance of interleaving its write message between the Child2 write and read messages.


text:
Q: Entity Framework inserting null record I am using the entity framework for a webapp I am working on.  The web app keeps track of venues.  Each venue can host several types of events.  I have a table with all the different type of event types (EventTypes) and another table that keeps track of which events each venue can have (VenueEventTypes), when I am adding a new venue I create a new VenueEventTypes collection which contains an EventType Propery and go out to the database and find the event type and add it to each of the VenueEventTypes.  The problem is when I save the venue it creates everything fine but it is adding an empty record in the database for the EventTypes, but the VenueEventType foreign key is point to the valid event type and not the newly create empty one.  Here is some code:
 public void addVenue(VEN_Venues venue)
    {
        using (var db = new VenueEntities())
        {
            var parish = from dbParish in db.VEN_Parishes
                         where dbParish.ParishID == venue.ParishID
                         select dbParish;

            venue.VEN_Parishes = parish.First();

            venue = this.processEventTypes(venue, db);
            db.VEN_Venues.AddObject(venue);
            db.SaveChanges();
        }
    }

    private VEN_Venues processEventTypes(VEN_Venues venue, VenueEntities db)
    {
        foreach (VEN_VenueEventTypes eventType in venue.VEN_VenueEventTypes)
        {
            eventType.VEN_EventTypes = new EventTypeFacade().findEventTypes(eventType.VEN_EventTypes, db);
        }
        return venue;
    }

Could someone point me to the error?
Thanks!

A: It doesn't seem like you are actually adding the VEN_EventType to the venue.VEN_VenueEventTypes.
You have to do something along these lines:
venue.VEN_VenueEventTypes.Add(eventType);

if you don't want any duplicates you will have to use attach:
venue.VEN_VenueEventTypes.Attach(eventType);


text:
Q: Angular2 + Jasmine: Testing Router Events Can someone please help me understand how to unit test the app component below? It's an Angular 2 application.
app.ts
import { Component, OnInit }     from '@angular/core';
import { Router, NavigationEnd, NavigationStart, NavigationCancel, NavigationError, RoutesRecognized } from '@angular/router';

import { DataService }           from '../services/data';

@Component({
  selector: 'app',
  template: '<messages></messages><router-outlet></router-outlet>',
  providers: [DataService]
})
export class AppComponent implements OnInit {

  constructor(private router: Router, private data: DataService) {}

  public ngOnInit(): void {
    this.router.events.subscribe((event: NavigationStart | NavigationEnd | NavigationCancel | NavigationError | RoutesRecognized) => {
        if (!(event instanceof NavigationEnd)) { return; }

        document.body.scrollTop = 0;
    });

    window.addEventListener(
        "offline", () => {
            if (this.data.settings.offlineEnabled) {
                this.data.toggleOffline();
                this.data.displayMessage("Internet connection lost, switching to offline mode.", "failure")
            } else {
                this.data.displayMessage("Internet connection lost", "failure")
            }
        }, false,
      );
  }
}

What I've got so far:
app.spec.ts
import { TestBed, async, ComponentFixture } from '@angular/core/testing';
import { AppComponent } from './app'

import { RouterTestingModule } from '@angular/router/testing';
import { MessagesComponent } from './messages/messages';

import { DataService }           from '../services/data';

/* Tests */
export class MockDataService {}

describe('Component: App', () => {
  let mockData = new MockDataService();
  let component: AppComponent;
  let dataService: DataService;
  let fixture: ComponentFixture<AppComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        AppComponent,
        MessagesComponent
      ],
      providers: [
        { provide: DataService, useValue: mockData }
      ]
    }).compileComponents();

    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    dataService = TestBed.get(DataService);
  }));

  it('should create the component', () => {
    expect(component).toBeTruthy();
  });

});

I'm getting the error:
Failed: No provider for e!
But, it appears to me that I'm importing everything that this component needs for instantiation.
I'm wondering if this is 1) either RouterTestingModule doesn't know router.events.subscribe; or, 2) window is not defined.
Any thoughts?
Thanks!
Edit 1:
It appears that the line that is causing my issues is this:
@Component({
  ...,
  ...,
  providers: [DataService]
})

It appears that Jasmine is injecting the MockDataService object into the app.component constructor, but it's not injecting the object for the provider.  Jasmine is providing the concrete DataService implementation.
How do I inject the MockDataService into the providers for the app.component?

A: It's possible your issue is arising because you are also declaring the MessagesComponent in your unit test. Angular will attempt to new up an instance of this class and if you aren't also injecting mocks for the services MessagesComponent uses then that is likely causing your error.
However, since you are unit testing your AppComponent you will not want to add MessagesComponent to your declarations because, as you are experiencing, everything appears to be working within your AppComponent but a dependency of your component is causing your tests to fail. The easiest way to fix this is to add NO_ERRORS_SCHEMA to your TestingModule like such:
TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        AppComponent
      ],
      providers: [
        { provide: DataService, useValue: mockData }
      ],
      schemas: [
        NO_ERRORS_SCHEMA
      ]
    }).compileComponents();

This will prevent the Angular compiler from complaining about custom HTML tags in your code like the  tag.


text:
Q: How can I loop through each Record and see if any of 3 requirements are missing? I have a table with ProducerName and ProducerRequirementsListID

Each ProducerName supposed to have 3 requirements(1,2,3), but some of them might missing at least one of them: either 1, 2 or 3.
So how can I catch unique ProcucerName that missing AT LEAST ONE of the ProducerRequirementsListID?
Ideally would be create 3 new columns Req_1,Req_2 Req_3 and for each unique ProducerName display TRUE or FALSE
Something like that:

Should I be using WHILE loop for operations like that?

A: It's not clear that you're actually trying to get a pivot or you are looking only for ProducerName that are missing requirements. Assuming the latter, then all you need to do is group by and filter by less than 3. For example:
SELECT ProducerName
FROM Table
GROUP BY ProducerName
HAVING COUNT(*) < 3

A: I would say a pivot would be what you are looking for.  Simple self extracting example.  While Loops while useful should not be done as a first resort in SQL as it is result set based language and performance could be bad over time when doing in a while loop what could be done with a pivot.
DECLARE @People TABLE (PersonName VARCHAR(128), Ord INT);

INSERT INTO @People (PersonName, Ord) VALUES ('Brett', 1), ('Brett', 2), ('Brett', 3), ('Emily', 1), ('Emily', 2);

SELECT
    PersonName
, [1] as FirstValue
, [2] as SecondValue
, [3] as ThirdValue
From @People
    PIVOT ( Count(Ord) FOR Ord IN ([1],[2],[3])) AS piv

A: You can use a quick case statement....
select
    ProducerName
    ,case when ProducerRequirementListID = 1 then 'TRUE' else 'FALSE' end as Req1
    ,case when ProducerRequirementListID = 2 then 'TRUE' else 'FALSE' end as Req2
    ,case when ProducerRequirementListID = 3 then 'TRUE' else 'FALSE' end as Req3
from ProducerName

Here is a way to get just a list of the producers who are missing one...
select ProducerName
from ProducerTable
group by ProducerName
having count(ProducerName) < 3

Here's a better way, using test data from django, to find which one is missing...
select
    ProducerName
    ,case
        when sum(ProducerRequirementListID) = 3 then 3
        when sum(ProducerRequirementListID) = 4 then 2
        when sum(ProducerRequirementListID) = 5 then 1
        when sum(ProducerRequirementListID) = 6 then NULL
    end as MissingReq
from ProducerTable
group by ProducerName

TEST DATA
DECLARE @People TABLE (PersonName VARCHAR(128), Ord INT);

INSERT INTO @People (PersonName, Ord) VALUES ('Brett', 1), ('Brett', 2), ('Brett', 3), ('Emily', 1), ('Emily', 2), ('Jake', 1), ('Jake', 3);

SELECT
    PersonName,
    case
        when sum(Ord) = 4 then 2
        when sum(Ord) = 3 then 3
        when sum(Ord) = 5 then 1
        when sum(Ord) = 6 then NULL
    end as MissingReq
from @People
group by PersonName


text:
Q: I get 404 error when I click on "Get UI Kits" on Adobe XD When I click on "Get UI Kits" on Adobe XD, on the application's library page, the URL https://www.adobe.com/products/xd/features/ui-kits.html#panel-3 comes and it is broken link.
I am trying to reach Adobe XD ready templates and libraries.

A: The automatic coming URL link from the application is broken. Instead of the link from the application, you should use:
https://www.adobe.com/in/products/xd/features/ui-kits.html


text:
Q: How do you check a field in a query for specific values if and only if another field had a specific value? I want to write an expression in my Access query to check to see if an item we are running next week has run in the 4 weeks before that date. I'm having trouble understanding how you can check something in the same query and then use the returned value of that check to check a few more things. The method I've tried is to write make another query that will use the results of the first query (where items from 7/20/2015 are isolated) to check the dates of those items, but I run into a problem because then I have to tie back that query to the original table, which duplicates the data.
Written in pseudo-code, it would look somewhat like the following:
If the item has a job_date of 7/20/2015, check all instances of that item prior to 7/20/2015 and if there is no instance for weeks 7/13/2015, 7/6/2015, 6/29/2015, or 6/22/2015, then return the item.
Written in a more visual way:
item          job_date
A             6/22/2015
A             6/29/2015
A             7/6/2015
A             7/13/2015
A             7/20/2015

item          job_date
B             6/15/2015
B
B
B
B
B             7/20/2015

item          job_date
C             6/22/2015
C
C
C             7/13/2015
C             7/13/2015
C             7/20/2015

item          job_date
D
D
D
D
D
D

Item A would not be returned because we have been running continuously. Item B would return because even though we ran it on 6/15/2015, that was more than 4 weeks before 7/20/2015. Item D would not return because it doesn't have a row with the target date (7/20/2015).
Notes:

*

*Ideally, I will use expressions that will always determine next week's date automatically, I just used hard dates here for clarity. If you want to use the hard dates as well please feel free.

*Our weeks begin on Mondays.

*An item can run multiple times in one week. For example, Item C can have 2 rows with 7/13/2015 and 7/13/2015. The job number (not shown, but exists in the same table) is the unique identifier in the table. If Item C were to run twice, then the jobs would be H000001584-0030 and H00001584A-0030.

A: The query below returns this result set from your sample data when I supply 7/20/2015 as the parameter value:
item
----
B

The query includes a subquery which returns those items which have rows with job_date values in the 28 days before the target date.  Note the subquery does not return an item which had no job_date values in that range --- so it gives you only those items which did have a job_date in that range.  Therefore left joining to the subquery and asking for only rows where the "right side" is Null means that we exclude those items from the final result set.
PARAMETERS pTarget DateTime;
SELECT j.item
FROM
    dbo_job AS j
    LEFT JOIN
    (
        SELECT [item]
        FROM dbo_job
        WHERE job_date>=DateAdd('d', -28, [pTarget]) And job_date<[pTarget]
        GROUP BY [item]
    ) AS sub
    ON j.item = sub.item
WHERE j.job_date=[pTarget] AND sub.item Is Null
GROUP BY j.item;


text:
Q: reCAPTCHA Enterprise, getting invalid_reason: 6 I am developing a web application with reCAPTCHA enterprise (score based, not checklist based). Everything has been integrated, and when I test it I often get reCAPTCHA error with invalid_reason "6". "6" however is not registered in the Google Cloud API Go library I am using. It is beyond the supported enum values in the library (extracted from the package recaptchaenterprise package):
TokenProperties_InvalidReason_name = map[int32]string{
        0: "INVALID_REASON_UNSPECIFIED",
        1: "UNKNOWN_INVALID_REASON",
        2: "MALFORMED",
        3: "EXPIRED",
        4: "DUPE",
        5: "MISSING",
    }

This is from the v1 package. The v1beta1 package, I guess, will make use of the v1beta1 API. Using this package, I got invalid_reason "7", again outside the supported enum values:
    TokenProperties_InvalidReason_name = map[int32]string{
        0: "INVALID_REASON_UNSPECIFIED",
        1: "UNKNOWN_INVALID_REASON",
        2: "MALFORMED",
        3: "EXPIRED",
        4: "DUPE",
        5: "SITE_MISMATCH",
        6: "MISSING",
    }

Looking at the documentation at https://cloud.google.com/recaptcha-enterprise/docs/reference/rest/v1/projects.assessments#invalidreason, there are 7 possible values for InvalidReason. The error is probably BROWSER_ERROR, something which I am not sure why.
This is not always the case though. Sometimes assessment can be made and the score is returned. This is a development site key that is configured to always return 0 score. Many times however I got that weird response.
A pattern that I have been seeing is that it succeeds in one network, and it fails in the other. I tried to create a setup in localhost with my web service and backend service running, and it succeeds with wifi connection, and it doesn't with mobile connection. Deploying the site to somewhere else I also get the same error. For now all I know is this error is flaky, not sure if it's related to network or not.
I have disabled domain verification for this key.
EDIT: I have created another key that is not a testing key. The result is still the same. I have modified the domain verification countless times, changing domains countless times, and the result is still the same.
A pattern that I have observed is the grecaptcha.enterprise.execute sometimes throw Timeout errors. This is an exception, and so the script will break. I don't know what it is doing but if, for the first time, execute runs for a few seconds, a token will be generated, but it will fail during assessment. If for the first time a token is generated quickly (less than a second), it will succeed. Successful tries mostly happen only in local deployment, in which I use the same domain (I used static DNS by putting the domain in /etc/hosts).
None of the documentation mention how to solve this issue. It does seem that we are better off using hCaptcha instead.


text:
Q: Packaging Python applications with PyQt and PyQwt (for Linux only) This is a follow-on from my question here; I think I will have to look at a different method.
I want to package my Python program with some of its dependencies. I'm aware of tools like cx_Freeze or bbfreeze, but as you can see in the linked question they have issues for my situation.
I don't want my users to have to install my application using the super user.
What I would really like is to package PyQt4 and PyQwt with my application, but use the system Python and other system libraries. Is this possible?


text:
Q: SQL Server - Message 145, but item is in the select List The following Query
select DISTINCT ID, field1, field2
from MyTable
where field1 = 'myValue' OR field2 = 'myValue'
order by case when field1 = 'myValue' THEN 1 else 2 end

gives this error:

Server: Msg 145, Level 15, State 1, Line 1 ORDER BY items must appear
  in the select list if  SELECT DISTINCT is specified.

which seems weird, since field1 obviously IS in the select List.
What is the reason and how can I change that?
(I am sure there is a workaround, but for the time being I want to keep at least the order by section)

A: When using distinct, you can't use anything in the order by clause that does not appear in exactly the same way in the select clause (except for ordinal positions in the order by clause, but I wouldn't recommend using that, ever).
If your select clause contains a case expression, you can use the same case expression in your order by clause - but you can't use a case expression in your order by clause if it's missing in the select clause, even if it only contains column names that exists in the select clause.
There are basically two ways you can solve this.
One is to replace the distinct with group by:
select ID, field1, field2
from MyTable
where field1 = 'myValue' OR field2 = 'myValue'
group by ID, field1, field2
order by case when field1 = 'myValue' THEN 1 else 2 end

and the other one is to use a derived query or a cte for the distinct, and order by in the outer query (I'll show the derived query since the other answer showed the cte option):
select *
from
(
    select DISTINCT ID, field1, field2
    from MyTable
    where field1 = 'myValue' OR field2 = 'myValue'
) x
order by case when field1 = 'myValue' THEN 1 else 2 end

You can see a live demo on rextester.


text:
Q: How to fetch elements from NSArray in Objective C I'm using a bus timetable API and want to display the nearby bus stop according to user current location. I've already got the the JSON response through url and parsed JSON to NSArray. The NSArray looks like this.
{
    result =         {
        distance = "0.00003292029";
        lat = "-37.92091";
        "location_name" = "Monash Medical Centre/Clayton Rd ";
        lon = "145.120682";
        "route_type" = 2;
        "stop_id" = 16518;
        suburb = Clayton;
        "transport_type" = bus;
    };
    type = stop;
},
    {
    result =         {
        distance = "0.00003728643";
        lat = "-37.92227";
        "location_name" = "Monash Surgical Private Hospital/291 Clayton Rd ";
        lon = "145.1202";
        "route_type" = 2;
        "stop_id" = 24348;
        suburb = Clayton;
        "transport_type" = bus;
    };
    type = stop;
},
    {
    result =         {
        distance = "0.00003804303";
        lat = "-37.9230766";
        "location_name" = "Clayton Railway Station/Clayton Rd ";
        lon = "145.120209";
        "route_type" = 2;
        "stop_id" = 22809;
        suburb = Clayton;
        "transport_type" = bus;
    };
    type = stop;
},
    {
    result =         {
        distance = "0.00003976311";
        lat = "-37.9186172";
        "location_name" = "Monash Specialist Centre/Clayton Rd ";
        lon = "145.121033";
        "route_type" = 2;
        "stop_id" = 22807;
        suburb = Clayton;
        "transport_type" = bus;
    };
    type = stop;
},
    {
    result =         {
        distance = "0.00004085229";
        lat = "-37.9186478";
        "location_name" = "Dixon St/Clayton Rd ";
        lon = "145.120911";
        "route_type" = 2;
        "stop_id" = 13889;
        suburb = Clayton;
        "transport_type" = bus;
    };
    type = stop;
}

)
My question is how to get the latitude and longitude from this NSArray. I wrote these code but it returns  nil.
    NSMutableArray *coordinateLatit = [[NSMutableArray alloc]init];
for (int i = 0; i<nearbyStop.count; i++) {
    NSString *latit = [[nearbyStop objectAtIndex:1] objectForKey:@"lat"];
    if(latit == nil)
    {
        NSLog(@"there is no data");
    }
    else
    {
    [coordinateLatit addObject:latit];
    }
}

And also i want to display the stops(use longitude&latitude from NSArray) on MKMapView, how should i manage to implement the MKLocalSearchRequest
Appreciate it if anyone can help me!

A: Your code overlooked the extra nested result level.
NSMutableArray *coordinateLatit=[[NSMutableArray alloc]init];

for(NSDictionary *d in nearbyStop)
{
    NSString    *latit=d[@"result"][@"lat"];

    if(lat) [coordinateLatit addObject:latit];
}

A: you miss a level of the json response, it should be
for (Stop *stop in nearbyStop) {
    NSString *latit = [[stop objectForKey:@"result"] objectForKey:@"lat"];
    if(latit == nil)
    {
        NSLog(@"there is no data");
    }
    else
    {
        [coordinateLatit addObject:latit];
    }
}

A: -(id) doApiCall:(NSString*)apiCall useCache:(BOOL)useCache
{

   NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@", mBaseURL, [MapViewController signApiCall:apiCall]]];

id response = [self httpWrapper:url];
    NSLog( @"%@", response );
return response;
}

-(id) httpWrapper:(NSURL*)url

{
    __block id response = nil;

void (^doStuff)() = ^void()
{
    int retry = 3;
    NSError * error;

    while( retry > 0) {
        NSData * data = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:url
                                                                                cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                                             timeoutInterval:600] returningResponse:nil error:&error ];

        if( data != nil )
        {
            response = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
            if( response != nil)
                retry = 0;
        }

        if(data == nil || response == nil)
        {
            NSLog(@"Bad response %@", url);
            NSLog(@"%@", error);
            --retry;
        }
    }
};

    doStuff();

    return response;
}

-(NSArray*) nearby:(CLLocation*)location
{

        return [self doApiCall:[NSString stringWithFormat:@"/v2/nearme/latitude/%f/longitude/%f?limit=5", location.coordinate.latitude, location.coordinate.longitude]];

}

Here is the code i'm using to call the API. I use id for the response from url request. so does nearby method returns NSArray type?


text:
Q: Not able to vertically align items in flexbox I am learning to use flexbox and I am not able to align content vertically inside of the class .headercontent. it seems to honor everything else like justify-content but ignores align-content. I searched and found this thread and this seems to suggest that the parent should have height explicitly set. I have set height by setting flex-basis and flex-grow and a min-height. But still by div containing the h1 is stuck to the top of the header. I want that green div to be in the vertical center of the header. what am I doing wrong?

html {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-size: 100%;
            line-height: 1.2em;
          }
          body {
            display: flex;
            flex-direction: column;
            justify-content: flex-start;
            align-items: stretch;
            height: 100vh;
            background-color: #cdc9c1;
          }
          header {
            background-color: #a99879;
            flex-basis: 10%;
            flex-grow: 1;
            min-height: 20px;
          }
          main {
            background-color: #5b431a;
            flex-basis: 80%;
            flex-grow: 8;
          }
          footer {
            background-color: #77613c;
            flex-basis: 10%;
            flex-grow: 1;
          }
          .headercontent {
            display: flex;
            flex-direction: row;
            justify-content: center;
            align-items: center;
            background-color: green;
            min-height: 20px;
          }
          .navstyle {
            list-style-type: none;
          }

This is the header

section1

section2

section3

 this is the main body

 this is the footer

Here is the codeine link to my work https://codepen.io/knows_not_much/pen/rNxXoOM

A:
I want that green div to be in the vertical center of the header. what
am I doing wrong?

Your header element is taking up 10% height of body. Your .headercontent does not take up the entire defined height of the header. Therefore, it is going to sit at the top. To address this, you can assign the header element to be a flex container and that is where you assign align-items: center; justify-content: center properties
header {
    background-color: #a99879;
    flex-basis: 10%;
    flex-grow: 1;
    display: flex; /* add these */
    align-items: center; /* add these */
    justify-content: center; /* add these */
}

Assign width: 100% to the .headercontent afterwards (as needed) if you must have the green background take up the space


text:
Q: Count points in polygon grouping by attribute using PyQGIS I have a point layer with an attribute table like this:
id_point  class
       1      A
       2      B
       3      A
       4      C
       5      B
...

What I need is to count how many points of any class are in every polygon. Something like this
id_pol   A   B   C
  pol1   1   2   0
  pol2   1   0   1
...

Is there a way to count points within polygons grouping by a point attribute using Python in QGIS 3?
I think QGIS 2 had a Count Unique Features by Polygon but I can't find it in QGIS 3.

A: Use this script:
from PyQt5.QtCore import QVariant

# layers
polygon_lyr = QgsProject.instance().mapLayersByName("Polygons")[0]
point_lyr = QgsProject.instance().mapLayersByName("Points")[0]

# index number of "class" field
field_index = point_lyr.fields().indexFromName('class')

# unique class names
unique_classes = point_lyr.uniqueValues(field_index)

polygon_lyr.startEditing()

# add a field for each class to polygon layer
for field_name in unique_classes:
    if polygon_lyr.fields().indexFromName(field_name)==-1:
        polygon_lyr.addAttribute(QgsField(field_name, QVariant.Int))

for feat in polygon_lyr.getFeatures():
    g = feat.geometry()
    req = QgsFeatureRequest(g.boundingBox()) # for performance
    classes = [p["class"] for p in point_lyr.getFeatures(req) if g.contains(p.geometry())]
    class_numbers_in_polygon = {cls: classes.count(cls) for cls in unique_classes}

    # add unique class numbers in polygon to the related field
    for cls in class_numbers_in_polygon:
        feat[cls] = class_numbers_in_polygon[cls]
        polygon_lyr.updateFeature(feat)

polygon_lyr.commitChanges()


text:
Q: MISRA 10.3 issue about AUTOSAR booleans In my firm project, the AUTOSAR platform defines booleans like this
typedef unsigned char boolean;

plus
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif

This is not modifiable. Then we get the MISRA 10.3 error Expression assigned to a narrower or different essential type [MISRA 2012 Rule 10.3, required] on the following two assignments (real code replaced, of course!)
boolean mybool = (boolean)FALSE;
if(some_condition)
{
   mybool = (boolean)TRUE;
}

We've tried other convertions with (uint8)FALSE or (unsigned char)FALSE or even without a convertion mybool = TRUE; without curing the issue. We would be happy to avoid justifying for deviation.
Does anyone has an idea of what happens and how to cure it?

@Fredrik Thanks for your first answer. I put this in a dummy header, included it in the 'culprit' .c and run PC-Lint/MISRA on this unit
#define testTRUE 1U
boolean x = testTRUE;
boolean y = (uint8)testTRUE;
boolean z = (boolean)testTRUE;

#define testTRUE_2 1
boolean x_2 = testTRUE_2;
boolean y_2 = (uint8)testTRUE_2;
boolean z_2 = (boolean)testTRUE_2;

unsigned char x_3 = (boolean)1;
unsigned char y_3 = (boolean)testTRUE;
unsigned char z_3 = (boolean)testTRUE_2;

and get the same issue on the first 6 assignments. As to last 3 assignments, the error is not raised but perhaps hidden by this one in replacement: Use of modifier or type 'unsigned' outside of a typedef [MISRA 2012 Directive 4.6, advisory]

A: The thing with MISRA-C and booleans is that MISRA encourage us to "pretend" that there is a boolean type in the language and treat for example the result from relational and equality operators as "essentially boolean".
That is, treat the boolean type as C++ would. C did introduce booleans in C99, but the result of the mentioned operators is still int, not bool like in C++. But MISRA wants us to "pretend" that they are bool, to get the code right. In addition, MISRA-C still covers C90 where there is no standard bool/true/false to be had.
So in order to get booleans to work like MISRA wants them, you need a way to tell your static analyser that boolean, TRUE and FALSE is your boolean type. Otherwise the tool will treat them as int and then you get all manner of implicit conversion warnings. I don't know how to do that on PC-Lint, but the error is a tool configuration issue.
As for the code posted, boolean mybool = FALSE; is MISRA compliant, given that this is the "essentially boolean" type. No need to cast. And if you didn't configure the tool, no   casting will save you. In general, never cast in C unless you know why you are doing it.

A:
This is not modifiable.

I understand that AUTOSAR has some strange type requirements, that pre-date C11.  Users of AUTOSAR have to live with that (and suggestions of how to get around them don't help)

Then we get the MISRA 10.3 error Expression assigned to a narrower or
different essential type [MISRA 2012 Rule 10.3, required] on the
following two assignments (real code replaced, of course!)

I think, at the heart of this is the apparent conflict between unsigned char and 0/1 (which are signed)... but this is addressed by Exception 1 of Rule 10.3 so not a violation.
But within the examples in the book there is:
bool_t bla = 0 /* Non-compliant: boolean and signed */

This implies that Exception 1 doesn't apply for booleans, which is curious!
Notwithstanding the use of the custom boolean type rather than standard _Bool or bool, I suspect this may be a tool configuration issue... you need to tell PCLINT that the custom boolean type (and TRUE/FALSE) is your essentially boolean type
Or failing that (ie if PCLINT doesn't have such a capability), you may need to deviate Rule 10.3
Disclaimer: See Profile!

UPDATE: I raised this question at a MISRA C WG (virtual) meeting.  The agreement of the WG is that this is a false-positive, and that the Tool should be configured to cope with this - AUTOSAR users in the WG reported their configuration (albeit not using PCLINT) correctly did not flag this.

A: On occasion, static analysis tools have bugs - I have run into this kind of problem a few times. You might have hit one of them. It is the best if you contact the provider of the tool and ask for their opinion on the error, as well as how to fix it - either the code, or the tool. Just explain them what you explained us here.

To my knowledge, AUTOSAR is driven a lot by politics, and "science" is secondary. Therefore, many unusual or unexpected things can be found there.
I do not have a static analysis tool of any kind at the moment, so I cannot test it. But I think that the most correct way to define TRUE and FALSE in the context would be:
#ifndef TRUE
#define TRUE ((boolean)(1==1))
#endif
#ifndef FALSE
#define FALSE ((boolean)(1==0))
#endif

This overcomes 2 issues with the original definition:

*

*Compilers are allowed to define their internal TRUE and FALSE values to any values. While FALSE is usually (always?) 0, TRUE might actually have any non-zero value.

*With the new definition, the TRUE and FALSE actually have the boolean type.

The most recommended definition would be:
typedef enum boolean_tag
{
    FALSE,
    TRUE
} boolean;

which would make any other value completely illegal.
I am not sure if the following would work:
typedef enum boolean_tag
{
    FALSE = (1==0),
    TRUE = (1==1)
} boolean;

Comment (might not be applicable to your current situation):
Statements like
if ( boolean_variable )
{
    /* do_smth */
}

are not a best practice. If I remember correctly there was even a MISRA rule to use
if (boolean_variable == TRUE)
{
    /* do_smth */
}

instead - exactly in order to avoid conflicts with the inner workings of the compiler.


text:
Q: Creating a simple html server with Jersey and Java only Not sure why I'm having so much trouble finding a way to make a simple webserver with Jersey.
public class AnotherJerseyHttpServer {

    public static void main(String[] args) throws IOException {
        System.out.println("Starting Crunchify's Embedded Jersey HTTPServer...\n");
        HttpServer webServer = createHttpServer();
        webServer.start();
        System.out.println(String.format("\nJersey Application Server started with WADL available at " + "%sapplication.wadl\n", getURI()));
        System.out.println("Started Crunchify's Embedded Jersey HTTPServer Successfully !!!");
    }

    public static HttpServer createHttpServer() throws IOException {
        ResourceConfig rc = new PackagesResourceConfig("com.daford");
        // This tutorial required and then enable below line: http://crunfy.me/1DZIui5
        //rc.getContainerResponseFilters().add(CrunchifyCORSFilter.class);
        return HttpServerFactory.create(getURI(), rc);
    }

    private static URI getURI() {
        return UriBuilder.fromUri("http://" + sHostname() + "/").port(4444).build();
    }

    private static String sHostname() {
        String hostName = "localhost";
        try {
            hostName = InetAddress.getLocalHost().getCanonicalHostName();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return hostName;
    }
}

AND
@Path("api")
public class RestAPI {

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String get() {
        return "this works";
    }
}

And I can do http://localhost:4444/api and get "this works". Now how do I allow for an html file based on the incoming URL? I get the various MediaType/mimi info, but I can't find anything online to tell me how to just return a file based on the incoming URL.

A: Assuming that the file you need to return is packed in your WAR file, you could try the following solutions:
Using Google Guava
@Path("/{fileName: .+}")
@Produces(MediaType.TEXT_HTML)
public class HtmlResource {

    @GET
    public Response getPage(@PathParam("fileName") String fileName) throws IOException {
        URL url = Resources.getResource(fileName);
        return Response.ok(Resources.toString(url, Charsets.UTF_8)).build();
    }
}

Using Plain Java Code
@Path("/{fileName: .+}")
@Produces(MediaType.TEXT_HTML)
public class HtmlResource {

    @GET
    public Response getPage(@PathParam("fileName") String fileName) throws IOException {
        InputStream stream = HtmlResource.class.getClassLoader()
                                 .getResourceAsStream(fileName);
        String responseContent = read(stream);
        return Response.ok(responseContent).build();
    }

    private String read(InputStream stream) throws IOException {
        try (BufferedReader buffer = new BufferedReader(new InputStreamReader(
                                             stream, StandardCharsets.UTF_8))) {
            return buffer.lines().collect(Collectors.joining("\n"));
        }
    }
}

For example, the fileName can be assets/index.html.