text:
Q: Delphi: Memory Leak Warning Message I am in the process of creating a small application in Delphi 2006. In one of the classes there is a property of another class. In my onCreate event, I instantiated the objects and also destroy them in the onDestroy event. When I close the application, I get a memory leak warning. I honestly cannot identity the memory leak. Here is the code that I am using, your help will be greatly appreciated.
I can't post an image of the error message, but here is a description.
An unexpected memory leak has occurred. The unexpected small block leaks are:
21 - 28 bytes: TPermanentAddress x 1

Here is the class:
unit uUser;

interface

uses
  classes,SysUtils,Dialogs;

type
TAddress = class
private
 FStreetAddress : string;
 FCity          : string ;
 FState         : string;
 FZipCode       : string;

 procedure setStreetAddress(const Value : string);
 procedure setCity(const Value : string);
 procedure setState(const Value : string);
 procedure setZipCode(const Value : string);

 protected

 public
 property StreetAddress : string read FStreetAddress write setStreetAddress;
 property City : string read FCity write setCity;
 property State : string read FState write setState;
 property ZipCode : string read FZipCode write setZipCode;

end;

type
  TPermanentAdddress = class (TAddress)
  private
  FStartDate     : string;
  FEndDate       : string;

  procedure setStartDate(const Value : string);
  procedure setEndDate(const Value : string);

  protected

  public

  property StartDate : string read FStartDate write setStartDate;
  property EndDate   : string read FEndDate write setEndDate ;
  end;

type
TUser = class(TObject)
  private
  FFirstName : string;
  FAddress : TPermanentAdddress;
  procedure setFirstName(const Value : string);
  procedure setAddress(const Value : TPermanentAdddress);

  protected

  public
  constructor Create(); reintroduce; overload;
  destructor Destroy();  override;
   property FirstName : string read FFirstName write setFirstName;
   property Address : TPermanentAdddress read FAddress write setAddress;

end;

implementation

procedure TAddress.setStreetAddress(const Value : string);
begin
  FStreetAddress := value;
end;

 procedure TAddress.setCity(const Value : string);
 begin
   FCity := Value;
 end;
 procedure TAddress.setState(const Value : string);
 begin
   FState := Value;
 end;
 procedure TAddress.setZipCode(const Value : string);
 begin
   FZipCode := Value;
 end;

 //Permanent Address
  procedure TPermanentAdddress.setStartDate(const Value : string);
  begin
    FStartDate := value;
  end;
  procedure TPermanentAdddress.setEndDate(const Value : string);
  begin
    FEndDate := Value;
  end;

  //tvxpatient
  procedure TUser.setFirstName(const Value : string);
  begin
    FFirstName := Value;
  end;
  procedure TUser.setAddress(const Value : TPermanentAdddress);
  begin
    FAddress := Value;
  end;

  constructor TUser.Create();
  begin
   FAddress := TPermanentAdddress.Create;
  end;

  destructor TUser.Destroy();
  begin
  //FAddress.Free;
  end;

end.

Here is the Form:
unit Home;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, uUser, StdCtrls;

type
  TForm1 = class(TForm)
    Memo1: TMemo;
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
  private
    { Private declarations }
protected

  public
    { Public declarations }
  aUser : TUser;

  end;
var
  Form1: TForm1;

implementation
{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
var
addr : TPermanentAdddress;
begin
  aUser := TUser.Create;
  aUser.Address := TPermanentAdddress.Create;
  aUser.FirstName := 'test';
  aUser.Address.StartDate := '03/10/2015';
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
 aUser.Address.Free; // I am destroying it here, so I thought.
 aUser.Free;
end;

end.

In the project, I turned on ReportMemoryLeaksOnShutdown.
program Testing;

uses
  Forms,
  Home in 'Home.pas' {Form1},
  uUser in 'uUser.pas';

{$R *.res}

begin
  ReportMemoryLeaksOnShutdown := DebugHook <> 0;
  Application.Initialize;
  Application.CreateForm(TForm1, Form1);
  Application.Run;
end.

A: destructor TUser.Destroy();
begin
  //FAddress.Free;
end;

Here you fail to destroy FAddress. Hence the memory leak.
Your should also call the inherited destructor. It should look like this:
destructor TUser.Destroy;
begin
  FAddress.Free;
  inherited;
end;

On top of this, you are wrong to create Address twice. Instead of:
procedure TForm1.FormCreate(Sender: TObject);
var
  addr : TPermanentAdddress;
begin
  aUser := TUser.Create;
  aUser.Address := TPermanentAdddress.Create;
  aUser.FirstName := 'test';
  aUser.Address.StartDate := '03/10/2015';
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
 aUser.Address.Free; // I am destroying it here, so I thought.
 aUser.Free;
end;

You need:
procedure TForm1.FormCreate(Sender: TObject);
begin
  aUser := TUser.Create;
  aUser.FirstName := 'test';
  aUser.Address.StartDate := '03/10/2015';
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  aUser.Free;
end;

Personally I would use the constructor/destructor of TForm1 rather than OnCreate and OnDestroy to managed owned objects.


text:
Q: Merge / Combine object arrays into single object I have an object with key values, and those keys each contain an array of objects:
var obj = {
  "0": [
    {
      "category": "A",
      "index": 0,
      "property": "Name",
      "value": "Bob"
    },
    {
      "category": "A",
      "index": 0,
      "property": "Surname",
      "value": "Dylan"
    }
  ],
  "1": [
    {
      "category": "A",
      "index": 1,
      "property": "Name",
      "value": "Elvis"
    },
    {
      "category": "A",
      "index": 1,
      "property": "Surname",
      "value": "Presley"
    }
  ]
}

How would I go about merging the objects into one single array with the objects combined therein? The objective is to have the result return the following:
var obj2 = [
        {
          "category": "A",
          "index": 0,
          "property": "Name",
          "value": "Bob"
        },
        {
          "category": "A",
          "index": 0,
          "property": "Surname",
          "value": "Dylan"
        },
        {
          "category": "A",
          "index": 1,
          "property": "Name",
          "value": "Elvis"
        },
        {
          "category": "A",
          "index": 1,
          "property": "Surname",
          "value": "Presley"
        }
    ]

I've tried to make use of LoDash union and join, however to no avail.

A: Assuming your example was wrong, and it's actually like below (since what you put in isn't even valid), you can just use Object.values(obj).flat()

var obj = {
    "0": [{
      "category": "A",
      "index": 0,
      "property": "Name",
      "value": "Bob"
    }],
    "1": [{
      "category": "A",
      "index": 1,
      "property": "Name",
      "value": "Jessica"
    }]
}

console.log(Object.values(obj).flat())

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get size of a object from a PDF file I need to save a chart from Microsoft Excel as a PDF file. (Save As -> File Type: PDF) This will produce a sigle page PDF file where the chart is always located in the middle and also the chart is scaled to fit the page width.
The result is fine but the chart can get lots of extra white space around it that I'd like to get rid of. I'm using PdfSharp to manipulate with the PDF file but I'm unable to find the chart (object) inside the PDF and calculate the actual size.
I know that Aspose.PDF library has a function for it - CalculateContentBBox but I cannot use the library in my project.
Is there anyway how to get the same or similar via PdfSharp?
I believe the chart is stored as '/Contents' in the internal structure

Here is what I have tried so far (An example PDF file is included on GitHub)
Thanks
https://github.com/PetLahev/PdfSharpQuestion
using System;
using System.Reflection;
using System.IO;
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
using PdfSharp.Pdf.Advanced;

namespace PDFSharpProject
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Provide path to a PDF file (or just hit enter to get the default)");
            string path = Console.ReadLine();
            if (string.IsNullOrWhiteSpace(path))
            {
                path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "TestPDF.pdf");
            }

            if (string.IsNullOrWhiteSpace(path)) return;
            TryToFindObject(path);
        }

        private static void TryToFindObject(string pdfPath)
        {
            PdfDocument pdf = PdfReader.Open(pdfPath);
            PdfPage page = pdf.Pages[0];
            PdfDictionary contents = page.Elements.GetDictionary("/Contents");
            if (contents == null) return;

            var items = contents.Elements.Values;
            Console.WriteLine("Here I don't know what to do");

        }
    }
}

So I'd like to get the content in the red 'rectangle' (of course this should be real rectangle). Mainly I need to get rid of the left/right white space. I can handle top/bottom


text:
Q: DNS error: when adding a subdomain using powerdns I recently added a subdomain m.domain.co.za and it just does not show, I defined the domain on the apache hosting server and added the relevant dns records but somehow it is still not working. The root domain works but not the subdomain. I'm using powerdns on a centos machine.
Detail
When I PING domain.co.za it gets a respone. If I ping m.domain.co.za I get no response
The setup looks as follows.
record  TTL     TYPE            value
m   28800   CNAME       domain.co.za

On the hosting server my virtualhost file looks like this
<VirtualHost *:80>
  DocumentRoot /var/www/html/m.domain.co.za
  ServerName m.domain.co.za
  ServerAlias www.m.domain.co.za
  ServerAdmin webmaster@domain.co.za
  DirectoryIndex default.php default.htm default.html index.html index.htm index.php index.php5 index.php4 index.php3 index.shtml index.cgi index.pl index.jsp Default.htm Default.php
</VirtualHost>

the folder m.domain.co.za exists
http -t showed no errors
If I use nslookup
I get the following
work@work-laptop:~$ nslookup m.domain.co.za
Server:     10.0.2.2
Address:    10.0.2.2#53

** server can't find m.domain.co.za: NXDOMAIN

The live site is on the same server as the syub domain, that's why I used CNAME

A: Your CName record currently looks like this:
record  TTL     TYPE            value
m   28800   CNAME       domain.co.za

it should look like this
record           TTL     TYPE            value
m.domain.co.za   28800   CNAME       domain.co.za

You need to specify the FQDN in the CName record.


text:
Q: OpenCL kernel doesn't get to be executed There is a set of rules, where each rule corresponds to ceratain cellular automaton. I need to check property of bijectivity for each of these rules. As there are too much of them (2^32 to be precise), I decided to use my GPU for this purpose. But after week or so I am still struggling with one bug.
Briefly speaking, when the kernel is enqueued and its execution is supposedly being performed on GPU, the usage of GPU is as if it is idle. Furthermore, after I added several statements to kernel code in order to see if kernel is being executed at all, I found no signs of that the statements and therefore kernel itself were executed. Besides, all error codes are equal to CL_SUCCESS. I might get something wrong as I'm new to OpenCL programming and will apreciate any help.
This is the host side code with some abbreviations:
#define CL_USE_DEPRECATED_OPENCL_2_0_APIS

//some includes here

