text:
Q: How to display the terms in a dropdown list in the admin option in wordpress I have a custom post type which has a custom taxonomy called "country". I want a drop-down list in the Dashboard -> Theme Option to select the term name under this taxonomy. So I have created the following function:
function featured_country($show_count = false, $country_array = array()) {
    $countries = get_terms( 'category', 'hide_empty=0&fields=all' );
    foreach ($countries as $countr) {
        $country_array[$countr->term_id] = $countr->name;
    }
    return $country_array;
}

Then I call this function as follows:
$this->admin_option('Front Page Option',
    'Featured country', 'featured_country',
    'select', '',
    array('options'=>$this->featured_country(true, array(''=>'Select Category')),
    'help'=>'Some helping text')
);

Unfortunately this drop-down list displays nothing. But when I put the parameter of get_terms() as "category" or "link_category" it works.
I can not understand where is my problem. How can I solve this? Please help me.

A: Try out this code
function get_terms_dropdown($taxonomies, $args){
    $myterms = get_terms($taxonomies, $args);
    $output ="<select name='TAXONOMY SLUG'>";
    foreach($myterms as $term){
        $root_url = get_bloginfo('url');
        $term_taxonomy=$term->taxonomy;
        $term_slug=$term->slug;
        $term_name =$term->name;
        $link = $term_slug;
        $output .="<option value='".$link."'>".$term_name."</option>";
    }
    $output .="</select>";
return $output;
}

(I took it from this forum thread)

A: Here's the example where Custom taxonomy" is courses" & custom post type for that is "help_lessions"
/*
 * Set Selectbox for Custom taxonomy "courses" in admin panel
 */

function custom_meta_box() {
    remove_meta_box('tagsdiv-courses', 'help_lessions', 'side');
    add_meta_box('tagsdiv-courses', 'Course', 'Courses_meta_box', 'help_lessions', 'side');
}
add_action('add_meta_boxes', 'custom_meta_box');

/* Prints the taxonomy box content */

function courses_meta_box($post) {

    $tax_name = 'courses';
    $taxonomy = get_taxonomy($tax_name);
?>
    <div class="tagsdiv" id="<?php echo $tax_name; ?>">

    <?php
    // Use nonce for verification
    wp_nonce_field(plugin_basename(__FILE__), 'courses_noncename');
    $help_ids = wp_get_object_terms($post->ID, 'courses', array('fields' => 'ids'));
    wp_dropdown_categories('taxonomy=courses&hide_empty=0&orderby=name&name=courses&show_option_none=Select Course&selected=' . $help_ids[0]);
    ?>

Select your Course

    <?php
}

/* When the post is saved, saves our custom taxonomy */

function courses_save_postdata($post_id) {
    // verify if this is an auto save routine.
    // If it is our form has not been submitted, so we dont want to do anything
    if (( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) || wp_is_post_revision($post_id))
        return;

    // verify this came from the our screen and with proper authorization,
    // because save_post can be triggered at other times

    if (!wp_verify_nonce($_POST['courses_noncename'], plugin_basename(__FILE__)))
        return;

    // Check permissions
    if ('help_lessions' == $_POST['post_type']) {
        if (!current_user_can('edit_page', $post_id))
            return;
    }
    else {
        if (!current_user_can('edit_post', $post_id))
            return;
    }

    // Now, we need to find and save the data

    $help_id = $_POST['courses'];
    $help = ( $help_id > 0 ) ? get_term($help_id, 'courses')->slug : NULL;
    wp_set_object_terms($post_id, $help, 'courses');
}
add_action('save_post', 'courses_save_postdata');


text:
Q: Can't represent data in OWL format using Jena I am trying to create Ontology in OWL format using Jena, but I can't. Eventually I get RDF not OWL, which I expected. Can I ask you what I am doing wrong?
Here is my code:
public class OntologyBuilder {

OntModel ontModel;
public OntologyBuilder() {
   this.ontModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
}

private void buildOnto() {
   final OntClass son = ontModel.createClass(OWL.NS + "Sun" );
}

public void performConvetring() {

  buildOnto();

  try {
      String filenameOWL2 = OntoConstants.dirname + OntoConstants.filename + OntoConstants.xmlExtension;

      FileWriter out = null;
      out = new FileWriter(filenameOWL2);
      ontModel.write(System.out);
  } catch(Exception e){
       e.printStackTrace();
  }

}
}

Eventually I get RDF
<rdf:RDF
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns:owl="http://www.w3.org/2002/07/owl#"
    xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema#" >
  <rdf:Description rdf:about="http://www.w3.org/2002/07/owl#Sun">
    <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Class"/>
  </rdf:Description>
</rdf:RDF>

Actually it should be smth like this
<owl:Class rdf:ID="Sun">
   ...
</owl:Class>

If anyone know how can do this with jena or maybe some other libs please share.
Thanks!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Format Y axis values, original figures in millions, only want to show first three digits Data for my Y axis (each country) has figures in millions:
{
  date: "1960",
  germany: "72542990",
  spain: "30327000",
  france: "46621166",
  italy: "50025500"
}

How do I write the .tickFormat(d3.format("")); on my Y axis variable to format the tick values so they show up in the Y axis scale like this:
0, 20 million, 40 million, 60 million, 80 million
Currently they show up as
0, 20000000, 40000000, 60000000,80000000
Thanks.

A: Declare Formatter
formatValue = d3.format(".2s");

Use inside TickFormat
.tickFormat(function(d) { return formatValue(d)});

to replace M with million try this..
.tickFormat(function(d) { return formatValue(d).replace('M', 'million'); });


text:
Q: How to rebuild only specific item in List (RxList) after updating it properties I have problem with updating my list after updating one item. I'm using GetX for state managment. It works fine when I add an item to my list, but not when i update some element.
But I want to rebuild also specific element (TestInternalWidget) when I change some property in list. I want to avoid rebuilding the entire list.
For testing when I double click on an element, a new element should be added (It works). And when I hold down a specific element, it should change
Here is my controller file "testcontroller.dart" for testing with item model class:
import 'package:get/get.dart';

class item {
  String a = "";
  String b = "";
  item(String a, String b)
  {
    this.a = a;
    this.b = b;
  }
}

class TestController extends GetxController {
  var itemsList = <item>[].obs;

  @override
  void onInit() {
    print("init controller");
    fetchItems();
    super.onInit();
  }

  updateItem(int index){
    print("UPDATING");
    itemsList[index].a = "xxxxx";
    itemsList[index].b = "XXXXX";
  }

  void fetchItems() async{
    print("fetching items");
    var item1 = item("aaaaa", "AAAAA");
    var item2 = item("bbbbb", "BBBBB");
    itemsList.add(item1);
    itemsList.add(item2);

  }
  addItem()
  {
    print("ADDING");
    var newItem = item("ccccc", "CCCCCC");
    itemsList.add(newItem);
  }
}

Here is my "main.dart" file:

import 'package:camera_app/views/widgets/testwidget.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'controllers/testcontroller.dart';

void main() async {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    final TestController testController = Get.put(TestController());
    return GetMaterialApp(
        title: 'test',
      home: Scaffold(
          appBar: AppBar(
            iconTheme: IconThemeData(color: Colors.black54),
            backgroundColor: Color(0xfffee6dc),
            centerTitle: true,
          ),
          backgroundColor: Color(0xfffff6f7),
          body: Obx(() => ListView.builder(
              cacheExtent: 10,
              addAutomaticKeepAlives: true,
              physics: BouncingScrollPhysics(),
              //physics : NeverScrollableScrollPhysics(),
              itemCount: testController.itemsList.length,
              itemExtent: 120,
              itemBuilder: (context, index) {
                print("item build");
                return InkWell(
                    onLongPress:() {
                      testController.updateItem(index);
                    },
                    onDoubleTap: () {
                      testController.addItem();
                    },
                    child: Obx(()=>  TestInternalWidget(testController.itemsList[index].a))
                );
              })
          )
      )

    );
  }

}

And last this is my test widget (testwidget.dart) used in list:
import 'package:flutter/material.dart';
class TestInternalWidget extends StatelessWidget {

  String text= "";
  TestInternalWidget(this.text);
  @override
  Widget build(BuildContext context) {
    print("internal widget build");
    return  Container(
        child:Text(text),
        decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(3),
        color: Color(0xffE4CFC6)
    )
    );
  }
}

A: IN GetX, the reactive variable reflects the changes in real-time if updated the item is itself.
But, if you just want to update a single attribute in the item, you have to refresh the reactive variable.

class TestController extends GetxController {
  var itemsList = <item>[].obs;

  @override
  void onInit() {
    print("init controller");
    fetchItems();
    super.onInit();
  }

  updateItem(int index){
    print("UPDATING");
    itemsList[index].a = "xxxxx";
    itemsList[index].b = "XXXXX";
    itemsList.refresh();
  }

  void fetchItems() async{
    print("fetching items");
    var item1 = item("aaaaa", "AAAAA");
    var item2 = item("bbbbb", "BBBBB");
    itemsList.add(item1);
    itemsList.add(item2);

  }
  addItem()
  {
    print("ADDING");
    var newItem = item("ccccc", "CCCCCC");
    itemsList.add(newItem);
  }
}


text:
Q: How to get coordinates of element during animation in SVG I have such code:
<defs>
    <g id="g0">
        <circle cx="0" cy="1" r="16" fill="blue" id="pr0" stroke-width="0" stroke="#2986dc"/>
        <circle cx="0" cy="0" r="14" fill="red" id="pp0" />
    </g>
</defs>
<use x="603" y="484" id="u0" href="#g0">
    <animateTransform attributeName="transform" attributeType="XML" type="rotate" id="t0" dur="30s" repeatCount="indefinite" from="0 494 494" to="360 494 494"/>
</use>

How can i get coordinates of group during animation using JavaScript?

A: The SVG 1.2 Micro DOM provides the get*PresentationTrait*() class of methods for accessing animated values, but I don't think they are supported yet by browsers. So maybe the easiest way would be to resort to JavaScript animation.


text:
Q: Returning errors from classes in javascript/typescript Suppose I have an interface like so:
class Something {
    constructor(things) {
        if (things) {
            doSomething();
        } else return { errorCode: 1 }
    }
}

Is this code ok? In TypeScript I get an error similar to property errorCode does not exist on type Something. What would be an alternative way to do this? Here is something that I thought of:
class Something {
    constructor(things) {
        if (things) {
            doSomething();
        } else this.error = { errorCode: 1 }
    }
}

Both of them have the same effect. But I would like to know which approach is better.

A: So define error as part of your class
interface MyError {
  errorCode: number;
}

class Something {
    private error: MyError;
    constructor(things) {
        if (things) {
            doSomething();
        } else this.error = { errorCode: 1 }
    }
}


text:
Q: Convert black and white image to grey I need to convert a black and white image to grey shade using javascript. I have already used a greyscale fuunction to convert color image to greyscale. My client uploaded a pure black text image which he needs to convert to a little greyshade.
Is this possible.


