text:
Q: Find Div in DataList in javascript I have a div in asp:DataList, which includes some other divs. I tried to find the divs by document.getElementByID("").
it called: Unable to get property 'style' of undefined or null reference.
As a result I understood that the .getElementById can't find it.
Then how can I get them?
I tried to find my datalist by old posts but none of them match to my problem.
Note: My divs should be dragged, and they do, but I can't get the value of their positions because of this problem.
Code:
function FullDragging() {
   // some code
   var dd = document.getElementById("DesigningDiv"); // frame
   var logoObject = document.getElementById("logoObject"); // draggable element
   var nameObject = document.getElementById("nameObject"); // draggable element

   function getDesigningDivSize() {
            var dd = document.getElementById("DesigningDiv");
            var aspDesigningDivHF = document.getElementById('<%=aspDesigningDivHF.ClientID %>'); // hidden-field which sends the changes in client-side to the server.
            aspDesigningDivHF.value = parseInt(dd.style.width) + "," + parseInt(dd.style.height);
        }
}
window.onload = FullDragging;

because the function is called onload, the error appears onload also.
HTML:
<asp:DataList ID="DataList1" runat="server" DataKeyField="ProductID" Height="400px" Width="1400px" OnEditCommand="DataList1_EditCommand" OnItemCommand="DataList1_ItemCommand" CellPadding="40" RepeatColumns="2" RepeatDirection="Horizontal" OnCancelCommand="DataList1_CancelCommand" OnItemDataBound="DataList1_ItemDataBound" OnUpdateCommand="DataList1_UpdateCommand">
 <ItemTemplate> ... </ItemTemplate>
 <EditItemTemplate>

 logo

 full name

 </EditItemTemplate>
</asp:DataList>

A: a few problems, you shouldn't be populating an item template with static IDs as an ID should only appear once in an html document.
Consider applying a class to these divs and referencing them that way.
Once your page is rendered, right click and inspect one of these elements. ASP may be adding an extra prefix to your IDs as it is part of a datalist (e.g. DivLabel1 in visual studio becomes DataList1_DivLabel1 once the page is loaded) javascript isn't in on this conversion so you are better off referring to these items by class


text:
Q: Reporting with DB2 I started learning .net about 3 years ago. I have gone thru a boot camp during that time learning OO and various data access technologies such as NHibernate, Subsonic, LINQ TO SQL.
didn't wanna try EF cause it hasn't reached version 3 :)
As far as reporting goes, I have heard that many ORM'S fall flat on their face when it comes to reporting. We have AS400 OR DB2 as our backend. I have heard that LLBLGEN does a good job on reporting for this product. But it is a commercial product and not FREE. Can someone point me to some good resources for Reporting from DB2? thanks for any links/blog articles

A: Reporting on DB2 will work the same as reporting on almost any other database - you can use ODBC, JDBC or native DB2 calls to the database.  So, you don't need DB2 reporting references - any database reporting references should meet your needs.
The only thing special about DB2 might be a little of the syntax extensions, and how you scale up the back end through parallel database servers (like MapReduce, Teradata, etc).  But neither should be of much concern - since it's extremely ansi compliant and the scalability should be largely invisible to the reporting developer.
And Crystal Reports, Brio, Cognos, Business Objects, Microstrategy, Actuate, JasperReports, Birt, etc should all work fine.
ORMs are typically terrible for reporting - since they're object rather than set oriented.  You'll especially feel the pain with very large data volumes, complex reports or a large number of reports.

A: Please, don't overlook the most obvious answer: Query/400!
It is native iSeries software. You configure and runs the report on the iSeries but it works great. It is simple, straight forward and maybe a little bit limited but you get most of the works done.
Don't be scared of the green screen or the simple interface. It's really a powerfull tool that does handle the iSeries database very well.

A:

Can someone point me to some good resources for Reporting from DB2?

RPG I!
Light up those indicators!

A: Query Manager:
You cam use SQL (that can take input parameters) to build it, then create a "form" that will provide totals, level breaks, counts, customized headers, titles, etc.
Query/400 does not accept parameters AFAIK.
Free manual at:
http://publib.boulder.ibm.com/infocenter/iseries/v6r1m0/topic/rzatc/sc415212.pdf

redpajama_set_name: RedPajamaStackExchange


text:
Q: Heapsort function behaves the same with push and unshift.(Perl) I've been trying to implement a heap-sort function but it sorts the array in reverse order. The weird part is that it doesn't matter if I use unshift or push, the elements always get printed reversed.
#!/usr/bin/perl -w
use 5.014;
no warnings 'recursion';

sub heapify{
  my $index = pop @_;
  my $larger;
  unless ($index > int(@_/2-1))
  {
    my $left  = 2 * $index + 1;
    my $right = 2 * $index + 2;
    if($right < @_ && ($_[$left]<$_[$right]))
    {
      $larger = $right;
    } else {
      $larger = $left;
    }
    if($_[$index] < $_[$larger])
    {
      ($_[$index],$_[$larger]) =
      ($_[$larger],$_[$index]) ;
      heapify(@_,$larger);
    }
  }

}

sub max_heap{
  for(my $i = int(@_/2 -1) ; $i > -1; --$i){
    heapify(@_,$i);
  }

}

sub heapsort{
  return unless @_ > 1 ;
  max_heap(@_);
  my $last = shift(@_);
  heapsort(@_);
  push(@_,$last);
}

my @test = (9,3,13,7,6,78,2);

heapsort(@test);

say "Heapsorted:";
say join("\n",@test);

A: Used pseudocode
use strict;
use warnings;

my @a = reverse 1..500;
heapSort(\@a);
print "@a\n";

sub heapSort {
    my ($a) = @_;
    # input:  an unordered array a of length count

    # (first place a in max-heap order)
    heapify($a);

    my $end = $#$a; # //in languages with zero-based arrays the children are 2*i+1 and 2*i+2
    while ($end) {
        # (swap the root(maximum value) of the heap with the last element of the heap)
        @$a[$end, 0] = @$a[0, $end]; # swap(a[end], a[0])
        # (decrease the size of the heap by one so that the previous max value will
        # stay in its proper placement)
        $end--;
        # (put the heap back in max-heap order)
        siftDown($a, 0, $end);
    }
}
sub heapify {
    my ($a) = @_;
    my $count = @$a;
    # (start is assigned the index in a of the last parent node)
    my $start = ($count - 2 ) / 2;

    while ($start >= 0) {
        #(sift down the node at index start to the proper place such that all nodes below
        # the start index are in heap order)
        siftDown($a, $start, $count-1);
        $start--;
        #(after sifting down the root all nodes/elements are in heap order)
    }
}
sub siftDown {
     my ($a, $start, $end) = @_;
     # input:  end represents the limit of how far down the heap
     #              to sift.
     my $root = $start;

     while ($root * 2 + 1 <= $end) { # (While the root has at least one child)
        my $child = $root * 2 + 1; # (root*2 + 1 points to the left child)
        my $swap = $root;          # (keeps track of child to swap with)
        #(check if root is smaller than left child)
        $swap = $child if $a->[$swap] < $a->[$child];

        #(check if right child exists, and if it's bigger than what we're currently swapping with)
        $swap = $child + 1 if $child+1 <= $end and $a->[$swap] < $a->[$child+1];

        # (check if we need to swap at all)
        if ($swap != $root) {
            # swap(a[root], a[swap])
            @$a[$root, $swap] = @$a[$swap, $root];
            $root = $swap; # (repeat to continue sifting down the child now)
        }
        else {
            return;
        }
     }
}

A: This is to mention the required change in the code by Сухой27 answered Dec 31 '13 at 17:46.
Code works fine when input array has even n number of elements, but goes wrong when n is odd.
For an input like  @a = qw(10  11  2);
Output would be = 2  11  10
The output is wrong because in the first step, the above script skips checking of left child of last parent. When left is larger, the same does not swap with its parent.
The fix is simple:
 my $start = int(($count - 2 ) / 2);


text:
Q: Android app widget listview onclick listener I am new to android development. I am trying to make a widget for my app which will contain a listview, with each listview having 2 buttons apart from heading and content.
I am trying to hide the corresponding element of the listitem in the app widget(on homescreen) when the button of that element is pressed.
First I tried to check if the button click is getting any response and if I could detect if I can get the position of the item. So I did this:
listprovider.java (implements remoteviewfactory) :
@Override
    public RemoteViews getViewAt(int position) {
        final RemoteViews remoteView = new RemoteViews(
                context.getPackageName(), R.layout.list_row);
        ListItem listItem = listItemList.get(position);
        remoteView.setTextViewText(R.id.heading, listItem.heading);
        remoteView.setTextViewText(R.id.content, listItem.content);

        Bundle extras = new Bundle();
        extras.putInt(WidgetProvider.EXTRA_ITEM, position);
        Intent fillInIntent = new Intent();
        fillInIntent.putExtras(extras);
        // Make it possible to distinguish the individual on-click
        // action of a given item
        remoteView.setOnClickFillInIntent(R.id.buttonwidget, fillInIntent);

        return remoteView;
    }

and then in the WidgetProvider.java (extends AppWidgetProvider) :
for (int i = 0; i < N; ++i) {
            RemoteViews remoteViews = updateWidgetListView(context,
                    appWidgetIds[i]);
            Intent clickIntent = new Intent(context, MainActivity.class);
            clickIntent.setAction(WidgetProvider.TOAST_ACTION);
            clickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
            clickIntent.setData(Uri.parse(clickIntent.toUri(Intent.URI_INTENT_SCHEME)));
            PendingIntent clickPI = PendingIntent.getActivity(context, 0,
                    clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);

            remoteViews.setPendingIntentTemplate(com.example.markup.R.id.listViewWidget, clickPI);
            appWidgetManager.updateAppWidget(appWidgetIds[i], remoteViews);
        }
        super.onUpdate(context, appWidgetManager, appWidgetIds);

The mainActivity.java is the default activity of the program, where I did this to get the item position:
public class MainActivity extends Activity {

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

        //Printing detail of clicked item from widget
        Intent intent = getIntent();
        if (intent.getAction().equals(WidgetProvider.TOAST_ACTION)) {
            int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                AppWidgetManager.INVALID_APPWIDGET_ID);
            int viewIndex = intent.getIntExtra(WidgetProvider.EXTRA_ITEM, 0);
            Toast.makeText(getApplicationContext(), "Touched view " + viewIndex, Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(getApplicationContext(), "Touched view none ", Toast.LENGTH_SHORT).show();
        }
    }

and I am thus able to open the main activity on a button click and getting a TOAST text in the bottom, giving exact result.
But I wish to hide/disable the corresponding element of the app widget when clicked. What should I do for that?