#define GLOBAL_SIZE 4096
#define LOCAL_SIZE 256
#define GLOBAL_SCOPE 0xffffffff
int main()
{
    //we assume that global_scope divides evenly into global_size
    //and therefore there is no need in processing remainder
    long rules_per_thread = GLOBAL_SCOPE / GLOBAL_SIZE;

    int * starts = new int[GLOBAL_SIZE];
    int * stops = new int[GLOBAL_SIZE];

    int count = 0;
    for (int i = 0; i < GLOBAL_SIZE; i++) {
        starts[i] = count;
        count += rules_per_thread;
        stops[i] = count;
        count++;
    }

    ...
    /*obtainig platform, device, building program*/
    ...

    /*====CREATING BUFFERS====*/
    //buffer for storing approved automata
    const int bufSize = 10000;  //size of buffer picked at random guess; might need to add some space later
    uint32_t* bijective_aut = new uint32_t[bufSize];
    std::fill(&bijective_aut[0], &bijective_aut[bufSize - 1], 0);
    //first value in array serves as global iterator over array
    //and initially is set to base offset
    bijective_aut[0] = 3;
    //second value serves as indicator of array length
    bijective_aut[1] = bufSize;

    cl::Buffer buf(context, CL_MEM_READ_WRITE, sizeof(uint32_t) * bufSize);
    cl::Buffer starts_buf(context, CL_MEM_READ_ONLY, sizeof(int) * GLOBAL_SIZE);
    cl::Buffer stops_buf(context, CL_MEM_READ_ONLY, sizeof(int) * GLOBAL_SIZE);

    /*====SETTING UP COMMAND QUEUE====*/
    cl::CommandQueue queue(context, device);

    err = queue.enqueueWriteBuffer(buf, CL_FALSE, 0, sizeof(uint32_t) * bufSize, bijective_aut);
    err = queue.enqueueWriteBuffer(starts_buf, CL_FALSE, 0, sizeof(int) * GLOBAL_SIZE, starts);
    err = queue.enqueueWriteBuffer(stops_buf, CL_FALSE, 0, sizeof(int) * GLOBAL_SIZE, stops);

    /*====CREATING KERNEL, SETTING ITS VARIABLES====*/
    cl::Kernel bc_kernel(program, "bijection_check", &err);
    err = bc_kernel.setArg(0, buf);
    err = bc_kernel.setArg(1, starts_buf);
    err = bc_kernel.setArg(2, stops_buf);

    /*====EXECUTING KERNEL====*/
    cl::Event event;
    err = queue.enqueueNDRangeKernel(bc_kernel, cl::NullRange, cl::NDRange(GLOBAL_SIZE), cl::NDRange(LOCAL_SIZE), nullptr, &event);
    event.wait();
    err = queue.enqueueReadBuffer(buf, CL_FALSE, 0, sizeof(uint32_t) * bufSize, bijective_aut);
    cl::finish();

}

Then there is the kernel code:
 __kernel void bijection_check (
                                __global uint * bijective_rules, //stores approved bijective rules
                                __global const uint * starts,
                                __global const uint * stops
                              )
{
    __private int idx = get_global_id(0);
    int iterator = bijective_rules[0];  //inditates next free cell to write in
    int start = starts[idx];
    int stop = stops[idx];
    bool check = true;
    //there is some variables required for test

    //iterating over rules between *start* and *stop*
    for (uint rule = start; rule < stop; rule++)
    {
        ...
        /*then there goes test of the rule for bijectivity*/
        ...

        //writing current rule to general list if it turned to be bijective
        if ((check == true) && (iterator < 10000))
        {
            bijective_rules[iterator] = rule;
            bijective_rules[0]++;
        }
        else
        {
            bijective_rules[2]++;
        }
    }
    bijective_rules[3]++;
}

Judging by the array read from the buffer after execution, both statements at the end were not performed a single time. That is, after kernel execution bijective_rules array is left in exactly same condition as it was previosly defined on the host side.

A: You have a race condition: You read bijective_rules[0];, but other threads at the same time might execute bijective_rules[0]++;, thereby reading and writing to that memory location. If two threads write different data to the same memory address, you have a race condition and it is random which of the two gets to decide the result. So your result will be random and non-reproducible.
If multiple threads need to increment a value in the same memory location, use the atoimic function atomic_inc. Atomic functions block the memory location while one thread is working on it, and all other threads have to wait.
To get rid of the race condition, read from one copy of the buffer (or one particular memory address) and write to a second copy (or address). This way, you never write to the memory that other concurrent threads are reading from.


text:
Q: In XSLT, is it possible to keep track of the path and use it dynamically? Yesterday I asked a question about loading external XMLs dynamically from XSLTs. It was answered, but now I have another problem. If you read that question you'll see an <include ref="/path/to/some.xml" /> at the third level. What if the level at which the <include> occurs varies?
Is there a way to dynamically choose to extract the nodes from that XML on the same level on which they occur in the original file?
EDIT:
To be clear: I'm talking about the "element path" in the XML (the position of the include element in the XML), not the file path.
merge.xslt:
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >

  <xsl:output indent="yes" method="xml" encoding="utf-8"
    omit-xml-declaration="yes" />

  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="include">
      <!-- the depth of the extraction path (fruit/*/*/*... etc) should
           be based on the position of the matched <include> element -->
      <xsl:apply-templates select="document(@ref)/fruit/*/*/*"/>
  </xsl:template>
</xsl:stylesheet>

fruit.xml:
<fruit>
  <local>
    <apples>
      <include ref="apples.xml" />
    </apples>
  </local>
  <exotic>
    <bananas>
      <deeperlevel>
        <include ref="bananas.xml" />
      </deeperlevel>
    </bananas>
    <oranges>
      <include ref="oranges.xml" />
    </oranges>
  </exotic>
</fruit>

bananans.xml:
<fruit>
  <exotic>
    <bananas>
      <deeperlevel>
        <banana type="chiquita" color="yellow" />
        <banana type="generic" color="yellow" />
      </deeperlevel>
    </bananas>
  </exotic>
</fruit>

result:
<fruit>
  <local>
    <apples>
      <apple type="jonagold" color="red"/><apple type="granny-smith" color="green"/>
    </apples>
  </local>
  <exotic>
    <bananas>
      <deeperlevel>
        <deeperlevel> <!-- I don't want the second <deeperlevel> here, instead
                           <bananas .../> should be extracted, right after the
                           first <deeperlevel> -->
          <banana type="chiquita" color="yellow"/>
          <banana type="generic" color="yellow"/>
        </deeperlevel>
      </deeperlevel>
    </bananas>
    <oranges>
      <orange type="juice-orange" color="orange"/><orange type="red-orange" color="red"/>
    </oranges>
  </exotic>
</fruit>

A: I've found a solution to my problem. It's not extremely nice IMHO, because it's an "eval"-type solution, but it works. I applied the 3rd suggestion in the answer of this question to my problem, the dynamic XPath evaluation extension (dyn:evaluate()). Luckily the xsltproc tool from the libxslt library (installed through macports, version 1.1.27) supports it.
I am going to leave the question open for a while, maybe someone has a better solution.
XSLT:
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:dyn="http://exslt.org/dynamic"
  extension-element-prefixes="dyn">

  <xsl:output indent="yes" method="xml" encoding="utf-8"
    omit-xml-declaration="yes" />

  <xsl:template match="@*|node()">
    <xsl:param name="depth" select="'/*'" />
    <xsl:copy>
      <xsl:apply-templates select="@*|node()">
        <xsl:with-param name="depth" select="concat($depth, '/*')" />
      </xsl:apply-templates>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="include">
    <xsl:param name="depth" />
    <xsl:apply-templates select="dyn:evaluate(concat('document(@ref)', $depth))">
      <xsl:with-param name="depth" select="$depth" />
    </xsl:apply-templates>
  </xsl:template>

</xsl:stylesheet>


text:
Q: How can I get a single column of output from the bdf command on HP-UX? I would like to monitor disk space usage. I'm using HP-UX and the bdf command.
I would like to check one directory and I can do that: bdf /exploit/

I would like to get only the row %used. How can I do it?

A: for /exploit only
bdf /exploit | awk 'NR==2 { printf "%d\n",$5 ;}

for any filesystem
bdf | awk '{printf "%3d %s\n",$5,$6}'

note

*

*you can use %s instead of %d to get back % sign...

*or use %d %%


text:
Q: Type erasure & Flink: what causes run time error? I have an abstract class whose abstract method creates a SourceFunction, so derived classes can return simple or more complex sources (e.g. KafkaConsumers etc).  ChangeMe is a simple auto-generated class created by the compilation of an AvroSchema.
public SourceFunction<ChangeMe> createSourceFunction(ParameterTool params) {
        FromElementsFunction<ChangeMe> dataSource = null;

        List<ChangeMe> changeMeList = Arrays.asList(
                ChangeMe.newBuilder().setSomeField("Some field 1").build(),
                ChangeMe.newBuilder().setSomeField("Some field 2").build(),
                ChangeMe.newBuilder().setSomeField("Some field 3").build()
        );
        try {
            dataSource = new FromElementsFunction<>(new AvroSerializer<>(ChangeMe.class), changeMeList);
        }
        catch (IOException ex){

        }

        return dataSource;
}

In my Flink job I basically have this:
SourceFunction<ChangeMe> source = createSourceFunction(params);
DataStream<T> sourceDataStream = streamExecutionEnvironment.addSource(source);

DataStream<ChangeMe> changeMeEventsStream = this.getSourceDataStream();  // gets sourceDataStream above
changeMeEventsStream.print();

When I run the job, I get this error with respect to the call to print():
Exception in thread "main" org.apache.flink.api.common.functions.InvalidTypesException: The return type of function 'Custom Source' could not be determined automatically, due to type erasure. You can give type information hints by using the returns(...) method on the result of the transformation call, or by letting your function implement the 'ResultTypeQueryable' interface.
……
Caused by: org.apache.flink.api.common.functions.InvalidTypesException: Type of TypeVariable 'T' in 'class org.apache.flink.streaming.api.functions.source.FromElementsFunction' could not be determined. This is most likely a type erasure problem. The type extraction currently supports types with generic variables only in cases where all variables in the return type can be deduced from the input type(s).

I am using the Eclipse compiler, so I had thought the type information would be included (although I thought this was just for lambdas, and there are none in the above).  What do I need to do to get this to run correctly?

A: If you want to directly instantiate a FromElementsFunction, then you have to manually provide a TypeInformation instance for the ChangeMe class when calling addSource. This is necessary for Flink to learn about the element type.
The following code snippet should do the trick:
SourceFunction<ChangeMe> source = createSourceFunction();

TypeInformation<ChangeMe> typeInfo = TypeInformation.of(ChangeMe.class);
DataStream<ChangeMe> sourceDataStream = env.addSource(source, typeInfo);

DataStream<ChangeMe> changeMeEventsStream = sourceDataStream;
changeMeEventsStream.print();


text:
Q: How can I check to see if the type of user using javascript from database In the database, I have three user types -- admin, student, teacher. I am making a javascript game which every account type can access. How can I check to see if the user accessing the game is admin, teacher, or student from the database.
There is a database called "user" in mysql and there is a "role" column in the user database and each user is assigned a role 1-3. 3 is the role assigned for students.
In my file, I want to do something like:
if the role of user is student (3)
     window.location = '/student_dashboard';
else
     window.location = '/other_dashboard';

How can I do this in the file?

A: Javascript by itself cannot be used to deal with database. That is done using php (Or the server side language of your choice). Ajax is used to send a request to your php script using javascript which will in turn communicate with the db. And it doesn't require a page refresh.
So what you are trying to do can be easily achieved using ajax. you can check out the $.ajax or $.post methods in jquery which make the process even more simple.
You need to process the form using ajax. The ajax request is sent to a php script which will make the necessary changes in the database and send the new link (link to edit.html) in the response. Upon getting the response, just replace the current anchor element with the new one ..
for eg..
$.post(url, formdataobject , function (resp) {
   $("a.youra").text('edit').attr('href', resp);
});