text:
Q: Rspec failed namespace has_many relationship In my app, one organisation has_many invoices, and organisation doesn't have any namespace, but invoice has Ihub::invoice, and in my organisation model I have
  has_many :invoices, class_name: 'Ihub::Invoice'

In my controller I have this line, works fine in development:
  @invoices = Ihub::Invoice.where(organisation_id: current_organisation.id).page(params[:page])

And my rspec failed with this error:
 Failure/Error: Unable to find matching line from backtrace
 ActiveRecord::StatementInvalid:
   PG::UndefinedTable: ERROR:  relation "invoices" does not exist
   LINE 5:                WHERE a.attrelid = '"invoices"'::regclass
                                             ^
   :               SELECT a.attname, format_type(a.atttypid, a.atttypmod),
                        pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod
                   FROM pg_attribute a LEFT JOIN pg_attrdef d
                     ON a.attrelid = d.adrelid AND a.attnum = d.adnum
                  WHERE a.attrelid = '"invoices"'::regclass
                    AND a.attnum > 0 AND NOT a.attisdropped
                  ORDER BY a.attnum

Update
already tried this doesn't help.
   RAILS_ENV=test rake db:drop db:create db:schema:load

Sql query in development
   Ihub::Invoice Load (0.2ms)  SELECT "ihub_invoices".* FROM "ihub_invoices" WHERE "ihub_invoices"."organisation_id" = $1  [["organisation_id", 89]]

Sql error in rspec (different query Ihub::Invoice.first), but you can see the namespace missing
         Failure/Error: Unable to find matching line from backtrace
 ActiveRecord::StatementInvalid:
   PG::UndefinedTable: ERROR:  relation "invoices" does not exist
   LINE 1: SELECT  "invoices".* FROM "invoices"  ORDER BY "invoices"."i...
                                     ^
   : SELECT  "invoices".* FROM "invoices"  ORDER BY "invoices"."id" ASC LIMIT 1

A: If it works in development but not in test, chances are that your test DB does not contain that table.
Try with:
bundle exec rake db:migrate
bundle exec rake db:test:prepare


text:
Q: Model binding addonLeft.text angular formly I am using bootstrap templates with angular-formly and I wanted to bind addonsLeft.text to a model so that it dynamically changes once a select option has changed.
This is how an input looks like:
  {
    key: 'my_input',
    type: 'input',
    templateOptions: {
      label: 'Text',
      addonLeft: {
            text: vm.model.select
      }
    }
  }

From what I understood bootstrap templates do not create a model for text / class option and therefore changing the model wouldn't affect the addonLeft.text.
Find a non-working example in this jsbin link.
I have found a hacky way of doing this butI am not sure if this is the right way.
Here is the solution in this jsbin link.

Should I create a custom template instead so that it has a proper model etc? Reason I haven't done this already it's because there is already an implemented solution that would keep my code cleaner.

A: This is a perfect case for Formly Expressions:
{
    key: 'my_input',
    type: 'input',
    templateOptions: {
        label: 'Text',
        addonLeft: {
            text: ''
        }
    },
    expressionProperties: {
      'templateOptions.addonLeft.text': 'model.select' // <- HERE
    }
}

Example JSBin: http://jsbin.com/tudivi/1/edit?html,js,console,output


text:
Q: Mysql/PHP: Substract 1 day from chosen input date field I have one input field, if user choose a date (format YYYY-MM-DD) then the page reloads (already using jquery/ajax for this), and then it should be getting the results from the day before the date user has inserted into the field.
I want to get a value from db, the day before the selected date user inputs.
Using DATE in mysql db, maybe it`s better to use timestamp ? Easier to modify and play with ?

A: You can use this:
DATE(DATE_ADD('2014-08-29', INTERVAL -1 DAY))

A: If you only have YYYY-MM-DD values, then using a DATE (SQL datatype) column is fine. For storing values that have both date and time components, (i.e. YYYY-MM-DD HH24:MI:SS) we'd use DATETIME or TIMESTAMP datatype for the column.
Working with those SQL datatypes is essentially the same. The choice of which of those datatypes to use is really a matter of selecting the most appropriate type for the actual data we need to represent.
For DATE, DATETIME and TIMESTAMP datatype columns, to pull rows with values that are a day before the specified value, we can use a predicate like this:
  FROM mytable t
 WHERE t.mydatecol >= '2014-08-27' + INTERVAL -1 DAY
   AND t.mydatecol <  '2014-08-27'

(This same pattern can extend to any range around a specified value, before and/or after a specified value, and any number of months, days, minutes, etc.)
For a DATE column, to return rows for just one previous day, where we are looking to match a single value in the column, we can just use equality comparison (instead of a range comparison), e.g.
  FROM mytable t
 WHERE t.mydatecol = '2014-08-27' + INTERVAL -1 DAY


text:
Q: Direct file access in delphi my application opens files does transformations and saves the data out to another file..or possible the same file.. the file size changes but i dont know how big or small its gona be untill i see the data inside the first file..
At the moment i load the file into a dynamic array do all that i need to do in there then save it back... this was looking good untill i got to my testing stage where i found transforming multi gigabyte files on a system with 128mb ram caused some issues...LOL
here is my code..
procedure openfile(fname:string);
var
  myfile: file;
  filesizevalue:integer;
begin
  AssignFile(myfile,fname);
  filesizevalue := GetFileSize(fname);
  Reset(myFile, 1);
  SetLength(dataarray, filesizevalue);
  BlockRead(myFile, dataarray[0], filesizevalue);
  CloseFile(myfile);
end;

what i need is direct file access to  minimise ram usage.. thats what i think i need/
is this what i need can it be done in delphi

A: I'd look at using a TFileStream, perhaps one with buffering, but you need to show what you are doing with the data really because it is hard to determine the best strategy. As gabr says, one option is memory mapped files, the code of which is in his link but since it is my code, I'll add it here too!
procedure TMyReader.InitialiseMapping(szFilename : string);
var
//  nError : DWORD;
    bGood : boolean;
begin
    bGood := False;
    m_hFile := CreateFile(PChar(szFilename), GENERIC_READ, 0, nil, OPEN_EXISTING, 0, 0);
    if m_hFile <> INVALID_HANDLE_VALUE then
    begin
        m_hMap := CreateFileMapping(m_hFile, nil, PAGE_READONLY, 0, 0, nil);
        if m_hMap <> 0 then
        begin
            m_pMemory := MapViewOfFile(m_hMap, FILE_MAP_READ, 0, 0, 0);
            if m_pMemory <> nil then
            begin
                    htlArray := Pointer(Integer(m_pMemory) + m_dwDataPosition);
                    bGood := True;
            end
            else
            begin
 //                      nError := GetLastError;
            end;
       end;
    end;
    if not bGood then
        raise Exception.Create('Unable to map token file into memory');
end;

A: You can also map parts of file directly into memory. That's definitely the most direct way. See What is the fastest way to Parse a line in Delphi for an example.

A: If problem permits, you can use BlockRead and BlockWrite to read chunk of input file, process it and then write that chunk to output file. Something like this:
  AssignFile(inFile,inFname);
  AssignFile(outFile,outFname);
  repeat
    BlockRead(inFile, buff, SizeOf(buff), bytesRead);
    ProcessBuffer(buff);
    BlockWrite(outFile, buff, bytesRead, bytesWritten);
  until (bytesRead = 0) or (bytesWritten <> bytesRead);

Code presumes that you won't change size of buffer while processing it. If size of file changes, then you should change last two lines of example code.

A: I prefer to use tFileStream for this kind of processing.  In this example I am assuming there is a constant ArraySize which is set to the size of a single array element.  For example, if your "array" is an array of integer then it would be set to:
ArraySize := SizeOf( Integer );

which would set the ArraySize to 4.
Function LoadPos(inFIlename:string;ArrayPos:Int64;var ArrayBuff) : boolean;
var
  fs : tFileStream;
begin
  result := false;
  fs := tFileStream.Create(inFilename,fmOpenRead);
  try
    // seek to the array position
    fs.Seek( ArrayPos * ArraySize, soFromBeginning);
    // load the element
    result := fs.Read( ArrayBuff, ArraySize ) = ArraySize;
  finally
    fs.free;
  end;
end;

The only problem with this approach is it only works for fixed size structures, variable length strings require a different approach.

A: I don't think you'll get a "more direct" file access. Do you use all the data in the file? Otherwise you could perhaps use a stream and load only the data needed into memory. But if you use all the data, there's only one solution IMHO: read the file in chunks. But that highly depends on the kind of transformation you want to apply. If the transformation is not local (so that combined data elements are all in the same chunk), you gonna have problems.


text:
Q: Executing Powershell script that requires arguments from Jenkins pipeline I've got a project that looks like this:
project
|
├───src
│       Utility.groovy
│
└───vars
        pipeline.groovy
        script.ps1

In pipeline.groovy I have utility object:
def util = new Utility(this)

and a step that calls util.scriptCall(arg1: "1", arg2: "2", arg3: "3"), which is defined as:
this.context.powershell returnStdout: true, script: ".\\script.ps1 -Arg1 ${args.arg1} -Arg2 ${args.arg2} -Arg3 ${args.arg3} -Workspace ${this.context.env.workspace}"

From everything I've found I'm supposedly invoking this correctly, however I'm getting the following error:
.\script.ps1 : The term '.\script.ps1' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

I've got the Powershell plugin installed but the lack of documentation for anything related to Jenkins isn't helping. I've moved script.ps1 into the src folder and even tried making a scripts folder for this with the same results.
Any idea why my invoking a script is getting interpreted as a cmdlet?

A: Because the script is not available in the location, where you're trying to invoke the script.
Use the absolute path to invoke the script. If the path includes whitespaces  use the call operator (&).
& "absolutePathToScript/script.ps1"

I'm not hundred percent sure, but Jenkins will inject the workspace via $env:workspace (at least it will do so in normal PowerShell build steps), so you be able to invoke the script via:
& "$($env:workspace)/vars/script.ps1"

A: I'm just a ding dong. The Workspace was the Git repo that was getting built. I had to relocate the script to that project and it worked as expected.


text:
Q: Is there a way to determine the source of a photo? Is there a way you can tell if a photo was either taken with the users camera, saved from a website, or is a screenshot?

A: With absolute certainty?  No.  It sounds like you want to know if an image given to you was legitimately taken by someone.
You can Google Image Search the file.  Google will look through its cached webpages to see if your image matches any others found on the web.  Granted, this will only work on indexed sites, but is a good start.
Some images contain metadata, such as exif data.  This can be viewed and give you information on how and where an image was taken.  Unfortunately that can be disabled, stripped, or modified.
As for knowing if something is a screenshot, there is no way to know.  A screenshot creates an image file just like any other source.

A: Try tineye[dot]com. All you need to do is upload the image or paste the url and it returns the results. Seems more accurate than even google images.


text:
Q: How to combine same table using union in mysql I want to get mysql records using union by combining same table based on different id
Table name :sample_value

id   width  userid
1    10X12   1
2    14X15   1
3    17X28   2
4    10X12   2
5    14X15   2
6    19X37   2

Mysql Union query:
select * from table sample_values where userid=1
union distinct
select * from table sample_values where userid=2

Suppose I want to get records based on two different id using union  lets say:

1) if userid=1 means it should get 10X12 and 14X15  2) if userid
  =2 means it should get 17X28  and combine with previous record of userid=1 but record 10X12 and 14X15 not get from userid=2 because same
  value is already present

so I wrote query for  this union query for this but it didn't help me
    Expected output:
id   width  userid
1    10X12   1
2    14X15   1
3    17X28   2
6    19X37   2

A: Use NOT EXISTS in the 2nd query of the UNION:
select * from sample_values where userid=1
union all
select * from sample_values s
where s.userid = 2 and not exists (
  select 1 from sample_values
  where userid = 1 and width = s.width
)

See the demo.
Results:
| id  | width | userid |
| --- | ----- | ------ |
| 1   | 10X12 | 1      |
| 2   | 14X15 | 1      |
| 3   | 17X28 | 2      |
| 6   | 19X37 | 2      |

A: This is a prioritization query.  Others have already shown how to use union all/not exists for this.  That doesn't generalize well when you have more than two or three values:
A more general solution is to use window functions, which are in MySQL 8+:
select sv.*
from (select sv.*,
             row_number() over (partition by width
                                order by (case when user_id = 1 then 1 else 2 end)
                               ) as seqnum
      from sample_value sv
     ) sv
where seqnum = 1;

You can also do this without a union all:
select sv.*
from sample_value sv
where sv.user_id = (select sv2.user_id
                    from sample_value sv2
                    where sv2.width = sv.width
                    order by (case when sv2.user_id = 1 then 1 else 2 end)
                    limit 1
                   );

In all these example, I have used a case for the order by.  For your particular examples, order by user_id is sufficient.

A: You could try using the union between the userid=1 and the not matching value between userid =1 and userid =2
    select *
    from table sample_values
    where userid=1
    union (
    select b.*
    from table sample_values a
    left JOIN sample_values b on a.width = b.with
        and a.userid = 1 and b.userid=2
    where b.width is null
    ) t

OR
Instead of an union
You could try using a join with agregated
    select s.* from sample_values s
    inner join (
        select width, min(userid) min_width
        from sample_values
        group by width
    ) t on t.min_width= s.width and t.userid = s.userid

A: Instead of UNION, you can utilize GROUP BY as well:
SELECT
  width,
  MIN(userid) AS userid
FROM sample_values
WHERE userid IN (1,2)
GROUP BY width

MIN(userid) will ensure that you give preference to earliest userid. This query would also be more efficient than using UNION with Subqueries.

Result View on DB Fiddle
| width | userid |
| ----- | ------ |
| 10X12 | 1      |
| 14X15 | 1      |
| 17X28 | 2      |
| 19X37 | 2      |


text:
Q: GWT Superdevmode interposing code server for CSS files I'm trying to move from Classic to Super dev mode and seeing a problem in the latter. The problem is two-fold. First, it is trying to use the code server to give the css files to the web page. Here is a line from the  element in the resultant web page:
<link rel="stylesheet" href="http://127.0.0.1:9876/tdome/../resources/standard.css">

You can see that it is piping the reference through the code server, which is running on port 9876. Now, that wouldn't be a big deal if it would serve the file. But it won't. The styles in that file are missing in the resultant page. This URL straight to the code server:
http://127.0.0.1:9876/resources/standard.css
... gives "server error". Eclipse is tossing a null pointer exception. It seems to have heartburn with files that are not in the /tdome tree. Just snuffling around and pecking in the names of existing files, sometimes Eclipse says it is ignoring the request. Sometimes it says the file doesn't exist when it does, and sometimes (when it really matters, like here), it gives the nullPointerException. At WebServer.java:272, fwiw.
So I need to either get superdevmode to leave these references alone, or get it to serve the file.
Any ideas? Many thanks-

A: Well, I really didn't find a way to make Super Dev Mode serve the files where they are. But I figured out where they should be instead of where they are. Probably common knowledge to everybody else: make a 'public' directory next to the 'your-project.gwt.xml' file and put them there. The references to them are in that xml file and do not need any qualification- just the filename, no directory path. Super Dev Mode will package them up, serve them, and let you at them.


text:
Q: react leaflet basic tutorial map do not display map correctly I follow react leaflet installation and got the setup page . They provide me a code snippet to use to see a  basic example. However here is what I got. Not sure which steps did I mess up.

import { GlobalStyle } from '../Theme';
import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet';
import styled from 'styled-components';
import Header from '../components/Header';

const StyledLocationsPageContainer = styled.div`
    width: 100%;
    .leaflet-map-container {
        height: 25rem;
    }