A: you must remove list item from the adapter when the button is pressed. And call
adapter.notifyDataSetChanged();

then the item will disappear.
Hopes this can help.


text:
Q: Polymorphism with parameters of child types in Java I have a java programming related problem.
I have the following classes:
public abstract class Animal {
    abstract void walk(AbstractWalkData abstractWalkData);
}

public class Mouse extends Animal{
    @Override
    void walk(AbstractWalkData abstractWalkData) {
        System.out.println(abstractWalkData.getWalkSound());
        System.out.println(abstractWalkData.getWalkSpeed());
        System.out.println(((MouseWalkData) abstractWalkData).getMouseSpecific());

    }
}

public class Tiger extends Animal{
    @Override
    void walk(AbstractWalkData abstractWalkData) {
        System.out.println(abstractWalkData.getWalkSound());
        System.out.println(abstractWalkData.getWalkSpeed());
        System.out.println(((TigerWalkData) abstractWalkData).getTigerSpecific());
    }
}

@Data
@SuperBuilder
public abstract class AbstractWalkData {
    private String walkSound;
    private int walkSpeed;
}

@Getter
@Setter
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
@SuperBuilder
public class MouseWalkData extends AbstractWalkData {
    private String mouseSpecific;
}

@Getter
@Setter
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
@SuperBuilder
public class TigerWalkData extends AbstractWalkData {
    private String tigerSpecific;
}

public class MainClass {
    public static void main(String[] args) {
        Animal mouse = new Mouse();
        MouseWalkData mouseData = MouseWalkData.builder()
                .walkSound("mouse walk sound")
                .walkSpeed(5)
                .mouseSpecific("mouse specific string")
                .build();
        mouse.walk(mouseData);
        Animal tiger = new Tiger();
        TigerWalkData tigerWalkData = TigerWalkData.builder()
                .walkSound("tiger walk sound")
                .walkSpeed(8)
                .tigerSpecific("tiger specific string")
                .build();
        tiger.walk(tigerWalkData);
    }
}

Note that I am using lombok to get rid of boilerplate code. Is there any way to get rid of the castings in the walk method of the Mouse and Tiger class?
I would like to do something like this:
public class Mouse extends Animal{
    @Override
    void walk(MouseWalkData mouseWalkData) {
        System.out.println(mouseWalkData.getWalkSound());
        System.out.println(mouseWalkData.getWalkSpeed());
        System.out.println(mouseWalkData.getMouseSpecific());

    }
}

But i get a compiler error.
Thank you all for any ideas.

A: That's how Java works but what you can do is start using generics in your code, for example, it will be something like this
abstract class Animal <T extends AbstractWalkData > {
    abstract void walk(T walkData);
}

and then, for example, your mouse class will be something like this
public class Mouse extends Animal <MouseWalkData>{
    @Override
    void walk(MouseWalkData mouseWalkData) {
        System.out.println(mouseWalkData.getWalkSound());
        System.out.println(mouseWalkData.getWalkSpeed());
        System.out.println(mouseWalkData.getMouseSpecific());

    }
}

and it will work
to learn more about generics I recommend to read about them and how it helped to avoid some of java's boilerplate code https://www.baeldung.com/java-generics

A: You can use 'instanceof' keyword to do that in Java. If you use concrete classes as parameter in your walk method as you mentioned, it is not polymorphism anymore. You should use an abstract class or interface in the parameter. Then pass any concrete child object to that method.
if(abstractWalkData instanceof MouseWalkData) {
   System.out.println((MouseWalkData)abstractWalkData.getMouseSpecific());
}


text:
Q: ImportError win32api When I try to run this script, I get this error:
Traceback (most recent call last):
  File "C:/Users/itsan/Desktop/Coding/Python/Enter.py", line 4, in <module>
    from pywinauto import Desktop, Application, keyboard
  File "C:\Users\itsan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pywinauto\__init__.py", line 59, in <module>
    import win32api  # noqa: E402
ImportError: DLL load failed: The specified module could not be found.

This is my script:
import keyboard
import time
from pywinauto import Desktop, Application, keyboard
from pywinauto.application import Application

app = Application().start("BlueStacks")

while True:
    if keyboard.is_pressed('enter'):
        time.sleep(1)
        app.window_(title_re="BlueStacks").window_(title="Send").click()
#2
        app.window_(best_match="BlueStacks" ).window_(best_match="Send").click()

I ran pip install pypiwin32 in the cmd , and it returned this:
Requirement already satisfied: pypiwin32 in c:\users\itsan\appdata\local\packages\pythonsoftwarefoundation.python.3.7_qbz5n2kfra8p0\localcache\local-packages\python37\site-packages (223)
Requirement already satisfied: pywin32>=223 in c:\users\itsan\appdata\local\packages\pythonsoftwarefoundation.python.3.7_qbz5n2kfra8p0\localcache\local-packages\python37\site-packages (from pypiwin32) (227)

I'm using IDLE python (3.7.6)


text:
Q: Can't set a subview below another subview This is the scenario:

I have this UIViewControllerof a MainVC class.
Inside this MainVC i have a UITextField of a TextFieldVC class.
Now inside TextFieldVC.m i'm creating a UITableView that should be inserted below the UITextFieldwith this code
            //TextFieldVC.m

            UIView *rootView = [self.window.subviews objectAtIndex:0];

            [self.superview bringSubviewToFront:self];
            [rootView insertSubview:self.autoCompleteTableView
                             belowSubview:self];

where autoCompleteTableView is the UITableView. The UITableView will be created whenever the user starts editing the UITextField, that is an @Outlet in MainVC.m
Now the problem is that this autoCompleteTableViewis created above the UITextField and i don't understand why.

A: A possible explanation for what is happening is that rootView does not have the text field among its subviews. Try this out:
        [self.superview insertSubview:self.autoCompleteTableView
                         belowSubview:self];

By doing this you are ensuring that you add the table view to the same view that also contains the text field, so the ordering between the two subviews can be enforced.

A: Strange behaviour, based on sergio answer.
If I have the root view frame at another location than 0,0 (exemple: self.view.frame= CGRectMake(0, 1100, 300, 400);).
= when I call this line on the control, the root view return at 0,0 !!!
  [self.superview insertSubview:self.autoCompleteTableView
                         belowSubview:self];

Any idea?


text:
Q: How to use Spring Kafka's Acknowledgement.acknowledge() method for manual commit I am using Spring Kafka first time and I am not able to use Acknowledgement.acknowledge() method for manual commit in my consumer code as mentioned here https://docs.spring.io/spring-kafka/reference/html/_reference.html#committing-offsets. Mine is spring-boot application. If I am not using manual commit process than my code is working fine. But when I use
Acknowledgement.acknowledge() for manual commit it shows error related to bean. Also If I am not using manual commit properly please suggest me the right way to do it.
Error message:
***************************
APPLICATION FAILED TO START
***************************

Description:

Field ack in Receiver required a bean of type 'org.springframework.kafka.support.Acknowledgment' that could not be found.

Action:

Consider defining a bean of type 'org.springframework.kafka.support.Acknowledgment' in your configuration.

I googled this error I found that I need to add @Component but that is already there in my consumer code.
My consumer code looks like this: Receiver.java
import java.util.concurrent.CountDownLatch;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Component;

@Component
public class Receiver {

    @Autowired
    public Acknowledgment ack;

    private CountDownLatch latch = new CountDownLatch(1);

    @KafkaListener(topics = "${kafka.topic.TestTopic}")
    public void receive(ConsumerRecord<?, ?> consumerRecord){
            System.out.println(consumerRecord.value());
            latch.countDown();
            ack.acknowledge();
    }
}

My producer code looks like this: Sender.java
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

@Component
public class Sender {

    @Autowired
    private KafkaTemplate<String, Map<String, Object>> kafkaTemplate;

    public void send(Map<String, Object> map){
            kafkaTemplate.send("TestTopic", map);

    }

}

EDIT 1:
My new consumer code looks like this: Receiver.java
import java.util.concurrent.CountDownLatch;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Component;

@Component
public class Receiver {

    private CountDownLatch latch = new CountDownLatch(1);

    @KafkaListener(topics = "${kafka.topic.TestTopic}", containerFactory = "kafkaManualAckListenerContainerFactory")
    public void receive(ConsumerRecord<?, ?> consumerRecord, Acknowledgment ack){
            System.out.println(consumerRecord.value());
            latch.countDown();
            ack.acknowledge();
    }
}

I changed my configuration class also:
import java.util.HashMap;
import java.util.Map;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.core.DefaultKafkaConsumerFactory;

@Configuration
@EnableKafka
public class ReceiverConfig {

    @Value("${kafka.bootstrap-servers}")
    private String bootstrapServers;

    @Value("${spring.kafka.consumer.group-id}")
    private String consumerGroupId;

    @Bean
    public Map<String, Object> consumerConfigs() throws SendGridException {
            Map<String, Object> props = new HashMap<>();
            props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
            props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
            props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
            props.put(ConsumerConfig.GROUP_ID_CONFIG, consumerGroupId);
            return props;

    }

    @Bean
    public ConsumerFactory<String, String> consumerFactory(){
        return new DefaultKafkaConsumerFactory<>(consumerConfigs());
    }

    /*@Bean
    public ConcurrentKafkaListenerContainerFactory<String, String> kafkaListenerContainerFactory(){
        ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(consumerFactory());

        return factory;
    }*/

    @Bean
    public ConcurrentKafkaListenerContainerFactory<String, String> kafkaManualAckListenerContainerFactory(){
        ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(consumerFactory());
        return factory;
    }

    @Bean
    public Receiver receiver() {
        return new Receiver();
    }
}

After adding containerFactory = "kafkaManualAckListenerContainerFactory" to my receive() method I am getting the below error.
***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 1 of method kafkaListenerContainerFactory in org.springframework.boot.autoconfigure.kafka.KafkaAnnotationDrivenConfiguration required a bean of type 'org.springframework.kafka.core.ConsumerFactory' that could not be found.
    - Bean method 'kafkaConsumerFactory' in 'KafkaAutoConfiguration' not loaded because @ConditionalOnMissingBean (types: org.springframework.kafka.core.ConsumerFactory; SearchStrategy: all) found bean 'consumerFactory'

Action:

Consider revisiting the conditions above or defining a bean of type 'org.springframework.kafka.core.ConsumerFactory' in your configuration.

A: Those who are using spring boot application, simple add below to your application.yml (or environment specific file).
spring:
  kafka:
    listener:
      ack-mode: manual

Above change will make Acknowledgment ack argument available inside
receive(ConsumerRecord<?, ?> consumerRecord, Acknowledgment ack) method automatically.