url - where the php script is located
formdataobject - a javascript object that will have the form data as key value pairs
the third parameter is an anonymous function also known as callback function since it will be invoked only when the response is received from the server. This is because ajax requests are asynchronous.
Inside the callback function, jquery is used to change the text inside the anchor element to edit and the href attribute is changed to value that came in the response.
$.post means we are using the post method. so the parameters can be accessed as elements of $_POST array in php. After updating the db, you can simply echo out the new link and it will be received in the response.
Also, there are other formats in which you can get the response for eg. xml, json.


text:
Q: How can I reverse a section of a list using a loop in Python? I'm in need of a little help reversing a section of a list in Python using a loop.
I have a list: mylist = ['a', 'b', 'c', 'd', 'e', 'f']
Also have an index number, this number will tell where to start the reversing. For example, if the reverse-index number is 3, it needs to be something like this: ['d', 'c', 'b', 'a', 'e', 'f']
What I currently have:
def list_section_reverse(list1, reverse_index):
    print("In function reverse()")

    n_list = []

    for item in range( len(list1) ):
        n_list.append( (list1[(reverse_index - 1) - item]) )
        item += 1
    return n_list

mylist = ['a', 'b', 'c', 'd', 'e', 'f']
print( list_section_reverse(mylist, 3) )

Which returns ['c', 'b', 'a', 'f', 'e', 'd']
How can I alter my code, so that it prints out ['d', 'c', 'b', 'a', 'e', 'f']?

A: You can simply use:
def list_section_reverse(list1, reverse_index):
    return list(reversed(list1[:reverse_index+1])) + list1[reverse_index+1:]

Edit: The problem with your existing solution is that you keep reversing after reverse_index. If you have to use a loop, try this:
def list_section_reverse(list1, reverse_index):
    print("In function reverse()")

    n_list = list1[:]

    for i in range(reverse_index + 1):
        n_list[i] = list1[-i-reverse_index]
    return n_list

mylist = ['a', 'b', 'c', 'd', 'e', 'f']
print(list_section_reverse(mylist, 3))

A: The pythonic solution:
list1[reverse_index::-1] + list1[reverse_index+1:]

Now, that's not using loops like you asked. Well, not explicitly... Instead we can break down the above into its constituent for loops.
def list_section_reverse(list1, reverse_index):
    if reverse_index < 0 or reversed_index >= len(list1):
        raise ValueError("reverse index out of range")
    reversed_part = []
    for i in range(reverse_index, -1, -1): # like for i in [n, n-1, ..., 1, 0]
        reversed_part.append(list1[i]

    normal_part = []
    for i in range(reverse_index + 1, len(list1)):
        normal_part.append(list1[i])

    return reversed_part + normal_part

A: You can try this. This makes use of no slicing, and can use either a while loop or for loop.
    def reversed_list(my_list, index):
        result = []
        list_copy = my_list.copy()

        i = 0
        while i < index+1:
            result.append(my_list[i])
            list_copy.remove(my_list[i])
            i+=1

        result.reverse()

        return result + list_copy

Or with a for loop
    def reversed_list(my_list, index):
        result = []
        list_copy = my_list.copy()

        for i in range(len(my_list)):
            if i < index + 1:
                result.append(my_list[i])
                list_copy.remove(my_list[i])

        result.reverse()

        return result + list_copy

A: Is it allowed to make a copy of the list?
def list_section_reverse(list1, reverse_index):
    print("In function reverse()")

    n_list = [ element for element in list1 ]

    for item in range( reverse_index + 1 ):
        n_list[ item ] = list1[ reverse_index - item ]
        item += 1

    return n_list

mylist = ['a', 'b', 'c', 'd', 'e', 'f']
print(list_section_reverse(mylist, 3))

Outs:
In function reverse()
['d', 'c', 'b', 'a', 'e', 'f']

A: You can modify the list inplace using a slice.
mylist[:4] = mylist[:4][::-1]


text:
Q: The colors in ggplot do not correspond to the colors in the legend I created a histogram from the World Happiness Report and reorder the values. However, I´d like the colors from the plot to match the colors from the legend.
ggplot(Top102018, aes(x= reorder(Country, -Life.Ladder), y=Life.Ladder))+
geom_col(aes(fill=Country)) +
scale_fill_discrete(name = "Country",
                    labels = c("Finland", "Denmark", "Switzerland","Netherlands","Norway","Austria", "Sweden","New Zealand", "Luxembourg","United Kingdom"))  +
theme_light()

A: Colors don't match the legend because of the line : scale_fill_discrete().
If you want the same order, use reorder() in the fill parameters too, not only in the x =
data.frame(
    Country     = c("Finland", "Denmark", "Switzerland"),
    Life.Ladder = c(10, 20, 15)
) %>%
    ggplot(aes(x = reorder(Country, -Life.Ladder), y = Life.Ladder)) + geom_col(aes(fill = reorder(Country, -Life.Ladder))) +
    labs(fill = 'Country')  +
    theme_light()


text:
Q: Application crashes when adding a Y constraint My code is very simple. I need to stack my view one after another. Adding both view in self.view with 20 px space
- (void)viewDidLoad {
    [super viewDidLoad];
    UILabel *label = [[UILabel alloc] init];
    [label setTranslatesAutoresizingMaskIntoConstraints:NO];
    [label.layer setBorderWidth:1.f];
    [label.layer setBorderColor:[[UIColor grayColor] CGColor]];
    [label setText:@"label1"];
    [self.view addSubview:label];
    NSLayoutConstraint *yConstraint =[NSLayoutConstraint
                                      constraintWithItem:label
                                      attribute:NSLayoutAttributeTop
                                      relatedBy:NSLayoutRelationEqual
                                      toItem:label.superview
                                      attribute:NSLayoutAttributeTop
                                      multiplier:1.f
                                      constant:20];
    [label.superview addConstraint:yConstraint];
    NSLayoutConstraint *width =[NSLayoutConstraint
                                constraintWithItem:label
                                attribute:NSLayoutAttributeWidth
                                relatedBy:NSLayoutRelationEqual
                                toItem:label.superview
                                attribute:NSLayoutAttributeWidth
                                multiplier:1.f
                                constant:0];
    [label.superview addConstraint:width];
    NSLayoutConstraint *centerX =[NSLayoutConstraint
                                  constraintWithItem:label
                                  attribute:NSLayoutAttributeCenterX
                                  relatedBy:NSLayoutRelationEqual
                                  toItem:label.superview
                                  attribute:NSLayoutAttributeCenterX
                                  multiplier:1.0
                                  constant:0];
    [label.superview addConstraint:centerX];

    NSLayoutConstraint *height =[NSLayoutConstraint
                                 constraintWithItem:label
                                 attribute:NSLayoutAttributeHeight
                                 relatedBy:NSLayoutRelationEqual
                                 toItem:nil
                                 attribute:NSLayoutAttributeNotAnAttribute
                                 multiplier:1.0
                                 constant:40];
    [label addConstraint:height];

    UILabel *labe2 = [[UILabel alloc] init];
    [labe2 setTranslatesAutoresizingMaskIntoConstraints:NO];
    [labe2 setText:@"label2"];
    [self.view addSubview:labe2];

    yConstraint =[NSLayoutConstraint
                                      constraintWithItem:labe2
                                      attribute:NSLayoutAttributeTop
                                      relatedBy:NSLayoutRelationEqual
                                      toItem:label
                                      attribute:NSLayoutAttributeBottom
                                      multiplier:1.f
                                      constant:20];
    [labe2 addConstraint:yConstraint]; //Crashes here

}

With message
2015-12-17 12:59:40.313 Testcase[16625:14518988] The view hierarchy is not prepared for the constraint: <NSLayoutConstraint:0x7ae4f990 V:[UILabel:0x7ae4ac30'label1']-(20)-[UILabel:0x7ae4f610'label2']>
    When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled. Break on -[UIView(UIConstraintBasedLayout) _viewHierarchyUnpreparedForConstraint:] to debug.
2015-12-17 12:59:40.315 Testcase[16625:14518988] View hierarchy unprepared for constraint.
    Constraint: <NSLayoutConstraint:0x7ae4f990 V:[UILabel:0x7ae4ac30'label1']-(20)-[UILabel:0x7ae4f610'label2']>
    Container hierarchy:
<UILabel: 0x7ae4f610; frame = (0 0; 0 0); text = 'label2'; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x7ae4f720>>
    View not found in container hierarchy: <UILabel: 0x7ae4ac30; frame = (0 0; 0 0); text = 'label1'; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x7ae4c3e0>>
    That view's superview: <UIView: 0x7ae4af30; frame = (0 0; 320 480); autoresize = W+H; layer = <CALayer: 0x7ae4a610>>

Plz help. struck for hours
 Gone through this but no help

A: Replace this
[labe2 addConstraint:yConstraint];

With
[self.view addConstraint:yConstraint];


text:
Q: Copying files from somewhere within a directory tree to a folder I have a mirror of a large website that I need to reorganize, most of the images and files I've been able to programmatically move and relink up; however, there are a few (few is a relative term, we're talking 3,000 odd files) I need to locate within the mess of folders.
I know the filename(s) (I have big long lists and I'm assuming they're unique, or at least unique enough that I can fix any collision manually) but not their location within the file structure, and I need to copy them to a separate directory so that I can then upload them.
In short, I have a list like
file1.jpg
file2.doc
file4.ppt
filesomethingelse.this

in a file (say, filelist.txt).
And I have a folder structure like
folder\subfolder\file1.jpg
folder\subfolder\file2.doc
folder\subfolder2\filesomethingelse.this
folder\file3.jpg
folder\file4.ppt

and I want to get
secondFolder\file1.jpg
secondFolder\file2.doc
secondFolder\file4.ppt
secondFolder\filesomethingelse.this

Note that file3.jpg should not be copied because it is not on the list.
Something command line like (xcopy or robocopy) would be the best option I guess, so I can batch up the requests.
Hope this makes sense.

A: If you want to copy only those files whose names are listed in filelist.txt,
and skip files that aren't (e.g., file3.jpg in your example), do
for /r folder %f in (*) do @findstr/i /x "%~nxf" filelist.txt > nul && copy %f secondfolder

*

*%f is assigned the full pathname of each file under folder;
%~nxf extracts the name and extension
(i.e., the base filename; everything after the last \).

*@ suppresses display of the following command.
This is cosmetic and discretionary.  Also, it is unnecessary
if you put this command in a batch file and begin it with @echo off.

*findstr looks for a string (or pattern) in a file (or other data set); it is essentially Windows' equivalent of grep.
We use it to determine whether each filename is in the filename list,
filelist.txt.

*

*/i — Do case insensitive matching.
You can leave this out if you're sure your list has correct capitalization.

*/x — Match entire line (like grep -x).
This prevents filenames like le2.do from matching file2.doc.

*> nul — equivalent to > /dev/null;
this prevents the output from findstr from being displayed.
(Of course this is just to avoid cluttering the screen, and is optional.)

*&& — Do the next command (copy)
if the previous command (findstr) succeeded.
(findstr succeeds if it finds a match; i.e., if the filename is in the list.)

*If you have any filenames with funny characters in them,
you may need to put the last %f into quotes ("%f")
and maybe change the findstr command.

