Is there any simplest way to create graphql server in next13 without using any toolkit (apollo, grafbase,graphql-yoga)

Question: I am trying to make the graphql server in next 13 without using any toolkit like apollo, grafbase,graphql-yoga. Just pure graphql server. But i am getting the error in the browser:Failed to load resource: the server responded with a status of 405 ()
Why I am unable to use this. Or can you please suggest the simplest way to create pure graphql server inside the next13.
HERE is my code:
api/graphql/route.js:
import schema from "../schema";
import resolvers from "../resolvers";
import {graphql} from "graphql";
import { NextResponse } from "next/server";
export async function POST() {
  // const { query } = req.body;
console.log("Helo")
  const response = await graphql(schema, query, resolvers);
  console.log(response);

  return NextResponse.json(JSON.stringify(response));
}

Trying to fetch like this:
app/login/page.js:
'use client';
import { useEffect } from 'react';

export default function GraphQLAPI() {
  useEffect(() => {
    const handleRequest = async () => {
      const response = await fetch('/api/graphql', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ query: '{ hello }' }),
      });

      const { data } = await response.json;
      console.log(data);
    };

    handleRequest();
  }, []);

  return
GraphQL API
;
}

Dependencies are:
"autoprefixer": "10.4.14",
    "bson": "^5.3.0",
    "dotenv": "^16.0.3",
    "eslint": "8.40.0",
    "eslint-config-next": "13.4.2",
    "graphql": "^15.8.0",
    "micro": "^10.0.1",
    "mongodb": "^5.5.0",
    "mongoose": "^7.2.1",
    "next": "13.4.2",
    "next-redux-wrapper": "^8.1.0",
    "postcss": "8.4.23",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "react-redux": "^8.0.5",
    "redux": "^4.2.1",
    "redux-devtools-extension": "^2.13.9",
    "redux-thunk": "^2.4.2",
    "tailwindcss": "3.3.2"

Please suggest me the simplest way to create graphql server without using any toolkit.
Answer: While I'd always recommend using a framework or library for this kind of thing (because most likely a lot more edge cases and security issues have been caught already) it is possible to do something like the following using graphql:
import { GraphQLError, graphql } from "graphql";
import { NextRequest, NextResponse } from "next/server";

function handler(req: NextRequest) {
  const { method, body } = req;

  if (method !== "GET" && method !== "POST") {
    return NextResponse.json(
      { message: "Method not allowed" },
      {
        status: 405,
        headers: {
          Allow: "GET,POST",
        },
      }
    );
  }

  const { query, variables, operationName } = body;

  try {
    const result = await graphql({
      schema,
      variableValues: variables,
      operationName,
      source: query,
    });
  } catch (err) {
    return NextResponse.json(new GraphQLError(err.message));
  }
}

export { handler as GET, handler as POST };

Note: You'll need to pass it your schema and handle the GET request. You could get from the url the query params and check for query and if that is not present, return another error similar to the method not allowed.


Drywall repair - trying to match texture

Question: There was a leak. And a hole made in the ceiling to solder the pipe. I attempted to repair the drywall and am having an issue with the texture. Interesting to note, if I turn on the ceiling lights, this is barely noticable. The color difference is due to the spotlight I used to take the picture. Once done, the whole ceiling will be painted.
For now, my question is what process/technique is used to get the less rough finish? I don't even know how to ask the question if I went to a hardware store. I'm assuming there's a tool that will give me a finer stroke than the drywall tools I used.
Comment: Maybe a finer/softer touch.  Texture matching is more of an art form than tool use.
Comment: I think your texture might be described as a stomp. Use a crowsfoot brush and pull down. That said, texture (especially this) is really tough.
Comment: Thanks, watching his videos now.
Comment: I think your first problem is getting the base even with the rest of the drywall.  I can see your repair is "lower" than the surrounding texture.
Comment: https://youtu.be/9l02eMhsRpQ — decent video
Comment: Good eye. Now, when I add more joint compound to adjust the texture, I'll also look to level it better. The Drywall I added must have been 1/8" thinner.
Answer: That texture is done with a paint brush.
Make what you have smooth.
Apply compound and use a paint brush the width of the swirls and swooshes you have originally.
Use a light touch and move the brush in the compound at about a 15 degree angle.
The bristles will make the high and low "canals"
Practice on some scrap first.
Varying the pressure on the brush will make the patterns more random.
I think you will find swiping the brush in an arc and lifting it while still moving will closely replicate that finish.
Good Luck...Practice...Practice...Practice.
Comment: Thanks. I'll take your advice and practice on scrap drywall first.
Answer: RMDman had some good thoughts.
Another thing to consider:  the lighter color your paint, the less noticeable any texture imperfections will be.
Answer: I have had good results with a sponge in a plastic bag for this effect.
If you've used a trowel or float before you may have experienced the float 'sticking' to the material; it feels like suction, it's difficult to pull the float directly off, so you have to slide in one direction pulling at the same time. The floated finish is not dissimilar to the photo you provided.
So replace the float for a sponge at least the size of a small float, place inside a bag, apply finish evenly, press the sponge into finish; not at an angle, but flat/parallel to the surface, then move it in the direction you want the swirl, lifting gently at the same time. You will need to practice this on some spare material to perfect your technique.
Comment: Thank-you. I'll practice this one if the brush isn't close to what I'm looking for. I don't need a perfect result, I know a nice thick coat of paint will cut down on the difference in look. Good enough is good enough.


Using variables in qt StyleSheets

Question: Is there any possibility of giving variable name to hex/rgb numbers in .qss file . For eh
myColor = #FFCC08
QPushButton { background-color: myColor;}

So that i can define the variable at the top of the stylesheet and use the variable name whereever required instead of using the hex code. Also if i need to change the color then i have to change in one place and it will be reflected throught the file.
I also searched for Saas but don't know how it can be used in qt.
Thanks :)
Answer: You could build your own tiny Sass quite easily:
1.Create a text file with definitions of variables. Use simple format like this:
@myColor  = #FFDDEE
@myColor2 = #112233
@myWidth  = 20px

2.In qss file use variable names:
QPushButton {
    background-color: @myColor;
    min-width: @myWidth;
}

3.Open both files and for each variable in definition file change its occurrence in qss file with the value (string) from the definition file. It is a simple string replacement.
4.Apply the preprocessed qss in the app.
This is the simplest solution. You can change both definition file and qss file outside the app and apply it without recompilation of code.
Comment: Thanks for your time. I used the same logic to create my own parser that replaces each custom variable-color that is defined in the .qss file with the actual color.
Answer: What you're trying to accomplish simply isn't possible using pure Qt style sheets.
You can achieve a similar effect by modifying and reloading your style sheets from within your C++ code, for example:
QString myColor = "#FFCC08";
QString styleSheet = "QPushButton { background-color: %1;}";
...
myWidget->setStyleSheet( styleSheet.arg(myColor) );

Unfortunately this has several drawbacks (inability to preview in designer, changing code rather than a style sheet), but it's about as close as you can get to what you're trying to achieve with Qt.
Comment: Yes I understand but the problem with the above approach is that we are specifying the stylesheet properties within the c++ code for each component and not reading from a .qss file. Thanks for your time.
Answer: Another way to accomplish this would be to use Dynamic Properties.  This would let you easily assign multiple properties to an object or group of objects, sort of like assigning a css class to an object.
https://wiki.qt.io/Dynamic_Properties_and_Stylesheets
For example, in your UI file, you could add a string dynamic property "colorStyle" with a value of "myStyle1".

Your stylesheet would look like:
QPushButton[colorStyle='myStyle1'] {
    background-color: #FFCC08;
    ... any other style changes...
}

Any QPushButton you assign 'myStyle1' will follow the stylesheet if you set it globally.
Answer: Here is a solution using sass. First, install the python bindings:
pip install sass

Then, use it:
import sys
import sass
app = QApplication(sys.argv)

# Create your sass style sheet (you can also write this in a file and load the file)
style = '''
$bg-dark: #292929;

QPushButton {
color: red;
background-color: $bg-dark;
}
'''.encode('utf-8')

# Compile Sass to CSS
style = sass.compile_string(style).decode()

# And set it to your app
app.setStyleSheet(style)

Comment: Good point, that works too for this particular answer. But sass can do more than just replacing variables, like mixins, imports, nested rules, etc. In the end, you can style complex applications much more easily and elegantly.
Comment: If you are using Python anyway, why not use the built-in string formatting, with kwargs, instead of `sass`? E.g. `'... background-color: {bg_dark}; ...'.format(..., bg_dark='#292929', ...)`
Answer: I have similar, but different problem. In my case, I want to connect window size to QCheckBoxIndicator. Code below won't work due to css already use the {}.
        self.checkBoxYes.setStyleSheet('''
        QCheckBox::indicator {
        width: {sz} px;
        height: {sz} px;
        }
        '''.format(sz=rel_sz))

However, workaround can be achieved using old-formatted string below:
def resizeEvent(self, a0) -> None:
    rel_wdth = self.width() // 20
    rel_hgh = self.height() // 10
    rel_sz = str(min(rel_hgh, rel_wdth))
    self.checkBoxYes.setStyleSheet('''
        QCheckBox::indicator {
        width: %s px;
        height: %s px;
        }
        ''' %(rel_sz, rel_sz))
    return super().resizeEvent(a0)

Answer: You can use string concatenation in Python. It is easy to implement.
 self.setStyleSheet("""QPushButton { %s;}""" % (myColor))
Answer: Based on the answer by @Pucor I created this function to automate the process and avoid having to create two files:
def load_style(path: str):
    invalid_syntax = Exception('Invalid syntax')
    stylesheet = ''
    with open(path, 'r') as file:
        # Block posidion code:
        # Its used to make sure the syntax is consistent with the rest of the file (I know there are better ways)
        root_block = 0  # 0= No parsing done yet
        variables = dict[str, str]()    # Create an empty dictionary to store the variables

        for line in file:
            if ':root' in line:
                root_block = 1      # 1= :root label found, expecting opening bracket
            if '{' in line:
                if root_block == 1:
                    root_block = 2  # 2= opening brakcet found, the block is "safe" to read
                    continue
                else:
                    raise invalid_syntax
            if '}' in line:         # If the closing bracket is found, check the opening bracket has been found first
                if root_block != 2: # If not the case, throw an error
                    raise invalid_syntax
                # Else we reached the end of the block and the rsulting stylesheet is the rest of the file from this point
                else:
                    stylesheet = file.read()
                    break
            # If its safe to read, then split the key, values by a colon
            if root_block == 2:
                split = line.split(':')

                # Using match/case since its cool; store the variable in the dict
                match split:
                    case  [key, value]:
                        variables[key.strip()] = value.strip()
                    case _:
                        raise invalid_syntax

    # This pattern uses a logical OR to capture the words in the brackets
    # The dictionary keys are sorted in reversed since the regex engine only captures the first occurence
    # If p.e. "primary" is set before "primary-dark" then it will only capture "primary"
    pattern = re.compile('@(' + '|'.join(sorted(variables, key= len, reverse=True)).strip('|') + ')')
    # Replace each match with the value of the variables dictionary (group 0 is a match that contains the @)
    stylesheet = pattern.sub(lambda match: variables[match.group(1)], stylesheet)
    return stylesheet