A: For those still looking for a solution to these errors concerning manual acknowledgment, you don't need to specify containerFactory = "kafkaManualAckListenerContainerFactory", instead you can just add:
factory.getContainerProperties().setAckMode(ContainerProperties.AckMode.MANUAL_IMMEDIATE);

to your receiver config just before you return the factory object.
Then you also need:
props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);

in consumer config props.
So in the end your listener method can simply look like:
@KafkaListener(topics = "${spring.kafka.topic}")
    private void listen(@Payload String payload, Acknowledgment acknowledgment) {
        //Whatever code you want to do with the payload
        acknowledgement.acknowledge(); //or even pass the acknowledgment to a different method and acknowledge even later
    }

A: You really should follow documentation:

When using manual AckMode, the listener can also be provided with the Acknowledgment; this example also shows how to use a different container factory.

@KafkaListener(id = "baz", topics = "myTopic",
          containerFactory = "kafkaManualAckListenerContainerFactory")
public void listen(String data, Acknowledgment ack) {
    ...
    ack.acknowledge();
}

There is really nowhere noted that Acknowledgment is a bean. So, change your receive() @KafkaListener method signature appropriately and remove that @Autowired for suspicious  Acknowledgment bean - it just doesn't exists because this object is a part (header) of each received message.


text:
Q: Business Objects RelativeDate function Cognos Equivalent I am converting a report from BO to Cognos and one of the query items in BO is as follows
    =RelativeDate(ToDate([Full Date];"MM/dd/yyyy");-6)

I am looking for the Cognos equivalent of this function.
Thanks for any answers in advance.

A: This should work:
_add_days([Full Date],-6)

A: That function is taking a string formatting it as a date then taking 6 days from it, the following function in Cognos should work:
dateadd ( ' { ' datepart ' } ' , integer_expression , date_expression )

So in your example, to take 6 days from today it would be
dateadd('dd',6,'2015-10-29')

This was taken from the Cognos 10.1.0 documentation


text:
Q: SVM to gender recognition i've been working this weeks in a gender recognition project (in python) using at first: Fisherfaces as Feature Extraction method and 1-NN classifier with Euclidean Distance but now i though it was not enough reliable (in my humble opinion) so i'm about to use SVM but im lost when i have to create and train a model to use it in my dataset of images,  but i can't find the solution for the commands i need in http://scikit-learn.org.
I've tried with this code but it doesn't work, dunno why
i have this error while executing:
  File "prueba.py", line 46, in main
    clf.fit(R, r)
  File "/Users/Raul/anaconda/lib/python2.7/site-packages/sklearn/svm/base.py", line 139, in fit
 X = check_array(X, accept_sparse='csr', dtype=np.float64, order='C')
  File "/Users/Raul/anaconda/lib/python2.7/site-packages/sklearn/utils/validation.py", line 350, in check_array
    array.ndim)
ValueError: Found array with dim 3. Expected <= 2

And this is my code:
import os, sys
import numpy as np
import PIL.Image as Image
import cv2
from sklearn import svm

def read_images(path, id, sz=None):
    c = id
    X,y = [], []
    for dirname, dirnames, filenames in os.walk(path):
        for subdirname in dirnames:
            subject_path = os.path.join(dirname, subdirname)
            for filename in os.listdir(subject_path):
                try:
                    im = Image.open(os.path.join(subject_path, filename))
                    im = im.convert("L")
                    # resize to given size (if given)
                    if (sz is not None):
                        im = im.resize(sz, Image.ANTIALIAS)
                    X.append(np.asarray(im, dtype=np.uint8))
                    y.append(c)
                except IOError as e:
                    print "I/O error({0}): {1}".format(e.errno, e.strerror)
                except:
                    print "Unexpected error:", sys.exc_info()[0]
                    raise
                        #c = c+1
    return [X,y]

def main():
    # check arguments
    if len(sys.argv) != 3:
        print "USAGE: example.py </path/to/images/males> </path/to/images/females>"
        sys.exit()
    # read images and put them into Vectors and id's
    [X,x] = read_images(sys.argv[1], 1)
    [Y, y] = read_images(sys.argv[2], 0)
    # R all images and r all id's
    [R, r] = [X+Y, x+y]
    clf = svm.SVC()
    clf.fit(R, r)

if __name__ == '__main__':
    main()

I'd appreciate any kind of help in how can i make gender recognition with SVM
Thanks for reading

A: X.append(np.asarray(im, dtype=np.uint8))

I guess this is appending a 2d-array. You might want to flatten it before appending so that each instance becomes this looking:
array([255, 255, 255, ..., 255, 255, 255], dtype=uint8)

instead of:
array([
   [255, 255, 255, ..., 255, 255, 255],
   [255, 255, 255, ..., 255, 255, 255],
   [255,   0,   0, ...,   0,   0,   0],
   ...,
   [255,   0,   0, ...,   0,   0,   0],
   [255, 255, 255, ..., 255, 255, 255],
   [255, 255, 255, ..., 255, 255, 255]], dtype=uint8)

Try this:
X.append(np.asarray(im, dtype=np.uint8).ravel())


text:
Q: Como contar numeros consecutivos dentro de un array? Buenas estoy practicando realizando distintos tipos de algoritmos y hay uno en el que no puedo entender la lógica o el porque estoy haciendolo mal.
Obtengo un array de numeros enteros del 1 al 9 por ejemplo
$myArray = array(1,2,2,4,5,6,7,8,8,8);

Y en el algoritmo debe devolver cual numero se repite mas veces de manera consecutiva y cuantas veces se repite de manera consecutiva.
En este caso sería el 8 que se repite 3 veces de manera consecutiva.
Para ello realicé lo siguieente:
$cont = 1;
$longest = $cont;
$number = $myArray[0];

for($i=0; $i<$myArray.length; $i++) {

    if($myArray[i] == $myArray[i+1]){

        $cont++;

        $longest = $cont;

        $number = $myArray[i];

    } else {

        $cont = 1;

    }

    if($cont > $longest){

        $longest = $cont;
        $number = $myArray[i];
    }

}

echo("Longest: " + $longest + "\n" + "Number: " + $number);

Pero por alguna razón esta mal.
El código lo escribí en php, pero al ser una cuestión de lógica no importa el lenguaje en si.

A: Buen día,
Una estrategia para obtener el número que más se repite y el número de veces que se repite es guardar el valor que tiene el arreglo en una variable, por ejemplo $old, y ese valor se va a comparar en la siguiente iteración con el valor que tiene el arreglo en ese ciclo
Si el valor de la iteración actual es igual al valor de la iteración anterior (Que estamos guardando en $old) entonces aumentamos un contador ($count) que revisa el número de repeticiones del valor actual.
El contador lo podemos inicializar en 1 ya que cada número por lo menos se repite una vez
El valor inicial del número que más se repite (Estoy llamando la variable $number) y del valor de la iteración anterior (Estoy llamando la variable $old) se inicializan en null porque no si inicializas las variables con cualquier valor numérico, por ejemplo 0, podría ser que en el arreglo ese valor también exista y entonces el conteo estaría mal.
En otra variable ($repetitions) guardamos el valor más grande de repeticiones seguidas, cuando $count sea mayor a $repetitions entonces guardamos el valor de $count en $repetitions y el valor numérico de la iteración actual en el número que más se repite
Cuando el valor de la iteración actual es diferente al valor de la iteración previa entonces regreso el contador $count a 1
El ejemplo del código funcionando:
<?php
$myArray = array(1,2,2,4,5,6,7,8,8,8,8,8,8,8,8,8,8,8,3,3,3,3,3,2,2,3,3,5,5,5,5,5,5,5,5);
$count = 1;
$repetitions = 0;
$number = null;
$old = null;

foreach ($myArray as $element){
    if ($old == $element) {
        $count++;
        if ($count > $repetitions) {
            $repetitions = $count;
            $number = $element;
        }
    }
    else {
        $count = 1;
    }

    $old = $element;
}
echo 'El número que más se repite es: '.$number. ' y se repite '. $repetitions . ' veces.';
?>

Resultado del código anterior:
El número que más se repite es: 8 y se repite 11 veces.


text:
Q: F# map/set comprehensions I'm looking for something akin to the dict/list/set comprehensions in Python. In Python you can do:
[x+2 for x in list if x > 10]

and in F#
[for x in list do if x > 10 yield x+2]

but in Python, you can also do:
{x+2 for x in list if x > 10}

to generate Sets, and
{k: (v+10)/2 for k, v in list.items() if k > 5}

to generate Dicts. Is there any equivalent (both in terms of function and in terms of overall tidyness) syntax for this sort of thing in F#?

A: There is a set function accepting seq<_>, so you can do:
set [for x in list do if x > 10 yield x+2]

Same with dict. Here are the relevant docs:
set: http://msdn.microsoft.com/en-us/library/ee353747.aspx
dict: http://msdn.microsoft.com/en-us/library/ee353774.aspx

A: Essentially F# does not have a special syntax for this but you can use array or list comprehension and pass the result to functions provided to the standard library.
let intSet = set [for x in list do if x > 10 yield x+2]

let intMap = dict [for (x, y) in list do if x > 10 yield (x,y+2)]


text:
Q: How to include external JS libraries like jQuery, jQuery DataTable, Charts.js with Parcel Bundler? I'm new to parcel and i need some help here: I have some external JS libraries that I used in my website development. So how do I include all those in my build? Note: I've used all CDN URLS like this
<script defer src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script defer src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<script src="js/main.js" defer></script>

A: It's very easy.

*

*Install the desired dependency

npm i jquery

*

*Use it in your code

import * as $ from 'jquery'

That's it. Bundling and even minification, Parcel will do automatically.
If you prefer to keep them on CDN, just include them into index.html and keep them there. You might install types with npm i @types/jquery -D if you want IntelliSense.
If you don't use something directly in the code, you may create separate file with vendors and import it directly to the HTML:
import 'jquery';
import 'popper.js';
import 'bootstrap';

  <script src="./vendors.ts"></script>

You may look for real-life example here: https://github.com/Drag13/perfrunner/blob/development/packages/perfrunner-reporters/src/reporters/html/index.html
Important: don't mix the approaches, you will do double loading.

A: With parcel v2 (parcel@next) I load form CDN jquery and this is my setup.
index.html
<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="dist/main.js" type="text/javascript" charset="utf-8" async defer></script>

package.json
"alias": {
  "jquery": {
    "global": "$"
  }
}
...

main.js
import $ from 'jquery'; $('id').toggle() // use jquery
I compile it like
parcel build main.js
The end result has my code and jquery has to be loaded before.
Note my example is not optimized for async load etc.
ps: I have to say I'm not expert in parcel(starting to learn) but this works for me.