`;

function Locations() {
    return (

    );
}

export default Locations;

Here is my package .json file:
    "dependencies": {
        "@testing-library/jest-dom": "^5.11.9",
        "@testing-library/react": "^11.2.3",
        "@testing-library/user-event": "^12.6.0",
        "leaflet": "^1.7.1",
        "react": "^17.0.1",
        "react-dom": "^17.0.1",
        "react-leaflet": "^3.0.5",
        "react-scripts": "4.0.1",
        "styled-components": "^5.2.1",
        "web-vitals": "^0.2.4"
    }

After I insert the following link in the index.html, it just becomes empty white space with the width and height I assign to the wrapper div,
    <link
      rel="stylesheet"
      href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css"
      integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
      crossorigin=""
    />

A: You need to assign height to your MapContainer explicitly
 <MapContainer
       center={[51.505, -0.09]}
       zoom={13}
       scrollWheelZoom={false}
       style={{height: '100vh'}}> //here assign the height
>
...

and not to the wrapper of the MapContainer to be displayed as expected

A: I had to import the leaflet css file explicitly for it to work for me, even after adding the height and width to map container.
import "leaflet/dist/leaflet.css";


text:
Q: Null pointer exception with values on text change listener android I have code to simply calculate compound interest. The calculation will change when the user edits the value in an EditText view.
public class CompoundInterest extends AppCompatActivity {

    TextView mCompBalance;
    TextView mBalance;
    EditText mYears;
    Integer balance;
    Integer years;
    Double compbalance;
    Double interest;
    boolean isNumber;

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

        interest = 0.025;

        mBalance = (TextView) findViewById(R.id.tv_savingsbalance);
        mCompBalance = (TextView) findViewById(R.id.tv_interestbalance);
        mYears = (EditText) findViewById(R.id.et_years);
        System.out.println(mYears.getText().toString());

        Resources res = getResources();
        balance = Integer.valueOf(res.getString(R.string.savings_balance));
        mBalance.setText("£"+ balance);

        mYears.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (mYears.getText().toString().matches("\\d+(?:\\.\\d+)?")){
                    years = Integer.valueOf(mYears.getText().toString());
                    System.out.println(years);
                    isNumber =true;
                } else {
                    isNumber =false;
                }

                if (isNumber){
                    compbalance = balance*Math.pow(1+interest, years);
                    mCompBalance.setText("£"+String.format("%.2f", compbalance));
                }

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

    }
}

When I try to edit the EditText view that sets the number of years for the calculation - I get this error and the app crashes:

java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference
                                                                                at com.###.android.citiapp.CompoundInterest$1.onTextChanged(CompoundInterest.java:63)
                                                                                at android.widget.TextView.sendOnTextChanged(TextView.java:8187)
                                                                                at android.widget.TextView.handleTextChanged(TextView.java:8249)
                                                                                at android.widget.TextView$ChangeWatcher.onTextChanged(TextView.java:10371)
                                                                                at android.text.SpannableStringBuilder.sendTextChanged(SpannableStringBuilder.java:1208)
                                                                                at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:578)
                                                                                at android.text.SpannableStringBuilder.delete(SpannableStringBuilder.java:230)
                                                                                at android.text.SpannableStringBuilder.delete(SpannableStringBuilder.java:229)
                                                                                at android.view.inputmethod.BaseInputConnection.deleteSurroundingText(BaseInputConnection.java:251)
                                                                                at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:459)
                                                                                at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:93)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

I'm not sure what's going on.

A: Use charSequence.toString() instead of mYears.getText().toString() in onTextChanged function. Hope it helps or specify exactly where NullPointerException is occurring?


text:
Q: Is it possible to run Cucumber example tables in parallel with webdriverio? I need to run a scenario multiple times with different data. I have a scenario with more than one example table and each example table has a different tag. Is it possible to run the scenario in parallel for each example table ?
thank you :)

A: Have a look at the following:
https://www.npmjs.com/package/wdio-cucumber-parallel-execution


text:
Q: Disable redirect on drag image or link The problem is the following:
I am using a tinymce editor (not related with the problem) and an external image manager aplication. We use the drag&drop functionality for users, to just drag the image from the image manager to the tinymce content area.
However, there is a problem when the user inadvertantly drags the image outside the content area. The browser opens the link inside the window it was dragged to, losing the form the user had in front of them.
I am wondering if there is some way to catch this link-drop event, to disable the redirect in the browser. If you want to see the problem, just have 2 windows open, and drag an image from one window to the other one.
The sollution can also be html/css if possible, not necessary to be in JS.

A: Use an onbeforeunload event on the body.  Basically, it pops a dialog saying (you specify the string), "Are you sure you want to leave the page?".  If they click Cancel, they will  stay on the current page.  StackOverflow itself (among other sites) uses this technique.


text:
Q: How to read this log cat? I have two OnItemClickListeners and two buttons for them and one listview and 2 adapters. Each button will set the adapter list:
lv.setAdapter(adapt);
lv.setAdapter(adaptb);

It works the first time I run it, but when I click the button again, these red lines show in the log cat and stop the app.
09-08 17:51:32.605: W/dalvikvm(24630): threadid=1: thread exiting with uncaught exception (group=0x41af9360)
09-08 17:51:32.635: E/AndroidRuntime(24630): FATAL EXCEPTION: main
09-08 17:51:32.635: E/AndroidRuntime(24630): java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
09-08 17:51:32.635: E/AndroidRuntime(24630):    at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
09-08 17:51:32.635: E/AndroidRuntime(24630):    at java.util.ArrayList.get(ArrayList.java:304)
09-08 17:51:32.635: E/AndroidRuntime(24630):    at com.example.gdrgrg.CustomListAdapter.getView(CustomListAdapter.java:51)
09-08 17:51:32.635: E/AndroidRuntime(24630):    at android.widget.AbsListView.obtainView(AbsListView.java:2306)
09-08 17:51:32.635: E/AndroidRuntime(24630):    at android.widget.ListView.makeAndAddView(ListView.java:1769)
09-08 17:51:32.635: E/AndroidRuntime(24630):    at android.widget.ListView.fillDown(ListView.java:672)
09-08 17:51:32.635: E/AndroidRuntime(24630):    at android.widget.ListView.fillFromTop(ListView.java:733)
09-08 17:51:32.635: E/AndroidRuntime(24630):    at android.widget.ListView.layoutChildren(ListView.java:1622)
09-08 17:51:32.635: E/AndroidRuntime(24630):    at android.widget.AbsListView.onLayout(AbsListView.java:2141)
09-08 17:51:32.635: E/AndroidRuntime(24630):    at android.view.View.layout(View.java:13844)
09-08 17:51:32.635: E/AndroidRuntime(24630):    at android.view.ViewGroup.layout(ViewGroup.java:4369)
09-08 17:51:32.635: E/AndroidRuntime(24630):    at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1003)
09-08 17:51:32.635: E/AndroidRuntime(24630):    at android.view.View.layout(View.java:13844)
09-08 17:51:32.635: E/AndroidRuntime(24630):    at android.view.ViewGroup.layout(ViewGroup.java:4369)
09-08 17:51:32.635: E/AndroidRuntime(24630):    at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
09-08 17:51:32.635: E/AndroidRuntime(24630):    at android.view.View.layout(View.java:13844)
09-08 17:51:32.635: E/AndroidRuntime(24630):    at android.view.ViewGroup.layout(ViewGroup.java:4369)
09-08 17:51:32.635: E/AndroidRuntime(24630):    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1679)
09-08 17:51:32.635: E/AndroidRuntime(24630):    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1537)
09-08 17:51:32.635: E/AndroidRuntime(24630):    at android.widget.LinearLayout.onLayout(LinearLayout.java:1450)
09-08 17:51:32.635: E/AndroidRuntime(24630):    at android.view.View.layout(View.java:13844)
09-08 17:51:32.635: E/AndroidRuntime(24630):    at android.view.ViewGroup.layout(ViewGroup.java:4369)
09-08 17:51:32.635: E/AndroidRuntime(24630):    at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
09-08 17:51:32.635: E/AndroidRuntime(24630):    at android.view.View.layout(View.java:13844)
09-08 17:51:32.635: E/AndroidRuntime(24630):    at android.view.ViewGroup.layout(ViewGroup.java:4369)
09-08 17:51:32.635: E/AndroidRuntime(24630):    at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:1890)
09-08 17:51:32.635: E/AndroidRuntime(24630):    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1706)
09-08 17:51:32.635: E/AndroidRuntime(24630):    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1009)
09-08 17:51:32.635: E/AndroidRuntime(24630):    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4243)
09-08 17:51:32.635: E/AndroidRuntime(24630):    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
09-08 17:51:32.635: E/AndroidRuntime(24630):    at android.view.Choreographer.doCallbacks(Choreographer.java:555)
09-08 17:51:32.635: E/AndroidRuntime(24630):    at android.view.Choreographer.doFrame(Choreographer.java:525)
09-08 17:51:32.635: E/AndroidRuntime(24630):    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)
09-08 17:51:32.635: E/AndroidRuntime(24630):    at android.os.Handler.handleCallback(Handler.java:615)
09-08 17:51:32.635: E/AndroidRuntime(24630):    at android.os.Handler.dispatchMessage(Handler.java:92)
09-08 17:51:32.635: E/AndroidRuntime(24630):    at android.os.Looper.loop(Looper.java:137)
09-08 17:51:32.635: E/AndroidRuntime(24630):    at android.app.ActivityThread.main(ActivityThread.java:4911)
09-08 17:51:32.635: E/AndroidRuntime(24630):    at java.lang.reflect.Method.invokeNative(Native Method)
09-08 17:51:32.635: E/AndroidRuntime(24630):    at java.lang.reflect.Method.invoke(Method.java:511)
09-08 17:51:32.635: E/AndroidRuntime(24630):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
09-08 17:51:32.635: E/AndroidRuntime(24630):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
09-08 17:51:32.635: E/AndroidRuntime(24630):    at dalvik.system.NativeStart.main(Native Method)

A: 09-08 17:51:32.635: E/AndroidRuntime(24630): FATAL EXCEPTION: main
09-08 17:51:32.635: E/AndroidRuntime(24630): java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
09-08 17:51:32.635: E/AndroidRuntime(24630):    at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)

These lines indicate that you are trying to reach th item 0 of your ArrayList but your Arraylist is empty. You should check your code. You must fill your Arraylist before getting an item of it.


text:
Q: Transferring files from Windows SSD to Linux SSD in the same PC? How would this scenario work: One PC with a Windows SSD and a separate Linux SSD. I want to run a Windows virtual machine within the Linux SSD. Transferring of files would only be done while booted in Windows SSD, to the Linux SSD (so from Windows, using Windows, to Linux). Then Linux would be booted and those transferred files copied and used in the virtual machine.
I doubt I could just copy and paste the files. If the Linux SSD had a NTFS partition, would Windows see it from the other drive?

A: You don't really run SSDs, you run Operating Systems (Windows and/or Linux in this instance). Each OS can use some or all of the available disk storage for its filesystem.
It's perfectly possible to run Windows as a VM on Linux. You can use part or all of an SSD as backing store for that Windows VM. (Either directly or as a file in the host filesystem.) With that VM and the host Linux system running you can transfer files between them using protocols such as CIFS/Samba or SSH.
However, it's probably going to be just as easy to copy files between the filesystems. Linux systems can read/write Windows filesystems reasonable successfully, and to some lesser extent windows can use third-party software Windows to read/write native Linux filesystems. Create an NTFS filesystem for your Linux-based system and Windows can read/write that directly. Just don't expect to read/write a filesystem directly from one OS that's actively being used by the other.


text:
Q: JSPDF javascript not working with Tableau I am trying to print a page in pdf that includes a tableau dashboard. So I am using the JS PDF library to do so. Though the issue is it prints everything except for the Tableau dashboard (within an iframe).
Could you please let me if this works?
Javascript code below:
 function loadpdf2(){
            if ($(document).width() > $(document).height()) {
            var pdf = new jsPDF('l', 'pt', [$(document).width(), $(document).height()]); //
            }
            else {
                var pdf = new jsPDF('p', 'pt', [$(document).height(), $(document).width()]); //
            }
            pdf.addHTML(document.body, function() {
                pdf.save('webtool.pdf');
            });
        }

Tableau iframe below (html code):
 <iframe name="iframe" id="youriframeins" src="tableau_sharedlink" height="1000px" width="100%"></iframe>

A: unfortunately, this functionality is not currently supported. You can vote for the idea here: https://community.tableau.com/ideas/1348


text:
Q: Calculate the division of 2 numbers and show the recurring pattern in Java Thanks for the thumbs down.
I want 2 numbers divided and I want to print the number with total accuracy.
After the decimal pattern occurred I want a comma and to indicate the length of the recurring pattern.

A: One way you can solve this is by doing long division sort of like this, what you want to do is solve your problem like you would long division on a piece of paper.
static void codeCamperDivison(long n, long d) {
    long r; // remainder
    long g; // goes into
    StringBuilder s = new StringBuilder();
    ArrayList<Long> rh = new ArrayList<Long>(); // remainder history
    ArrayList<Long> gh = new ArrayList<Long>(); // goes into history
    for (long i = 0;; i++) {
        r = n % d;
        g = n / d;
        s.append(g);
        if (i == 0) // whole number portion
            s.append(".");
        if (r == 0) { // non-recurring number
            s.append(0);
            break;
        }
        gh.add(g);
        if (rh.contains(r)) { // recurring pattern found
            s.append(",");
            List<Long> pattern = gh.subList(rh.lastIndexOf(r) + 1, gh.size());
            for (long l : pattern)
                s.append(l);
            s.append("...");
            if (pattern.size() == 1)
                s.append("\nrecurring length=infinite");
            else
                s.append("\nrecurring length=" + pattern.size());
            break;
        }
        rh.add(r);
        n = r * 10; // add a 0 like in long division
    }
    System.out.println(s.toString()); // print results
}


text:
Q: MySQL attribute database I have an attribute database. Each attribute value is stored in a table with an ID to its parent attribute.
In a stand alone table I would write an SQL statement that would pull data
WHERE username = '' AND domain = ''

In the attribute table as each value is stored as a separate row, I can not do this.. I have a join that allows me to bring back one value + result (see below), however i need a result based on 2 criteria as shown above..
SELECT upa.value, up.status, u.status
  FROM user_product up, product_attribute pa, product p, user u, user_product_attribute upa

 WHERE pa.attribute_name = 'username'
   AND pa.product_attribute_id = upa.product_attribute_id
   AND pa.product_id = p.product_id
   AND u.user_id = up.user_id
   AND up.user_product_id = upa.user_product_id

   AND p.product_name = 'email'
   AND upa.value      = 'exampleuser'

I presume i would need to join the above able again in some sort of union? Any input would be helpful..
Thanks

A: Please don't use implicit join syntax. A second set of joins is needed to get a second attribute.
SELECT upa1.value, upa2.value, up1.status, u1.status
  FROM product p
    /* These joins get attribute/value for 'username' attribute */
    INNER JOIN product_attribute pa1
      ON p.product_id = pa1.product_id
        AND pa1.attribute_name = 'username'
    INNER JOIN user_product_attribute upa1
      ON pa1.product_attribute_id = upa1.product_attribute_id
    INNER JOIN user_product up1
      ON upa1.user_product_id = up1.user_product_id
    INNER JOIN user u1
      ON up1.user_id = u1.user_id
    /* These joins get attribute/value for 'domain' attribute */
    INNER JOIN user_product_attribute upa2
      ON upa1.user_product_id = upa2.user_product_id
    INNER JOIN product_attribute pa2
      ON upa2.product_attribute_id = pa2.product_attribute_id
        AND pa2.attribute_name = 'domain'
  WHERE p.product_name = 'email'

A: You need to repeat all of the joins twice to get both attributes. It's not pretty especially if you need more than 2 or 3 attributes at one time.
SELECT upa.value, up.status, u.status
FROM user_product up
JOIN user u    ON u.user_id = up.user_id

-- Join to get attribute 'username'
JOIN user_product_attribute upa1 ON up.user_product_id = upa1.user_product_id
JOIN product_attribute pa1 ON pa1.product_attribute_id = upa1.product_attribute_id
JOIN product p1                  ON pa1.product_id = p1.product_id

-- Join to get attribute 'domain'
JOIN user_product_attribute upa2 ON up.user_product_id = upa2.user_product_id
JOIN product_attribute pa2 ON pa2.product_attribute_id = upa2.product_attribute_id
JOIN product p2                  ON pa2.product_id = p2.product_id

WHERE pa1.attribute_name = 'domain'
  AND p1.product_name = 'email'
  AND upa1.value      = 'exampledomain.com'

  AND pa2.attribute_name = 'username'
  AND p2.product_name = 'email'
  AND upa2.value      = 'exampleuser'
;


text:
Q: 302 redirection for proxy calls to microservice with oauth2 behind zuul proxy I have one micro service "user-service". It is secured with spring-cloud-oauth2. It has one REST endpoint "/data/v1" which returns some JSON response.
When I send GET request to this endpoint it gets redirected to /oauth/login for authentication and after successful authentication it returns the token and then I am able to get the JSON response.
Later I added zuul proxy service ("micro-proxy-service") to route all external requests to internal back end services like "user-service".
It has single route "/resource" which then forwards the request to "/data/v1"
But now if I send GET requests to "/resource/data/v1" even after successful oauth2 authentication I get HTTP 302 response code with redirection to /login page.
If I try to access the "/data/v1" without zuul proxy then I am able to get response after oauth2. But when I request through zuul then I get 302.
If I remove the oauth2 from "user-service" then I can access "/data/v1" in both ways: directly or through zuul.
Please let me know If I am missing anything in zuul configuration.
Thanks.

A: Zuul strips the authentication headers by default, to enable them use the following configuration
zuul:
  sensitiveHeaders: Cookie,Set-Cookie


text:
Q: FFTW plan rountine returns back null I need someone with experience using FFTW
I am writing a program which needs to do a real to complex transform, but my planning routine returns back null and I am not sure why. I am passing valid integer parameters for the size, and non-NULL pointers for the array. I have consulted the documentation but all it says is that if it cannot make the plan it returns NULL, but besides doing the opposite of what I mentioned above, it does not list any other reasons for my plan failing. Below is piece of sample code
int size ={64, 128, 256};

float *spatial = malloc(size[1]*size[1]*sizeof(float));
fftwf_complex *fourier = fftwf_alloc_complex(size[1]*size[1]);

for(int i=0; i< size[1]; i++){
    for(int j=0; j<size[1]; j++){
        spatial = //fill spatial array;
    }
}

for(int i=0; i< size[1]; i++){
    for(int j=0; j<size[1]; j++){
        fourier = //fill fourier array;
    }
}

fftwf_plan plan = fftwf_plan_dft_r2c_2d(size[1], size[1], spatial, fourier, FFTW_FORWARD);
fftwf_execute(plan);

the  fftwf_plan_dft_r2c_2d() continually returns back NULL for plan and I am not sure why
Note: I am using Windows 8.1 with Visual Studios 2012

A: I was able to reproduce your problem on ubuntu...
The problem comes from the flag FFTW_FORWARD used by fftwf_plan_dft_r2c_2d. I don't know where it is documented, but it is not working. The reason is that fftwf_plan_dft_r2c_2d is always a forward transform, the backward transform being fftwf_plan_dft_c2r_2d
Moreover, you can reduce the memory footprint of your program. Indeed, in case of r2c transforms, only half the complex coefficients are computed and stored. Hence, the array allocated by fftwf_alloc_complex(size[1]*size[1]); is about twice the needed size. Take a look at the documentation to know more about the extra padding and the layout of frequencies.
Here is a program compiled by gcc main.c -o main -lfftw3f -lm -std=c99 (may be different on your computer...). The flag FFTW_FORWARD is replaced by FFTW_ESTIMATE. And #include <complex.h> is placed before #include <fftw3.h> so that fftw can use the float complex type of complex.h
#include <complex.h>

#include <fftw3.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>

int main(int argc, char* argv[]){
    int size [3] ={64, 128, 256};

    float *spatial = malloc(size[1]*size[1]*sizeof(float));
    if(spatial==NULL){fprintf(stderr,"malloc failed\n");exit(1);}
    fftwf_complex *fourier = fftwf_alloc_complex(size[1]*(size[1]/2+1));
    if(fourier==NULL){fprintf(stderr,"fftwf_alloc_complex failed\n");exit(1);}
    for(int i=0; i< size[1]; i++){
        for(int j=0; j<size[1]; j++){
            spatial[i*size[1]+j] =1; //fill spatial array;
        }
    }

    for(int i=0; i< size[1]; i++){
        for(int j=0; j<(size[1]/2+1); j++){
            fourier[i*(size[1]/2+1)+j]  =2.0+I ;//fill fourier array;
        }
    }

    fftwf_plan plan = fftwf_plan_dft_r2c_2d(size[1], size[1], spatial, fourier, FFTW_ESTIMATE);

    if(plan==NULL){printf("fftwf_plan_dft_r2c_2d : big problem %d\n",size[1]);fflush(stdout);}
    fftwf_execute(plan);

    printf("average is %g\n",creal(fourier[0])/(size[1]*size[1]));

    fftwf_destroy_plan(plan);
    free(fourier);
    free(spatial);

    return 0;
}


text: Q: i am Hosting my MERN stack Application on shared hosting but getting this error "Can't acquire lock for an app:" i want to host MERN stack application on shared hosting but when i click RUN NPM INSTALL or try to stop my app it give me the errror "Can't acquire lock for an app:"


text:
Q: Extract left- and right-going waves from FFT I am looking for a way to get information on the direction a wave is traveling. What I have got is a real function $\Phi(x,t)$ and it's time derivative $\dot{\Phi}(x,t)$ that obeys the wave equation $\Phi_{tt} - \Phi_{xx} = 0$.
I can decompose this wave into reft and right going parts
$\Phi(x,t) = f(x - c t) + g(x+ct)$.
Now is there a possibility to get from a FFT only the frequencies of left going waves $g(x + ct)$ if I know $\Phi(x,t)$ and it's time derivative $\dot{\Phi}(x,t)$?


text:
Q: VIM substitution: Using the current line as the search string Assuming the following text file, which is actually a data dump of funds and price statistics:
PBCPDF
05/01/2006
 0.0000
 0.0000
PBCPDF
 0.0000
06/01/2006
 0.0000
 0.0000
PBCPDF
 0.0082
[… lines repeat …]

What I wanted to achieve is to delete all instances of PBCPDF except for the first one, which I could write the substitution command as :.+1,$s/PBCPDF\n//g.
However, since I wanted to program a macro to process multiple fund names, I need a means to use some sort of pattern that would retrieve the current line as the search pattern without me doing it by hand.
Is there a way to do that?

A: ggyy:+1,$s/<Ctrl-R>"<BS>//g

Let's see what that does, exactly.
Go to the first line
gg

Yank the entire liine
yy

Start the substitution
:+1,$s/

Get the current line from the register to which you yanked it to:
<Ctrl-R>"

Note: Don't type the ", you have to actually hold Control and press R, followed by a double quote.
Delete the end of line character:
<BS>

Note: press Backspace.
Replace with nothing.
//g

You can record this in a macro by wrapping it with a qq/q, or whatever.

A: If you're doing this in a macro (using the q command) it's smart enough to catch when you do some of the more esoteric keystroke commands - the one I'm specifically thinking about is CTRL-R, CTRL-W, which will insert the word under the cursor into the command line. So, for example, if you did

ESC
qw
/[CTRL-R, CTRL-W] (you should see the word under the cursor enter the command line)
[enter]
q

then you just created a macro that searches for the next word in the buffer that's the same as this one, get it? It will dynamically yank the word under the cursor into the command as part of the macro. There might be something like CTRL-W in the command above that does this for the whole line, but I don't know it offhand.

A: Having studied sykora's and Matt's answers, I came up with a slightly better improvement which works on a line-wise basis rather than a word-wise basis (as per Matt's solution).
This command is to be executed after the cursor is positioned on the line of which the deletion is to occur:
:.+1,$s/<CTRL-R>=getline(".")<CR>\n//g

Explanation for VIM beginners:
:.+1,$s/

Start substitution from the line after the current line (.+1) and the end-of-file ($)
<CTRL-R>=getline(".")<CR>\n

<CTRL-R> refers to the actual pressing of the CTRL and R keys, which allows you to enter special expressions. In this case, =getline(".") which retrieves the text of the current line.
<CR> refers to the pressing of the enter key, which completes the <CTRL-R> expression. I also specify the newline character (\n) at the end of the search pattern as I need to remove it.
//g

And then replace with nothing.


text:
Q: Facebook iOS SDK login error (Invalid Scopes: public_profile, openid.) I receive the follow error when trying to login using the iOS Facebook SDK:
Invalid Scopes: public_profile, openid.

I have followed the instructions from here which has resulted in this set up:
info.plist
<plist version="1.0">
<dict>
    ...
    <key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleTypeRole</key>
            <string>Editor</string>
            <key>CFBundleURLName</key>
            <string></string>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>GOOGLE_URL_SCHEME</string>
                <string>fbMY_FB_APP_ID</string>
            </array>
        </dict>
    </array>
    <key>FacebookAppID</key>
    <string>MY_FB_APP_ID</string>
    <key>FacebookClientToken</key>
    <string>MY_FB_CLIENT_TOEN</string>
    <key>FacebookDisplayName</key>
    <string>MY_FB_APP_NAME</string>
    <key>LSApplicationQueriesSchemes</key>
    <array>
        <string>fbauth2</string>
        <string>fbapi</string>
        <string>fb-messenger-share-api</string>
    </array>
</dict>
</plist>

AppDelegate.swift
 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    FirebaseApp.configure()
    ApplicationDelegate.shared.application( application, didFinishLaunchingWithOptions: launchOptions )
    return true
}

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]
 ) -> Bool {
    return ApplicationDelegate.shared.application(app, open: url, sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String, annotation: options[UIApplication.OpenURLOptionsKey.annotation])
 }

Login snippet
let loginManager = LoginManager()
loginManager.logIn(permissions: ["public_profile"], from: self) { result, error in
    if let error = error {
        print("FB Error: \(error)")
    } else if let result = result, result.isCancelled {
        print("FB Cancelled")
    } else {
        print("FB Logged In")
    }
}

I am on iOS 16.2 using the facebook-ios-sdk version 15.1.0. The same error occurs with FB app in live and development mode. I receive the same error on the simulator and device. I can successfully login on the web when using the FB app JS library. I believe I have followed the instructions correctly. What am I missing?
Edit: Settings Screenshots

Edit:
So I just downloaded this sample from the facebook-ios-sdk. Added my FB App Id to the FacebookAppID field and URL Schemes in the plist. Added the FB Client Token to the plist and updated the bundle identifier to the one listed in the Facebook app, but I get the same error when I run the sample. What the hell is going on? The issue must be in the Facebook app set up, but where? I can't find this issue reported anywhere on the net. Surely someone has seen this before.

A: I figured it out. I was missing the facebook login from my facebook app products. I found it by accident and now I can login successfully.


text:
Q: creating SSIS package using SSDT 2017 I want to use Visual Studio 2017 SSDT to create a SSIS package. However, I can't see any SSIS template in SSDT 2017, as it exists in previous versions of Visual Studio such as VS 2015. Could someone give me some hints on how to do that? Thanks, A

A: It's a 2-step process.  You need to ensure that you enabled Data storage and processing from your Visual Studio installation AND you need to download and install the SSDT standalone installer.
This page details the instructions: https://learn.microsoft.com/en-us/sql/ssdt/download-sql-server-data-tools-ssdt?view=sql-server-2017
SSDT standalone installer is here: https://download.microsoft.com/download/D/F/8/DF8B51B9-8E9F-47F3-A27B-33EEDADD8966/SSDT-Setup-ENU.exe


text:
Q: Is it not necessary for a callback method to have a definition in node.js? I am new to node.js. I have been seeing code where a callback method is just called but it is never defined anywhere in the file. So without definition what does that call to the callback method do exactly? For example
CollectionDriver.prototype.findAll = function(collectionName, callback) {
this.getCollection(collectionName, function(error, the_collection) {
  if( error ) callback(error);
  else {
    the_collection.find().toArray(function(error, results) {
      if( error ) callback(error);
      else callback(null, results);
    });
  }
});

};
I understand that based on the success or failure of the this.getCollection(collectionName) method, the callback method "callback" is called appropriately, however there is no definition available for the callback method. So how is this call useful?

A: The callback argument is passed when findAll() is called.  It is up to the caller to define it appropriately and pass a reference to it.  This is a characteristic of Javascript, so it's not just node.js.
You should see something like this in the calling code:
var driver = new CollectionDriver(...);
driver.findAll("foo", function(err, results) {
    if (err) {
        console.log(err);
    } else {
        // process results here
    }
});

Here, the callback is defined by the caller and passed to the findAll() method.

It also doesn't have to be an inline function definition like above.  The caller could also be like this:
function findCallback(err, results) {
    if (err) {
        console.log(err);
    } else {
        // process results here
    }
}

var driver = new CollectionDriver(...);
driver.findAll("foo", findCallback);

In either case, you're passing a reference to a function to .findAll() which it calls when it completes.

A: callback is a parameter to findAll (function(collectionName, callback)!). You would use it like so:
// assuming `driver` is an instantiated `CollectionDriver`:
driver.findAll("collectionOfCows", function(error) {
  console.log("findAll called us back with", error);
});


text:
Q: java ee maven project on intellij with tomcat cannot be resolved to a type this is my first java ee project on IntelliJ and I want to use maven.
I create a java ee project on IntelliJ and add maven framework to it then move WEB-INF directory to src/main/resource and edit run configuration and set tomcat server local and fix it.
it's work and project run but if I add any  dependency to the pom file, for example, Jsoup or icu4j when run the project error 500 return whit this result:
An error occurred at line: [18] in the jsp file: [/index.jsp]
Jsoup cannot be resolved
15:
16:
Wellcome

17: <%
18:     Jsoup.connect("http://google.com");
19: %>
20:
21:

A: tnx from @CrazyCoder my problem solve and I explain it here maybe help other. last setting I must do is going to File->Project Strucher->Artifacts then select the artifact and in the front of that in Output Layout tab in Available Elements section right click on libraries and select Put into /WEB-INF/lib or simply double-click on it.
with this setting, IntelliJ add library you add to pom in WEB-INF/lib then deploy it to server


text:
Q: A relation between sine and cosine I cannot figure out how this relation:
$$\cos(\omega t)+ \frac{\zeta}{\sqrt{1-\zeta^2}}\sin(\omega t)  $$
is equal to:
$$\frac{1}{\sqrt{1-\zeta^2}}\sin\left(\omega t + \tan^{-1}\frac{\sqrt{1-\zeta^2}}{\zeta}\right)$$
I only found that this is not true for $\zeta<0$, and specifically it must be $0\leqslant\zeta<1$.

A: This probably comes from $a\sin(\gamma)+b\cos(\gamma)$. To simplify this, a key idea is to find a triangle with catets $a$ and $b$ and hypothenuse $\sqrt{a^2+b^2}$. You shall choose an angle $\theta$ from the triangle such that $\sin(\theta)=b/\sqrt{a^2+b^2}$ and $\cos(\theta)=a/\sqrt{a^2+b^2}$ so you can write $$a\sin(\gamma)+b\cos(\gamma)=\sqrt{a^2+b^2}\left(\frac{a}{\sqrt{a^2+b^2}}\sin(\gamma)+\frac{b}{\sqrt{a^2+b^2}}\cos(\gamma)\right)\\=\sqrt{a^2+b^2}\left(\cos(\theta)\sin(\gamma)+\sin(\theta)\cos(\gamma)\right)\\= \sqrt{a^2+b^2}\sin(\gamma+\theta).$$ Now, you can write $\theta$ using the relations from the triangle we wrote.

A: The key thing to notice is that a right angled triangle with sides of length $\sqrt{1-\zeta^2}$ and $\zeta$ has hypotenuse of length $1$ by Pythagoras' Theorem. So
$\sin(\tan^{-1}(\frac{\sqrt{1-\zeta^2}}{\zeta}) = \sqrt{1-\zeta^2}$ and
$\cos(\tan^{-1}(\frac{\sqrt{1-\zeta^2}}{\zeta}) = \zeta$
Then use the rule for $\sin(a+b)$ and it should come out.


text:
Q: Working of split method for 0.0.0.0. && 0.0.0.0 `
class GfG{
public String multiply(String a,String b){
        String s = "0.0.0.0";
        String[] str = s.split("\\.");
        for(String p:str){
            System.out.println(p);
        }
        return "";
    }
}