*Before you run this command for real,
you might want to change copy to echo copy,
so you can do a dry run and see what the command will do.

*If you put the command into a batch file,
change all occurrences of % to %%.

*If you want to get a listing (log) of where the files were found, you can do

for /r folder %f in (*) do @findstr/i /x "%~nxf" filelist.txt > nul && (echo %f & copy %f secondfolder)

A: I think this:
for /R c:\source %f in (*) do copy "%f" x:\destination\

should do the job for you.


text:
Q: Django Channels Consumer won't execute method I'm trying to develop a chat application that saves messages in the database via a WebSocket with Django Channels.
settings.py:
ASGI_APPLICATION = "app.asgi.application"
CHANNEL_LAYERS = {
    'default': {
    'BACKEND': "channels.layers.InMemoryChannelLayer",
    },
}

asgi.py:
from api.routing import websocket_urlpatterns

application = ProtocolTypeRouter({
"http" : get_asgi_application(),
"websocket": JWTAuthMiddleware(
    URLRouter(
        websocket_urlpatterns
    )
  ),
})

routing.py:
websocket_urlpatterns = [
    path('ws/chat/<chat_uuid>/', consumers.ChatConsumer.as_asgi())
]

consumers.py
class ChatConsumer(AsyncJsonWebsocketConsumer):
    @database_sync_to_async
    def create_message(self, sender, message, chat):
        if sender:
            if content_validation(message):
                chat = Chat.objects.filter(uuid=chat)
                if chat.exists():
                    msg = Message.objects.create(sent_by=sender, content=message)
                    chat.first().messages.add(msg)

                    return msg

        return None

    @database_sync_to_async
    def check_security(self, user, uuid):
        # Chat has to exist and user has to be part of it
        chat = Chat.objects.filter(Q(Q(user1=user) | Q(user2=user)) & Q(uuid=uuid))
        if chat.exists():
            return True

        return False

    async def connect(self):
        self.chat_uuid = self.scope['url_route']['kwargs']['chat_uuid']
        self.room_group_name = 'chat_%s' % self.chat_uuid

        user = self.scope["user"]

        if user:
            check = await self.check_security(user, self.chat_uuid)
            if check == True:
                # Join room group
                await self.channel_layer.group_add(
                    self.room_group_name,
                    self.channel_name
                )

                await self.accept()

        await self.disconnect(401)

    async def disconnect(self, close_code):
        # Leave room group
        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name
        )

    # Receive message from WebSocket
    async def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']
        name = text_data_json['name']
        print(text_data_json)

        user = self.scope["user"]
        # Is this smart? User not receiving a message for whatever reason won't trigger the create event
        new_msg = await self.create_message(user, message, self.chat_uuid)

        if new_msg != None:
            # Send message to room group
            print("Receiving")
            await self.channel_layer.group_send(
                self.room_group_name,
                {
                    'type': 'chat_message',
                    'message': message,
                    'name': name
                }
            )
        else:
            await self.channel_layer.group_send(
                self.room_group_name,
                {
                    'type': 'content_guideline_violation',
                    'message': "",
                    'name': name
                }
            )

    # Receive message from room group
    async def chat_message(self, event):
        message = event['message']
        name = event['name']
        print(event)

        # Send message to WebSocket
        print("Sending")
        await self.send(text_data=json.dumps({
            'message': message,
            'name': name
        }))

I won't post the JWTAuthMiddleware for now since everything worked fine after first implementing it.
The problem is that even though connect and receive are being executed just fine, it just won't execute chat_message anymore for whatever reason.
My Postman requests are looking like the following:
ws://127.0.0.1:8000/ws/chat/<chat_uuid>/?Bearer=<jwt_token>

Postman is able to connect to the websocket and it sends messages as well as saves them in a database but it doesn't show these messages for the other user in the chat.


text:
Q: margin property in a div of another div html:
div id="wrapper">

 Title

This is dumy content.This is dumy content.This is dumy content.This is dumy content.This is dumy content.This is dumy content.This is dumy content.This is dumy content.This is dumy content.This is dumy content.This is dumy content.This is dumy content.This is dumy content.This is dumy content.This is dumy content.This is dumy content.

           </il>

css:
#wrapper
{
    width:850px;
    margin: 0 auto;
    background: #B3B3B3;

}
#itro
{
    width:550px;
    border: 6px solid #000;
    margin: 0 auto;
    position: relative;
    background:#E7E7E7;
    margin-top:70px;
}

I want to set margin on #itro  but when I see it in browser div id="wrapper"> is also set top margin:70px;  why?

A: css:
#wrapper{
    width:850px;
    margin: 0 auto;
    background: #B3B3B3;
    height:500px;
}
#itro
{
    width:550px;
    border: 6px solid #000;
    margin: 0 auto;
    position: relative;
    background:#E7E7E7;
    margin-top:70px;
    float: left;
}

html:

 Title

This is dumy content.This is dumy content.This is dumy content.This is dumy content.This is dumy content.This is dumy content.This is dumy content.This is dumy content.This is dumy content.This is dumy content.This is dumy content.This is dumy content.This is dumy content.This is dumy content.This is dumy content.This is dumy content.

some tags were with their typing wrong

A: Set your position on absolute for the wrapper and add a height. In my case I used auto but this could be any value.
see the fiddle here!


text:
Q: A zookeeper wants to give an animal 42 mg of vitamin A and 65 mg of vitamin D per day. He has two supplements: the first contains $10\%$ vitamin A and $25\%$ vitamin D; the second contains $20\%$ vitamin A and $25\%$ vitamin D. How much of each supplement should he give the animal each day?
Let $x$ = vitamin A
Let $y$ = vitamin B
I began with the equations
$$\begin{align*}0.1x + 0.25x &= 42 \\
0.2x + 0.25y &= 65 \end{align*}$$
I used row operations on a series of matrices to receive the solutions
$$\begin{align*}x &= 230 \\
y &= 190 \end{align*}$$
I just don't know how to phrase the conclusion.. do I say that the zookeeper needs $230$ mg of the first supplement and $190$ of the second supplement? From a biological perspective this seems too much but if I remember correctly excessive vitamins get washed out via urination. How would I properly phrase the conclusion?

A: Your system is wrong. Let $x$ denote the amount of the first supplement and $y$ the amount of the second supplement. Then the total amount of vitamin A is $0.1x + 0.2y$ and the total amount of vitman D is $0.25x + 0.25y$. This means your system of equations should be:
$$\begin{align*}0.1x + 0.2y &= 42 \\ 0.25x + 0.25y &= 65 \end{align*}$$
Now you need to solve this system correctly. The solution of this system is

 $x = 100$ and $y = 160$. These amounts will lead to the animal getting exactly $42$ mg of vitamin A and $65$ mg of vitamin D.


text:
Q: AFNetworking get JSON after 404 Bad Request still getting a JSON response I have a Django Rest Api with a iOS app and right now I'm testing AFNetworking to change the HTTP Request my app is doing but i came with this dilema that i dont know how to handle, first is that on REST Standards when i get an error i should return a 404_BAD_REQUEST as a status if either sends or something wrong happens and this is OK. The issue comes when AFNetworking sees this 404. I still want to see the JSON that it returns.
curl -X POST http://domain.com:8000/user-login/ -d "nick=superUser&pass_field=superPassword"

i get 202 Status HTTP:
{
 "nick": "eddwinpaz", "rate": 30, "name": "Eddwin Paz", "avatar": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-prn2/t1.0-1/p160x160/10270540_10154074250190063_1762683854515424400_n.jpg", "id": 9}eddwinpazs-MacBook-Pro:~ eddwinpaz$
}

When i get 404 BAD REQUEST i get:
{"message": "Invalid Username or Password"}

I want to grab that message json tag if i get a 404 Error
I've the following code. and put it on the message on the Alert
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

NSDictionary *parameters = @{@"nick": @"eddwinpaz",@"pass_field":@"eddwinpaz1"};

AFHTTPRequestOperation *operation = [manager POST:@"http://domain.com/user-login/"];
[operation addAcceptableStatusCodes:[NSIndexSet indexSetWithIndex:404]];

[manager POST:@"http://domain.com/user-login/" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         NSLog(@"JSON: %@", responseObject);

     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

         NSLog(@"Error: %@", error);

         UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Login Failed"
                                                         message:@"E-mail or password are wrong, Please Try Again"
                                                        delegate:nil
                                               cancelButtonTitle:@"OK"
                                               otherButtonTitles:nil];
         [alert show];
         [hud hide:YES];

     }];

A: Per default the error code 404 is handled as an error code. You could add it as one of the accepted error codes via
AFHTTPRequestOperation *operation = [manager POST:@"http://doma...
[operation addAcceptableStatusCodes:[NSIndexSet indexSetWithIndex:404]];

Then success: is called on an 404 response and you can handle it there.

A: The answer by @miho did not work for me. addAcceptableStatusCodes does not exist in AFNetworking 2.5.0 from what I can tell. I had to do the following.
NSMutableIndexSet *acceptedCodes = [[NSMutableIndexSet alloc]
    initWithIndexSet:operation.responseSerializer.acceptableStatusCodes];
[acceptedCodes addIndex:304];
operation.responseSerializer.acceptableStatusCodes = [acceptedCodes copy];


text:
Q: Confirm("Message") does not appear when putting in  The onclick='return confirm('Delete this comment?')' seems to be not working at all:
<?php
     if($sesType == 'Admin') {
        echo "Edit ";
        echo "Delete";
    } else if($_SESSION["username"] != NULL AND $_SESSION["username"] == $postname) {
        echo "Edit  ";
        echo "Delete";
    }
?>

But the confirmation box does not appear.

A: You're using single quotes inside of single quotes. Use double quotes to wrap your code instead:

Link

A: Just change this code, and it will work.
echo "Delete";

A: You have misused the single quote and double quotes. You have to put slash ()  on quotes to escape. The html should look like this:
 Link

Take note that single quote should be inserted inside the double quotes ""
from your code:
echo " Delete";

It should be:
 echo "Delete";


text:
Q: Suggestion with best customizable crawlers and scrapers I have a website which is pretty good but with very less information.
So i felt like adding informtion like news regarding particular sector(for eg politics, hollywood etc). I believe crawlers are best approach to do so? Is my understanding correct, please suggest if you feel any other way to get information without using crawlers from various sources.
Secondly I am doing research from last 2 days and I cannot find a particular source which is capable of doing so. Now I want crawlers to find information, normalize and store in mysql database. Sounds pretty simple ha. But It isnt for me.
As this is very resource and time consuming . what all things should i take into consideration before choosing a crawler. Also I wish to customize it so any tool which is open source and good to be customized will be great.
Any source giving information and research about factors need to take into consideration while creating crawlers or educating about crawlers will be great.
I prefer coding in java but i can code in any other language in case you feel that you have some language.
I hope i have given enough information. Please dont hesitate if you need any more information to give suggestion.

A: You can use httrack to copy a target website. There is one firefox plugin as well named spiderzilla. But, they will just save the pages.
If you want to parse the data in the pages, then you can use simple_html_dom and store the information in mySQL.

A: Try the GNU Wget tool. You can add a lot of intelligence to the way it crawls and creates data dumps of web pages. It is open-source and customisable as well, and very fast too.


text:
Q: C++ Casting between template invocations suppose X<T> is a template class taking a class as parameter and A and B are classes with B being derived from A without involvement of multiple or virtual inheritance (i.e. no pointer adjustments necessary when casting between A and B).
is it safe to perform a chainsaw reinterpret cast from X<A*> to X<B*> or vice versa? Of course, a X<A*> is no X<B*>, but shouldn't these classes always share the same behaviour? Because pointers are used, the memory layout should be equal. Thus, it might be okay to let methods of X<B*> operate on an instance which is actually an X<A*>.
Of course, this somehow ruins type safety as I could for example insert an element of A* into an X<B*>, but this is out of the scope of this question.

A: It's better to write something like this, if you REALLY need it.
X<A*> a(new B());
X<B*> b( dynamic_cast<B*> ( a.get_pointer() ) );
if(b.get_pointer() != NULL)
{
    ...
}

A: No you can't. If B is of a polymorphic class casting B* to A* might change the value of the pointer. Generally speaking using reinterpret_cast is never safe, and if still you need it, then you probably wrote something wrong (There are some cases, where you need to you it, but this isn't one of them).
And by the way, templates can be specialized on template parameters, so X and X might not even have the same internal structure.