text:
Q: What is the better way of forming this logic for filling nulls in pandas? I have nulls in a column named 'rtd' of a dataframe. To fill those nulls, first I need to find such a value in 'rtd' where acquired_year, acquired_month, secondarycategory are matching and payment_month is 12 less than the payment month of null on which we are currently calculating. At last, multiply such a value by 0.7, and that should be the final value.
Dataframe snippet
Currently, to get the desired result im using this code, but this seems inefficient way. I need a more pythonic/optimised way, probably by using fillna or some other method.
index_ls = df[(df['payment_month']>=12) & (df['rtd'].isnull())].index.tolist()
for i in index_ls:
    df.at[i,'rtd'] = df.loc[(df['acquired_year'] == df.at[i, 'acquired_year']) & (df['acquired_month'] == df.at[i, 'acquired_month']) & (df['secondarycategory'] == df.at[i, 'secondarycategory']) & (df['payment_month'] == df.at[i, 'payment_month']-12), 'rtd']*0.7


text:
Q: node.js - move the res.send() outside of function? currently what i have is:
var server = http.createServer(function(req,res){
    res.writeHead(200,{'Content-Type': 'text/html; charset=utf-8'});
    var oo = require('/test.js');
    oo(connection, function (e, result) {
        res.end(result);
    });
}).listen(80);

what i would like to do is
var server=http.createServer(function(req,res){
    res.writeHead(200,{'Content-Type': 'text/html; charset=utf-8'});
    var oo = require('/test.js');
    oo(connection, function (e, result) {});
    res.end(result);
}).listen(80);

but this does not work.
the idea is to move
res.end(result);

right above
}).listen(80);

A: I have no idea why you want to do so, please read about async and sync code, not best article, - but you can find many of them, but I have a solution for you.
Before you go, install Fibers package:
npm install fibers

Solution:
var Future = require('fibers/future');
var server = http.createServer(function(req,res){
   fut = new Future();
   res.writeHead(200,{'Content-Type': 'text/html; charset=utf-8'});
   var oo = require('/test.js');
   oo(connection, function (e, result) {
      fut.return(result);
   });
   res.end(fut.wait());

}).listen(80);

And read about JS Conventions, please.

A: It cannot be moved outside the callback function, because in such case it would be executed before callback, which I guess generates an output to res. This result won't be sent, because you closed res before.


text:
Q: JSON parsing error, Expecting 'EOF', '}', ',', ']' I try to find out why my JSON is not legal.
I use this site: http://jsonlint.com/
The first example which is good is:
{
        "data": 1290,
        "value": "a"
}

The second which is not good is:
{
    "data": 1290,
    "value": "a"
}

I dont understand why the second one does not work. Its the same as the first one.

EDIT
I found this sings at the end of the string.

How to remove them using PHP? the string source is from php.

A: There might be some additional output after you output your json. Try trimming output and terminating further execution.
$json = array('data' => 1290, 'value' => 'a');

echo json_encode($json);
die();


text:
Q: How to resize webview according to screen resolution in iphone app? I am using storyboards. I am unable to resize webview according to the screen size in my storyboard.

I want header to be of same size for both resolution but change the height of webview according to screen resolution.
I can't use Autolayout because I want to deploy my app for ios5 and above.
Please help.