Please note that the funciton is not bulletproof since it depends on a procedurally made regex capturing group at the end that I havent tested in depth..
Usage:
In your stylesheet.qss:
:root{
    primary: #1a1f1f
    primary-dark: #101010
    primary-light: #353535
    secondary: #2a82da
    secondary-dark: #163f68
}
QWidget{
    border: 0px;
    background-color: @primary;
    color: white;
}

The parser will start by storing all the "variables" inside the :root block and then replace each referenced variable starting with a @ in the rest of the file.
To use it in your application:
style = load_style('stylesheet.qss')
app.setStyleSheet(style)

I understand the code is messy and unreadable

Using variables in qt StyleSheets


How do I turn off the WPF XCeed DataGridControl alway selecting the first cell when the datagrid gets focus?

Question: I have several WPF XCeed DataGrids defined.
Whenever a DataGrid gets focus, the 1st cell of the DataGrid is highlighted.
I would like to turn off this behavior as I am handling my own selection for these grids.
Here is the XAML definition of the DataGrid:
<xcdg:DataGridControl
  x:Name="ReEnrollmentStepsDetailsGrid"
  VerticalAlignment="Stretch"
  HorizontalAlignment="Stretch"
  AutoCreateColumns="False"
  SelectionMode="Extended"
  SelectionUnit="Cell"
  AllowDrag="True"
  AllowSearch="True"
  ReadOnly="True"
  SelectionChanged="SampleGrid_SelectionChanged"
  Style="{StaticResource SampleGridStyle}"
  ItemContainerStyle ="{StaticResource SampleGridRowStyle}"

After reading several posts, I tried adding the following attribute to my XAML definition.
SynchronizeCurrent="False"

That attribute doesn't seem to have any effect. I still get the same results.
How do I disable this (what appears to be) default behavior?
Thanks
Answer: You can accomplish this by using adding some code behind for the Loaded event.
GridControl xaml:
<xcdg:DataGridControl
     ...
     Loaded="DataGridControl_Loaded">

c# code begin:
private void DataGridControl_Loaded(object sender, System.Windows.RoutedEventArgs e)
{
    if (sender is DataGridControl dg)
    {
        dg.SelectedItem = null;
    }
}


Trouble creating surveys with iOS elements

Question: I'm working with a client on a project that will include survey elements within the app.  There are a few survey elements that I've never seen on a native app and would appreciate some guidance on how best to construct the elements, or a close approximation.

Static Text Response, Long form or fill in the blank (Easy these are UITextFields of UITextView)
Multiple Choice Question single or multiple answer (A UIPicker would work for single selection but not sure how to do this for multiple selection)
Matrix Table, single and multiple answer -- I'm unsure how to begin to tackle this, I'd assume a picker for each row in the table but that seems messy and like the UI would deviate very far from the same form on the web.
Ranking, Drag to order, stack ranking order, and Likert Scale -- I'm really grasping at straws on ranking.  Likert would make the most sense to use a UIPicker with traditional Likert options.  Stack ranking looks like I would use a picker on each value to select a value, but it would seem like I would need to do a significant amount of error handling so I don't give two values the same rank.  Is there a simpler/cleaner solution?
Answer: I guess it depends who is filling up that survey. If I was designing it for some enterprise solution or for beta testers of my app, I would make it condense and simple without focus on UI/UX, but if I'm building it for regular users of my app, I would split it up into multiple screens and try to make it pretty.
I would have some kind of an indicator at the bottom so the user knows how many questions are ahead. It can be a number representation (2/13) or something like attached below if there aren't too many questions.
In order to move to next question I would have the NEXT button in the upper right + users could swipe left/right between questions.
Static question with textView (multi line input). I would preselect the input field so users don't have to tap it. Also remember that the keyboard would cover the bottom of the app so maybe consider sliding the indicators above the keyboard as it appears.

Multiple answers is pretty simple. Users toggle on/off things they agree with

Matrix alternative. I would break it down so people can focus on one question at a time, but I would still try to have all questions of same type close to each other and maybe with same indicator color on the bottom.

Ranking is a bit more complex and I guess it could be done in multiple ways. You can ask users to tap on choices in order of preference and then offer dragging options up and down to change their order.

I hope that helps or gives you another perspective.
Please let us know what you did in the end. Good luck.
Answer: I've never been a fan of long forms. No one is.
However, forms are an essential method of taking user inputs in bulk.
Recently, one startup is changing the way how we perceive forms & helping create a somewhat pleasant user experience - Typeforms
I know this might sound out of context right now, but we'll get there.

Neat Minimal Forms = No distractions
One Input element at a time = Focus and user's attention
Progress Indicators = User's awareness about the progress
Beautiful Transitions among pages = User's engagement

Now, I don't work for them or anything, but from the UX point of view it's a win.
Coming to your problem with creating lengthy forms on mobile device - here are the takeaway points:

Break the flow of the form into singular units - one at a time
Now, you have an entire screen for displaying current problem and inputs as well as overall user progress to create a state of awareness.
You can use white space or negative space to improve readability, focus and reduce the clutter

Finally, Since you are restricted to using iOS default elements and have to create your experience using them - there is always a crafty way to utilize existing stuff.
Example: Let's say you have to do a multiple choice button with some description text and 5 choices, you can use plain buttons but the same can also be achieved using a list-controller with 5 items. Each Item is clickable and should take you to the next question directly.
The main motif of this exchange is to discuss UX in general and not for a product specific problem. The answers should be generic enough to help anyone in need. So you have it, List out your tools, get a big (huge) sample of questions, try and create a list of all the unique type of questions there are, create another list of all the various controls you have at your disposal (work with your developers with that), come up with a mapping of how different type of questions can be represented using which iOS elements and you're good to go.
UX design is all about understanding the problem, finding right approach through research and solving it the most intuitive way - always pushing the boundaries of what can be done :)
PS: Sorry for going overboard with whole "That's how we UX" Speech :)
Cheers


save value after postback at client side using jquery

Question: i need to save the value after postback. for ex: i have different tab in the page. when user click on tab i getting the value based on the tab name bind the repeater control. each time when user click on tab same repeater control bind with different. now in the repeater control i have checkbox. so for ex user is in the first tab and check the checkbox and it clicked on second tab. i need to get previous tab checkbox value at client side using jquery or javascript.
please help me.
Answer: I don't really understand what you're saying, but maybe localStorage can help?
localStorage.setItem('foo_value', 1)

Then when you the user goes back to the old tab...
value = localStorage.getItem('foo_value')
// Do something with the value

Comment: i need to preserve value after postback at client side using script.what is "localstorage" ? can i write above line in script or somewhere else.
Comment: Yeah, localStorage is javascript, it stores data on the client side.


Custom templates using 'radioContainer' in Cakephp 3

Question: My default radio inputs are like this
$this->Form->radio('email_notifications', ['one','two']);

I have this in default:
<input type="radio" id="usertype-0" value="0" name="userType">
one

And need to rephrase this structure to:

    <input type="radio" id="usertype-0" value="0" name="userType">one

Had tried with custom templates. It works fine with 'inputContainer', but not 'radioContainer'. Had used the following to test, by adding a div for radio buttons:
$this->Form->templates([
       'radioContainer' => '{{input}}{{text}}
'
 ]);
But nothing work for me as I get only the default structure. Am I doing someway wrong? I tried to  configure with reference to this too: Cakephp 3 multiple custom template formhelpers
Answer: I'm not sure what makes you think there would be a template named radioContainer, maybe this existed in earlier versions? The radio element related templates are radio and radioWrapper.

http://book.cakephp.org/3.0/en/views/helpers/form.html#list-of-templates (not completely up to date yet)
https://github.com/cakephp/cakephp/blob/603f4ee01735f2e8e3c2283540199b4bba70ded7/src/View/Helper/FormHelper.php#L103-L104

Anyways, the default output looks different to what you are showing, by default radio elements are nested in label elements, ie exactly what you are looking for according to your sample code.
This
$this->Form->radio('email_notifications', ['one','two']);

will generate the following HTML (indentations and linebreaks added by me)
<input type="hidden" name="email_notifications" value="">

    <input type="radio" name="email_notifications" value="0" id="email-notifications-0">one

    <input type="radio" name="email_notifications" value="1" id="email-notifications-1">two