text:
Q: Java Executor Service waiting for all tasks to complete I am using executor service to run my 10 tasks with 2 tasks at a time.
ExecutorService executor = Executors.newFixedThreadPool(2);
for (int i = 0; i < 10; i++) {
    String name = "NamePrinter " + i;
    Runnable runner = new TaskPrint(name, 1000);
    System.out.println("Adding: " + name + " / " + 1000);
    executor.execute(runner);
}

How can I wait for all tasks to complete

A: Use java 8 CompleteableFuture with join method to wait:
ExecutorService executor = Executors.newFixedThreadPool(2);
CompletableFuture[] futures = new CompletableFuture[10];
for (int i = 0; i < 10; i++) {
    String name = "NamePrinter " + i;
    Runnable runner = new TaskPrint(name, 1000);
    System.out.println("Adding: " + name + " / " + 1000);
    futures[i] =  CompletableFuture.runAsync(runner, executor);

}
CompletableFuture.allOf(futures).join(); // THis will wait until all future ready.

A: Assign your callables to futures and check that you can get results from each future.
        Future future = workerExecutor.submit(new Callable() {
            @Override
            public Object call() throws Exception {
                try {
                    System.out.println("MyItemTree.TimedRunnable");
                    ReturnInterface returnInterface = (ReturnInterface) commandInterface.call();
                    returnInterface.submitResult();
                } catch (Exception ex) {
                    ex.printStackTrace();
                    throw new RuntimeException(ex);
                }
                return null;
            }
        });

        try {
            Object get = future.get();
        } catch (InterruptedException | ExecutionException ex) {
            Throwable cause = ex.getCause();

            ex.printStackTrace();
            cause.printStackTrace();
            Throwable cause1 = cause.getCause();

            if (cause1 instanceof CommandInterfaceException) {
                System.out.println("[MyItemTree].scheduleTask Cause 1= COMMANDINTERFACE EXCEPTION");
                this.componentInterface.getAlertList().addAlert(((CommandInterfaceException) cause1).getResolverFormInterface());
            }
        }

    }


text:
Q: Set property on body using bean() I'm trying to set a property called "articleId" on the exchange's body and I thought the most explicit way to do this would be to use bean().  However, I can't get it to work.  When I have the following in my route:
.bean(body(Article.class), "setArticleId(${header.articleId})")

I get this error message:

Caused by: org.apache.camel.component.bean.MethodNotFoundException: Method with name: setArticleId(${header.articleId}) not found on bean: bodyAs[com.example.model.Article] of type: org.apache.camel.builder.ValueBuilder

My solution has been to use a processor() and a few lines of code in order to set the articleId property from the header value, but to me that seems like overkill.

A: I've been complaining on camel-users that there isn't a good way to do this. For now here is how I tackle it:
.setHeader("dummy").ognl("request.body.articleId = request.headers.articleId")

Which requires adding camel-ognl dependency.
UPDATE
Actually, there is also a language endpoint that can do this without the setHeader, but you have to say transform=false or else it replaces your body with the result:
.to("language:ognl:request.body.articleId = request.headers.articleId?transform=false") // remember ?transform=false

A: I think you need to spend some time to go through this page, if you don't know how to tell camel which method of the bean you want it invoke.
If you just want to set the exchange property, you can just use the DSL

setProperty("articleId", body());

to do this kind of work.


text:
Q: Xml Response in web api mvc Getting XML in Web API response in a single object having string format. but I got an issue in that XML while running in postman, it got values like
<?xml version=\"1.0\"?><?xml-stylesheet type=\"text/xsl\" href=\"cda.xsl\"?>\r\n<ClinicalDocument xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:sdtc=\"urn:hl7-org:sdtc\" moodCode=\"EVN\" xmlns=\"urn:hl7-org:v3\">\r\n  <realmCode code=\"US\" />\r\n  <typeId root=\"2.16.840.1.113883.1.3\" extension=\"POCD_HD000040\" />\r\n  <templateId root=\"2.16.840.1.113883.10.20.22.1.1\" extension=\"2015-08-01\" />\r\n  <templateId root=\"2.16.840.1.113883.10.20.22.1.2\" extension=\"2015-08-01\" />\r\n  <id root=\"2.16.840.1.113883.3.9999999989\" extension=\"EP_CCD_2017-November\" />\r\n  <code code=\"3

it should be like
<?xml version="1.0"?><?xml-stylesheet type="text/xsl" href="cda.xsl"?><ClinicalDocument xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:sdtc="urn:hl7-org:sdtc" moodCode="EVN" xmlns="urn:hl7-org:v3">  <realmCode code="US" />  <typeId root="2.16.840.1.113883.1.3" extension="POCD_HD000040" />  <templateId root="2.16.840.1.113883.10.20.22.1.1" extension="2015-08-01" />  <templateId root="2.16.840.1.113883.10.20.22.1.2" extension="2015-08-01" />  <id root="2.16.840.1.113883.3.9999999989" extension="EP_CCD_2017-November" />  <code code="3

A: Postman is escaping the characters
Postman escapes the " character by placing a \ before it.
This should not form a problem with parsing in ASP.Net Web Api.


text:
Q: Is there a way to modify list of items to be passed in writer? I have a reader which is reading data from a flat file.
I would like to modify this list of items(to see for duplicates) before they are passed to the writer.
I tried using ItemWriteListener but it does not return the list, the return type of beforeWrite() method is void.
The whole list is not available to me in reader or processor, so I cannot do any manipulation there.
So, how do I actually modify this list before writer is called?

A: you can use ItemWriteListener<Item> and save your items in a @Bean List<Items> like this:
@Component
public class `MyItemWriterListener implements ItemWriteListener<MyItem> {
@Autowired
final List<MyItems> listMyItems;
@Override
public void beforeWrite(List<MyItem> items) throws Exception {
    //what I want to do before my Writer method
    listMyItems.addAll(...)
}
...

and get your updated List of Items in the writer :
public class MyItemWriter implements ItemWriter<Item> {
    @Autowired
    final List<MyItems> listMyItems;
    void write(List<Item> items) {
        //save listMyItems
}
}

Or you can promote your data on a JobExecutionContext  like explainedhere


text:
Q: Ensure WPF Taskbar Window Preview is actualized How can I ensure that the hower preview of my WPF application (.net 4) is refreshed when the user places the mouse over the taskbar icon.
I have an app that visualizes some status values. If the app window is minimized and the user hovers over the taskbar button, the preview window that is shown shows the last view of the window at which the window was active. However I would like to have an actualized view.
Is there a possiblity to achieve that?

A: I believe you'd need to customize the preview, as described here (under the Customizing Preview section). Which leverages the Windows API Code Pack for Microsoft® .NET Framework.
An example can be found here, but looks like:
TabbedThumbnail preview = new TabbedThumbnail(parentForm.Handle, childForm.Handle);
TaskbarManager.Instance.TabbedThumbnail.AddThumbnailPreview(preview);
preview.TabbedThumbnailBitmapRequested += (o, e) =>
    {
        Bitmap bmp = new Bitmap(width, height);

        // draw custom bitmap...

        e.SetImage(bmp);
        e.Handled = true;
    };

Another example, can be found here which states:

The CustomWindowsManager class
  provides an abstraction of a
  customized window thumbnail preview
  and live preview (peek), including the
  facilities to receive a notification
  when a preview bitmap is requested by
  the Desktop Window Manager (DWM) and
  to automatically grab the preview
  bitmap of a window.

The download link for this code is here, which includes the CustomWindowsManager class. This appears to provide the live preview.

A: You probably can't. Windows 7 pipes the graphics of an open window to the live preview from the Taskbar. It can't know what the window now looks like while it is minimized because it isn't being drawn at all.
I guess it's not impossible to do custom thumbnails. Aside from CodeNaked's answer, I also found this article, which even includes multiple thumbnails from the same app.


text:
Q: MSI X58 Pro-E Mainboard wont Post anymore I used my MSI X58 Pro-E Mainboard Intel LGA 1366 for about three weeks with a Xeon X5690. Yesterday I got an i7-920 CPU and wanted to test out if it is working anymore. It doesn't want to boot, so I put my Xeon X5690 back in. But then it wasn't posting anymore. I get three Beeps every time I use my 8 Gb Crucial DDR3L 1600 Ram in the Blue Slots. The Fans work. And it is trying to boot and boot. Three Beeps mean Bad Memory, but I was using this memory for Weeks. I tried another Stick with 4 Gb 1600mh, but the same problem. If I put it in the Black slots, it won't beep, but the light goes out after a second and won't post. It's just Rebooting endless with the Fans running but no light
I don't know what to to more. The System was running great and Stable for Weeks. I tried all this out:
I cleared the CMOS
I Checked the CPU Pins
I removed the BIOS Battery over night
I tried using a Xeon W3680, I7-920 and X5690
I tried another Power Supply
Tried other Ram Slots
Also other Ram (4GB Kingston)
Can it be the CPU Clock changer at the bottom of the Mainboard? Default is on off off but i don't know anymore what it had when i used the first time.


text:
Q: .htaccess rewrite multiple urls in the same folder I want to rewrite some URLs but because I'm kind of a .htaccess fresher, I have no idea how to make it myself.
So far I have: example.com/page/AAA0001/?id=78324#78324 now the page is loading from AAA0001/index.php, I need what ever folder name ex: AAA0001 or AAA0002 index.php should serve from example.com/page/index.php, but the above URL should not change (eg. example.com/page/AAA0001/?id=78324#78324)
How can I do this using .htaccess?

A:
now the page is loading from AAA0001/index.php

So AAA0001 is a physical "directory" on the filesystem, not simply a (virtual) URL-path segment. (But then why does /page/AAA0001/index.php exist to begin with?)
The DirectoryIndex directive (part of mod_dir) determines what file Apache tries to serve when requesting a directory.
Currently, this is probably set to something like DirectoryIndex index.php (a relative URL-path), so this tries to serve index.php from whatever directory is requested.
However, you can set this to a root-relative URL-path so it will always serve a specific file when a directory is requested. For example:
DirectoryIndex /page/index.php

Now, when you request a URL like example.com/page/AAA0001/?id=78324#78324 (where /page/AAA0001 is a physical directory) it will serve /page/index.php instead of /page/AAA0001/index.php.
You can also set both, so that it will serve index.php in the requested directory if it exists, otherwise fallback to /page/index.php:
DirectoryIndex index.php /page/index.php

Reference:

*

*https://httpd.apache.org/docs/2.4/mod/mod_dir.html#directoryindex

On the other hand, if this should only apply to requests of the form /page/ABC01234/ (where the directory consists of 3 uppercase letters followed by 4 digits - as per your examples) then you can combine the DirectoryIndex directive with an <If> expression. For example:
<If "%{REQUEST_URI} =~ m#^/page/[A-Z]{3}\d{4}/#">
    DirectoryIndex /page/index.php
</If>

Alternatively, use mod_rewrite instead:
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^page/[A-Z]{3}\d{4}/ page/index.php [L]

The preceding condition (RewriteCond directive) is perhaps unnecessary, but this ensures that only requests for physical directories are rewritten to /page/index.php and not /page/ZZZ9999/ that may not exist. This mimics the behaviour of DirectoryIndex as mentioned above.


text:
Q: When I remote R&S network analyzer,I can't store a file by 'Print to file'? I try store the analyzer's diagram to specified path us follow python code,but failed,who can tell me why?
inst = res.open_resource('TCPIP::10.3.19.100::inst0')
print(inst.query('*IDN?'))
inst.write("HCOPy:DEVice:LANGuage BMP")
inst.write("MMEMory:NAME 'C:\25.bmp'")
inst.write("HCOP:MIT:LOGO ON; TIME ON")
inst.write("HCOP:MPAG:WIND ALL")
inst.write("HCOP:DEST'MMEM'; :HCOP")```