A: you can set Your Webview frame according to UIScreen like Bellow where you alloc your `webview
CGRect webFrame = [[UIScreen mainScreen] applicationFrame];
webFrame.origin.y -= 20.0; // statusbar 20 px cut from y of frame
webView = [[UIWebView alloc] initWithFrame:webFrame];
webView.scalesPageToFit = YES;
webView.autoresizesSubviews = YES;
webView.autoresizingMask=(UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth);
[webView setBackgroundColor:[UIColor clearColor]];

A: In your .m file under viewDidLoad add this code.
webview.frame = CGRectMake(0,0,self.view.frame.size.width,self.view.frame.size.height);

Add a referencing outlet of your web view to webView and then that should set the webView height to your view height.
Explanation: The view will get longer when you deploy to a 4 inch simulator causing the webView to change to the view's size.


text:
Q: CodeIgniter create a layout/template library Before I begin I have to say that I have recently started learning CodeIgniter, so I'm sorry if I repeat this subject once again.
In procedural php I would do something like this
// the header.php
<!DOCTYPE html>

      <meta name="description" content="blah blah">
      <title>My Site</title>
      <link href="css/main.css" rel="stylesheet" media="screen">
<php? if($current_page == 'about.php'): ?>
      <link href="css/secondary.css" rel="stylesheet" media="screen"> // or some embed styles (<stlye> ... </style>)
   <?php endif; ?>

      <php? if($current_page == 'contact.php'): ?>

      <?php endif; ?>

     // end of header.php

     include('template/header.php');

Heading1

Lorem Ipsum...

     include('template/footer.php');

    //footer.php
    //maybe some js and here

So I would like to do something similar and in CI. All pages/views will have the same main styles or scripts, but in some cases, some specific pages (like contact.php) may include, and only in these pages, some specific styles or scripts (like the validation.js).
I have found this video that shows how to create a template/layout library using CI, but I'm not quite sure how I can apply this functionality to work properly.

A: Put the bottom class in libraries/Layout.php (your app not the sys). In the autoload add the library:
$autoload['libraries'] = array('layout');

In your controller just write $this->layout->render();
The class will render the layout views/layouts/default.php and the view views/$controller.views/$method.php
In the default layout just put
<?php $this->load->view($view,$data); ?>

and thats it.
The code is
<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

class Layout
{
    public $data = array();
    public $view = null;
    public $viewFolder = null;
    public $layoutsFodler = 'layouts';
    public $layout = 'default';
    var $obj;

    function __construct()
    {
        $this->obj =& get_instance();
    }

    function setLayout($layout)
    {
        $this->layout = $layout;
    }
    function setLayoutFolder($layoutFolder)
    {
        $this->layoutsFodler = $layoutFolder;
    }

    function render()
    {

        $controller = $this->obj->router->fetch_class();
        $method = $this->obj->router->fetch_method();
        $viewFolder = !($this->viewFolder) ? $controller.'.views' : $this->viewFolder . '.views';
        $view = !($this->view) ? $method : $this->view;

        $loadedData = array();
        $loadedData['view'] = $viewFolder.'/'.$view;
        $loadedData['data'] = $this->data;

        $layoutPath = '/'.$this->layoutsFodler.'/'.$this->layout;
        $this->obj->load->view($layoutPath, $loadedData);
    }
}
?>

A: I'm doing layout thing is like bellow.
I get content to data['content'] variable.
This is my controller.
    class Article extends MY_Controller {

        function __construct() {
            parent::__construct();
            $this->load->model('article_model');
        }

        public function index() {

            $data['allArticles']    =   $this->article_model->getAll();

            $data['content']        =   $this->load->view('article', $data, true);
            $this->load->view('layout', $data);

        }

This is my Layout.I'm using bootstrap layout.
    <!DOCTYPE html>

            <meta charset="utf-8">
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <meta name="description" content="">
            <meta name="author" content="">
            <title>Starter Template for Bootstrap</title>
            <base href="<?php echo base_url(); ?>" />

            <link href="assets/bootstrap3.0.1/css/bootstrap.min.css" rel="stylesheet">

                        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                            Toggle navigation

                        </button>
                         Article Management System

Home

                                 Admin

Add Article

All Article

                <?php echo $content; ?>

This is my content view

All Articles

                        Title
                        Description

                    <?php foreach ($allArticles as $row) { ?>

                        <?php echo $row->title; ?>
                        <?php echo substr($row->description,0,100); ?> ....

                    <?php } ?>

A: I have achieved the same thing with the following:
Put this code in your ./application/core/MY_Controller.php file:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

    class MY_Controller extends CI_Controller
    {
        protected $layout = 'layout/main';

        public function __construct()
        {
            parent::__construct();
        }

        protected function render($file = NULL, &$viewData = array(), $layoutData = array())
        {
            if( !is_null($file) ) {
                $data['content'] = $this->load->view($file, $viewData, TRUE);
                $data['layout'] = $layoutData;
                $this->load->view($this->layout, $data);
            } else {
                $this->load->view($this->layout, $viewData);
            }

            $viewData = array();
        }
   }

Create a layout folder inside ./application/views directory and then create your files with the entire html in it. Just put the <?php echo $content; ?> in that file where you want to put the dynamic content in it. Then in your controllers use $this->render(); and pass your file path and data. If you want to use a different layout for specific page just put the $this->layout = 'path_to_your_layout_file'; it will override the layout file to be used.

A: I have struggled with a similar problem not long ago. My solution to it was the following :
In your controller constructor create 2 arrays one of css files and one of js files and put in them the files common to all views.
And in each function in the controller add to them logic specific files.
For your example you'll have something like this :
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Home extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->page_data = array();
        $this->page_data['css']=array('main.css','bootstrap.css');
        $this->page_data['js']=array('main.js','bootstrap.js');
    }
    public function about()
    {
       array_push($this->page_data['css'],'secondary.css');
       $this->load->view('main_layout',$this->page_data)
    }
    public function contact()
    {}

 }

And in your view file you'll just iterate over the $css and $js array and include them one by one.
You can extend that easily to include header and footer templates by pushing them into the page_data array.
I ended up switching to doing all the templating on the client-side with Backbone and using Code Igniter as a REST API only but this technique gave me relatively clean code for what I needed.

A: I use this, in older version of CodeIgniter and it works for version 3 as well.
<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

class Layout
{

    var $obj;
    var $layout;

    function Layout($layout = "layout_main")
    {
        $this->obj =& get_instance();
        $this->layout = $layout;
    }

    function setLayout($layout)
    {
      $this->layout = $layout;
    }

    function view($view, $data=null, $return=false)
    {
        $loadedData = array();
        $loadedData['content_for_layout'] = $this->obj->load->view($view,$data,true);

        if($return)
        {
            $output = $this->obj->load->view($this->layout, $loadedData, true);
            return $output;
        }
        else
        {
            $this->obj->load->view($this->layout, $loadedData, false);
        }
    }
}
?>

and to call this in the controller I use:
$this->layout->view('apps/apps', $data);

A: 5 Simple Steps to create CodeIgniter Template:
Step #1
Template.php @ libraries
Step #2
Write following code
/* Start of file Template.php */
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Template {
        var $template_data = array();
        function set($name, $value)
        {
            $this->template_data[$name] = $value;
        }
        function load($template = '', $view = '' , $view_data = array(), $return = FALSE)
        {
            $this->CI =& get_instance();
            $this->set('contents', $this->CI->load->view($view, $view_data, TRUE));
            return $this->CI->load->view($template, $this->template_data, $return);
        }
}
/* End of file Template.php */
/* Location: ./system/application/libraries/Template.php */

Step #3
open config/autoload.php
at line 55 replace
$autoload['libraries'] = array('database', 'session','encrypt');
with this code
$autoload['libraries'] = array('database', 'session','encrypt', 'template');

Step #4
On my controller call template as
//start
$this->template->load(TEMPLATE_NAME, VIEW_NAME , $this->data);
//end

Step #5
On views
create a file as custom_template.php
And place there following code--
//start
<?php $this->load->view('elements/header'); ?>

<?php echo $contents;?>

<?php $this->load->view('elements/footer'); ?>
//end

N.B. In views in elements folder create two files as header.php And footer.php


text:
Q: Modified proof environment I have been using the following proof environment for a while now:
\renewenvironment{proof}
{
    \vspace{6 pt}
    \begin{mdframed}[skipabove=0pt, skipbelow=0pt, innertopmargin=0pt, innerbottommargin=0pt, bottomline=false,topline=false,rightline=false]%
    \noindent \textit{\textbf{Proof.}}
}
{%
    \end{mdframed}
    \vspace{6 pt}
}

which usually gives something like this, i.e. the desired result:

but once every 50 pages (it's just a way of saying this does not happen often), something like this happens:

The issue is obviously that little line at the bottom going a little too far down (about one line of text too far) when it is supposed to come at the same height as the text (since I set the bottom margins to zero), but unfortunately it is not. I don't know how to force mdframed to stick with that text. The vertical spaces are there to mimic the space lost by setting margins down to zero.
Any better ideas?
(I really love this line on the side for the following two reasons: makes it immediate to see how long a proof is, and it really separates results from proofs nicely, so that the reader interested in a proof does not look forever in blocks of text. So I would really appreciate if this problem could be fixed! More importantly, it gives me error messages (bad boxes), so I don't want to look if an error is "just that" or if it's something else when my documents have hundreds of pages.)
Added : The code of the example where it fails. Just to give you an idea how random this phenomenon is : if I modify something somewhere else in the document and this particular proof landed a few lines higher, the line would align correctly.
\begin{proof}
    We already know that localization is right-exact by \refthm{localization-and-tensor}, so it suffices to show that localization preserves injective maps ; in other words, if $M_1 \subseteq M_2$, then the map $S^{-1} M_1 \to S^{-1}M_2$ defined by $S^{-1}M_1 \ni \frac ms \to \frac ms \in S^{-1}M_2$ is injective. There is not much to say : given $\frac ms \in S^{-1}M_1 \setminus \{0\}$, there exists no $s' \in S$ such that $sm = 0$ ; therefore $\frac ms \in S^{-1}M_2 \setminus \{0\}$. Flatness of $S^{-1}A$ as an $A$-module follows by \refthm{localization-and-tensor}.
\end{proof}

Just to remove any black boxes, here is how \refthm is defined :
\newcommand{\refthm}[1]{Theorem~\ref{#1}}

(where \ref comes from the amsmath package) and here is an example of the exact same content but modifications 4-5 pages earlier so that the same content lands correctly displayed in the middle of a page:

EDIT : When going with egreg's answer, I notice some slightly undesirable phenomenon, but not problematic:

I used to control the spacing before and after the line on the left by adding some vertical spacing before and after my box. Is there some tcolorbox command which would allow me to do it neatly? I tend to dislike manually doing vertical spacing.

A: My impression is that the issue arises when a proof ends too near to the end of a page, so mdframed tries to break it.
The tcolorbox package seems more robust under this respect.
\documentclass{article}
\usepackage{amsthm}
\usepackage[many]{tcolorbox}
\usepackage{xpatch}

\usepackage{lipsum}

\xpatchcmd{\proof}{\itshape}{\bfseries\itshape}{}{}

\tcolorboxenvironment{proof}{
  blanker,
  before skip=\topsep,
  after skip=\topsep,
  borderline west={0.4pt}{0.4pt}{black},
  breakable,
  left=12pt,
  right=12pt, % I'd avoid this
}

\begin{document}

\lipsum[2]

\begin{proof}
\lipsum*[3]
\end{proof}

\lipsum[3]

\end{document}


text:
Q: How to change line width in ggplot? Datalink:
the data used
My code:
ccfsisims <- read.csv(file = "F:/Purdue University/RA_Position/PhD_ResearchandDissert/PhD_Draft/GTAP-CGE/GTAP_NewAggDatabase/NewFiles/GTAP_ConsIndex.csv", header=TRUE, sep=",", na.string="NA", dec=".", strip.white=TRUE)
ccfsirsts <- as.data.frame(ccfsisims)
ccfsirsts[6:24] <- sapply(ccfsirsts[6:24],as.numeric)
ccfsirsts <- droplevels(ccfsirsts)
ccfsirsts <- transform(ccfsirsts,sres=factor(sres,levels=unique(sres)))

library(ggplot2)

#------------------------------------------------------------------------------------------
#### Plot of food security index for Morocco and Turkey by sector
#------------------------------------------------------------------------------------------

#_Code_Begin...

datamortur <- melt(ccfsirsts[ccfsirsts$region %in% c("TUR","MAR"), ]) # Selecting regions of interest
datamortur1 <- datamortur[datamortur$variable %in% c("pFSI2"), ] # Selecting the food security index of interest
datamortur2 <- datamortur1[datamortur1$sector %in% c("wht","gro","VegtFrut","osd","OthCrop","VegtOil","XPrFood"), ] # Selecting food sectors of interest
datamortur3 <- subset(datamortur2, tradlib !="BASEDATA") # Eliminating the "BASEDATA" scenario results

allfsi.f <- datamortur3
fsi.wht <- allfsi.f[allfsi.f$sector %in% c("wht"), ]

Figure29 <- ggplot(data=fsi.wht, aes(x=factor(sres),y=value,colour=factor(tradlib)))
Figure29 + geom_line(aes(group=factor(tradlib),size=2)) + facet_grid(regionsFull~., scales="free_y", labeller=reg_labeller) + scale_colour_brewer(type = "div") +
theme(axis.text.x = element_text(colour = 'black', angle = 90, size = 13, hjust = 0.5, vjust = 0.5),axis.title.x=element_blank()) +
ylab("FSI (%Change)") + theme(axis.text.y = element_text(colour = 'black', size = 12), axis.title.y = element_text(size = 12, hjust = 0.5, vjust = 0.2)) +
theme(strip.text.y = element_text(size = 11, hjust = 0.5, vjust = 0.5, face = 'bold'))

My result:

Newresult with aes(size=2):

My question:
Is there a way to control for line width more precisely to avoid the result in the second plot? I particularly find it document-unfriendly, and more so for publishing purposes to include the plot with the newly defined line width.
best,
ismail

A: Line width in ggplot2 can be changed with argument size= in geom_line().
#sample data
df<-data.frame(x=rnorm(100),y=rnorm(100))
ggplot(df,aes(x=x,y=y))+geom_line(size=2)

A: If you want to modify the line width flexibly you can use "scale_size_manual," this is the same procedure for picking the color, fill, alpha, etc.
library(ggplot2)
library(tidyr)

x = seq(0,10,0.05)

df <- data.frame(A = 2 * x + 10,
                 B = x**2 - x*6,
                 C = 30 - x**1.5,
                 X = x)

df = gather(df,A,B,C,key="Model",value="Y")

ggplot( df, aes (x=X, y=Y, size=Model, colour=Model ))+
  geom_line()+
  scale_size_manual( values = c(4,2,1) ) +
  scale_color_manual( values = c("orange","red","navy") )

A: Whilst @Didzis has the correct answer, I will expand on a few points
Aesthetics can be set or mapped within a ggplot call.

*

*An aesthetic defined within aes(...) is mapped from the data, and a legend created.

*An aesthetic may also be set to a single value, by defining it outside aes().
As far as I can tell, what you want is to set size to a single value, not map within the call to aes()
When you call aes(size = 2) it creates a variable called `2` and uses that to create the size, mapping it from a constant value as it is within a call to aes (thus it appears in your legend).
Using size = 1 (and without reg_labeller which is perhaps defined somewhere in your script)
Figure29 +
    geom_line(aes(group=factor(tradlib)),size=1) +
    facet_grid(regionsFull~., scales="free_y") +
    scale_colour_brewer(type = "div") +
    theme(axis.text.x = element_text(
          colour = 'black', angle = 90, size = 13,
          hjust = 0.5, vjust = 0.5),axis.title.x=element_blank()) +
    ylab("FSI (%Change)") +
    theme(axis.text.y = element_text(colour = 'black', size = 12),
          axis.title.y = element_text(size = 12,
          hjust = 0.5, vjust = 0.2)) +
    theme(strip.text.y = element_text(size = 11, hjust = 0.5,
          vjust =    0.5, face = 'bold'))

and with size = 2
 Figure29 +
     geom_line(aes(group=factor(tradlib)),size=2) +
     facet_grid(regionsFull~., scales="free_y") +
     scale_colour_brewer(type = "div") +
     theme(axis.text.x = element_text(colour = 'black', angle = 90,
          size = 13, hjust = 0.5, vjust =
          0.5),axis.title.x=element_blank()) +
     ylab("FSI (%Change)") +
     theme(axis.text.y = element_text(colour = 'black', size = 12),
          axis.title.y = element_text(size = 12,
          hjust = 0.5, vjust = 0.2)) +
      theme(strip.text.y = element_text(size = 11, hjust = 0.5,
          vjust = 0.5, face = 'bold'))

You can now define the size to work appropriately with the final image size and device type.

A: Line width in ggplot2 can be changed with argument lwd= in geom_line().
geom_line(aes(x=..., y=..., color=...), lwd=1.5)

A: It also looks like if you just put the size argument in the geom_line() portion but without the aes() it will scale appropriately. At least it works this way with geom_density and I had the same problem.

A: Just add the size command outside the aes() function, with any fractional value desired, e.g. size = 1.5
geom_line(data,aes(x=x,y=y), size=1.5)


text:
Q: Fast method to get a unique identity for video files I need a unique hash for video files, which can handle the following:
- Change in filename
- Change in file location
- Two files with exactly the same filesize, but different contents within (should be treated as different files)
Now while the hashing algorithms like md5, sha1 seem to be a good candidate, I need something which takes fraction of seconds to produce.
On a 2GB video file, it takes 5 sec to produce the md5 checksum value.
I assume the long processing time is natural because of having to read the large video file.
Is there something I could use, which specifically utilizes the properties of video files, maybe does the comparison just using video file headers or something. Goal here is to obtain the unique video id in fraction of seconds.

A: As a first approach, I would consider taking crc32 from first 10 Mb plus maybe file size. You will have collisions with this method and will need to handle them but all hashing algorithms have collisions.
UPDATE
Alternatively you can use utility ffprobe (which comes with ffmpeg) to get video headers and compute md5 from them. But running it as a process will be slow and it seems it doesn't exist as a python library to import.


text:
Q: SpringSecurity using memory authentication don't returns error 403 in http put method I don't receive the error 403 in http "put" method using SpringSecurity in memory authentication. The method returned 200 when it should return 403.
The same code using http "post" method works normally.
Note the exemple:
The Websecurity configuration:
@Configuration
public class WebSecutiryConfigurer extends WebSecurityConfigurerAdapter {

    @Override
    @Bean
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Override
    @Bean
    protected UserDetailsService userDetailsService() {
        return super.userDetailsService();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(passwordEncoder()).withUser("11111111111")
                .password(passwordEncoder().encode("minhasenha")).roles("Administrador").and().withUser("22222222222")
                .password(passwordEncoder().encode("minhasenha")).roles("Consulta");
    }

}

This is my ResourceServerConfigurerAdapter:
@Configuration
public class ResourceServerConfigurer extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {

         http
          .csrf().disable()
            .authorizeRequests()

                .antMatchers(HttpMethod.GET, "/v1/cnaes").hasAnyRole("Administrador", "Alteracao", "Consulta")
                .antMatchers(HttpMethod.POST, "/v1/cnaes").hasRole("Administrador")
                .antMatchers(HttpMethod.DELETE, "/v1/cnaes").hasRole("Administrador")
                .antMatchers(HttpMethod.PUT, "/v1/cnaes/delete").hasRole("Administrador")
                .antMatchers(HttpMethod.PUT, "/v1/cnaes").hasRole("Administrador")

              .and()
                .anonymous().disable()
                .exceptionHandling();

    }
}

This is my method in a test class:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class CnaeTeste {

    @LocalServerPort
    private int port;

    private String urlGeracaoToken = "http://localhost:8088/oauth/token";

    private String oauthTokenPerfilAdministrador;
    private String oauthTokenPerfilConsulta;

    @Before
    public void setup() {

        RestAssured.baseURI = "http://localhost:5555/mysystem/v1/cnaes";

    }

    @Before
    public void autenticarPerfilAdministrador() {

        Response response = RestAssured.given().auth().basic("usuario-bearer", "omissospj-pwd-bearer")
                .formParam("scope", "intranet").formParam("username", "07068684718").formParam("password", "minhasenha")
                .formParam("grant_type", "password").when().post(this.urlGeracaoToken);
        this.oauthTokenPerfilAdministrador = response.jsonPath().get("access_token");

    }

    @Before
    public void autenticarPerfilConsulta() {

        Response response = RestAssured.given().auth().basic("usuario-bearer", "omissospj-pwd-bearer")
                .formParam("scope", "intranet").formParam("username", "22222222222").formParam("password", "minhasenha")
                .formParam("grant_type", "password").when().post(this.urlGeracaoToken);
        this.oauthTokenPerfilConsulta = response.jsonPath().get("access_token");

    }

    @Test
    public void falhaAtualizarQuandoUsuarioPerfilAlteracaoStatusCode403() throws Exception {

        // insert
        Cnae cnae = new Cnae(0L, "2222222", "CNAE de Teste - Criada - Perfil Administrador", false);

        ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
        String json = ow.writeValueAsString(cnae);

        Response responseInclusao = RestAssured.given()
                .headers("Authorization", "Bearer " + this.oauthTokenPerfilAdministrador, "Content-Type",
                        ContentType.JSON, "Accept", ContentType.JSON)
                .body(json).when().post();

        Assertions.assertThat(responseInclusao.getStatusCode()).isEqualTo(201);

        // update
        String stringResponse = responseInclusao.getBody().asString();
        JSONObject jsonObject = new JSONObject(stringResponse);
        String idCadastrado = jsonObject.getString("id");
        Long idAtualizado = Long.parseLong(idCadastrado);

        cnae = new Cnae(idAtualizado, "2222222", "CNAE de Teste - Atualizada - Perfil Alteração", false);

        ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
        json = ow.writeValueAsString(cnae);

        Response responseAlteracao = RestAssured.given().headers("Authorization",
                "Bearer " + this.oauthTokenPerfilConsulta, "Content-Type", ContentType.JSON, "Accept", ContentType.JSON)
                .body(json).when().put("/" + idCadastrado);

        Assertions.assertThat(responseAlteracao.getStatusCode()).isEqualTo(403);

        // delete
        Response responseExcluir = RestAssured.given()
                .headers("Authorization", "Bearer " + this.oauthTokenPerfilAdministrador, "Content-Type",
                        ContentType.JSON, "Accept", ContentType.JSON)
                .when().delete("/" + idCadastrado).then().extract().response();

        Assertions.assertThat(responseExcluir.getStatusCode()).isEqualTo(200);

    }
}

I'm receive the 200 status code, when I expect to receive 403:
Assertions.assertThat(responseAlteracao.getStatusCode()).isEqualTo(403);

Any suggestion?

A: Is it also failing for delete, or only put?
Your put is directed to the url  http://localhost:5555/mysystem/v1/cnaes/idCadastrado
but you only match for /v1/cnaes :
.antMatchers(HttpMethod.PUT, "/v1/cnaes").hasRole("Administrador")
Maybe you need to ensure that other requests be authenticated:
.antMatchers(HttpMethod.PUT, "/v1/cnaes/**").authenticated() or
.antMatchers(HttpMethod.PUT, "/v1/cnaes/**").hasRole("Administrador") or
.anyRequest().hasRole("Administrador") (place at the end after adding all other antMatchers)
It should still fail if there is no mapping in your controller to /v1/cnaes/:id, but I cannot see your controller entry points in the code you provided. I imagine that if the entry point exists, with the security level of @PreAuthorize("permitAll"), then you are successfully invoking it.


text:
Q: Avoid loading event chains in javascript I have a problem in my code where many entities have async loading procedures and can't be used until these are complete. There are chains of these dependencies.
So A->B->C where A needs B needs C.
I have written code like
class B{
  constructor(callback){
    this.loaded=false
    this.load(callback)
  }
  load(callback){
    ...do stuff
    this.loaded=true
    callback()
  }
}

class A{
  constructor(){
    this.loaded=false
    this.b=new B(()=>{this.loaded=true})
  }
}

This seems really bad. Can anyone suggest a better solution?

A: Usually, it is a bad practice to perform async task directly in constructor (as stated here). With this taken in account, you can follow VLAZ advice and start using promises.
You would then have something like this:
class B {
  constructor() {
    this.loaded = false
  }

  load() {
    return new Promise((resolve =>  {
      this.loaded = true;
      // do stuff
      return resolve()
    }))
  }
}

class A {
  constructor() {
    this.loaded = false
  }

  load() {
    return new Promise(resolve => {
      this.b = new B()
      this.loaded = true
      return resolve(this.b)
    })
  }
}

// Use it like this
const a = new A()

a.load()
  .then(b => b.load())
  .then(/* and so on */)


text:
Q: WhiteLabel error page while trying to access swagger-ui.html using springfox configuration I am trying to generate Swagger documentation from a springboot project using Springfox and following https://www.baeldung.com/swagger-2-documentation-for-spring-rest-api documentation.
Initially I got the error "Full authorization is required to access the resource" since I am using OAuth2 in my application. I changed the configuration to permit all the requests ending with /swagger-ui.html.
Now I have been getting "WhiteLabel error page - This application has no explicit mapping for /error" while trying to access /swagger-ui.html on my local.
I went through various posts but none of the solutions worked for me - I am not using @webmvcconfiguration which can interfere.
Can anyone help?

A: For Swagger 3.0, The URL is changed to
http://localhost:8080/swagger-ui/index.html

A: *

*Remove the v2 dependencies from your pom.xml or comment them out.
 <dependency>
     <groupId>io.springfox</groupId>
     <artifactId>springfox-swagger2</artifactId>
     <version>3.0.0</version>
 </dependency>

 <dependency>
     <groupId>io.springfox</groupId>
     <artifactId>springfox-swagger-ui</artifactId>
     <version>3.0.0</version>
 </dependency>

*Add the springfox-boot-starter
 <dependency>
     <groupId>io.springfox</groupId>
     <artifactId>springfox-boot-starter</artifactId>
     <version>3.0.0</version>
 </dependency>

*Change the URL in your browser to:
http://localhost:8080/swagger-ui/index.html
The general form for the URL is:

*

*http://host/context-path/swagger-ui/index.html
OR

*http://host/context-path/swagger-ui/

For more info check this link that leads to the relevant documentation:
https://springfox.github.io/springfox/docs/snapshot/#changes-in-swagger-ui

A: This is how I solved my problem. Here is my detailed code, if someone want to look.
https://github.com/xbox2204/SpringBoot-JPA-Swagger
Now, I used 3.0.0-SNAPSHOT and a latest spring-boot starter project I created from here:
https://start.spring.io/

*

*My pom.xml, I added following dependencies:

    <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>3.0.0-SNAPSHOT</version>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.plugin</groupId>
                    <artifactId>spring-plugin-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>3.0.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.plugin</groupId>
            <artifactId>spring-plugin-core</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>

*In my application.properties, I added following:

spring.resources.add-mappings=true

*In my SpringBoot Main/Runner class, I added these annotations

@EnableWebMvc
@EnableSwagger2
@SpringBootApplication

*My Docket returning function looked like this

@Bean
    public Docket productApi() {
        Contact contact =new Contact(
                "Vineet Mishra",
                "https://github.com/xbox2204",
                "whatwillyoudo@withmyemail.com"
        );
        ApiInfo apiInfo= new ApiInfoBuilder().title("VINEET SPRING-BOOT API")
                .description("Spring-Boot for all")
                .termsOfServiceUrl("jUST CHILL!!!")
                .contact(contact)
                .licenseUrl("something@something.com").version("1.0").build();

        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo)
                .select()
                .apis(RequestHandlerSelectors.any())
                .build();
    }

*Finally, I accessed my swagger-ui from

http://localhost:8080/swagger-ui/index.html#
Image of final result

A: The swagger-ui.html page makes a number of calls to get all the details. If you use your browser's dev tools (usually just press F12 to open) you will see failing requests in the network tab. You'll need to permit requests to
    "/v2/api-docs",
    "/swagger-resources/**",
    "/swagger-ui.html**",
    "/webjars/**"

There's some info in the springfox docs , do a find for 'security' or 'authorization'


text:
Q: "if (fn) fn()" or "fn && fn()" I've seen many times that fn && fn() is an optimization of if (fn) fn().
My question are: why? and, what is the generated code for both solutions?

A: So, by if (fn) fn(), you want make sure fn is existing before executing it. the if condition checks a Boolean value or expression, in JavaScript any falsy value could turn to a false value in the if Boolean checking condition. Falsy values could be:

*

*false

*null

*undefined

*The empty string ''

*The number 0

*The number NaN (yep, 'Not a Number' is a number, it is a special
number)

any other value will be a truthy value.
So, if the fn is either a null or undefined value, the if checking will protect you from executing a non-function object.
By fn && fn(), you are doing the same: in JavaScript, Boolean expression is lazy checked which means if the first part, in an && operation, is falsy then the second part would not be executed. So, with this feature, you could protect your code from executing a non-function object.
fn && fn() is not an optimized version of the other one in terms of performance but is a short version in written.
Both code snippets require a precondition: the function fn could be either not defined or an actual function object. If in your code, the fn has the possibility of being an object of other types, such as a string, you need add type check before executing, such as:
if (fn instanceof Function) fn()

A: The && operator in JavaScript is short-circuited, meaning that if the left-hand side is false, the right-hand side isn't evaluated at all. That's why fn && fn() is safe even if fn is falsey (null, undefined, etc.).
The "code generated" will depend entirely on the JavaScript engine, but I'd expect it to be quite similar in both cases (the && and the if).
It's not an "optimization" in the sense of running faster, but rather in the sense of being shorter to write (particularly so if, like me, you never leave {} off if statements). It has the downside of being slightly less clear to people who are new to the language, but it's an idiom quickly learned.

A: In terms of optimization, IMHO, I would say its because its a better way of making it a one line if then, without having to sacrifice braces and compromising readability, but it wouldn't make the code execute any faster


text:
Q: Making a syntax parser (part of a compiler in C++) I'm making a compiler, written in C++.
Currently, it takes text from an input file in the same folder, and I can successfully strip out all the strings of contiguous characters, isolate by type of character/keyword/identifier (i.e. it recognizes 'int' and 'bool' as keywords, and it stores the 'word' in a vector of strings while it stores the 'token type' as an int in a vector of ints at the same index).
So I'm currently at the phase where I have all the input stored and categorized, ready to check the syntax.
...I think I have a good grasp of the theory, but all the methods I've come up with to parse the syntax have serious failings. For reference, this is the structure that should be able to handle any construction of assignment or declaration statements, starting with a generic Statement:
<Statement> -> <Declarative>
<Declarative> -> <Type> <id>

<Statement> -> <Assign>
<Assign> -> <ID> = <Expression>;

<Expression> -> <Expression> + <Term> | <Expression> - <Term> | <Term>

<Term> -> <Term> * <Factor> | <Term> / <Factor> | <Factor>

<Factor> -> ( <Expression> ) | <ID> | <num>

<ID> -> id

My goal is for the compiler to be able to read each token in sequence, and tell what Expression/Term/Factor/ID it is, in the order it was read.
I'm still trying to come up with a function to parse the grammar of a given statement. Is there a way to make it 'inline' or '1 token at a time,' or am I stuck? I'm trying to design this before I try to debug something that doesn't work - so I hope the general design of my pseudocode can tell you what I'm doing wrong.
and things in <angle brackets> are token types
Method A: "whole line" - reads 1st token in line, looks ahead to find ';' and manipulate  from there

*

*able to grab whole of <expression>

*won't be able to individually label tokens in order

until reach end of file (while loop)
   determine statement type (if)
   if the <type> and <id> are the same, the immediate next step to be taken is the same
      need to determine length of statement to be parsed (find start and end of current 'line')
      in <type> and <id> cases, it should be 'current' to 'index of next ;' (length of statement should be from <type> or <id> to the next ';')
   if <type>, should be easy - target format is <type> <id>;
      if token pattern matches that, then is valid, and is noted as such in output
   if <id>, more complex, is assignment
      if token 0 is <id>, token 1 (=) and token 'index' (;) should be the same every time
         between 1 and 'index' is the <expression> to evaluate

...and I don't know how I can evaluate the <expression> portion, given that it will need to be some kind of recursion
Method B: "save state" - function gets fed some input that states what the previous 'state' of the statement was

*

*possible to evaluate token-by-token

*... but I don't know how I'm going to evaluate an <expression> without peeking ahead to check if there's an operator token, which is the big deal of the whole exercise

until reach end of file (while loop)
   get passed int to represent previous state, determine current token
      if 0, the statement is starting
         if <type>, expect to be a declaration statement
            return 1
         else if <id>, expect assignment statement
            return 3
      if 1, <type> found previously
         if current token is <id>
            return 2
      if 2, <type> <id> found previously
         if current token is ';'
            return 0, statement complete
      if 3, <id> found previously
         if current token '='
            return 4
      if 4, <id> = found previously
         expression needs evaluation, expect rat's nest of code here

That's all I have so far.
Addendum: Method C, which is an idea I had, just now, which seems very messy:
Adding something like 4 different functions, all of which can call each other:
function 1 - to read/determine if it's a declaration or assignment statement
function 2 - to determine if an Expression is addition, subtraction, or a Term
function 3 - to determine if a Term is multiplication, division, or a Factor
function 4 - to determine if a Factor is an expression but in parenthesis, an identifier, or a number

This last method seems like it's going to be very vulnerable to huge recursion and memory leaking, but it also seems more easy to isolate problems.

A: As was already pointed out in the comments, your method C is known as recursive descent and is the way to go, but can't handle left recursion. So how to deal with that?
You can rewrite your grammar to remove the left recursion and you'd come up with something like this:
<Expression>     -> <Term> <ExpressionTail>
<ExpressionTail> -> + <Term> <ExpressionTail> | - <Term> <ExpressionTail> | ε

If you directly translated this into code, you'd end up with something like:
Expression* parseExpression() {
    Expression* operand = parseTerm();
    ExpressionTail* tail = parseExpressionTail();
    return new Expression(operand, tail);
}

ExpressionTail* parseExpressionTail() {
    if (current token is '+' or '-') {
        char operator = current token;
        move to next token;
        Expression* operand = parseTerm();
        ExpressionTail* tail = parseExpressionTail();
        return new OperatorExpressionTail(operator, operand, tail);
    } else {
        return new EmptyExpressionTail();
    }
}

There's a couple of problems with that though:
First of all the rewritten grammar is decidedly less readable than the original. Of course you could avoid this problem by documenting one version of the grammar and implementing another one, but the structure of the code still contains the same complexity. Having separate parseFooTail() methods for every level of left-recursive definitions can sure be annoying and clutter up the code.
The most important caveat, however, is the structure of the tree we're generating: In the above code the generated tree is directly based on the rewritten grammar and will not look like one for the original grammar would. This tree is unwieldy to work with because we can't even directly access the right operands of an operator - we have to iterate over the tail pointers instead. What we'd want is to generate a tree where each infix expression is represented as a node with an operator and two operands just like in the original grammar.
To do that we could replace return new Expression(operand, tail) with code that iterates over the tail and constructs a proper expression tree from that. Or we could get rid of the ExpressionTail structure altogether and generate that tree directly inside parseExpressionTail by passing the left operand along as an argument:
Expression* parseExpression() {
    Expression* operand = parseTerm();
    return parseExpressionTail(operand);
}

Expression* parseExpressionTail(Expression* leftOperand) {
    if (current token is '+' or '-') {
        char operator = current token;
        move to next token;
        Expression* rightOperand = parseTerm();
        Expression* newLeftOperand = new InfixExpression(operator, leftOperand, rightOperand);
        return parseExpressionTail(newLeftOperand);
    } else {
        return leftOperand;
    }
}

Now this will produce the kind of tree we want, but it's still not particularly nice to read. One thing you might notice is that parseExpressionTail is now tail-recursive, which means that it can easily be rewritten as a loop. Once we did that the function will no longer be directly recursive, so it can be inlined into parseExpression. So let's do that:
Expression* parseExpression() {
    Expression* leftOperand = parseTerm();
    while (current token is '+' or '-') {
        char operator = current token;
        move to next token;
        Expression* rightOperand = parseTerm();
        expression = new InfixExpression(operator, leftOperand, rightOperand);
    }
    return leftOperand;
}

If we look back at the grammar, we might notice that expressionTail could best be described as "match the pattern (+ | -) <Term> zero or more times". So if we introduce a repetition operator (like * in regular expressions or {} as used in EBNF) into our grammar notation, we can rewrite it as
<Expression> -> <Term> ((+ | -) <Term>)*

or
<Expression> -> <Term> {(+ | -) <Term>}

depending on which notation you prefer. Now if you write your grammar using this notation in the first place, you can come up with the above code in a more direct way than by first writing it recursively and then re-writing the tail recursion: You could write your grammar using repetition operators wherever it makes sense and then simply use a while loop wherever you see a repetition operator when translating the grammar into code.
Now we've arrived at a perfectly feasible way of parsing infix expressions in a recursive descent parser, but having a separate parseFoo method for each level of precedence can still become annoying once you have a lot of levels of precedence and the same goes for having a non-terminal in the grammar for every level of precedence. On the grammar level, we can solve this by simply writing the grammar ambiguously like this:
<Expression> -> <Expression> + <Expression>
              | <Expression> - <Expression>
              | <Expression> * <Expression>
              | <Expression> / <Expression>
              | <Factor>

You can then disambiguate it by listing each operator's precedence and associativity separately from the grammar. For the parser code we'd want to do the same thing: Have a table containing each operator and its precedence and associativity and then have a single function that can parse all infix expressions by simply going through that table.
The way to accomplish that would be to use recursive descent for everything else, but use a specialized algorithm inside the function that parses infix expressions, such as precedence climbing (see this blog post by Eli Bendersky and/or the explanation on Wikipedia).


text:
Q: Passing SSM Parameter Via Environment Variable VS Fetching SSM Parameter Directly From Spring Properties Basically I have a service that is fetching a variable and placing it on my AWS account Parameter Store.
From here I have my services (running on that same account) fetch the parameter via the CloudFormation template and passing it to the container of the service as an Environment Variable.
After this, I fetch this environment variable in my Spring Boot application.properties file and then create a class that uses this environment variable.

Yet, while doing this, I discovered that there is another way to fetch SSM parameters and bypassing this process of fetching it via CloudFormation and passing it to the container as an environment variable.
Apparently the SSM parameter can be fetched directly from Spring Boot's Application Properties file and made, therefore, available to the service (As exemplified in the diagram below)

Now my question is, is there a recommended best practice for this process? Which would be the most correct way to fetch the SSM parameters? Via CloudFormation or directly via Properties file?
In either case, what are the advantages and disadvantages of either approach?
Thank you in advance for all answers/input.


text:
Q: How can I get an automatic refresh when I click a button on Angular? I'm building a chat application. All works fine; however, when I click send, the message isn't displayed until I manually reload the page.
I think I'm missing something after the subscribe.
    onSubmit() {
    this.chatService
      .sendMessage(
        'https://db_url/message.json',
        {
          message: this.chatForm.value.message,
          username: this.authService.user.displayName,
        }
      )
      .subscribe((data) => {
        // ...

        console.log(data);
      });

    this.chatForm.reset();
  }

Could someone point out what I might be missing or doing wrong in my code? Thank you.

A: You can try storing the subscribed data in a messages array like
 messages: Array<Message> = []; and then subscribe to it on the onInit() method, and display the messages maybe with <div *ngFor="let message of messages | slice: ind:messages.length"> (or just display it on the console, whatever you want).
It may also be because of subscribing to the sendMessages function instead of the getMessages? (without reading the rest of the code, I can't tell exactly)


text:
Q: How to print the update query which is going to execute in laravel 5.1 This is my code
$id = "'".str_replace(",","','",$id)."'";   //'7','8','9'
DB::update("UPDATE `category`
            SET status = if(status = 'active', 'inactive', 'active')
            WHERE cid in (?)", [$id]);

I need to print this update query in laravel5.1.

A: You can use Laravel method DB::enableQuerylog() & DB::getQuerylog() like as
DB::enableQuerylog();
$id = "'".str_replace(",","','",$id)."'";   //'7','8','9'
DB::update("UPDATE `category` SET status = if(status = 'active', 'inactive', 'active') WHERE cid in (?)", [$id]);
dd(DB::getQuerylog());


text:
Q: Which of these 2 MySQL DB Schema approaches would be most efficient for retrieval and sorting? I'm confused as to which of the two db schema approaches I should adopt for the following situation.
I need to store multiple attributes for a website, e.g. page size, word count, category, etc. and where the number of attributes may increase in the future. The purpose is to display this table to the user and he should be able to quickly filter/sort amongst the data (so the table strucuture should support fast querying & sorting). I also want to keep a log of previous data to maintain a timeline of changes. So the two table structure options I've thought of are:
Option A
website_attributes
id, website_id, page_size, word_count, category_id, title_id, ...... (going up to 18 columns and have to keep in mind that there might be a few null values and may also need to add more columns in the future)
website_attributes_change_log
same table strucuture as above with an added column for "change_update_time"
I feel the advantage of this schema is the queries will be easy to write even when some attributes are linked to other tables and also sorting will be simple. The disadvantage I guess will be adding columns later can be problematic with ALTER TABLE taking very long to run on large data tables + there could be many rows with many null columns.
Option B
website_attribute_fields
attribute_id, attribute_name (e.g. page_size), attribute_value_type (e.g. int)
website_attributes
id, website_id, attribute_id, attribute_value, last_update_time
The advantage out here seems to be the flexibility of this approach, in that I can add columns whenever and also I save on storage space. However, as much as I'd like to adopt this approach, I feel that writing queries will be especially complex when needing to display the tables [since I will need to display records for multiple sites at a time and there will also be cross referencing of values with other tables for certain attributes] + sorting the data might be difficult [given that this is not a column based approach].
A sample output of what I'd be looking at would be:
Site-A.com, 232032 bytes, 232 words, PR 4, Real Estate [linked to category table], ..
Site-B.com, ..., ..., ... ,...
And the user needs to be able to sort by all the number based columns, in which case approach B might be difficult.
So I want to know if I'd be doing the right thing by going with Option A or whether there are other better options that I might have not even considered in the first place.

A: I would recommend using Option A.
You can mitigate the pain of long-running ALTER TABLE by using pt-online-schema-change.
The upcoming MySQL 5.6 supports non-blocking ALTER TABLE operations.
Option B is called Entity-Attribute-Value, or EAV.  This breaks rules of relational database design, so it's bound to be awkward to write SQL queries against data in this format.  You'll probably regret using it.
I have posted several times on Stack Overflow describing pitfalls of EAV.
Also in my blog: EAV FAIL.

A: Option A is a better way ,though the time may be large when alert table for adding a extra column, querying and sorting options are quicker. I have used the design like Option A before, and it won't take too long when alert table while millions records in the table.

A: you should go with option 2 because it is more flexible and uses less ram. When you are using option1 then you have to fetch a lot of content into the ram, so will increases the chances of page fault. If you want to increase the querying time of the database then you should defiantly index your database to get fast result

A: I think Option A is not a good design. When you design a good data model you should not change the tables in a future. If you domain SQL language, using queries in option B will not be difficult. Also it is the solution of your real problem: "you need to store some attributes (open number, not final attributes) of some webpages, therefore, exist an entity for representation of those attributes"

A: Use Option A as the attributes are fixed. It will be difficult to query and process data from second model as there will be query based on multiple attributes.


text:
Q: Developing email client apps in Windows Phone 7 in C# I am starting  windows phone 7 programming. For one of  my program I need to send email. For example I want to send email using google. For desktop application is can do it. For Windows Phone 7 I found  EmailComposeTask term for related on this. But I don't know how to login or sending email using this. I find some code in net but those are not working also. Here is the code:
EmailComposeTask emailcomposer = new EmailComposeTask();
emailcomposer.To"test@ginktage.com";
emailcomposer.Subject = "subject from test app";
emailcomposer.Body = "This is a test mail from Email Composer";
emailcomposer.Show();

But here from which email client the mail is send?
What will be the solution?

A:
i find some code in net but those are not working also.here is the
  code.........but here from which email client the mail is send?

The phone would launch the installed email client.  I would assume if Windows Phone is anything like Android this would depend on which application the user selected as the default.
Have you actually ran this code to see what it does.  What you are trying to do is not 100% clear.  What you have right now would simply offer the user to send an email likely using THEIR system email account, certainly would not use your google mail account, or even be guaranteed to use a google account.

A: You are actually facing problems because the emulator is feature locked. This question is a repeat of: How to setup email account on Windows Phone 7 emulator? .


text:
Q: Executing C++ object file on web server While working on localhost, I am executing C++ object file from php file using exec() call. The object file then send request to daemon process, which is also one executable file;works as server(I need to execute it manually so that it remains in listening mode i.e. ./server).
Now I want to put my php file as a website on internet. Do I need any specific hosting plan or general plan like enter link description here is sufficient?
My needs are php, mysql, ajax, jquery, JS, Executing c, c++ files!

A: This isn't really a c++ question.
Make sure you have the right permissions to execute the file. Remember, php executes as the www-data user.
chmod a+x to grand everyone execution permissions.
Then add the location of ./server in your path and simply exec() it.


text:
Q: How can I take a reference to specific hash value in Perl? How do I create a reference to the value in a specific hash key.  I tried the following but $$foo is empty.  Any help is much appreciated.
$hash->{1} = "one";
$hash->{2} = "two";
$hash->{3} = "three";

$foo = \${$hash->{1}};
$hash->{1} = "ONE";

#I want "MONEY: ONE";
print "MONEY: $$foo\n";

A: use strict;
use warnings;
my $hash;

$hash->{1} = "one";
$hash->{2} = "two";
$hash->{3} = "three";

my $foo = \$hash->{1};
$hash->{1} = "ONE";
print "MONEY: $$foo\n";

A: Turn on strict and warnings and you'll get some clues as to what's going wrong.
use strict;
use warnings;

my $hash = { a => 1, b => 2, c => 3 };
my $a = \$$hash{a};
my $b = \$hash->{b};

print "$$a $$b\n";

In general, if you want to do things with slices or taking refs, you've got to use the old style, piled sigil syntax to get what you want.  You may find the References Quick Reference handy, if you don't recall the piled sigil syntax details.
update
As murugaperumal points out, you can do my $foo = \$hash->{a};  I could swear I tried that and it didn't work (to my surprise).  I'll chalk it up to being fatigue making me extra foolish.

A: a classic, and yet the examples don't seem to be complete until you illustrate it both ways
use strict;
use warnings;

my $hash = { abc => 123 };
print $hash->{abc} . "\n"; # 123 , of course

my $ref = \$hash->{abc};
print $$ref . "\n"; # 123 , of course

$hash->{abc} = 456;
print $$ref . "\n"; # 456 , change in the hash reflects in the $$ref

$$ref = 789;
print $hash->{abc} . "\n"; # 789 , change in the $$ref also reflects in the hash

PS: despite being an old topic, I decided to throw my two cents, since I saw I've visited this same question before


text:
Q: Correct way to use DbConnection, DbTransaction with connection pooling, transactionScope and dependency injection? I have a Oracle database and I'm using the Oracle.ManagedDataAccess.
In some cases I will need to do actions in a single transactions, but often not.
I'm not sure what the best way to handle DbConnection objects within a single TransactionScope.
I could inject a DbConnection into the repositories and then even use LifetimePerScope to ensure they all get the same DbConnection instance. But is that a smart move, is it ok to .Open() the connection once.
using (var scope = _lifetimeScope.BeginLifetimeScope())
{
    var connection = scope.Resolve<IDbConnection>();
    var personRepo = scope.Resolve<IPersonRepository>();
    var workRepo = scope.Resolve<IWorkRepository>();
    connection.Open();
    var transaction = connection.BeginTransaction()
    personRepo.DeleteById(someId);
    workRepo.DeleteByPersonId(someId);
    transaction.Commit();
}

This would force me to always use a LifetimeScope, even if not using a Transaction, and open the connection outside the repository method.
Are TransactionScopes dependent on a single connection or can I open multiple connections (how does the connectionPool handle that while a transaction is open?) within the same transaction?
I'm a total outsider to DbConnections and all that so I might be totally misunderstanding the best way to use TransactionScope and DbConnections.

A: Possible duplicate of: Why always close Database connection?
Since this has a bounty, I can't flag it as a duplicate :(
Anyway, connection pooling is largely done for you.  You should close connections as soon as you can, to return them to the pool.
Transactions are related to a specific open connection and should be finished when closing the connection.

A: TransactionScope related to BeginTransaction() is specific to a connection.
If you want to maintain a transaction across multiple connections(multiple DBs,resources), then you need DTC aware TransactionScope. Here is a similar SO post.  You need to use Oracle.ManagedDataAccessDTC.dll to facilitate that.
You might want to go through these links:
1.All about transactionscope
2.How To Configure DTC to Support Oracle Transactions
Hope this helps.