So the fix should be to update to the latest (dev) version.
Comment: I had used the version available [here](http://bakery.cakephp.org/articles/lorenzo/2014/09/28/cakephp_3_0_0-beta2_released). I should update it?
Comment: Updating to latest dev version, throws error = > Error: Unable to locate widget class "Cake\View\Widget\BasicWidget"
Comment: @G.J I can't help you with that error, at least not without seeing the exact stacktrace and the related code, also this might be something for new question. Please try your form code with a fresh CakePHP installation.
Comment: I fixed this by updating to latest version. Thanks for the shot!


Angular create reusable/generic html-structure

Question: I thought it would be easy, but i cant find any solution for my problem.
So, i want to create a generic table.component. My idea is to give all the information that is needed by doing some expression stuff in html code.
the given data look like this:
  myData: [
    {
      id: 1,
      name: 'name1',
      stuff: 'stuff..'
    },...
]

table.component:
My thought is to use the column identifiers/titles to get the data-informations from the tableData - something like this: {{row}}.{{item}} // item is the column identifier, otherwise item is the identifier for the data-values and row is the current element out of the loop.
@Component({
  selector: 'app-table',
  template: `

{{tableName}}

          <ng-container matColumnDef="{{item}}">

             {{item}}
             {{row}}.{{item}}

          </ng-container>

  `,

  styleUrls: ['./table.component.css']
})
export class TableComponent implements OnInit {
  @Input() tableName: string;
  @Input() tableData: any;

  displayedColumns: string[] = ['id',  'name', 'stuff'];

  // doing in other component.
  tableData = myData;

Is there a (easy) way to concatenate two expression to create a new expression? (parse two expression to string, concatenate them to a dotted notation and parse them back to an expression?)
Answer: To dynamically access the row object's property, you have to use bracket notation instead of dot notation:
 {{row[item]}}

Also, since you're using Angular Material, you might be interested in using their MatTextColumn instead: https://material.angular.io/components/table/api#MatTextColumn
Answer: You can create a function that takes row and item as parameter:
getDataBy(row, item) => {
    return this.myData[row][item]
}

Comment: Ja thanks, just this notation {{row[item]}} is even enough :)!


ARM Ubuntu won't let me change my resolution

Question: I know this question has been asked at least twice, but I downloaded the 64-bit version of Ubuntu onto my Raspberry Pi 4. I looked at a few tutorials but I couldn't find anything that worked for changing my screen resolution. It decided to set my resolution to 1824 x 984 (9:5)
I have no clue how to fix this. Could the smart people of AskUbuntu please help me? I have the official version from the Ubuntu website. I have used lsb_release -a to find my version and it says I'm using Ubuntu 18.04.4 LTS.
I have used xrandr but the results are very strange:
ubuntu@ubuntu:~$ xrandr
xrandr: Failed to get size of gamma for output default
Screen 0: minimum 1824 x 984, current 1824 x 984, maximum 1824 x 984
default connected primary 1824x984+0+0 0mm x 0mm
   1824x984       0.00*
ubuntu@ubuntu:~$ xrandr --output default --mode 1920x1080
xrandr: cannot find mode 1920x1080

What do I write as the display? I have never used Ubuntu before and help would be appreciated. I don't even know how to change the file /boot/firmware/usrconfig.txt
Comment: Please click [edit] to let us know which release number?  Please do not use Add Comment; Comments are a channel from us to you, whereas the Question should contain all the facts you have about the issue.
Answer: I had this problem and this is how I fixed it. Open a terminal window and type
    nano /boot/firmware/usercfg.txt

(note you will need to run it with sudo, alternatively use any text editor). Then you can add the settings to set display resolution. Mine looks like this:
    # Place "config.txt" changes (dtparam, dtoverlay, disable_overscan, etc.) in
    # this file. Please refer to the README file for a description of the variouszn

    # configuration files on the boot partition.

    [HDMI:0]
    hdmi_group=2
    hdmi_mode=82
    hdmi_drive=2

    [HDMI:1]
    hdmi_group=2
    hdmi_mode=82
    hdmi_drive=2

Note the two groups HDMI:0/1 this is because RiP4 has two hdmi outputs and they can be configured individually. Also see that the hdmi_group=2 refers to computer monitors, 1 would be for television screens. hdmi_mode=82 refers to my resolution which is 1080p 60Hz. To find a full list of mode numbers that corresponds to resolutions and rates, you can go here:
https://www.raspberrypi.org/documentation/configuration/config-txt/video.md
Refer to hdmi_mode section.
Once these changes are made, you can restart.
Comment: This doesn't work for me. I had to use xrandr add mode and newmode calls to add a new resulution and activate it.
Comment: Worked, but the display contrast became low.
The background black turned into a white-ish black, and I haven't understood why.
Maybe something to do with scaling?  Anyone know?
Comment: Can confirm this solution still works for Ubuntu 20.04.
Answer: You can use:
% xrandr -q

to list the available modes to pick from.
Comment: This doesn't work and still returns message `xrandr: Failed to get size of gamma for output default`


What is the maximum group size for Dragonstar Arena in Elder Scrolls Online

Question: Our ESO group is looking at tackling Dragonstar Arena in Craglorn.
But the wiki says it's "aimed at groups of four players rather than twelve".
Does that mean it's limited to 4 players like a dungeon & we can't play as a group of 5 or 6? What is the maximum group size for Dragonstar Arena?
Answer: The game basically knows three sizes for its end game PvE "raid" content,so called trials:

Regular trials are challenges for up to 12 players:

Craglorn: Aetherian Archive
Craglorn: Hel Ra Citadel
Craglorn: Sanctum Ophidia
Reaper's March: Maw of Lorkhaj (requires Thieves Guild DLC)
Vvardenfell: Halls of Fabrication (requires Morrowind Chapter)
Clockwork City: Asylum Sanctorium (requires Clockwork City DLC)

Dragonstar Arena is a special 4 player trial you can find in Craglorn.
Mahlstrom Arena is a special solo trial you can find in Wrothgar (requires Orsinium DLC).


How can I make a function that returns a function?

Question: Big picture: I have a module with functions and a module with procedures and functions over those functions.
When I combine two functions (from function's module interface):
double f1(double alpha, double x);
double f2(double beta, double x);

In several ways, (one of them is adding):
double OP_Addition(double (*f)(double,double) , double (*g)(double,double), double param1, double param2, double x);

Gives no problem with the following (piece of) implementation:
z1 = (*f)(param1, x);
z2 = (*g)(param2, x);
y = z1 + z2;
return y;

But when I want to return a pointer to a "new" function, something like:
void *OP_PAdd( double (*f)(double,double), double param3 );

I can not get it to work properly, neither make the right "call". I want to have use the output "function" as input in other functions.
Comment: Note that C does not have lambdas (AKA anonymous functions). You can return a pointer to function in C, but that function must be declared at compile time. E.g. you can't take an integer and return a function adding such integer to its parameter. Or take two function pointers and return a pointer to the pointwise sum of these two functions. There might be some nonportable libraries for lambdas (or partial application), and lambdas are built-in in C++ now, but there's no built-in support in C.
Comment: @chi *yet*. WG14 seems to like [this proposal](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2030.pdf) to add lambdas to the language for C2X.
Comment: Functions are not first order objects in C. You can pass around pointers to existing functions, but functions itself are not objects that can be created or passed by value. I suspect you may come from a functional or dynamically typed language background (OCaml, Haskell, Python, Ruby, Lisp), where functions *are* first order objects. Note that this is not an inherent limitation of imperative low-level programming. There are other compiled system programming languages where functions are first order objects. Also as @chi pointed out there's a proposal to add this to C2x.
Comment: I don't understand what you're trying to do and what you mean by "can not get it to work properly".
Comment: Why do you ask, and what actual application do you have in mind?
Comment: Can you give a more concrete example of what you're trying to accomplish?  Perhaps then we can offer a more concrete answer.
Answer: When returning a function from another function, the cleanest way to do this is with a typedef:
typedef double (*ftype)(double, double);

Then you can declare your function like this:
ftype OP_PAdd( ftype f, double param3 )
{
    ....
    return f1;
}

You can do this without a typedef, but it's messy:
double (*OP_PAdd( double (*f)(double,double), double param3 ))(double,double)
{
    return f1;
}

So when you have function pointers as either parameters or return values of other functions, use a typedef.
EDIT:
While you could declare the type like this:
typedef double ftype(double, double);

You can never directly use a type like this in practice.  A function can't return a function (only a pointer to a function), and a variable of this type can't be assigned to.
Also, you don't need to explicitly dereference a function pointer to call the function, so the fact that the pointer itself is hidden is not a big issue.  It's also convention to define function pointers as a typedef.  From the man page for signal:
   #include <signal.h>

   typedef void (*sighandler_t)(int);

   sighandler_t signal(int signum, sighandler_t handler);

Comment: In general, yes it's not a good idea to hide pointers within typedefs.  But the case of functions, it's unavoidable.  There's no such thing as a function type, only a pointer to a function.
Comment: Nonsense: `typedef double ftype(double, double); ftype *OP_PAdd(ftype *f, double param3);`
Comment: I don't like hiding pointers behind typedefs. I think it's better to make `ftype` an actual function type, then return `ftype *`.
Comment: @melpomene Functions in parameters are automatically adjusted to function pointers.
Comment: @melpomene; Moreover, typedefing function in this case makes code clean and more readable.
Comment: "*You can never directly use a type like this in practice.*"  You actually can, for silly reasons: `void foo(ftype f)` works.
Comment: @melpomene: I can think of lots of good reasons to never hide "object pointers" (C's term for non-function pointers) behind typedefs, but none of them apply to function pointers. And the implicit function-to-function-pointer conversion obviously makes the distinction less significant. Can you explain your rationale for applying such a rule to function pointers?
Comment: @haccks I never argued against `typedef`ing in general.
Comment: @sleeptightpupper Yes, that's the silliness I was referring to.
Comment: @ruakh No, at this point it's just a gut feeling. I don't have a good argument.
Answer: Other answers are correct and interesting, but you should be aware that in portable C99, there is no way to have genuine closures as C functions (and this is a fundamental limitation of C). If you are not aware of what closures are, read the wiki page carefully on them (and also read SICP, notably its §1.3). Notice however that in C++11 you do have closures, using std::function and lambda-expressions. And most other programming languages (Ocaml, Haskell, Javascript, Lisp, Clojure, Python,  ....) have closures.
Because of the lack of genuine closures in C ("mathematically" the only closed values in C functions are global or static variables or literals), most libraries accepting C function pointers provide an API handling callbacks with some client data (a simple example could be qsort_r, but more seriously look inside GTK). That client data (generally an opaque pointer) can be used to keep closed values. You probably want to follow a similar convention (so systematically pass function pointer as callbacks with some additional client data), so you'll need to change the signatures of your C functions (instead of passing just a raw function pointer, you'll pass both a function pointer and some client data as a callback, to "emulate" closures).
You could sometimes generate a C function at runtime (using non-standard features, probably with the help of the operating system or some external library). You might use some JIT compiling library such as GNU lightning, libjit (both would generate some slow-running code quickly), asmjit (you'll generate each machine instruction explicitly, and it is your responsibility to emit fast x86-64 code), GCCJIT or LLVM (both are above existing compilers so can be used to emit -a bit slowly- some optimized code). On POSIX & Linux systems, you could also emit some C code in some temporary file /tmp/tempcode.c, fork a compilation (e.g. gcc -fPIC -Wall -O2 -shared /tmp/tempcode.c -o /tmp/tempcode.so) of that code into a plugin, and dynamically load that generated plugin using dlopen(3) & dlsym(3)..
BTW we don't know what the actual application you are coding is, but you might consider embedding inside it some interpreter, e.g. Lua or Guile. You'll then use and provide callbacks to the embedded evaluator/interpreter.
Comment: DV because "...there is no way to have genuine closures as C functions" - I just explained how to do it, without relying on machine-dependent inline assembly, and only using standard functions.
Comment: I down-voted because I feel you assumed they meant newly generated when they stated "new" (their quotes, not mine), and the general discussion of closures and other languages - Since they specified C as a tag, this was largely irrelevant, although it was quite interesting :).  I did appreciate loading in a newly compiled module, as I've done that in the past.  I would remove the down-vote if you added a something similar to @dbush's answer.
Answer: Do you mean something like this? The decider() function returns a pointer to another function, which is then called.
#include <stdio.h>
#include <stdlib.h>

typedef double(*fun)(double, double);

double add(double a, double b) {
    return a + b;
}

double sub(double a, double b) {
    return a - b;
}

double mul(double a, double b) {
    return a * b;
}

fun decider(char op) {
    switch(op) {
        case '+': return add;
        case '-': return sub;
        case '*': return mul;
    }
    exit(1);
}

int main(void)
{
    fun foo;

    foo = decider('+');
    printf("%f\n", foo(42.0, 24.0));

    foo = decider('-');
    printf("%f\n", foo(42.0, 24.0));

    foo = decider('*');
    printf("%f\n", foo(42.0, 24.0));

    return 0;
}

Program output:
66.000000
18.000000
1008.000000

EDIT: Following comments under the @dbush answer, this version steps back from the typedef as a pointer, to just a function. It gives the same output, but in decider() it compiles cleanly and gives the correct output, no matter whether I write return add; or return &add;
#include <stdio.h>
#include <stdlib.h>

typedef double(fun)(double, double);

double add(double a, double b) {
    return a + b;
}

double sub(double a, double b) {
    return a - b;
}

double mul(double a, double b) {
    return a * b;
}

fun *decider(char op) {
    switch(op) {
        case '+': return add;     // return &add;
        case '-': return sub;
        case '*': return mul;
    }
    exit(1);
}

int main(void)
{
    fun *foo;

    foo = decider('+');
    printf("%f\n", foo(42.0, 24.0));

    foo = decider('-');
    printf("%f\n", foo(42.0, 24.0));

    foo = decider('*');
    printf("%f\n", foo(42.0, 24.0));

    return 0;
}

Comment: @WeatherVane The compiler knows the difference.  The latter will generate a warning:  `format '%s' expects type 'char *', but argument 2 has type 'char (*)[6]'`
Comment: C is very loose about converting function types to function pointer types.  For example, to get a pointer to a function, you can use the function name by itself, or you can apply the address-of operator `&`, and it will work either way.  Similarly, when invoking a function through a function pointer, you can explicitly dereference the pointer when calling the function, or you can omit the `*` and again it will work either way.  I personally would prefer it if C were more strict about requiring the address-of and dereference operators, but for historical reason it's not.
Comment: @WeatherVane: Not sure I know what you mean. `str` and `&str` **do** yield a different result! Most likely not the value (buit even that is not guaranteed), but just the type, but they differ very well.
Comment: @WeatherVane: Again: It might give the same **assembler code**, but not the same result. A function name will be converted to a pointer to that function, as will `&func`. For an array, the types will not be the same. So different semantics and any better compiler will warn about a type conflict for the array-case.
Comment: @WeatherVane: It is wrong from the language aspect. And an implementation might generate different values (e.g. if the type is encoded in the pointer - unlikely for current systems, but allowed). Also the compiler might generate any kind of code, as that invokes undefined behaviour. For a function, it is well defined that both `func` and `&func` **here** generate excactly the same result (i.e. including the same type). Things differ for e.g. `sizeof` where `sizeof(func)` is UB per definitionem.
Comment: @WeatherVane; `str` and `&str` are not the same thing. `str` will decay to *pointer to it's first element* while `&str` is the address of array `str` itself. In case of `function` both `func` (after conversion) and `&func` are address of function. There is nothing like elements in case of function.
Comment: @melpomene interesting comments under **dbush** answer, so I added a second version here. But I am unsure why the function return value works both ways, as I remarked in the revision.
Comment: @TomKarzes thank you, I was expecting `return add;` to generate a compiler error along the lines of "ill-formed function call".
Comment: Perhaps there is a parallel with this: `char str[42];` followed by `scanf("%s", str);` or `scanf("%s", &str);` In MSVC either is acceptable but in an earlier question I was told the latter is an error. Certainly it would be if `str` was a pointer, not an array.
Comment: @WeatherVane: `&str` has the wrong type and a modern compiler which checks those variadic arguments against the format string should definitively warn about that type-missmatch.
Comment: @Olaf my point was why is it right with a function but not with an array? How can `str` give anything different to `&str` when `str[]` is an array (not a function argument)?
Comment: @Olaf part of my edit to this answer, was to ask why the function is acceptable either as `add` or `&add` and was drawing a comparison with the array example using `str` or `&str`. In both examples, each coding give *exactly* the same result.
Comment: @Olaf I repeat: `scanf("%s", str);` and `scanf("%s", &str);` have **exactly** the same result. What else could possibly be different? There is only one piece of information about the array `str` apart from its type and size.
Comment: @dbush we have been through that. I am asking why it's ok for a function but not for an array. OIaf said the assembler code might be the same, but... that's my point: it's the same.
Comment: But surely a reference to the array `str` decays to a pointer, whereas `&str` is the address of the array, which is the same thing. So what *is* the difference?
Answer: in C, you can return pointer to function, but to do that, function needs to exist first, and dynamically creating functions is not something C says is possible, never mind how to do it
if your code is going to work only on one OS and one processor (and probably some other restrictions), you may be able to:

allocate page of memory
write data and machine code doing what you want, calling functions passed by pointer etc.
change memory protection from read/write to read/execute
return pointer to created function
don't worry that you you need 4kB per function

there probably are somewhere libraries for that, but necessarily not portable
Comment: Some libraries are able to generate a new C function (with non-portable tricks or operating system help). See [my answer](http://stackoverflow.com/a/37775530/841108).
Answer: So you want a function to return a pointer to a function.
double retfunc()
{
   return 0.5;
}

double (*fucnt)()
{
  return retfunc;
}

main()
{
   printf("%f\n", (*funct())());
}

Answer: Since some people are apparently paranoid about writing a hack to solve this problem, here's a less-hacky way to do it: Use a static struct with setjmp and longjmp.
jmp_buf jb;

void *myfunc(void) {
    static struct {
        // put all of your local variables here.
        void *new_data, *data;
        int i;
    } *_;
    _ = malloc(sizeof(*_));
    _.data = _;
    if (!(_.new_data = (void *)(intptr_t)setjmp(jb)))
        return _.data;
    _.data = _.new_data;
    /* put your code here */
    free(_);
    return NULL;
}

To explain what's going on here, setjmp will return a value of 0 when the jump buffer is created, otherwise it'll return the value passed by longjmp (eg. longjmp(jb, 5) will cause setjmp to return 5).
So, what we're doing is having our function return a pointer to it's allocated data structure; and then calling our closure like:
void *data = myfunc();
longjmp(jb, (int)(intptr_t)data);

Please note that an int is not guaranteed to be large enough to store a pointer on all platforms; so you may need to create a data pool and return/pass the data by handle (index in the pool).
As I've stated before, a closure is just a function with all of it's data allocated on the heap.
I've been writing hacks for N64 and PSP games for years. People claiming that this is impossible have likely never tinkered with that kind of stuff. Mostly just boils down to a lack of experience.
Comment: Interesting hack. Unfortunately it is not standard conforming. By the standard `setjmp` cannot appear in assignment expressions and `longjmp` may not refer to a `jmp_buf` initialize  in a function scope that is now dead.  Also you should at least ensure that `_` is `_Thread_local` and `volatile`.
Comment: Good point. In any case, there are other ways to implement closures in C. I won't say they're pretty, but the concept is simple enough. Just allocate the state for the closure on the heap. Actually, I used this same trick a long time ago to implicitly pass a 'this' parameter to functions to fake classes in C. Didn't think about it back then, but it's technically closures.
Comment: Your approach doesn't make a function (pointer), it makes an object that needs to be handled differently from an ordinary function (pointer). If that can be admitted as a solution, why not just use a struct containing a function pointer and some state and call that as `someStruct->funPtr(someStruct)` in order to implement closures? I don't understand why you need these complicated things.
Comment: Since "you've been writing PSP hacks" and "it boils down to lack of experience", I hope you'll accept some feedback from one of the main HBL devs (back in the MoHH/Patapon exploits days). There is *no portable way* to do it in C. Other commenters have already highlighted the flaws in your approach. The only ways are 1) using a global var to keep the allocated state (portable, but bye bye multithreading) or 2) dynamically generating an assembly trampoline (arch and OS specific, since you need *executable* memory). Of course you'd wrap everything up in #defines to keep sanity.
Comment: By the way, this works only if your function is very simple (no stack state, everything's in registers) or if the stack isn't touched between `myfunc()` and `longjmp(...)`, so that the saved SP still points to valid local state. In your example, it depends on how much stack `longjmp` trashes. (This is because you're jumping to a dead scope)
Comment: @AndreaBiondo "There's no portable way to do it in C"...This post was actually meant to be an alternative to my previous post which was downvoted because it implemented a stack smash via setjmp that relocated the current stack frame to the heap; and that's apparently scary to some people. Note that the technique does both of the things you mentioned; and entirely in C using only standard functions. Also note that I declared the fake 'stack' as `static` in the above answer so that it wasn't included in the stack frame itself.
Comment: @DeftlyHacked I appreciate cool hacks (and yours are), but what you propose in the other post is *not* a good idea. You're assuming the stack layout, and you *don't* know that. What if I use a different compiler/arch/ABI/layout? About `static`, I didn't notice it at first, but it blows reentrancy out of the window, just like global vars. The point I'm making is that the `myfunc` scope which `setjmp` stores is dead. The fact that `_` is not on the stack doesn't change that.
Comment: @DeftlyHacked Also (after fixing syntax errors) I compiled this answer with GCC 6.1.1, on a x86_64 Fedora 24 box. I got a segfault. I go check it out, and I find GCC is loading a value from stack when getting back control (after `setjmp`), then it dereferences that value and crashes because it's crap. That is because the stack got corrupted. Even if `_` is not on the stack, GCC is still using (in my case) 16 bytes of stack.
Comment: _ isn't on the stack. it's a static object. not sure why you got a segfault, but this was merely a proof-of-concept anyway. I didn't actually test it.
Comment: @DeftlyHacked I didn't say it was (it isn't). It segfaults because of what I said earlier: this works if `myfunc()` doesn't use the stack or if it isn't touched between `myfunc()` and `longjmp()`. None of which is true 99% of the time. Making locals `static` often won't keep the compiler from using a minimal amount of stack. Sorry if it sounds like a rant, didn't mean it to be one :)
Comment: Well, there is one way to portably solve this problem in C that I can think of off the top of my head. If you create a dummy-func that just calls setjmp and returns; and then call it from 2 different scopes; you can do a memory comparison of the 2 stack frames and the only thing that's different should be the return address. Any time you want to call a closure, call the dummy first, and copy the return address of the dummy over the return address in the stack frame of your closure.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/121785/discussion-between-andrea-biondo-and-deftlyhacked).
Answer: I'm gonna get really hacky here, so hold on to your breeches.
The standard C api comes with a 2 functions called setjmp and longjmp. Poor naming aside, what they essentially do is store a copy of the current state (including the stack position and register values) into a jmp_buf (or, the technical name, a continuation).
Now, lets say you create a function:
jmp_buf jb;

void sfunc(void) {
    void *sp_minus1 = 0xBEEFBABE;
    setjmp(jb);
}

When you call sfunc, a stack frame will be created. Because there are no arguments to this function, the first entry in the stack will be the return address and immediately after it will be the sp_minus1 object.
Why is this relevant? Well, the address of sp_minus1 is relative to the start of the stack frame. If you can find the address of the stack frame in jb, you can change it...say, to a location in the heap?
What we've got at this point is a way to create stack frames for longjmp function calls on the heap that can contain additional state about the context in which they were called; or in other words, closures.
I don't think I've ever seen anyone use longjmp/setjmp this way, but if you're looking for a way to dynamically generate and return functions in C, I think this would be your best route.
EDIT:
Here's an example implementation of the hack I'm describing:
#include <inttypes.h>  // intptr_t
#include <setjmp.h>    // longjmp, setjmp
#include <stdio.h>     // printf
#include <stdlib.h>    // malloc, free
#include <string.h>    // memcpy

typedef struct {
    jmp_buf jb;
    int fixupc;
    int fixupv[10];
    size_t stack_size;  // this is only an approximation
    void *stack_ptr;
} CLOSURE;

int getclosure(CLOSURE *closure) {
    unsigned int i, size;
    void *i_ptr = &i, *sp;
    unsigned char *data = (unsigned char *)(void *)closure->jb;
    memset(closure, 0, sizeof(CLOSURE));
    if (!setjmp(closure->jb)) {
        printf("looking for 0x%08X...\n\n", (unsigned int)(intptr_t)i_ptr);
        for (i = 0; i < sizeof(closure->jb); i++) {
            memcpy(&sp, &data[i], sizeof(void *));
            size = (unsigned int)(intptr_t)(sp - i_ptr);
            if (size < 0x300) {
                closure->fixupv[closure->fixupc++] = i;
                printf("  fixup @ 0x%08X\n", (unsigned int)(intptr_t)sp);
                if (sp > closure->stack_ptr) {
                    closure->stack_size = size;
                    closure->stack_ptr = sp;
                }
            }
        }
        if (!closure->stack_ptr)
            return 0;
        printf("\nsp @ 0x%08X\n", (unsigned int)(intptr_t)closure->stack_ptr);
        printf("# of fixups = %i\n", closure->fixupc);
        /*
         * once we allocate the new stack on the heap, we'll need to fixup
         * any additional stack references and memcpy the current stack.
         *
         * for the sake of this example, I'm only fixing up the pointer
         * to the stack itself.
         *
         * after that, we would have successfully created a closure...
         */
         closure->stack_size = 1024;
         sp = malloc(closure->stack_size);
         memcpy(sp, closure->stack_ptr, closure->stack_size);
         memcpy(&data[closure->fixupv[0]], &sp, sizeof(void *));
         closure->stack_ptr = sp;
         return 1;
    } else {
        /*
         * to this bit of code right here
         */
        printf("holy shit!\n");
        return 0;
    };
}

void newfunc(CLOSURE *closure) {
    longjmp(closure->jb, 1);
}

void superfunc(CLOSURE *closure) {
    newfunc(closure);
}

int main(int argc, char *argv[]) {
    CLOSURE c;
    if (getclosure(&c)) {
        printf("\nsuccess!\n");
        superfunc(&c);
        free(c.stack_ptr);
        return 0;
    }
    return 0;
}

This is technically a form of stack smashing, so by default, GCC will generate stack canaries that cause the program to abort. If you compile with '-fno-stack-protection', it'll work.
Comment: I don't want to think what kind of can of worms this opens. But then again, maybe I fear it because I don't know it.
Comment: @DeftlyHacked Interesting!  I'll  have to play around with this.  btw, I though you downvoted the post you commented on.
Comment: Well, I meant to, but at the time, I didn't actually have the privilege. If you find this interesting, you may also find it cool that you can use this same technique to create exploits. Setjmp/Longjmp pretty much indirectly gives you control of the stack pointer, and once you have that, arbitrary code execution is possible. I believe libpng was once used to exploit a gaming console like this.
Comment: This is an implementation specific trick. As you are saying, some valid compilers or options (`-fstack-protection`) disallow such a trick.
Comment: @BasileStarynkevitch, if you bothered to read the last line of the post, I specifically stated, "This is technically a form of stack smashing, so by default, GCC will generate stack canaries that cause the program to abort. If you compile with '-fno-stack-protection', it'll work.". The OP merely asked how to return a pointer to a new function; he didn't say that it couldn't involve disabling safety precautions and hacking the stack pointer. Pretty much all C threading libraries do this same trick (eg. libmill); they just do it in assembly instead of C.
Comment: @DeftlyHacked It's not just stack smashing. You'd be scribbling all over the heap since your new stack pointer is incorrectly set up on all architectures I know of except HPPA. This is assuming you managed to overwrite the stack pointer at all, which I'm not so sure about. I'm pretty sure you're just overwriting the saved register that happened to contain `&i` considering that many operating systems (including Linux) use xor cookies on the sp and ip in the `jmp_buf` to prevent exploits from doing what you just tried to do.
Comment: Yup. Just checked. On my flavor of Linux you're thinking that the stack pointer is where a normal register is saved, which happens to contain some garbage value (garbage since it's not used in this function at all) that happens to be close enough to the value you're looking for.
Comment: @Art, if you read the code, you can see that's how it's intended to work. It initializes a jmp_buf with setjmp. Then, it searches for any values within it that are within 0x300 bytes of the address of a local variable. It's reasonable to assume that anything that close is also on the stack; so it adds those matches to a list of fixups. After all of the fixups are found, it's assumed that because stack grows downward that the fixup with the highest address is the address of the stack frame. We allocate more memory than we need and just memcopy. Hence the comment, "this is only an approximation"
Comment: @Art, please note that this function's purpose isn't to alter the return address of the stack frame, it's to preserve the stack frame by relocating it to the heap before the stack is unwound; that way the original context (the state of all local variables) when setjmp was called is preserved; just like a closure.


Wordpress Rest API with advanced custom fields Google map field returns weird string

Question: I want to use a Wordpress backend with advanced custom fields and the json Wordpress API to serve data to a mobile app.
For this project the client needs to select a location in the maps custom field. The API should return a json array with some other data and the data from the Google maps field.
The object the API returns is formatted as follows:
{
"0": [
    {
      "title": "Test 1",
      "evenement_afbeelding": "38",
      "kunstenaars": "Name One",
      "openingstijden": "9:00 - 18:30",
      "evenementbeschrijving": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ac pharetra tortor.",
      "evenement_lokatie": "a:3:{s:7:\"address\";s:40:\"Jansweg 50, 2011 KN Haarlem, Netherlands\";s:3:\"lat\";s:17:\"52.38513460768028\";s:3:\"lng\";s:17:\"4.638633728027344\";}",
      "biografie": "Lorem ipsum dolor sit amet\r\n\r\nConsectetur adipiscing elit. Nullam ac pharetra tortor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos."
    }
],
    "status": "ok"
}

The weird thing is that the value on key "evenement_lokatie" (the Google maps field) returns a string that I cannot convert to an array. The value on the "evenement_lokatie" key should contain another array like this:
{
"0": [
    {
      "title": "Test 1",
      "evenement_afbeelding": "38",
      "kunstenaars": "Name One",
      "openingstijden": "9:00 - 18:30",
      "evenementbeschrijving": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ac pharetra tortor.",
      "evenement_lokatie": [
        {
          "Stad": "Haarlem",
          "lang": "32143241",
          "lat": "721321"
        }
  ],
      "biografie": "Lorem ipsum dolor sit amet\r\n\r\nConsectetur adipiscing elit. Nullam ac pharetra tortor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos."
    }
],
    "status": "ok"
}

This is the PHP code that should format the data in wordpress:
<?php

class json_api_events_controller{

    public function hello_world(){
        return array('message'=>'Hello World!');
    }

    public function get_events(){
        $array = array();

        $args = array('post_type'=>'evenementen', 'posts_per_page'=>-1, 'order_by'=>'title', 'order'=>'ASC');
        $loop = new WP_Query($args);

        $counter = 0;

        while ( $loop->have_posts() ) : $loop->the_post();

            $id = get_the_id();
            $custom = get_post_custom($id);

            // add the title
            $array[$id][$counter]['title'] = get_the_title();

            // add all the custom fields
            foreach($custom as $k => $v){

                // if key starts with '_' symbol, don't add to the array
                if(strpos($k, '_') !== 0) {

                    $array[$id][$counter][$k] = array_shift($v);

                }
            }

            $counter++;
        endwhile;

        return $array;
    }

}

Also there are weird chracters in the string, like ";s:17:" and ";s:40:".
Can anyone show me how I can convert such a string to an array like I described?
Thanks in advance!
Comment: You can have a look at [`preg_replace`](http://php.net/manual/en/function.preg-replace.php) and use it while iterating over your json_decoded array elements (specificaly the `evenement_lokatie` one)
Comment: I was hoping to avoid this approach since or is not really future proof. But it seems it is the only way to go. Thanks for your help!
Comment: *The value on the "evenement_lokatie" key should contain another array like this:* are you sure? Did you read the docs to see if this is indeed the format JSON output you get? Or is this just the format you *wanted*?
Comment: Thanks for your reply! Sorry, I should have been more clear. The second example is actually the format I need, not necceceraly what i expected. In either case I didn't expect the string to be formatted like this, with the ;s:40 characters.
Answer: The "weird" value is actually serialized PHP - you can deserialize it serverside using unserialize before you json_encode, and you should be fine.
Wordpress serializes metadata in this way, so that any object can be saved as strings. The trick is to use PHP deserialization to get a valid PHP object before creating the valid JSON object.
Hope this helps.
Answer: The way I resolved it is to query the posts, get the location field and it's data, add two meta fields for lat and lng.
The query:
  while( $query->have_posts() ) : $query->the_post();
    $id = get_the_ID();
    $location = get_field('location');
    $lat = $location['lat'];
    $lng = $location['lng'];
    if (! metadata_exists( 'post', $id, 'lat' ) ) {
      add_post_meta($id, 'lat', $lat, true);
    }
    if (! metadata_exists( 'post', $id, 'lng' ) ) {
      add_post_meta($id, 'lng', $lng, true);
    }

And then since I am using javascript, I am reading that data like this:
      $.each(data, function(i) {
        var lat = data[i]["details"]["lat"];
        var lng = data[i]["details"]["lng"];


ffmpeg - script to extract 1st frame of each second with deinterlacing

Question: i'm trying to write a shell script to analyse some videos by using the first frame of each second of video as a basis. i'm using ffmpeg to extract the frames. i thought i'd hit gold when this thread came up in my searches, but it doesn't handle the deinterlacing.
i'm using a time-based approach that works well for various formats as long as the video is progressive. it doesn't work so well for interlaced video (only the first field is output in that case, creating a half-height image). i've tried various combinations of deinterlacing (yadif/bwdif) with select but the filter chains i create either cause errors or still return a half-sized image.
here is my call w/a filter that works correctly for progressive video source :
ffmpeg -i $infile -vf "select='if(eq(n\,0),1,floor(t)-floor(prev_selected_t))" -vsync 0 $outfile
the following still return only half-height images for interlaced source :
... -vf "bwdif=0,select='if(eq(n\,0),1,floor(t)-floor(prev_selected_t))'"
... -vf "bwdif=0,select='between(mod(n\,$ips)\,1\,2)'" -- $ips is images per second
... -vf "select='between(mod(n\,$ips)\,1\,2)',bwdif=0"
i've also tried various permutations of the above w/explicit frame reference (-r, -vframes, ...), still no joy.
can someone help me with the syntax ?
--EDIT--
here is the complete output of running the command with the first filter :
ffmpeg version N-104925-gfe95731e3d-g68457c1e85+3 Copyright (c) 2000-2021 the FFmpeg developers
  built with gcc 11.2.0 (Rev5, Built by MSYS2 project)
  configuration:  --pkg-config=pkgconf --cc='ccache gcc' --cxx='ccache g++' --ld='ccache g++' --disable-autodetect --enable-amf --enable-bzlib --enable-cuda --enable-cuvid --enable-d3d11va --enable-dxva2 --enable-iconv --enable-lzma --enable-nvenc --enable-zlib --enable-sdl2 --enable-ffnvcodec --enable-nvdec --enable-cuda-llvm --enable-libmp3lame --enable-libopus --enable-libvorbis --enable-libvpx --enable-libx264 --enable-libx265 --enable-libdav1d --enable-libaom --disable-debug --enable-libfdk-aac --enable-fontconfig --enable-libass --enable-libbluray --enable-libfreetype --enable-libmfx --enable-libmysofa --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libsnappy --enable-libsoxr --enable-libspeex --enable-libtheora --enable-libtwolame --enable-libvidstab --enable-libvo-amrwbenc --enable-libwebp --enable-libxml2 --enable-libzimg --enable-libshine --enable-gpl --enable-avisynth --enable-libxvid --enable-libopenmpt --enable-version3 --enable-librav1e --enable-libsrt --enable-libgsm --enable-libvmaf --enable-libsvtav1 --enable-chromaprint --enable-decklink --enable-frei0r --enable-libbs2b --enable-libcaca --enable-libcdio --enable-libflite --enable-libfribidi --enable-libgme --enable-libilbc --enable-libsvthevc --enable-libsvtvp9 --enable-libkvazaar --enable-libmodplug --enable-librist --enable-librtmp --enable-librubberband --enable-libtesseract --enable-libxavs --enable-libzmq --enable-libzvbi --enable-openal --enable-libcodec2 --enable-ladspa --enable-libglslang --enable-vulkan --enable-libdavs2 --enable-libxavs2 --enable-libuavs3d --enable-opencl --enable-opengl --enable-libopenh264 --enable-openssl --extra-cflags=-DLIBTWOLAME_STATIC --extra-libs=-lstdc++ --extra-cflags=-DCACA_STATIC --extra-cflags=-DMODPLUG_STATIC --extra-cflags=-DCHROMAPRINT_NODLL --extra-libs=-lstdc++ --extra-cflags=-DZMQ_STATIC --extra-libs=-lpsapi --extra-cflags=-DLIBXML_STATIC --extra-libs=-liconv --disable-w32threads --extra-cflags=-DKVZ_STATIC_LIB --enable-nonfree --extra-cflags=-DAL_LIBTYPE_STATIC --extra-cflags='-IC:/ffab/local64/include' --extra-cflags='-IC:/ffab/local64/include/AL'
  libavutil      57. 11.100 / 57. 11.100
  libavcodec     59. 14.100 / 59. 14.100
  libavformat    59. 10.100 / 59. 10.100
  libavdevice    59.  0.101 / 59.  0.101
  libavfilter     8. 20.100 /  8. 20.100
  libswscale      6.  1.101 /  6.  1.101
  libswresample   4.  0.100 /  4.  0.100
  libpostproc    56.  0.100 / 56.  0.100
Passing a number to -vsync is deprecated, use a string argument as described in the manual.
Guessed Channel Layout for Input Stream #0.1 : stereo
Input #0, mxf, from 'mire-720-576-16-9.mxf':
  Metadata:
    operational_pattern_ul: 060e2b34.04010101.0d010201.01010900
    product_uid     : adab4424-2f25-4dc7-92ff-29bd000c0002
    uid             : adab4424-2f25-4dc7-92ff-29bd000c0000
    generation_uid  : adab4424-2f25-4dc7-92ff-29bd000c0001
    company_name    : FFmpeg
    product_name    : OP1a Muxer
    product_version_num: 18.104.22.168.0
    product_version : 58.38.100
    toolkit_version_num: 18.104.22.168.0
    material_package_umid: 0x060A2B340101010501010D001375063852947134C97506380052947134C97500
    timecode        : 00:00:00:00
  Duration: 00:02:00.00, start: 0.000000, bitrate: 55987 kb/s
  Stream #0:0: Video: jpeg2000, yuv422p10le(top first), 720x288, lossless, SAR 32:45 DAR 16:9, 50 tbr, 50 tbn
    Metadata:
      file_package_umid: 0x060A2B340101010501010D001375063852947134C97506380052947134C97501
      track_name      : Picture
  Stream #0:1: Audio: pcm_s24le, 48000 Hz, stereo, s32 (24 bit), 2304 kb/s
    Metadata:
      file_package_umid: 0x060A2B340101010501010D001375063852947134C97506380052947134C97501
      track_name      : Sound
Stream mapping:
  Stream #0:0 -> #0:0 (jpeg2000 (native) -> png (native))
Press [q] to stop, [?] for help
Output #0, image2, to 'testout%04d.png':
  Metadata:
    operational_pattern_ul: 060e2b34.04010101.0d010201.01010900
    product_uid     : adab4424-2f25-4dc7-92ff-29bd000c0002
    uid             : adab4424-2f25-4dc7-92ff-29bd000c0000
    generation_uid  : adab4424-2f25-4dc7-92ff-29bd000c0001
    timecode        : 00:00:00:00
    material_package_umid: 0x060A2B340101010501010D001375063852947134C97506380052947134C97500
    product_version_num: 22.214.171.124.0
    toolkit_version_num: 18.104.22.168.0
    encoder         : Lavf59.10.100
  Stream #0:0: Video: png, rgb48be(pc, gbr/unknown/unknown, progressive), 720x288 [SAR 32:45 DAR 16:9], q=2-31, 200 kb/s, 50 fps, 50 tbn
    Metadata:
      file_package_umid: 0x060A2B340101010501010D001375063852947134C97506380052947134C97501
      track_name      : Picture
      encoder         : Lavc59.14.100 png
frame=    1 fps=0.0 q=0.0 size=N/A time=00:00:00.00 bitrate=N/A speed=   0x
frame=    1 fps=0.0 q=0.0 size=N/A time=00:00:00.00 bitrate=N/A speed=   0x
frame=    2 fps=1.8 q=-0.0 size=N/A time=00:00:00.02 bitrate=N/A speed=0.0177x
frame=    3 fps=1.8 q=-0.0 size=N/A time=00:00:01.02 bitrate=N/A speed=0.617x
frame=    4 fps=1.9 q=-0.0 size=N/A time=00:00:02.02 bitrate=N/A speed=0.938x
frame=    5 fps=1.9 q=-0.0 size=N/A time=00:00:03.02 bitrate=N/A speed=1.13x
frame=    6 fps=1.9 q=-0.0 size=N/A time=00:00:04.02 bitrate=N/A speed=1.26x
frame=    6 fps=1.6 q=-0.0 size=N/A time=00:00:04.02 bitrate=N/A speed=1.09x
frame=    7 fps=1.7 q=-0.0 size=N/A time=00:00:05.02 bitrate=N/A speed=1.19x
frame=    8 fps=1.7 q=-0.0 size=N/A time=00:00:06.02 bitrate=N/A speed=1.27x
frame=    9 fps=1.7 q=-0.0 size=N/A time=00:00:07.02 bitrate=N/A speed=1.33x
frame=   10 fps=1.7 q=-0.0 size=N/A time=00:00:08.02 bitrate=N/A speed=1.38x
frame=   11 fps=1.7 q=-0.0 size=N/A time=00:00:09.02 bitrate=N/A speed=1.43x
frame=   12 fps=1.8 q=-0.0 size=N/A time=00:00:10.02 bitrate=N/A speed=1.47x
frame=   13 fps=1.8 q=-0.0 size=N/A time=00:00:11.02 bitrate=N/A speed= 1.5x
frame=   14 fps=1.8 q=-0.0 size=N/A time=00:00:12.02 bitrate=N/A speed=1.53x
frame=   15 fps=1.8 q=-0.0 size=N/A time=00:00:13.02 bitrate=N/A speed=1.56x
frame=   16 fps=1.8 q=-0.0 size=N/A time=00:00:14.02 bitrate=N/A speed=1.58x
frame=   17 fps=1.8 q=-0.0 size=N/A time=00:00:15.02 bitrate=N/A speed= 1.6x
frame=   18 fps=1.8 q=-0.0 size=N/A time=00:00:16.02 bitrate=N/A speed=1.62x
frame=   19 fps=1.8 q=-0.0 size=N/A time=00:00:17.02 bitrate=N/A speed=1.63x
frame=   20 fps=1.8 q=-0.0 size=N/A time=00:00:18.02 bitrate=N/A speed=1.64x
frame=   21 fps=1.8 q=-0.0 size=N/A time=00:00:19.02 bitrate=N/A speed=1.65x
frame=   22 fps=1.8 q=-0.0 size=N/A time=00:00:20.02 bitrate=N/A speed=1.66x
frame=   22 fps=1.8 q=-0.0 size=N/A time=00:00:20.02 bitrate=N/A speed=1.59x
frame=   24 fps=1.8 q=-0.0 size=N/A time=00:00:22.02 bitrate=N/A speed=1.69x
frame=   25 fps=1.8 q=-0.0 size=N/A time=00:00:23.02 bitrate=N/A speed= 1.7x
frame=   25 fps=1.8 q=-0.0 size=N/A time=00:00:23.02 bitrate=N/A speed=1.64x
frame=   26 fps=1.8 q=-0.0 size=N/A time=00:00:24.02 bitrate=N/A speed=1.65x
frame=   27 fps=1.8 q=-0.0 size=N/A time=00:00:25.02 bitrate=N/A speed=1.66x
frame=   28 fps=1.8 q=-0.0 size=N/A time=00:00:26.02 bitrate=N/A speed=1.67x
frame=   29 fps=1.8 q=-0.0 size=N/A time=00:00:27.02 bitrate=N/A speed=1.68x
frame=   30 fps=1.8 q=-0.0 size=N/A time=00:00:28.02 bitrate=N/A speed=1.68x
frame=   31 fps=1.8 q=-0.0 size=N/A time=00:00:29.02 bitrate=N/A speed=1.69x
frame=   32 fps=1.8 q=-0.0 size=N/A time=00:00:30.02 bitrate=N/A speed= 1.7x
frame=   33 fps=1.8 q=-0.0 size=N/A time=00:00:31.02 bitrate=N/A speed= 1.7x
frame=   34 fps=1.8 q=-0.0 size=N/A time=00:00:32.02 bitrate=N/A speed=1.71x
frame=   35 fps=1.8 q=-0.0 size=N/A time=00:00:33.02 bitrate=N/A speed=1.72x
frame=   36 fps=1.8 q=-0.0 size=N/A time=00:00:34.02 bitrate=N/A speed=1.72x
frame=   37 fps=1.8 q=-0.0 size=N/A time=00:00:35.02 bitrate=N/A speed=1.73x
frame=   37 fps=1.8 q=-0.0 size=N/A time=00:00:35.02 bitrate=N/A speed=1.69x
frame=   38 fps=1.8 q=-0.0 size=N/A time=00:00:36.02 bitrate=N/A speed=1.69x
frame=   39 fps=1.8 q=-0.0 size=N/A time=00:00:37.02 bitrate=N/A speed= 1.7x
frame=   40 fps=1.8 q=-0.0 size=N/A time=00:00:38.02 bitrate=N/A speed= 1.7x
frame=   41 fps=1.8 q=-0.0 size=N/A time=00:00:39.02 bitrate=N/A speed=1.71x
frame=   42 fps=1.8 q=-0.0 size=N/A time=00:00:40.02 bitrate=N/A speed=1.71x
frame=   43 fps=1.8 q=-0.0 size=N/A time=00:00:41.02 bitrate=N/A speed=1.72x
frame=   44 fps=1.8 q=-0.0 size=N/A time=00:00:42.02 bitrate=N/A speed=1.72x
frame=   45 fps=1.8 q=-0.0 size=N/A time=00:00:43.02 bitrate=N/A speed=1.73x
frame=   46 fps=1.8 q=-0.0 size=N/A time=00:00:44.02 bitrate=N/A speed=1.73x
frame=   47 fps=1.8 q=-0.0 size=N/A time=00:00:45.02 bitrate=N/A speed=1.74x
frame=   48 fps=1.8 q=-0.0 size=N/A time=00:00:46.02 bitrate=N/A speed=1.74x
frame=   49 fps=1.8 q=-0.0 size=N/A time=00:00:47.02 bitrate=N/A speed=1.75x
frame=   50 fps=1.8 q=-0.0 size=N/A time=00:00:48.02 bitrate=N/A speed=1.75x
frame=   50 fps=1.8 q=-0.0 size=N/A time=00:00:48.02 bitrate=N/A speed=1.72x
frame=   51 fps=1.8 q=-0.0 size=N/A time=00:00:49.02 bitrate=N/A speed=1.72x
frame=   52 fps=1.8 q=-0.0 size=N/A time=00:00:50.02 bitrate=N/A speed=1.73x
frame=   53 fps=1.8 q=-0.0 size=N/A time=00:00:51.02 bitrate=N/A speed=1.73x
frame=   54 fps=1.8 q=-0.0 size=N/A time=00:00:52.02 bitrate=N/A speed=1.73x
frame=   55 fps=1.8 q=-0.0 size=N/A time=00:00:53.02 bitrate=N/A speed=1.74x
frame=   56 fps=1.8 q=-0.0 size=N/A time=00:00:54.02 bitrate=N/A speed=1.74x
frame=   57 fps=1.8 q=-0.0 size=N/A time=00:00:55.02 bitrate=N/A speed=1.75x
frame=   58 fps=1.8 q=-0.0 size=N/A time=00:00:56.02 bitrate=N/A speed=1.75x
frame=   60 fps=1.8 q=-0.0 size=N/A time=00:00:58.02 bitrate=N/A speed=1.78x
frame=   61 fps=1.8 q=-0.0 size=N/A time=00:00:59.02 bitrate=N/A speed=1.79x
frame=   63 fps=1.9 q=-0.0 size=N/A time=00:01:01.02 bitrate=N/A speed=1.82x
frame=   64 fps=1.9 q=-0.0 size=N/A time=00:01:02.02 bitrate=N/A speed=1.82x
frame=   65 fps=1.9 q=-0.0 size=N/A time=00:01:03.02 bitrate=N/A speed=1.82x
frame=   67 fps=1.9 q=-0.0 size=N/A time=00:01:05.02 bitrate=N/A speed=1.85x
frame=   68 fps=1.9 q=-0.0 size=N/A time=00:01:06.02 bitrate=N/A speed=1.86x
frame=   69 fps=1.9 q=-0.0 size=N/A time=00:01:07.02 bitrate=N/A speed=1.86x
frame=   71 fps=1.9 q=-0.0 size=N/A time=00:01:09.02 bitrate=N/A speed=1.89x
frame=   72 fps=1.9 q=-0.0 size=N/A time=00:01:10.02 bitrate=N/A speed=1.89x
frame=   73 fps=1.9 q=-0.0 size=N/A time=00:01:11.02 bitrate=N/A speed=1.89x
frame=   74 fps=1.9 q=-0.0 size=N/A time=00:01:12.02 bitrate=N/A speed=1.89x
frame=   75 fps=1.9 q=-0.0 size=N/A time=00:01:13.02 bitrate=N/A speed=1.89x
frame=   77 fps=2.0 q=-0.0 size=N/A time=00:01:15.02 bitrate=N/A speed=1.92x
frame=   78 fps=2.0 q=-0.0 size=N/A time=00:01:16.02 bitrate=N/A speed=1.92x
frame=   79 fps=2.0 q=-0.0 size=N/A time=00:01:17.02 bitrate=N/A speed=1.92x
frame=   80 fps=2.0 q=-0.0 size=N/A time=00:01:18.02 bitrate=N/A speed=1.92x
frame=   81 fps=2.0 q=-0.0 size=N/A time=00:01:19.02 bitrate=N/A speed=1.92x
frame=   82 fps=2.0 q=-0.0 size=N/A time=00:01:20.02 bitrate=N/A speed=1.92x
frame=   83 fps=2.0 q=-0.0 size=N/A time=00:01:21.02 bitrate=N/A speed=1.92x
frame=   84 fps=2.0 q=-0.0 size=N/A time=00:01:22.02 bitrate=N/A speed=1.92x
frame=   85 fps=2.0 q=-0.0 size=N/A time=00:01:23.02 bitrate=N/A speed=1.92x
frame=   86 fps=2.0 q=-0.0 size=N/A time=00:01:24.02 bitrate=N/A speed=1.92x
frame=   89 fps=2.0 q=-0.0 size=N/A time=00:01:27.02 bitrate=N/A speed=1.97x
frame=   90 fps=2.0 q=-0.0 size=N/A time=00:01:28.02 bitrate=N/A speed=1.96x
frame=   90 fps=2.0 q=-0.0 size=N/A time=00:01:28.02 bitrate=N/A speed=1.94x
frame=   91 fps=2.0 q=-0.0 size=N/A time=00:01:29.02 bitrate=N/A speed=1.94x
frame=   92 fps=2.0 q=-0.0 size=N/A time=00:01:30.02 bitrate=N/A speed=1.94x
frame=   92 fps=2.0 q=-0.0 size=N/A time=00:01:30.02 bitrate=N/A speed=1.92x
frame=   93 fps=2.0 q=-0.0 size=N/A time=00:01:31.02 bitrate=N/A speed=1.92x
frame=   94 fps=2.0 q=-0.0 size=N/A time=00:01:32.02 bitrate=N/A speed=1.92x
frame=   94 fps=1.9 q=-0.0 size=N/A time=00:01:32.02 bitrate=N/A speed= 1.9x
frame=   95 fps=1.9 q=-0.0 size=N/A time=00:01:33.02 bitrate=N/A speed= 1.9x
frame=   95 fps=1.9 q=-0.0 size=N/A time=00:01:33.02 bitrate=N/A speed=1.88x
frame=   96 fps=1.9 q=-0.0 size=N/A time=00:01:34.02 bitrate=N/A speed=1.88x
frame=   96 fps=1.9 q=-0.0 size=N/A time=00:01:34.02 bitrate=N/A speed=1.86x
frame=   97 fps=1.9 q=-0.0 size=N/A time=00:01:35.02 bitrate=N/A speed=1.86x
frame=   98 fps=1.9 q=-0.0 size=N/A time=00:01:36.02 bitrate=N/A speed=1.86x
frame=   98 fps=1.9 q=-0.0 size=N/A time=00:01:36.02 bitrate=N/A speed=1.84x
frame=   99 fps=1.9 q=-0.0 size=N/A time=00:01:37.02 bitrate=N/A speed=1.84x
frame=   99 fps=1.9 q=-0.0 size=N/A time=00:01:37.02 bitrate=N/A speed=1.83x
frame=  100 fps=1.9 q=-0.0 size=N/A time=00:01:38.02 bitrate=N/A speed=1.83x
frame=  100 fps=1.8 q=-0.0 size=N/A time=00:01:38.02 bitrate=N/A speed=1.81x
frame=  101 fps=1.8 q=-0.0 size=N/A time=00:01:39.02 bitrate=N/A speed=1.81x
frame=  102 fps=1.8 q=-0.0 size=N/A time=00:01:40.02 bitrate=N/A speed=1.81x
frame=  102 fps=1.8 q=-0.0 size=N/A time=00:01:40.02 bitrate=N/A speed=1.79x
frame=  103 fps=1.8 q=-0.0 size=N/A time=00:01:41.02 bitrate=N/A speed= 1.8x
frame=  103 fps=1.8 q=-0.0 size=N/A time=00:01:41.02 bitrate=N/A speed=1.78x
frame=  104 fps=1.8 q=-0.0 size=N/A time=00:01:42.02 bitrate=N/A speed=1.78x
frame=  105 fps=1.8 q=-0.0 size=N/A time=00:01:43.02 bitrate=N/A speed=1.78x
frame=  105 fps=1.8 q=-0.0 size=N/A time=00:01:43.02 bitrate=N/A speed=1.76x
frame=  106 fps=1.8 q=-0.0 size=N/A time=00:01:44.02 bitrate=N/A speed=1.76x
frame=  106 fps=1.8 q=-0.0 size=N/A time=00:01:44.02 bitrate=N/A speed=1.75x
frame=  107 fps=1.8 q=-0.0 size=N/A time=00:01:45.02 bitrate=N/A speed=1.75x
frame=  108 fps=1.8 q=-0.0 size=N/A time=00:01:46.02 bitrate=N/A speed=1.75x
frame=  108 fps=1.8 q=-0.0 size=N/A time=00:01:46.02 bitrate=N/A speed=1.74x
frame=  109 fps=1.8 q=-0.0 size=N/A time=00:01:47.02 bitrate=N/A speed=1.74x
frame=  109 fps=1.8 q=-0.0 size=N/A time=00:01:47.02 bitrate=N/A speed=1.72x
frame=  110 fps=1.8 q=-0.0 size=N/A time=00:01:48.02 bitrate=N/A speed=1.73x
frame=  111 fps=1.8 q=-0.0 size=N/A time=00:01:49.02 bitrate=N/A speed=1.73x
frame=  111 fps=1.7 q=-0.0 size=N/A time=00:01:49.02 bitrate=N/A speed=1.71x
frame=  112 fps=1.7 q=-0.0 size=N/A time=00:01:50.02 bitrate=N/A speed=1.71x
frame=  112 fps=1.7 q=-0.0 size=N/A time=00:01:50.02 bitrate=N/A speed= 1.7x
frame=  113 fps=1.7 q=-0.0 size=N/A time=00:01:51.02 bitrate=N/A speed= 1.7x
frame=  113 fps=1.7 q=-0.0 size=N/A time=00:01:51.02 bitrate=N/A speed=1.69x
frame=  114 fps=1.7 q=-0.0 size=N/A time=00:01:52.02 bitrate=N/A speed=1.69x
frame=  115 fps=1.7 q=-0.0 size=N/A time=00:01:53.02 bitrate=N/A speed=1.69x
frame=  115 fps=1.7 q=-0.0 size=N/A time=00:01:53.02 bitrate=N/A speed=1.68x
frame=  116 fps=1.7 q=-0.0 size=N/A time=00:01:54.02 bitrate=N/A speed=1.68x
frame=  116 fps=1.7 q=-0.0 size=N/A time=00:01:54.02 bitrate=N/A speed=1.67x
frame=  117 fps=1.7 q=-0.0 size=N/A time=00:01:55.02 bitrate=N/A speed=1.67x
frame=  117 fps=1.7 q=-0.0 size=N/A time=00:01:55.02 bitrate=N/A speed=1.66x
frame=  118 fps=1.7 q=-0.0 size=N/A time=00:01:56.02 bitrate=N/A speed=1.66x
frame=  118 fps=1.7 q=-0.0 size=N/A time=00:01:56.02 bitrate=N/A speed=1.65x
frame=  119 fps=1.7 q=-0.0 size=N/A time=00:01:57.02 bitrate=N/A speed=1.65x
frame=  120 fps=1.7 q=-0.0 size=N/A time=00:01:58.02 bitrate=N/A speed=1.65x
frame=  120 fps=1.7 q=-0.0 size=N/A time=00:01:58.02 bitrate=N/A speed=1.63x
frame=  120 fps=1.7 q=-0.0 Lsize=N/A time=00:01:59.02 bitrate=N/A speed=1.64x
video:43029kB audio:0kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: unknown

Comment: Share full log for first bwdif filter attempt.
Comment: thanks @Gyan, i've updated my post.
Answer: Your input is detected as interlaced but with half-height (288) and double the framerate (50). This may be due to missing or unrecognized boundary markers in the JPEG2000 packets. I assume this is meant to be PAL --> 720x576@25i.
Try using the tinterlace filter first to interleave the input "frames" to double-height and half fps, and then continue the original sequence of filters.
"tinterlace=mode=merge,bwdif=0,select='if(eq(n\,0),1,floor(t)-floor(prev_selected_t))'"
Comment: wonderful !  thank you, @gyan, tinterlace was the key.


Will I be demoted to a lower league in Starcraft 2 if I don't play?

Question: I've just been promoted from platinum league to diamond and master pretty fast (in 4 vs 4). This was totally amazing for me but I'm afraid I will be demoted again to a lower league as fast as I came higher.
If I don't play any 4 vs 4 anymore, will they demote me to a lower league automatically or do they only do so, if I play?
Answer: For Master, Diamond, Platinum, Gold, Silver, and Bronze leagues, you will not be demoted for inactivity. (Inactive players are demoted out of Grandmaster league.)
However, your league membership only lasts for a season. And, if you are inactive for a full season, then play in a later season, you are considered a "new player" for league purposes.
Edit: If you skip an entire season, your MMR will be reset.

MMR persists from one season to the next for each game type as long as
  a Seasonal Placement Match was played for that season. If a Seasonal
  Placement Match was not played last season, then MMR and uncertainty
  are both reset to their default values and the system effectively
  "forgets" about that player.

http://wiki.teamliquid.net/starcraft2/Battle.net_Leagues#Hidden_.22Matchmaking_Rating.22_.28MMR.29
Comment: It's worth noting that your MMR won't change if you don't play, even across seasons. Other people who keep playing might attain a higher MMR, giving the illusion of demotion, when you're actually just staying in the same place.
Answer: I would add one more point: if you don't play for more then couple of seasons your skills degenerate severely so you anyway downgrade. Restore playing, push hard, and you can climb back. But it is really good you will be downgraded after inactivity as you will get some fun restoring your skills and competing with lower player guys.


Displaying large list from flask to html table no responding

Question: I pass the click signal through ajax , and get a list from the flask route, then append to the html table. however, when the list size exceeds 20000, the page will pop up a window and tell me to wait or close, no matter how long I wait, the result doesn't seems to come out, I don't think 20000 is a big number, and don't know if it's the problem of browser memory, any advice would help, thanks!
*this code works when the number of elements in list = 10000
flask code
@app.route('/get_tag', methods=['GET','POST'])
def get_tag():
if request.method == 'POST':
    point_list = ["123"]*100000
return jsonify({'taglist':point_list})

js code
            $("#search-tag").on('click',function(event){

            $.ajax({
              type : 'POST',
              url : "/get_tag",
              data:{
                text:$('#query').val()
            },
            success: function(data) {
            $("#tabletest > tr").remove();
            for(i in data.taglist){
                var tr;
                tr= '<input type="checkbox" style="width: 20px;" class="checkchild">	'+ ''+data.taglist[i]+'	';
                $("#tabletest").append('
'+tr+'
');
                }
              }

            });
            event.preventDefault();
        });

html code

Comment: since 10k works and 20k doesnt... it probably cant handle that much...
something you could look into is streaming the results... as they come, you append and it can already "discard" it... so, memory wise, it will be limited only by how big the table will be...
Comment: either this, or: https://stackoverflow.com/questions/589120/jquery-and-appending-large-amounts-of-html the problem might be in jquery itself... from what i saw... maybe try to append less times (by batching it)
Answer: Well, I don't know why the loop using jquery is extremely slow, so I changed the loop to the python backend, it's like 100 times faster.
flask backend
@app.route('/get_tag', methods=['GET','POST'])
def get_tag():
    if request.method == 'POST':

    point_list = ["123"]*100000

    result= ""

    for idx, i in enumerate(point_list):
      tr= '<input type="checkbox" style="width: 20px;" class="checkchild">
      	'+ ''+i+'	'
    result += '
'+tr+'
';

return jsonify({'taglist':result})

js
$(document).ready(function(){
        $("#search-tag").on('click',function(event){

            $.ajax({
              type : 'POST',
              url : "/get_tag",
              data:{
                text:$('#query').val()
            },
            success: function(data) {
            $("#tabletest > tr").remove();

              $("#tabletest").append(data.taglist);

              }

            });
            event.preventDefault();
        });


What is the maximum number of rows that can be returned over REST API?

Question: I am writing a GET request (using Angular 10, Spring boot, & Postgres). It does a 'Get' request to fetch 3357 records from a database. Then, it renders it to the UI
    return this.http.get<IFileMetadata[]>(this.resourceUrl, { params: options, observe: 'response' });

The problem is that it only shows 2000 records in the UI, which is not correct, as it should be 3357 records.
Is there any limit for the number of rows that can be returned in a 'Get' request?
Comment: Probably your API only gives 2000 record max. Usually, it should be a param (like "per_page"), which is for get more (i.e: per_page: 9999). I'm talking in "abstract", I don't know how that it works with Spring, sorry.
Comment: I think I found the issue here https://stackoverflow.com/questions/23751193/spring-data-jpa-limit-pagesize-how-to-set-to-maxsize
Comment: If Spring works in a different way (It have not "per_page"), you should do it taking care manually of the "pagination". A way of do this could be as @cluis92 shows in his link.
Answer: As an user suggested in his comment, the limit of 2000 records is due to the fact that spring fixes a default 2000 limit per_page stored in the properties spring.data.web.pageable.max-page-size   and spring.data.rest.max-page-size property for the maximum size of pages both documented here, so you can add the spring.data.web.pageable.max-page-size= newvalue inside the spring boot application.properties to override the default value or an equivalent method or change the pageable maximum size for spring.data.rest.max-page-size in the same way.