text:
Q: How to extend JQuery UI plugin The existing dialog plugin doesn't have an option to close dialog on clicking modal overlay, how to add an option to provide the functionality?

A: (function($){
   var _init = $.ui.dialog.prototype._init;
   $.ui.dialog.prototype._init = function(){
        var self = this;
        _init.apply(this,arguments);
        $('.ui-widget-overlay').live('click', function(){
            if (self.options['overlay_close']){
                self.destroy();
            }
        });
    }
})($);

A: It would be even better if the self-provided answer worked.
I get no response when clicking outside the dialog. Here is my jsFiddle for testing.
Maybe I am doing something wrong, but it doesn't seem to do its desired function.
@JamesLin provided the key insight. I needed to add the new option in my initialization:
$("#myDialog").dialog({
    overlay_close:true,
    modal: true
});

The jsFiddle is also updated.


text:
Q: Finding records having at least one upper-case character in mysql database I'm trying to find in the database all records having records with Email field having at least one uppercase character.
Select * from `Profile` where Email REGEXP '[a-z0-9]*[A-Z]+[a-z0-9]*'

it's not even working when I want to ask for the first uppercase character only
Select * from `Profile` where Email REGEXP '^[A-Z].*' limit 10

In both cases I'm getting all records.


text:
Q: How to mock a spring bean? I'm trying to mock an class that uses JAXRS and this class are a spring component.
@Component
public class PostmanClient {

  private WebTarget target;

  public PostmanClient() {
    Client client = ClientBuilder.newClient();
    target = client.target(...);
  }

  public String send(String xml) {
    Builder requestBuilder = target.request(MediaType.APPLICATION_XML_TYPE);
    Response response = requestBuilder.post(Entity.entity(xml, MediaType.APPLICATION_XML_TYPE));
    return response.readEntity(String.class);
  }
}

This is my test method:
@Test
public void processPendingRegistersWithAutomaticSyncJob() throws Exception {
  PostmanClient postmanClient = mock(PostmanClient.class);
  String response = "OK";
  whenNew(PostmanClient.class).withNoArguments().thenReturn(postmanClient);
  when(postmanClient.send("blablabla")).thenReturn(response);

  loadApplicationContext(); // applicationContext = new ClassPathXmlApplicationContext("/test-context.xml");
}

When i debug the postmanClient instance, its a instance created by Spring and not a mock.
How can i avoid this behavior and get a mock instance ?

A: If you are using PowerMock with Spring, you should consider following tips:
1. Use @RunWith(SpringJunit4Runner.class)
2. Use @ContextConfiguration("/test-context.xml") // load spring context before test
3. Use @PrepareForTest(....class) // to mock static method
4. Use PowerMockRule
5. The simplest way to mock a spring bean is to use springockito
Back To You Question:
If I don't understand you wrong, you have PostmanClient defined in spring context, which means, you only need use springockito to achieve your goal, just follow the tutorial on springockito page.

A: You can use BDD framework Spock to write UT for your Spring Framework. With Spock Spring extension (Maven: groupId:org.spockframework, artifactId:spock-spring), you can load Spring context in your unit test.
@WebAppConfiguration
@ContextConfiguration(classes = Application.class)
class MyServiceSpec extends Specification {
    @Autowired
    UserRepository userRepository
}

If you have some beans you want to mock them instead of loading from Spring context, you can add following annotation on the bean you want to mock.
@ReplaceWithMock

This article has the detailed intro about how to write UT for your Spring app with Spock.

A: Im not sure what is wrong with your implementation. Maybe PostmanClient should be an interface instead of class?
However I've implemented a similar unit test in my practice/test project. Maybe it will help:
https://github.com/oipat/poht/blob/683b401145d4a4c2bace49f356a5aa401fe81eb1/backend/src/test/java/org/tapiok/blogi/service/impl/PostServiceImplTest.java

A: Register your mock with Spring-ReInject before the application context starts in your test's constructor. The original bean will be replaced with a mock, and the mock will be used by Spring everywhere, including injected fields. The original bean will be never created.

A: There is an option to fake Spring bean with just plain Spring features. You need to use @Primary, @Profile and @ActiveProfiles annotations for it.
I wrote a blog post on the topic.

A: I've created the example to answer another question, but also cover your case. Simple replace MockitoJUnitRunner via SpringJUnit4ClassRunner.
In nutshell, I create Java Spring Configuration which includes only classes which should be tested/mocked and returns mocked object instead really object, and then give Spring does it work. Very simple and flexible solution.
It also works fine with MvcMock

A: As of Spring Boot 1.4.x you can use new annotation called @MockBean.


text:
Q: Mongodb query performance extremly bad with $or I use MongoDB 3.2.13 and I have a collection C with about 500K documents. The documents contain a String field A which can only a handful of different values. If I query the collection for specific values like
db.getCollection('C').count({'A':{'$eq': 'valueA'}})
db.getCollection('C').count({'A':{'$eq': 'valueB'}})

I get results in under 1 second.
If i do a combined search using $or
 db.getCollection('C').count({'$or':
       [
       {'A':{'$eq': 'valueA'}},
        {'A':{'$eq': 'valueB'}}
       ]
 })

the query runs about 165 seconds.
I have an index an A. I can't explain why the $or query is so much slower? This is just a simple example that could be solved by just adding the results of the first two queries but we have other queries that can not easily be split up.
Can anyone explain what is wrong the $or query? Or give me a hint how to speed it up?
db.getCollection('C').find(query).explain() gives:
 {
     "queryPlanner" : {
         "plannerVersion" : 1,
         "namespace" : "db.C",
         "indexFilterSet" : false,
         "parsedQuery" : {
             "$or" : [
                 {
                     "A" : {
                         "$eq" : "valueA"
                     }
                 },
                 {
                     "A" : {
                         "$eq" : "valueB"
                     }
                 }
             ]
         },
         "winningPlan" : {
             "stage" : "SUBPLAN",
             "inputStage" : {
                 "stage" : "FETCH",
                 "inputStage" : {
                     "stage" : "IXSCAN",
                     "keyPattern" : {
                         "A" : 1
                     },
                     "indexName" : "A",
                     "isMultiKey" : false,
                     "isUnique" : false,
                     "isSparse" : true,
                     "isPartial" : false,
                     "indexVersion" : 1,
                     "direction" : "forward",
                     "indexBounds" : {
                         "A" : [
                             "[\"valueA\", \"valueA\"]",
                             "[\"valueB\", \"valueB\"]"
                         ]
                     }
                 }
             }
         },
         "rejectedPlans" : []
     },
     "executionStats" : {
         "executionSuccess" : true,
         "nReturned" : 2513596,
         "executionTimeMillis" : 133764,
         "totalKeysExamined" : 2513597,
         "totalDocsExamined" : 2513596,
         "executionStages" : {
             "stage" : "SUBPLAN",
             "nReturned" : 2513596,
             "executionTimeMillisEstimate" : 131660,
             "works" : 2513597,
             "advanced" : 2513596,
             "needTime" : 0,
             "needYield" : 0,
             "saveState" : 20912,
             "restoreState" : 20912,
             "isEOF" : 1,
             "invalidates" : 0,
             "inputStage" : {
                 "stage" : "FETCH",
                 "nReturned" : 2513596,
                 "executionTimeMillisEstimate" : 131490,
                 "works" : 2513597,
                 "advanced" : 2513596,
                 "needTime" : 0,
                 "needYield" : 0,
                 "saveState" : 20912,
                 "restoreState" : 20912,
                 "isEOF" : 1,
                 "invalidates" : 0,
                 "docsExamined" : 2513596,
                 "alreadyHasObj" : 0,
                 "inputStage" : {
                     "stage" : "IXSCAN",
                     "nReturned" : 2513596,
                     "executionTimeMillisEstimate" : 4420,
                     "works" : 2513597,
                     "advanced" : 2513596,
                     "needTime" : 0,
                     "needYield" : 0,
                     "saveState" : 20912,
                     "restoreState" : 20912,
                     "isEOF" : 1,
                     "invalidates" : 0,
                     "keyPattern" : {
                         "A" : 1
                     },
                     "indexName" : "A_1",
                     "isMultiKey" : false,
                     "isUnique" : false,
                     "isSparse" : true,
                     "isPartial" : false,
                     "indexVersion" : 1,
                     "direction" : "forward",
                     "indexBounds" : {
                         "A" : [
                             "[\"valueA\", \"valueA\"]",
                             "[\"valueB\", \"valueB\"]"
                         ]
                     },
                     "keysExamined" : 2513597,
                     "dupsTested" : 0,
                     "dupsDropped" : 0,
                     "seenInvalidated" : 0
                 }
             }
         },
         "allPlansExecution" : []
     },
     "serverInfo" : {
         "host" : "xxxx",
         "port" : 27017,
         "version" : "3.2.13",
         "gitVersion" : "23899209cad60aaafe114f6aea6cb83025ff51bc"
     },
     "ok" : 1.0
 }

A: Use $in instead of $or (Mongo $or vs $in docs):
db.getCollection('C').count({'A':{'$in': ['valueA', 'valueB']}})

UPDATE
Or try with a find(..).count() like this:
db.getCollection('C').find({'A':{'$in': ['valueA', 'valueB']}}).count()

A: After searching and searching i found the reason. One of the values i was search for had null values. Null is not covered by the index so every document was read from disk to check if is ha null or not.
It's also mentioned in the Mongo University Workshops. I can strongly recommend taking the classes. They helped me a lot!