`
I am splitting "0.0.0.0" and "0.0.0.0.".
In both the cases i m getting same array of strings i.e 4 "0" strings.
Can someone explain how this split is working for the two above cases.

A: The reason that you are not receiving the empty string that you think should have been returned at the end is by design in split.
From the docs:
public String[] split(String regex)

This method works as if by invoking the two-argument split method with
  the given expression and a limit argument of zero. Trailing empty
  strings are therefore not included in the resulting array

The important part of this is that Trailing empty string are therefore not included.
Reference: Official documentation

A: It appears that you ran the following
jshell> "0.0.0.0".split("\\.")
$1 ==> String[4] { "0", "0", "0", "0" }

jshell> "0.0.0.0.".split("\\.")
$2 ==> String[4] { "0", "0", "0", "0" }

and you are happy with the first result but you are wondering why the last result is not
String[4] { "0", "0", "0", "0", "" }

This is a good question to ask because if the dot was at the beginning of the string you would get the empty string!
jshell> ".0.0.0.0".split("\\.")
$3 ==> String[5] { "", "0", "0", "0", "0" }

This is just how split works. If there is a delimiter at the end of the string, no empty string is returned.
Duplicate of Java String split removed empty values, where it is explained in detail.


text:
Q: Client side validation on button click before AJAX request I'm using MVC 4 and I want to be able to validate a single row, from a collection of rows in a table, to ensure that the fields are entered correctly and pass validation.
The Attributes are correctly applied on the model, for example:
[Required]
[MaxLength(50)]
[MinLength(5)]
public string Name {get; set;}

Now, on the client side - how do I enable client side validation before calling an AJAX method?
To add more complications - I have a button where you can dynamically add a row to the table, fill out fields and finally hit the update button, which will do a POST via ajax. But before this post, I want to validate that particular row on client side.
how can I do this?
thank you

A: As long as you're implementing the validation helpers in your View, this is actually really simple.
var form = $('#form');
$.validator.unobtrusive.parse(form);
form.validate();

if (form.valid()) {
    .... ajax stuff
}

Call the above before initiating the http request and it will make sure that your form is validated.


text:
Q: It seems natural to say "who'd've" in speech, but is this incorrect? It definitely seems strange in writing. All of the following make sense:

who would have
who'd have
who would've

But what about this?

who'd've

A: SpringKS pretty much covers it in her answer, yet I would like to build on her answer with a few numbers to help get a very rough idea of the relative popularity of some of the proposed ways of spelling who would have.
First off you should take a look at Google's Ngram Viewer, which gathers it's data from books. This graph shows who would have as the clear winner. This is completely expected as books tend to be quite formal.
The internet tends to be a little less formal, so by searching for some of these phrases with quotes we get the following number of results returned:

*

*Who would have - 134,000,000 results

*Who would've - 9,340,000 results

*Who'd have - 6,210,000 results

*Who'da - 511,000 results

*Who'd've - 68,800 results

*Who'd 'ave - 11,000 results

*Whowoulda - 3,840 results

Even in a slightly more informal setting you can still see the majority of people taking the precious extra few seconds to type out the entire thing. Who would've and who'd have seem to be reasonably close. Who'da also seems to be more common than who'd've. As mentioned earlier however there is nothing wrong with any of these options in the right context. They will all get the meaning across.

A: Written English is different from spoken English. If "who'd've" is part of a direct quote or you're trying to reproduce colloquial speech, it fine.
However, in almost all other cases, the reader will stumble around with all those apostrophes. Our brains don't read words the same way we hear them. Your three options of "who would have," "who'd have," and "who would've" are all good options for print. "Who would have" is more formal and good for texts that do not use contractions. If contractions are used in the text, then "who'd have" and "who would've" can be used interchangeably without issue.

A: It really depends on who you are talking to. It is slang of a sort so if you are trying to impress someone I would not say it. For common speech it is fine.


text:
Q: Android set style attribute to dynamically created ImageView Is there a way to set style to dynamically created ImageView?
I'm shocked how limited styling Android have compared to css...
Maybe i can somehow a blank ImageView with predefined style in fragment xml and then clone it for each dynamically required image and then change src drawable in it?
Argh....

A: Yes offcourse you can set,
imageView.setBackgroundResource(R.drawable.style);

Where R.drawable.style is you predefined style xml file in your resources.


text:
Q: Form fields generated by Spring Roo Does anyone know how to customize the form fields that Spring Roo generates so I can change the with of the associated label?
For example,
<field:input field="firstName" id="c_com_myclass_Person_firstname" label="What is your first name?" z=""/>

The field is rendered inside a div that is the full width of the screen, but the label is split onto two lines as if the tag has decided to give the label e.g. 50px width or something. e.g.
What is
your first name?:

There's no 'style' attribute on the tag and I can't find anything that looks like it would let me control the width.
Thanks

A: It's in the standard.css - class label has a 100px fixed width. Was so obsessed with finding in extracted dijit tundra css files I forgot to check the obvious.
Have to say, there are lots of things I like about Roo, but the tag libs and dijit stuff make working with the presentation side of things a real chore if you want to customise the appearence of your app...


text:
Q: PC starts automatically when plugged in and gets shut down after some time My desktop was working fine till yesterday but suddenly it logged off. When I tried to start it again it started but shut down again after some time. This is now happening continuously. The PC starts automatically when I plug in.
I tried to swap the POWER and RESET switch on the motherboard but that did not work. Finally I used a screwdriver to short and my PC started working. But I don't want to use a screwdriver everytime to start my PC.
Can anybody suggest me how can I start my PC using POWER and RESET switch?
I have a PC with an Intel motherboard.

A: Sounds like you have an intermittent connection problem.  To start, if the motherboard does not exhibit the same behavior with the power and reset button attached as not attached, it probably is not the MB; it is probably the buttons.  But, if it does the same thing when you isolate the MB from everything else (disconnect buttons and technically all other hardware except CPU and RAM just for thoroughness), it is probably the MB or the PS.
Test the resistance of your power button with a multimeter.  It should normally be infinite (usually read as "1") ohms.  Then, with the multtimeter, push the button, it should read near 0 ohms.
Test your reset button as well the same way, it should exhibit the same behavior.
Also check to make sure the back plane of you MB is not shorting the power pins by reading the resistance across the pins, it should read something other than near 0 ohms; not sure what though could be high, could be low.  Put a small smount of pressure on the board with your fingures at that location, and test resistance at the same to see if it changes, it should not.
Problem with your question is the power button and rest button typically (not always) do the same thing and usually can be swapped with each other.  So if you swapped them, and it still came on right away, then either both buttons are bad or it is something other than the buttons, like a short on the back plane;  but then it should have started and /or turned off with the buttons disconnected as well..
Could be you connectors themselves are bad also if the screwdriver works but the buttons do not and they test properly with a multimeter.  You could do the same test to the buttons with them connected to the MB out of the computer and test the resistance of the buttons on the MB itself, it should do the same things as above.  Infinite resistance usually, 0 when button pressed.


text:
Q: Request object is null - Symfony 3.4 I'm having a problem with a submitted form.
I create a form object in a controller method, and I specify that when submitted, it should be handled in another action method.
    $invoiceForm = $oldInvoiceForm ?? $this->createForm(InvoiceProjectInvoiceType::class, $invoiceProject, [
        'action' => $this->generateUrl('invoice_edit', ['id' => $invoiceProject->getId()]),
    ]);

Here's the invoice_edit route
/**
 * @param Request $request
 * @param InvoiceProject $invoiceProject
 * @return Response
 * @Route("/{id}/edit/invoice", name="invoice_edit", methods="POST")
 */
public function editInvoice(Request $request, InvoiceProject $invoiceProject){

    $form = $this->createForm(InvoiceProjectInvoiceType::class, $invoiceProject);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $this->getDoctrine()->getManager()->flush();
        $this->addFlash("notice", "La config a bien été créée");
        return $this->redirectToRoute('invoice_show', ['id' => $invoiceProject->getId()]);
    }
    else{
        return $this->forward("ClientBundle:InvoiceProject:show", [
            'id' => $invoiceProject->getId(),
            'oldInvoiceForm' => $form
        ]);
    }
}

I do get to that method but I get this error message:
Controller "ClientBundle\Controller\InvoiceProjectController::editInvoice()" requires that you provide a value for the "$request" argument. Either the argument is nullable and no null value has been provided, no default value has been provided or because there is a non optional argument after this one.
So I do a little test, I put "Request $request = null", to make it optional, and it goes through. Obviously it crashes later in the handleRequest part, but I wonder why the request Object isn't injected in the action...
Here's the html of rendered form (without the inputs because there are lots of them)
    <form name="clientbundle_invoiceproject_invoice" method="post" action="/client/131/edit/invoice">
    <button type="submit" class="btn btn-secondary">Modifier les informations</button>
     </form>

Does anyone see anything unusual in the code ?

A: It seems that you don't have include the Request class in your file header
<?php

namespace App\AppBundle\Controller;

use Symfony\Component\HttpFoundation\Request;


text:
Q: Append huge files to each other without copying them There are 5 huge files ( file1, file2, .. file5) about 10G each and extremely low free space left on the disk and I need to concatenate all this files into one.
There is no need to keep original files, only the final one.
Usual concatenation is going with cat in sequence for files file2 .. file5:
cat file2 >> file1 ; rm file2

Unfortunately this way requires a at least 10G free space I don't have.
Is there a way to concatenate files without actual copying it but tell filesystem somehow that file1 doesn't end at original file1 end and continues at file2 start?
ps. filesystem is ext4 if that matters.

A: AFAIK it is (unfortunately) not possible to truncate a file from the beginning (this may be true for the standard tools but for the syscall level see here). But with adding some complexity you can use the normal truncation (together with sparse files): You can write to the end of the target file without having written all the data in between.
Let's assume first both files are exactly 5GiB (5120 MiB) and that you want to move 100 MiB at a time. You execute a loop which consists of

*

*copying one block from the end of the source file to the end of the target file (increasing the consumed disk space)

*truncating the source file by one block (freeing disk space)
for((i=5119;i>=0;i--)); do
  dd if=sourcefile of=targetfile bs=1M skip="$i" seek="$i" count=1
  dd if=/dev/zero of=sourcefile bs=1M count=0 seek="$i"
done

But give it a try with smaller test files first, please...
Probably the files are neither the same size nor multiples of the block size. In that case the calculation of the offsets becomes more complicated. seek_bytes and skip_bytes should be used then.
If this is the way you want to go but need help for the details then ask again.
Warning
Depending on the dd block size the resulting file will be a fragmentation nightmare.

A: Instead of catting the files together into one file, maybe simulate a single file with a named pipe, if your program can't handle multiple files.
mkfifo /tmp/file
cat file* >/tmp/file &
blahblah /tmp/file
rm /tmp/file

As Hauke suggests, losetup/dmsetup can also work. A quick experiment; I created 'file1..file4' and with a bit of effort, did:
for i in file*;do losetup -f ~/$i;done

numchunks=3
for i in `seq 0 $numchunks`; do
        sizeinsectors=$((`ls -l file$i | awk '{print $5}'`/512))
        startsector=$(($i*$sizeinsectors))
        echo "$startsector $sizeinsectors linear /dev/loop$i 0"
done | dmsetup create joined

Then, /dev/dm-0 contains a virtual block device with your file as contents.
I haven't tested this well.
Another edit: The file size has to be divisible evenly by 512 or you'll lose some data. If it is, then you're good.  I see he also noted that below.

A: You'll have to write something that copies data in bunches that are at most as large as the amount of free space you have. It should work like this:

*

*Read a block of data from file2 (using pread() by seeking before the read to the correct location).

*Append the block to file1.

*Use fcntl(F_FREESP) to deallocate the space from file2.

*Repeat

A: I know it's more of a workaround than what you asked for, but it would take care of your problem (and with little fragmentation or headscratch):
#step 1
mount /path/to/... /the/new/fs #mount a new filesystem (from NFS? or an external usb disk?)

and then
#step 2:
cat file* > /the/new/fs/fullfile

or, if you think compression would help:
#step 2 (alternate):
cat file* | gzip -c - > /the/new/fs/fullfile.gz

Then (and ONLY then), finally
#step 3:
rm file*
mv /the/new/fs/fullfile  .   #of fullfile.gz if you compressed it


text:
Q: Pretty printing XML in Python What is the best way (or are the various ways) to pretty print XML in Python?

A: I had some problems with minidom's pretty print.  I'd get a UnicodeError whenever I tried pretty-printing a document with characters outside the given encoding, eg if I had a β in a document and I tried doc.toprettyxml(encoding='latin-1').  Here's my workaround for it:
def toprettyxml(doc, encoding):
    """Return a pretty-printed XML document in a given encoding."""
    unistr = doc.toprettyxml().replace(u'<?xml version="1.0" ?>',
                          u'<?xml version="1.0" encoding="%s"?>' % encoding)
    return unistr.encode(encoding, 'xmlcharrefreplace')

A: You have a few options.
xml.etree.ElementTree.indent()
Batteries included, simple to use, pretty output.
But requires Python 3.9+
import xml.etree.ElementTree as ET

element = ET.XML("text")
ET.indent(element)
print(ET.tostring(element, encoding='unicode'))

BeautifulSoup.prettify()
BeautifulSoup may be the simplest solution for Python < 3.9.
from bs4 import BeautifulSoup

bs = BeautifulSoup(open(xml_file), 'xml')
pretty_xml = bs.prettify()
print(pretty_xml)

Output:

<?xml version="1.0" encoding="utf-8"?>
<issues>
 <issue>
  <id>
   1
  </id>
  <title>
   Add Visual Studio 2005 and 2008 solution files
  </title>
 </issue>
</issues>

This is my goto answer. The default arguments work as is. But text contents are spread out on separate lines as if they were nested elements.
lxml.etree.parse()
Prettier output but with arguments.
from lxml import etree

x = etree.parse(FILE_NAME)
pretty_xml = etree.tostring(x, pretty_print=True, encoding=str)

Produces:

  <issues>
    <issue>
      <id>1</id>
      <title>Add Visual Studio 2005 and 2008 solution files</title>
      We need Visual Studio 2005/2008 project files for Windows.
    </issue>
  </issues>

This works for me with no issues.

xml.dom.minidom.parse()
No external dependencies but post-processing.
import xml.dom.minidom as md

dom = md.parse(FILE_NAME)
# To parse string instead use: dom = md.parseString(xml_string)
pretty_xml = dom.toprettyxml()
# remove the weird newline issue:
pretty_xml = os.linesep.join([s for s in pretty_xml.splitlines()
                              if s.strip()])

The output is the same as above, but it's more code.

A: from yattag import indent

pretty_string = indent(ugly_string)

It won't add spaces or newlines inside text nodes, unless you ask for it with:
indent(mystring, indent_text = True)

You can specify what the indentation unit should be and what the newline should look like.
pretty_xml_string = indent(
    ugly_xml_string,
    indentation = '    ',
    newline = '\r\n'
)

The doc is on http://www.yattag.org homepage.

A: I wrote a solution to walk through an existing ElementTree and use text/tail to indent it as one typically expects.
def prettify(element, indent='  '):
    queue = [(0, element)]  # (level, element)
    while queue:
        level, element = queue.pop(0)
        children = [(level + 1, child) for child in list(element)]
        if children:
            element.text = '\n' + indent * (level+1)  # for child open
        if queue:
            element.tail = '\n' + indent * queue[0][0]  # for sibling open
        else:
            element.tail = '\n' + indent * (level-1)  # for parent close
        queue[0:0] = children  # prepend so children come before siblings

A: Here's my (hacky?) solution to get around the ugly text node problem.
uglyXml = doc.toprettyxml(indent='  ')

text_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</', re.DOTALL)
prettyXml = text_re.sub('>\g<1></', uglyXml)

print prettyXml

The above code will produce:
<?xml version="1.0" ?>
<issues>
  <issue>
    <id>1</id>
    <title>Add Visual Studio 2005 and 2008 solution files</title>
    We need Visual Studio 2005/2008 project files for Windows.
  </issue>
</issues>

Instead of this:
<?xml version="1.0" ?>
<issues>
  <issue>
    <id>
      1
    </id>
    <title>
      Add Visual Studio 2005 and 2008 solution files
    </title>

      We need Visual Studio 2005/2008 project files for Windows.

  </issue>
</issues>

Disclaimer: There are probably some limitations.

A: import xml.dom.minidom

dom = xml.dom.minidom.parse(xml_fname) # or xml.dom.minidom.parseString(xml_string)
pretty_xml_as_string = dom.toprettyxml()

A: Here's a Python3 solution that gets rid of the ugly newline issue (tons of whitespace), and it only uses standard libraries unlike most other implementations.
import xml.etree.ElementTree as ET
import xml.dom.minidom
import os

def pretty_print_xml_given_root(root, output_xml):
    """
    Useful for when you are editing xml data on the fly
    """
    xml_string = xml.dom.minidom.parseString(ET.tostring(root)).toprettyxml()
    xml_string = os.linesep.join([s for s in xml_string.splitlines() if s.strip()]) # remove the weird newline issue
    with open(output_xml, "w") as file_out:
        file_out.write(xml_string)

def pretty_print_xml_given_file(input_xml, output_xml):
    """
    Useful for when you want to reformat an already existing xml file
    """
    tree = ET.parse(input_xml)
    root = tree.getroot()
    pretty_print_xml_given_root(root, output_xml)

I found how to fix the common newline issue here.

A: XML pretty print for python looks pretty good for this task.  (Appropriately named, too.)
An alternative is to use pyXML, which has a PrettyPrint function.

A: You can use popular external library xmltodict, with unparse and pretty=True you will get best result:
xmltodict.unparse(
    xmltodict.parse(my_xml), full_document=False, pretty=True)

full_document=False against <?xml version="1.0" encoding="UTF-8"?> at the top.

A: As of Python 3.9, ElementTree has an indent() function for pretty-printing XML trees.
See https://docs.python.org/3/library/xml.etree.elementtree.html#xml.etree.ElementTree.indent.
Sample usage:
import xml.etree.ElementTree as ET

element = ET.XML("text")
ET.indent(element)
print(ET.tostring(element, encoding='unicode'))

The upside is that it does not require any additional libraries. For more information check https://bugs.python.org/issue14465 and https://github.com/python/cpython/pull/15200

A: As others pointed out, lxml has a pretty printer built in.
Be aware though that by default it changes CDATA sections to normal text, which can have nasty results.
Here's a Python function that preserves the input file and only changes the indentation (notice the strip_cdata=False). Furthermore it makes sure the output uses UTF-8 as encoding instead of the default ASCII (notice the encoding='utf-8'):
from lxml import etree

def prettyPrintXml(xmlFilePathToPrettyPrint):
    assert xmlFilePathToPrettyPrint is not None
    parser = etree.XMLParser(resolve_entities=False, strip_cdata=False)
    document = etree.parse(xmlFilePathToPrettyPrint, parser)
    document.write(xmlFilePathToPrettyPrint, pretty_print=True, encoding='utf-8')

Example usage:
prettyPrintXml('some_folder/some_file.xml')

A: Take a look at the vkbeautify module.
It is a python version of my very popular javascript/nodejs plugin with the same name. It can pretty-print/minify XML, JSON and CSS text. Input and output can be string/file in any combinations. It is very compact and doesn't have any dependency.
Examples:
import vkbeautify as vkb

vkb.xml(text)
vkb.xml(text, 'path/to/dest/file')
vkb.xml('path/to/src/file')
vkb.xml('path/to/src/file', 'path/to/dest/file')

A: You can try this variation...
Install BeautifulSoup and the backend lxml (parser) libraries:
user$ pip3 install lxml bs4

Process your XML document:
from bs4 import BeautifulSoup

with open('/path/to/file.xml', 'r') as doc:
    for line in doc:
        print(BeautifulSoup(line, 'lxml-xml').prettify())

A: lxml is recent, updated, and includes a pretty print function
import lxml.etree as etree

x = etree.parse("filename")
print etree.tostring(x, pretty_print=True)

Check out the lxml tutorial:
http://lxml.de/tutorial.html

A: If you have xmllint you can spawn a subprocess and use it. xmllint --format <file> pretty-prints its input XML to standard output.
Note that this method uses an program external to python, which makes it sort of a hack.
def pretty_print_xml(xml):
    proc = subprocess.Popen(
        ['xmllint', '--format', '/dev/stdin'],
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
    )
    (output, error_output) = proc.communicate(xml);
    return output

print(pretty_print_xml(data))

A: Another solution is to borrow this indent function, for use with the ElementTree library that's built in to Python since 2.5.
Here's what that would look like:
from xml.etree import ElementTree

def indent(elem, level=0):
    i = "\n" + level*"  "
    j = "\n" + (level-1)*"  "
    if len(elem):
        if not elem.text or not elem.text.strip():
            elem.text = i + "  "
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
        for subelem in elem:
            indent(subelem, level+1)
        if not elem.tail or not elem.tail.strip():
            elem.tail = j
    else:
        if level and (not elem.tail or not elem.tail.strip()):
            elem.tail = j
    return elem

root = ElementTree.parse('/tmp/xmlfile').getroot()
indent(root)
ElementTree.dump(root)

A: I tried to edit "ade"s answer above, but Stack Overflow wouldn't let me edit after I had initially provided feedback anonymously.  This is a less buggy version of the function to pretty-print an ElementTree.
def indent(elem, level=0, more_sibs=False):
    i = "\n"
    if level:
        i += (level-1) * '  '
    num_kids = len(elem)
    if num_kids:
        if not elem.text or not elem.text.strip():
            elem.text = i + "  "
            if level:
                elem.text += '  '
        count = 0
        for kid in elem:
            indent(kid, level+1, count < num_kids - 1)
            count += 1
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
            if more_sibs:
                elem.tail += '  '
    else:
        if level and (not elem.tail or not elem.tail.strip()):
            elem.tail = i
            if more_sibs:
                elem.tail += '  '

A: If you're using a DOM implementation, each has their own form of pretty-printing built-in:
# minidom
#
document.toprettyxml()

# 4DOM
#
xml.dom.ext.PrettyPrint(document, stream)

# pxdom (or other DOM Level 3 LS-compliant imp)
#
serializer.domConfig.setParameter('format-pretty-print', True)
serializer.writeToString(document)

If you're using something else without its own pretty-printer — or those pretty-printers don't quite do it the way you want —  you'd probably have to write or subclass your own serialiser.

A: An alternative if you don't want to have to reparse, there is the xmlpp.py library with the get_pprint() function. It worked nice and smoothly for my use cases, without having to reparse to an lxml ElementTree object.

A: I found this question while looking for "how to pretty print html"
Using some of the ideas in this thread I adapted the XML solutions to work for XML or HTML:
from xml.dom.minidom import parseString as string_to_dom

def prettify(string, html=True):
    dom = string_to_dom(string)
    ugly = dom.toprettyxml(indent="  ")
    split = list(filter(lambda x: len(x.strip()), ugly.split('\n')))
    if html:
        split = split[1:]
    pretty = '\n'.join(split)
    return pretty

def pretty_print(html):
    print(prettify(html))

When used this is what it looks like:
html = """\

'IDK!'

Hi

Try for 2

Oh No!

"""

pretty_print(html)

Which returns:

'IDK!'

      Hi

Try for 2

Oh No!

A: I found a fast and easy way to nicely format and print an xml file:
import xml.etree.ElementTree as ET

xmlTree = ET.parse('your XML file')
xmlRoot = xmlTree.getroot()
xmlDoc =  ET.tostring(xmlRoot, encoding="unicode")

print(xmlDoc)

Outuput:
<root>
  <child>
    <subchild>.....</subchild>
  </child>
  <child>
    <subchild>.....</subchild>
  </child>
  ...
  ...
  ...
  <child>
    <subchild>.....</subchild>
  </child>
</root>

A: I had this problem and solved it like this:
def write_xml_file (self, file, xml_root_element, xml_declaration=False, pretty_print=False, encoding='unicode', indent='\t'):
    pretty_printed_xml = etree.tostring(xml_root_element, xml_declaration=xml_declaration, pretty_print=pretty_print, encoding=encoding)
    if pretty_print: pretty_printed_xml = pretty_printed_xml.replace('  ', indent)
    file.write(pretty_printed_xml)

In my code this method is called like this:
try:
    with open(file_path, 'w') as file:
        file.write('<?xml version="1.0" encoding="utf-8" ?>')

        # create some xml content using etree ...

        xml_parser = XMLParser()
        xml_parser.write_xml_file(file, xml_root, xml_declaration=False, pretty_print=True, encoding='unicode', indent='\t')

except IOError:
    print("Error while writing in log file!")

This works only because etree by default uses two spaces to indent, which I don't find very much emphasizing the indentation and therefore not pretty. I couldn't ind any setting for etree or parameter for any function to change the standard etree indent. I like how easy it is to use etree, but this was really annoying me.

A: For converting an entire xml document to a pretty xml document
(ex: assuming you've extracted [unzipped] a LibreOffice Writer .odt or .ods file, and you want to convert the ugly "content.xml" file to a pretty one for automated git version control and git difftooling of .odt/.ods files, such as I'm implementing here)
import xml.dom.minidom

file = open("./content.xml", 'r')
xml_string = file.read()
file.close()

parsed_xml = xml.dom.minidom.parseString(xml_string)
pretty_xml_as_string = parsed_xml.toprettyxml()

file = open("./content_new.xml", 'w')
file.write(pretty_xml_as_string)
file.close()

References:
- Thanks to Ben Noland's answer on this page which got me most of the way there.

A: from lxml import etree
import xml.dom.minidom as mmd

xml_root = etree.parse(xml_fiel_path, etree.XMLParser())

def print_xml(xml_root):
    plain_xml = etree.tostring(xml_root).decode('utf-8')
    urgly_xml = ''.join(plain_xml .split())
    good_xml = mmd.parseString(urgly_xml)
    print(good_xml.toprettyxml(indent='    ',))

It's working well for the xml with Chinese!

A: If for some reason you can't get your hands on any of the Python modules that other users mentioned, I suggest the following solution for Python 2.7:
import subprocess

def makePretty(filepath):
  cmd = "xmllint --format " + filepath
  prettyXML = subprocess.check_output(cmd, shell = True)
  with open(filepath, "w") as outfile:
    outfile.write(prettyXML)

As far as I know, this solution will work on Unix-based systems that have the xmllint package installed.

A: Use etree.indent and etree.tostring
import lxml.etree as etree

root = etree.fromstring('
Welcome
')
etree.indent(root, space="  ")
xml_string = etree.tostring(root, pretty_print=True).decode()
print(xml_string)

output

Welcome

Removing namespaces and prefixes
import lxml.etree as etree

def dump_xml(element):
    for item in element.getiterator():
        item.tag = etree.QName(item).localname

    etree.cleanup_namespaces(element)
    etree.indent(element, space="  ")
    result = etree.tostring(element, pretty_print=True).decode()
    return result

root = etree.fromstring('<cs:document xmlns:cs="http://blabla.com"><name>hello world</name></cs:document>')
xml_string = dump_xml(root)
print(xml_string)

output
<document>
  <name>hello world</name>
</document>

A: I solved this with some lines of code, opening the file, going trough it and adding indentation, then saving it again. I was working with small xml files, and did not want to add dependencies, or more libraries to install for the user. Anyway, here is what I ended up with:
    f = open(file_name,'r')
    xml = f.read()
    f.close()

    #Removing old indendations
    raw_xml = ''
    for line in xml:
        raw_xml += line

    xml = raw_xml

    new_xml = ''
    indent = '    '
    deepness = 0

    for i in range((len(xml))):

        new_xml += xml[i]
        if(i<len(xml)-3):

            simpleSplit = xml[i:(i+2)] == '><'
            advancSplit = xml[i:(i+3)] == '></'
            end = xml[i:(i+2)] == '/>'
            start = xml[i] == '<'

            if(advancSplit):
                deepness += -1
                new_xml += '\n' + indent*deepness
                simpleSplit = False
                deepness += -1
            if(simpleSplit):
                new_xml += '\n' + indent*deepness
            if(start):
                deepness += 1
            if(end):
                deepness += -1

    f = open(file_name,'w')
    f.write(new_xml)
    f.close()

It works for me, perhaps someone will have some use of it :)