text:
Q: Projeto WebAPI - .NET Estou desenvolvendo uma aplicação Asp.Net WebApi (primeira aplicação REST).
Até o momento esta tudo ok, mesmo por que estou na fase de testes utilizando o PostMan. Acredito que devo finalizar esta primeira etapa dentro de duas semanas.
O projeto possui as camadas de Serviço, Domínio, Infra, WebApi, Validações e Injeção de Dependência, todas separadas por projetos dentro da mesma solução.
O próximo passo será desenvolver a "Camada" que servirá como View aos usuários.
Deverei utilizar AngularJs2.
Agora vem a minha duvida.
Para esta camada devo criar um novo projeto? se sim, qual tipo sendo que as Views são paginas HTML?
Todo o projeto será hospedado no mesmo servidor. Espero ter sido claro com a minha duvida :)
Flávio Oliveira

A:
Para esta camada devo criar um novo projeto?

Não necessariamente. Por exemplo, em um projeto similar eu tenho uma estrutura onde armazeno minhas classes ORM em um folder chamado model, meus endpoints API em controllers e o conteúdo Angular em frontend:

A decisão de se criar um projeto à parte pode ser simplesmente de natureza organizacional.


text:
Q: Reverse engineered project to graphical UML diagram I've started to work on a quite big C++ project. I've used BOUML to import the code base with the intention to create a visual UML diagram.
Now I've reversed the project and I see the classes, namespaces, methods and such in the project browser but I can't figure out how to create a graphical UMl from it, may anyone here help me?
Manually draggign the elements from the browser into the main area doesn't seem to be allowed as the cursor gets a forbidden icon and dropping the elments doesn't do anything then... how do I even create the UML myself?

A: muszeo2 is right, the reverse create the packages / views / artifacts and classes and their members, after you have to create the diagrams by yourself. Sorry but BoUML is not extra lucid and it cannot by itself create the right diagrams of the right kind containing the right elements with the right drawing options ;-) So create your diagrams and drag&drop the elements you want to show etc, they are several features helping you to make diagrams with elements already created or not.

A: I also made some video tutorials available on https://www.bouml.fr/documentation.html, I encourage you to look at them, starting by starting.wmv then cpp_example.wmv for instance, but you can also look at the others because the rules are quite identicals. These video tutorials are old and many features was added since I made them, but this is a good start.
You cannot drag&drop from browser to no where (I mean not into an opened diagram) nor when the element cannot be added in a diagram


text:
Q: Smallest positive number that is evenly divisible by all of the numbers from 1 to 20? What is wrong with my code? When i run the program nothing is printed. I want to print the smallest number that is evenly divisible by all of the numbers from 1 to 20.
found = False
i = 20
while found==False:
    c = 0    # c checks if the number is the one im looking for
    for x in range(1,21):
        if i%x==0:
            c = c + 1
    if c==20: # if c = 20 then its the number im looking for
        print i
        found = True
    i = i + 1

A: Brute force:
from itertools import count
for i in count(20):
    if all(map(lambda x: i % x == 0, range(1, 21))):
        print i
        break

Non-brute-force:
from itertools import count, takewhile

def primes(n):
    "Generate prime numbers up to n"
    seen = list()
    for i in xrange(2, n + 1):
        if all(map(lambda prime: i % prime, seen)):
            seen.append(i)
            yield i

def smallest(n):
    result = 1
    for prime in primes(n):
        bprime = max(takewhile(lambda x:x<=n, (prime ** c for c in count(1))))
        # we could just take last instead of max()
        result *= bprime
    return result

print smallest(20)

A: Brute forcing this is WAY too slow. You need to find out what the prime factors of each number below 20 are, and then construct the smallest number that includes the same, and it will be the answer.
from collections import Counter

primes_below_20 = [2, 3, 5, 7, 11, 13, 17, 19]

def prime_factors(n):
    # Assume n <= 20
    if n == 1:
        return []
    for prime in primes_below_20:
        if n % prime == 0:
            return [prime] + prime_factors(n / prime)

 primes_needed = Counter()

 for n in range(2, 21):
     primes = Counter(prime_factors(n))
     primes_needed = primes_needed | primes  # | gives the max of existing values

 total = 1
 for prime, amount in primes_needed.items():
     total *= prime ** amount

 print total

A: def is_divisible(n):
    for divisor in range(2, 21):
         if n % divisor != 0:
              return False
         return True

number = 1
while not is_divisible(number):
     number+=1
print(number)

However, you don't have to check all numbers 1..20. If a number is divisible by 20, it is divisible by 2, 5, 10. Extending this, it would be sufficient to check only divisors from 11..20. Another simple thing would be to increase the candidate solutions by 20 (number += 20) instead of 1, since any other number would not be divisible by 20.
however, you are essentially looking for the least common multiple of the numbers from 1 to 20, and this can be done using prime factorization: You write each number in [1, 20] as multiple of primes, you take the largest exponential for each prime and then you multiply the results (try it manually to understand it). In this way, the number you are looking for is 2^4 *3^2 * 5 * 7 * 11 * 13 * 17 * 19

A: My take (though I love @ondra solution for its elegancy):
from collections import Counter, defaultdict

def primes(n):
    return list(x for x in range(1,n+1)
        if all(x%y for y in range(2,x)))

primes_20 = primes(20)

def prime_factors(n):
    if n <= 0 or n < 20:
        raise ValueError
    factors = []
    while n > 1:
        for x in primes_20[1:]:
            if not n % x:
                n = n / x
                factors.append(x)
                break
    return factors

max_count = defaultdict(int)

for i in range(2,21):
    factors = prime_factors(i)
    counts = Counter(factors)
    for factor in counts:
        max_count[factor] = max(max_count[factor], counts[factor])

total = 1
for factor, count in max_count.items():
    total *= factor**count

assert any(total%x for x in range(2)) == False
print total

A: Another clean and quick thing in Ruby
def compute_lowest_dividing_number number
  for i in 2..(number/2)
    return i if number%i == 0
  end
  number
end

lcm = 1
n = 20
for i in 1..n
  # look ahead appraoch
  next_number = [i+1, n].min
  lcm *= compute_lowest_dividing_number(next_number) if lcm % next_number != 0
end
puts lcm

A: I tried this method and it was more easier to understand
i=1
while True:
    if i%11==0 and i%12==0 and i%13==0 and i%14==0 and i%15==0 and i%16==0 and i%17==0 and i%18==0 and i%19==0 and i%20==0:
        break
    else:
        i+=1
print(i)

But this can be done in milliseconds by finding the prime factors from 11 to 20 and multiplying them.

A: So it is Euler's problem #5.
I've got that one:
#making loop for range of numbers
def rangeCount(number):
    lst = [] #using lists to see divisions
    for x in range(1, 21):
        svalue = number % x
        if svalue == 0:
            lst.append(x)
    else:
        break #Need to break to minimize computation.
return lst

number = 2520 #is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. Minimazing compute
lstpst = [] #list pasted/returned from function
while len(lstpst) < 20:
    lstpst = rangeCount(number)
    print(f"With {number} we get {lstpst}")
    number += 2 #even number must be the answer to the problem. Minimazing compute.

And it is my first post/comment on StackOverflow.

A: if you think carefully the answer is LCM of the numbers from 1 to n.
here is the code in C++.
#include <bits/stdc++.h>
#define IOS                         \
  ios_base::sync_with_stdio(false); \
  cin.tie(NULL);

#define ll long long int

using namespace std;

ll lcm(int n) {
  ll ans = 1;
  for (ll i = 1; i <= n; i++)
    ans = (ans * i) / (__gcd(ans, i));
  return ans;
}

int main() {
  int i;
  cin >> i;

  cout << lcm(i);

  return 0;
}

A: Simplest Solution using Python:
num = 21

while True:
    div = 2

    while num%div == 0 and div!=21:
        div+=1

    if div == 21:
        print(num)
        break

    num+=1


text:
Q: AngularJS can't find my controller I know this is a common problem but I haven't been able to find a solution by reading through previously asked questions.
I'm actually getting two errors but the first one is about angular not being able to find my controller.
http://errors.angularjs.org/1.4.2/$injector/nomod?p0=myApp.controllers
My directory structure looks like the following:
.
└── static
    ├── index.html
    ├── js
    │   ├── app.js
    │   └── controllers.js
    ├── lib
    │   └── angular-ui-router.min.js
    └── partials
        ├── view1.html
        └── view2.html

My index file looks like the following:
<html ng-app="myApp">
    <head>
        <meta charset="UTF-8">
        <title>Hello AngularJS</title>
    </head>
    <body>
        <div ui-view></div>
        <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.2/angular.min.js"></script>
        <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.2/angular-route.min.js"></script>
        <script type="text/javascript" src="lib/angular-ui-router.min.js"></script>
        <script type="text/javascript" src="js/controllers.js"></script>
        <script type="text/javascript" src="js/app.js"></script>
    </body>
</html>

My app.js file looks like the following:
(function(angular) {

    var app = angular.module('myApp', ['ui.router', 'myApp.controllers']);

    app.config(function($stateProvider) {
        $stateProvider.state('view1', {
            url: '/view1',
            templateUrl: 'partials/view1.html',
            controller: 'View1Controller'
        }).state('view2', {
            url: '/view2',
            templateUrl: 'partials/view2.html',
            controller: 'View2Controller'
        });
    }).run(function($state) {
        $state.go('view2');
    });

})(angular);

My controller.js file looks like the following:
(function(angular) {
    var app = angular.module('myApp.controllers');

    app.controller('View1Controller', function($scope) {
        $scope.data = 'my view 1';
    });

    app.controller('View2Controller', function($scope) {
        $scope.data = 'my view 2';
    });

})(angular);

Also a second error which might be related.
As stated above angular is unable to find my controller. Does anyone have a clue about what I'm doing wrong? Please let me know if I need to paste more code.
I've shared the code on github in case someone finds it easier to deal with.
https://github.com/tonsV2/angular-ui.route/tree/master/src/main/resources/static

A: In angular angular.module() is a setter and a getter. According to the angular.module docs (via @DanAtkinson's comment):

Passing one argument retrieves an existing angular.Module, whereas
  passing more than one argument creates a new angular.Module.

Getter
var app = angular.module('myApp.controllers'); uses module as a getter.
It fails because the module myApp.controllers haven't been created yet.
Setter
To use it as a setter change it to
var app = angular.module('myApp.controllers', []); // note the []


text:
Q: Create thumbnail for pdf file using php I have been working to create thumbnail for pdf file. I have used below link for installation and configuration of ImageMagick
installation and configuration of ImageMagick and code I have used below code to for conversion of pdf file to thumbnail
<?php
 exec("C:/ImageMagick-6.8.0-Q16/convert.exe a.pdf -resize 546x274^ -quality 80 temp.jpg 2>&1", $array);

?>

It is not converting but it is converting images. The code is
<?php
 exec("C:/ImageMagick-6.8.0-Q16/convert.exe a.jpg -resize 546x274^ -quality 80 temp.jpg 2>&1", $array);
?>

Can any one please help me to create thumbnail for pdf file .Thanks in advance.

A: I use the built in PHP calls on my own server. This works for me.
 if(!file_exists(THUMBS_DIR . $name . "." . $out_format))
    {
        $im = new imagick();
        $im->setResolution(300,300);
        $im->readImage(ABS_PATH . $path);
        //$im->setImageColorspace(255);
        //$im->adaptiveSharpenImage(2,1);
        //$im->setCompression(Imagick::COMPRESSION_JPEG);
        $im->setCompressionQuality(100);
        $im->resizeImage(700,1000,Imagick::FILTER_LANCZOS,1, TRUE);
        $im->setImageFormat($out_format);
        $im->writeImage(THUMBS_DIR . $name . "." . $out_format);
        $im->clear();
        $im->destroy();
    }

A: A free direct download PDF test file with detailed instructions to solve a "PDF Thumbnail Generation Problem" in TYPO3 CMS is available at Smargasy, Inc. "http://www.smargasy.com/fileadmin/media_data/community/Smargasy_PDF-Thumbnail-Compatibility-Test-File.pdf". The test file helps isolate the problem on systems that use ImageMagick and GhostScript as the image processing and conversion program in a shared hosting environment.
This should also help with your problem since the solution is both the Example PHP scripts and using the example standards compliant PDF file for testing.
Best Regards,
Michael Brice


text:
Q: extract cab file and execute the exe file(inside the cab file) automatically I have a cab file(w/ an executable file inside) embedded on my webpage. When the user access the page the cab file will be automatically extracted and the executable file inside should be executed as well. Is this possible? My hunch is that this will be configured in my inf file but I don't know how. I would appreciate your help in this.

A: You need to use the hook&run values, like in this sample

[version]
signature="$CHICAGO$"
AdvancedINF=2.0

[Add.Code]
time.ocx=time.ocx
msvcrt.dll=msvcrt.dll
mfc42.dll=mfc42.dll
olepro32.dll=olepro32.dll

[time.ocx]
file-win32-x86=thiscab
clsid={DCF0768D-BA7A-101A-B57A-0000C0C3ED5F}
FileVersion=1,0,0,0
RegisterServer=yes

[msvcrt.dll]
FileVersion=4,20,0,6164
hook=mfc42installer

[mfc42.dll]
FileVersion=4,2,0,6256
hook=mfc42installer

[olepro32.dll]
FileVersion=4,2,0,6068
hook=mfc42installer

[mfc42installer]
file-win32-x86=http://activex.microsoft.com/controls/vc/mfc42.cab
run=%EXTRACT_DIR%\mfc42.exe


text:
Q: UICollectionView.reloadData or UICollectionView.deleteItemsAtIndexPaths makes cell hidden but still clickable I got a UICollectionView with several cells in it.
I deleted the first cell by clicking a button on it, it works good no matter I choose [UICollectionView reloadData] or [UICollectionView deleteItemsAtIndexPaths:].
Now the following cells will move forward, so the first cell now would be the second one before the deletion, easy to understand, right?
Now comes the weird part:

*

*I click on the first cell's delete button, it shows:
 <MyCell: 0x7fc5de566590; baseClass = UICollectionViewCell; frame = (220 20; 80 104); alpha = 0; hidden = YES; layer = <CALayer: 0x7fc5de566740>>

*I print the visible cells:
< __NSArrayM 0x7fc5de655830>(
< MyCell: 0x7fc5de55c060; baseClass = UICollectionViewCell; frame = (20 134; 80 104); layer = < CALayer: 0x7fc5de55c210>>,
< MyCell: 0x7fc5de635290; baseClass = UICollectionViewCell; frame = (120 134; 80 104); layer = < CALayer: 0x7fc5de635440>>
)

see? the cell I clicked on is actually that one been deleted, unless it's NOT! it has a flag hidden = YES, and it has a frame and superview also(yes the superview is the collection view).
Now that brings me problem because I meant to delete this guy MyCell: 0x7fc5de55c060.
So any clue on this? Thank you!

A: Problem solved.
It's because I override hittest in MyCell.
I didn't expect that deleted cells would still be subview of the collection view.


text:
Q: How to align side by side 2 differents component in angular with Flexbox How can I align 2 different Component side by side using flexbox ?
I have my 1st component "nav-menu" and the 2nd "homepage" I would like it to be side by side.
homepage.component.html
    <app-nav-menu></app-nav-menu>

I gave a width to my container
homepage.component.css
.container {
    display: flex;
    width: 50%;
}

div.container>div {
    flex-grow: 1;
}

img {
    width: 20%;
    height: auto;
}

nav-menu.component.html

Furniture

Home

Shop

Product

Cart

I gave a width to my nav
nav-menu.component.css
    * {
    box-sizing: border-box;
}

h1 {
    display: flex;
    justify-content: space-between;
    margin-left: 30px;
    margin-bottom: 100px;
}

nav {
    width: 40%;
}

.nav ul {
    margin: 0px;
    padding: 0px;
    background: white;
    list-style: none;
}

.nav a {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    padding: 0.5em;
    text-decoration: none;
    color: black;
    font-size: 2em;
    width: 10px;
}

.nav a:hover {
    color: #FFA500;
    transition: 0.1s;
}

whats the next step ?
thanks.

A: you have to wrap your both components in a flex

  <app-component-1></app-component-1>
  <app-component-2></app-component-2>


text:
Q: Einstein Recipe column value transformation formula (First letter to uppercase and rest should be lower case in a shipping city name) I am using the following formula :
UPPER(LEFT("Account.ShippingCity", 1)) &
LOWER(RIGHT("Account.ShippingCity", LEN("Account.ShippingCity") - 1))

to transform the values of one of the recipe columns (Shipping_city) with the first letter to uppercase and the rest should be lowercase, I am facing the error :
Something's wrong with the function at line 1, column 11. A parameter is missing, or it uses a field name that's also a function name.
I guess Left right functions are not valid in recipe formulas, any other suggestion than the creation of a separate formula field on that object? Thanks in advance!


text:
Q: Game code error line skipping - Python I have this code for a number guessing game and i was playing it when I noticed a problem.
# Guessing the number
print("I'm thinking of a number between 1 and 20. Can you guess my number?")

r = str(input('{} please enter a integer between 1 and 10: '.format(name)))

r = str(input('{} please enter a integer between 1 and 10: '.format(name2)))

print (name, ' you chose ', r)
print (name2, ' you chose ', p)
r1 = random.randrange(10)

Printing who won
if r == p:
    print('Plz choose different numbers from each other')
if r == r1:
    print('Computer chose', r1,',',name,' Wins!')
if p == r1:
    print('Computer chose', r1,',',name2,' Wins!')
elif (r > 'r1' and p < 'r1'):
    print('Computer chose', r1, ' both of you lose')
elif (r < 'r1' and p < 'r1'):
    print('Computer chose', r1, ' both of you lose')
elif (r > 'r1' and p > 'r1'):
    print('Computer chose', r1, ' both of you lose')
elif (r < 'r1' and p > 'r1'):
    print('Computer chose', r1, ' both of you lose')

When the computer read this part of the code
if r == p:
    print('Plz choose different numbers from each other')
if r == r1:
    print('Computer chose', r1,',',name,' Wins!')
if p == r1:
    print('Computer chose', r1,',',name2,' Wins!')
elif (r > 'r1' and p < 'r1'):
    print('Computer chose', r1, ' both of you lose')
elif (r < 'r1' and p < 'r1'):
    print('Computer chose', r1, ' both of you lose')
elif (r > 'r1' and p > 'r1'):
    print('Computer chose', r1, ' both of you lose')
elif (r < 'r1' and p > 'r1'):
    print('Computer chose', r1, ' both of you lose')

It skipped the first parts and keep saying that both players lost. Why is this happening and how can I fix it?

A: I think the problem is here:
r = str(input('{} please enter a integer between 1 and 10: '.format(name)))

r = str(input('{} please enter a integer between 1 and 10: '.format(name2)))

Don't you mean to assign to p the second time through? p = str(...
Also, these lines don't make much sense:
elif (r > 'r1' and p < 'r1'):
    print('Computer chose', r1, ' both of you loose')
elif (r < 'r1' and p < 'r1'):
    print('Computer chose', r1, ' both of you loose')
elif (r > 'r1' and p > 'r1'):
    print('Computer chose', r1, ' both of you loose')
elif (r < 'r1' and p > 'r1'):
    print('Computer chose', r1, ' both of you loose')

You're comparing r and p to the string 'r1'. You probably mean to be comparing to r1 itself, but even then the logic is really strange. I think you just want if r != r1 and p != r1, but the below is much simpler:
if r == p:
    print('Plz choose different numbers from each other')
elif r == r1:
    print('Computer chose', r1,',',name,' Wins!')
elif p == r1:
    print('Computer chose', r1,',',name2,' Wins!')
else:
    print('Computer chose', r1, ' both of you loose')

(Note, though, that the word is spelled "lose.")
UPDATE
You probably want integers:
r = int(input('{} please enter a integer between 1 and 10: '.format(name)))

r = int(input('{} please enter a integer between 1 and 10: '.format(name2)))


text:
Q: Is this a bug with cout and getline in g++ 4.7.2? 2012/11/13 Update:
I found my question had already been asked.
Here is a good solution for handling different line ending text files:
Getting std :: ifstream to handle LF, CR, and CRLF?
Is it possible to contribute to libstdc++? How?

2012/11/11
I found there's something wrong with cout.
If there are two strings returned from getline(),
the second string will overwrite the first one in the output.
This is sample code:
#include<iostream>
#include<fstream>
using namespace std;

int main()
{
    //normal code
    cout << "Normal result:" << endl;
    string str1 = "hello";
    cout << str1;
    str1 = "123";
    cout << str1;

    cout << endl;

    //broken code
    cout << "Bug?" << endl;
    ifstream fin;
    fin.open("test.dat");

    string str;

    getline(fin, str);
    cout << str;

    getline(fin, str);
    cout << str;

    fin.close();
    return 0;
}

And here is the input file (test.dat):
hello
123

The output will be:
Normal result:
hello123
Bug?
123lo

I'm using ubuntu 12.10 64-bit,
and the version of compiler is
g++ (Ubuntu/Linaro 4.7.2-2ubuntu1) 4.7.2.
Any advice?
Is there anyone tell me where to file a bug?

A: More likely than a bug in libstdc++ (which can occur, as well as in gcc, but are rather rare these days), there is incorrect line termination in your input file - likely it is using the DOS/Windows CR+LF line endings, which - as getline() discards the LF - results in the second string written over the first one. You can easily see this, if you run output of your program through some kind of hex-dumper, e.g. xxd.
Either check for \r at the end of the strings you read (btw, MacOS to version 9 used just this as the EOL marker), fix your input, or duly add new-lines to output, when printing.


text: Q: First Hochschild cohomology in a local selfinjective algebra Given a non-semisimple local selfinjective finite dimensional algebra $A$ with enveloping algebra $A^e$. Can one have $Ext_{A^{e}}^{1}(A,A)=0$ (that is the first hochschild cohomology zero)? I can prove that it is always nonzero in case A is addionally commutative.


text: Q: Deriving Coulombs law from QED - why must the particles be distinguishable? It is possible to derive Coulomb's potential from QED by considering the scattering process $e^-+e^-\rightarrow e^-+e^-$. The argument can be found in Peskin and Schroeder p.125, and it is reproduced in this stackexchange answer. The authors state that it is necessary to assume that the particles are distinguishable, meaning that only the $t$-channel diagram is included, and not the $u$-channel diagram. Why is this the case? Indistinguishability is of course not unique to QFT (i.e. it is a QM effect also) so I don't understand why it would be ignored in this limit. I expect that it has something to do with the fact that one electron is treated as fixed, but I don't quite follow how.