text:
Q: plesk: how to configure reverse proxy rules properly? [edit]: FWI, thanks to Vadym's comment below, I discovered that I had overlooked to enable mod_proxy_http on my Plesk server. Loading this module (alongside mod_proxy) fixed the original error.
I'm trying to configure reverse proxy rules in vhost.conf. I have Apache-2.2.8 on Ubuntu-8.04, monitored by Plesk-10.4.4.
What I'm trying to achieve is defining a reverse proxy rule that defers all traffic to -say- http://example.com/tomcat/ to the Tomcat server running on port 8080. I have mod_rewrite and mod_proxy loaded in Apache. As far as I understand mod_proxy docs, entering following rules in /var/www/vhosts/mydomain/conf/vhost.conf should work:
<Proxy *>
  Order deny,allow
  Allow from all
</Proxy>

ProxyRequests off
RewriteRule ^/tomcat/(.*)$ http://example.com:8080/$1 [P]

Yet, I am getting a HTTP 500: internal server error when requesting above URL. (Note: I decided to use a rewrite rule in order to at least get some information logged.)
I have made mod_rewrite log extensively, and find following entries in the logs [note: due to a limitation of max. 2 URLs in posts of new users, I have modified all following URLs so that they only contain 1 slash after http:. In case you're suspecting typos: this was done on purpose):
192.0.2.23 - - [19/Mar/2012:16:42:59 +0100] [example.com/sid#b06ab8][rid#1024af8/initial] (2) init rewrite engine with requested uri /tomcat/testApp/
192.0.2.23 - - [19/Mar/2012:16:42:59 +0100] [example.com/sid#b06ab8][rid#1024af8/initial] (3) applying pattern '^/tomcat/(.*)$' to uri '/tomcat/testApp/'
192.0.2.23 - - [19/Mar/2012:16:42:59 +0100] [example.com/sid#b06ab8][rid#1024af8/initial] (2) rewrite '/tomcat/testApp/' -> 'http:/example.com:8080/testApp/'
192.0.2.23 - - [19/Mar/2012:16:42:59 +0100] [example.com/sid#b06ab8][rid#1024af8/initial] (2) forcing proxy-throughput with http:/example.com:8080/testApp/
192.0.2.23 - - [19/Mar/2012:16:42:59 +0100] [example.com/sid#b06ab8][rid#1024af8/initial] (1) go-ahead with proxy request proxy:http:/example.com:8080/testApp/ [OK]

This suggests that the rewrite and proxy part is processed ok; still the proxied request produces a 500 error. Yet:

*

*Addressing the testApp directly via http://example.com:8080/testApp does work.

*The same setup does work on my local computer.

Is there something else (Plesk-related, perhaps?) I should configure?

A: Are there any clues within ErrorLog?
Have you tried the same thing without mod_rewrite (just mod_proxy) like this:
  <Location /tomcat>
    ProxyPass http://example.com:8080/
    ProxyPassReverse http://example.com:8080/
  </Location>


text:
Q: Justifying summation factoring In my notes I have this formula ($\mu_P,\mu_Q$ here is the Möbius function and $[x,x'],[y,y']$ are intervals in locally finite Posets P,Q).
$$\sum_{x\leq u \leq x',y\leq v \leq y'}\mu_P(u,x)\mu_Q(y,v)=\left(\sum_{x\leq u \leq x'}\mu_P(x,u)\right)\left(\sum_{y\leq v \leq y'}\mu_Q(y,v)\right)$$
It's glossed over like something completely obvious, but I can't quite see it. I guess LHS is somethink like adding ''squares'' (''areas'') and the RHS is like adding's lengths first, then multiplying them to get the same ''area'' but I can't justify it rigorously.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Expand a variable and wrap it in quotes Consider this snippet:
$foo = "b a r"
Some-Cmdlet -MyParam $foo

I'd like to pass b a r as -MyParam parameter. It obviously won't work because the call will evaluate to:
Some-Cmdlet -MyParam b a r

and spaces will split the parameter into 3 separate characters. I could add quotes like this:
Some-Cmdlet -MyParam '"'+$foo+'"'

but I was wondering if there's a way to add the quotes without concatenating them while expanding the variable. In other words: without using +. Probably something like this:
Some-Cmdlet -MyParam "\"$foo\""

had \ been an escape operator.

A: Your assumption about the interpretation of the string is incorrect.  If you pass a string, it stays a string.
Function '/a r g 1'
"$($Args[0])"
> /a r g 1


text:
Q: How do I correctly iterate through an object in render? Hi I have an object that I'm trying to iterate through:
this.props.recentMessages = {
    '4383456789': {
          'number': '4383456789',
          'created': 1531142643,
          'text': "Hello World"
     },
    '5141234567': {
          'number': '5141234567'
          'created': 1531173846
          'text': "This is the second text"
     }
}

But the problem I get right now is that it says that this.props.recentMessages.map is not a function so I'm not sure how I would correct iterate through as I was able to successfully iterate through an array of strings earlier. I want to check that this.props.recentMessages exist first before I iterate through it.
render() {
  return (

      <LeftNav className="chat-left-nav">
        {this.props.recentMessages
          ? this.props.recentMessages.map(function(thread, index) {
              <LeftNavSC.Item>

                  {thread.number}

              </LeftNavSC.Item>;
            })
          : ""}
      </LeftNav>

  );
}

A: You can't iterate over an object with map the same way you do with an array. You could use Object.keys to get an array of all the keys in the object, and map over that:
render() {
  const { recentMessages } = this.props;

  return (

      <LeftNav className="chat-left-nav">
        {recentMessages &&
          Object.keys(recentMessages).map(key => (
            <LeftNavSC.Item key={key}>

                {recentMessages[key].number}

            </LeftNavSC.Item>
          ))}
      </LeftNav>

  );
}

A: Objects in JavaScript don't come with map function but you can use Object.entries to get an array of key-value pairs which you can iterate.
{Object.entries(this.props.recentMessages).map(([key, thread]) => {
  <LeftNavSC.Item>

      {thread.number}

  </LeftNavSC.Item>;
})}

Down below you can see what Object.entries returns from your sample data:

const entries = Object.entries({
  '4383456789': {
    'number': '4383456789',
    'created': 1531142643,
    'text': "Hello World"
   },
  '5141234567': {
    'number': '5141234567',
    'created': 1531173846,
    'text': "This is the second text"
   }
})

console.log(entries)

In order to prevent getting errors while iterating non-existing collection you can use short-circuiting && operator or use the or operator || to provide a default value of an empty object to iterate empty collection which will both result in empty views:
this.props.recentMessages && Object.entries(this.props.recentMessages).map(...)

Or with default value:
Object.entries(this.props.recentMessages || {}).map(...)


text:
Q: How would I integrate values with a discrete time step and discrete distance that correspond to a specific velocity value? I am just curious to how I would go about integrating data points that I get from a simulation that I am running ? In this simulation I get velocity values along a line (i.e alonge the line $x=3$ and $0 \leq y \leq 1$) at discrete distance markers (say 0.5 step size) but the values for these are taken at a specific time step during the simulation. I am wondering how would I be able to integrate this line so I can get values for the velocity as a function of distance and time and then to plot it ?
Here would be an example of the data points I would be given (u,v,h are the variable for the velocities just for clarity):
$$ at \ \ t=0 :
 \begin{array}{|c|c|c|c|}
\hline
\Delta y& u & v & h \\ \hline
 0& 0& 0& 0\\ \hline
 0.5 & 1.0 & 0.5 & 0.5\\ \hline
 1& 2.0 & 1.0& 1.0\\ \hline
\end{array}
\\
at \ \ t=0.5:
 \begin{array}{|c|c|c|c|}
\hline
\Delta y& u & v & h \\ \hline
 0& 0& 0& 0\\ \hline
 0.5 & 0.75 & 1.5 & 0.5\\ \hline
 1& 2.0 & 1.0& 1.0\\ \hline
\end{array} $$
These are not the exact values that I get from my simulation but rather an example of how my data is stored.
My first intuition is to integrate along the $\Delta y$ line at each time step and then to go back and integrate those lines for all time, i.e integrate along the line for $t=0$ and $t=0.5$ then integrate those lines for all time.
But the problem with my intuition that I am second guessing is

*

*Wouldn't that take an extremely long time for small enough $\Delta y$ and large enough $t$ ?

*What kind of integration methods would be used to do this ?

*Wouldn't that take up a lot of memory doing each integration independently ?

Any help would be greatly appreciated and any suggestions on either changing up my idea of thinking/suggesting a better way to do this would be greatly appreciated.
Note I can post a couple of actual data files on Github and share them if my example wasn't clear enough or you want to see exactly how the data is laid out in .txt files.


text:
Q: Getting Multiple IDs for Same Row While Testing CRUD in Spring with JUnit I am using JUnit4 with AbstractTransactionalJUnit4SpringContextTests, and would like to create simple CRUD unit tests - as shown below.  However, the call to SQL update is causing the transaction manager to generate a new ID for my test instance.  Since the new ID isn't passed back during the update I no longer have the primary key for the row I am testing - which foils the remainder of the test.
Is there a way to prevent the transaction manager from generating a new ID for the book when update is called?  (failing that is there a better way to test CRUD?)
@Test
public void testCRUDBook() {
    Book b1 = new Book(title, author);
    BookFactory factory = database.getBookFactory();
    int id = factory.createBook(b1);

    Book b2 = factory.readBook(id);
    assertEquals(b1.getTitle(), b2.getTitle());
    assertEquals(b1.getAuthor(), b2.getAuthor());

    b2.setTitle("title 2");
    b2.setAuthor("author 2");
    assertTrue(factory.updateBook(b2));

    // The problem arises here as updating the book record causes a new Id
    // to be generated so querying by Id is no longer possible.
    Book b3 = factory.readBook(b2.getId());
    assertEquals(b3.getTitle(), "title 2");
    assertEquals(b3.getAuthor(), "author 2");

    assertTrue(factory.deleteBook(b3));
}

Book looks like this:
public class Book {
    private int id;
    private String title;
    private String author;

    public Book() {}

    // NEW
    public Book(String title, String author) {
        this.title = title;
        this.author = author;
    }

    // READ
    public Book(int id, String title, String author) {
        this.id = id;
        this.title = title;
        this.author = author;
    }

    // GENERIC ACCESSORS (left out for brevity)
}

For completeness - the factory:
public class BookFactory extends BaseDatabaseFactory {

        @Transactional
    public int createBook(final Book b) {
        final String insertSQL = "INSERT INTO book (author, title) VALUES (?, ?)";
        KeyHolder keyHolder = new GeneratedKeyHolder();
        try {
            int update = jdbcTemplate.update(
                    new PreparedStatementCreator() {
                        @Override
                        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                            PreparedStatement ps = connection.prepareStatement(insertSQL, PreparedStatement.RETURN_GENERATED_KEYS);
                            ps.setString(1, b.getTitle());
                            ps.setString(2, b.getAuthor());
                            return ps;
                        }
                    },
                    keyHolder);
            if (update != 1) {
                throw new IllegalStateException("Adding book record to database resulted in " + update + " records.");
            }
            return keyHolder.getKey().intValue();
        } catch (DataAccessException ex) {
            String msg = "Falied to create new book:" + b.toString() + "ex:" + ex.getMessage();
            throw new RuntimeException(msg);
        }
    }

    private static class BookRowMapper implements RowMapper {
        @Override
        public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
            Book b = new Book();
            b.setId(rs.getInt("id"));
            b.setTitle(rs.getString("title"));
            b.setAuthor(rs.getString("author"));
            return b;
        }
    }

    @Transactional
    public Book readBook(int id) {
        Book b = null;
        try {
            String sql = "SELECT * FROM book WHERE id = " + id;
            b = (Book) jdbcTemplate.queryForObject(sql, new Object[]{}, new BookRowMapper());
        } catch (DataAccessException ex) {
            throw new RuntimeException("Falied to locate book.", ex);
        }
        return b;
    }

    @Transactional
    public boolean updateBook(final Book b) {
        final String updateSQL = "UPDATE book SET author = ?, title = ? WHERE id = ?";
        try {
            jdbcTemplate.update(
                    new PreparedStatementCreator() {
                        @Override
                        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                            PreparedStatement ps = connection.prepareStatement(updateSQL);
                            ps.setString(1, b.getAuthor());
                            ps.setString(2, b.getTitle());
                            ps.setInt(3, b.getId());
                            return ps;
                        }
                    });
        } catch (DataAccessException ex) {
            log.error("Falied to update Book:" + b.toString(), ex);
            return false;
        }
        return true;
    }

    @Transactional
    public boolean deleteBook(final Book b) {
        try {
            jdbcTemplate.update("DELETE FROM book WHERE id = ?", b.getId());
        } catch (DataAccessException ex) {
            log.error("Falied to delete Book:" + b.toString(), ex);
            return false;
        }
        return true;
    }
}

A: Can you make the id an Integer type instead? It looks as if the factory causes a new instance to be created when you do the update to b2. id should be nullable.

A: Fixed the problem while trying to document the problem (by pasting in tidy factory code).  The createBook(book) and readBook(int) factory methods were missing a @Transactional annotations; I had thought that the transaction was inherited from the invoking test container - apparently this is not the case.  Splitting the test across transactions must have created multiple instances of the row.
I hope this helps someone else who runs into the same problem.


text:
Q: How to run a packet from archive manager I loaded a packet (sleepyhead) and it appears in the archive manager.  However I do not know how to get this program to run...  help me please.

A: sleepyhead sleep tracking software can be installed in Ubuntu 16.04 and later from the default Ubuntu repositories or from the terminal with the following command:
sudo apt install sleepyhead

For information about usage type:
man sleepyhead
cat /usr/share/doc/sleepyhead/usage.html

A: You can see which files are in the sleepyhead package with
dpkg -L sleepyhead


text:
Q: App crash on addsubview when enable ARC When I used tradition function
   [self.navigationController pushViewController:viewcontroller animated:YES];

or
   [self presentModalViewController:viewcontroller animated:YES];,

Everything is ok. But when I used
   [self.view addSubview:viewcontroller.view];

I can't do anything in next view, all view's membory pointer has gone. And it crashes all the time.

A: I think your viewController object is declared locally. Make it class level variable (declare in .m file). Reason why your app crashes is you declare object locally and it is released after that function is finished. So no object for addSubView. When you push or present object is retained once and hence not released and application works. So if you want to use addSubView then make it class level variable so that it wont be released.


text:
Q: How to fix triggerPhrase Error in Jenkins Pipeline I just want to use triggerPhrase to trigger my jenkins pipeline if you give the comment such as "Rebuild"
triggerPhrase('Rebuild')

but I got this error
 No signature of method: javaposse.jobdsl.dsl.helpers.triggers.TriggerContext.triggerPhrase() is applicable for argument types: (java.lang.String) values: [Rebuild]

any solutions?


text:
Q: What happens when an inline function is passed as a parameter in C? Today I was writing some C code to sort an array of structs using quicksort with a custom comparator function to determine their ordering.
At first I wrote it with the call to the comparator function hard-coded into the quicksort function. Then I thought perhaps it would be nicer to pass that function as an argument to a generic quicksort function.
In my original code, I had declared the comparator function inline. In my new code, I kept the inline declaration, even though that didn't really make much sense to me, given that the function was being passed as a parameter. However, the compiler didn't complain!
My question is: is the inline declaration having any effect here, or is it merely a recommendation to the compiler which is being ignored?
Original code:
typedef struct _CGRect {
    CGPoint origin;
    CGSize size;
} CGRect;

typedef enum _NSComparisonResult {
     NSOrderedAscending = -1,
     NSOrderedSame,
     NSOrderedDescending
} NSComparisonResult;

static inline NSComparisonResult CGRectCompareRowsFirst(CGRect r1, CGRect r2)
{
    if (r1.origin.y < r2.origin.y)
        return NSOrderedAscending;
    else if (r1.origin.y > r2.origin.y)
        return NSOrderedDescending;
    else
    {
        if (r1.origin.x < r2.origin.x)
            return NSOrderedAscending;
        else if (r1.origin.x > r2.origin.x)
            return NSOrderedDescending;
        else
            return NSOrderedSame;
    }
}

static void CGRectQuicksortRowsFirst(CGRect *left, CGRect *right)
{
    if (right > left) {
        CGRect pivot = left[(right-left)/2];
        CGRect *r = right, *l = left;
        do {
            while (CGRectCompareRowsFirst(*l, pivot) == NSOrderedAscending) l++;
            while (CGRectCompareRowsFirst(*r, pivot) == NSOrderedDescending) r--;
            if (l <= r) {
                CGRect t = *l;
                *l++ = *r;
                *r-- = t;
            }
        } while (l <= r);
        CGRectQuicksortRowsFirst(left, r);
        CGRectQuicksortRowsFirst(l, right);
    }
}

static void CGRectSortRowsFirst(CGRect *array, int length)
{
    CGRectQuicksortRowsFirst(array, array+length-1);
}

New code:
static inline NSComparisonResult CGRectCompareRowsFirst(const void *s1, const void *s2)
{
    CGRect r1 = *(CGRect *)s1, r2 = *(CGRect *)s2;

    if (r1.origin.y < r2.origin.y)
        return NSOrderedAscending;
    else if (r1.origin.y > r2.origin.y)
        return NSOrderedDescending;
    else
    {
        if (r1.origin.x < r2.origin.x)
            return NSOrderedAscending;
        else if (r1.origin.x > r2.origin.x)
            return NSOrderedDescending;
        else
            return NSOrderedSame;
    }
}

static void quick(CGRect *left, CGRect *right, NSComparisonResult(*f)(const void *, const void *))
{
    if (right > left) {
        CGRect pivot = left[(right-left)/2];
        CGRect *r = right, *l = left;
        do {
            while (f(&*l, &pivot) == NSOrderedAscending) l++;
            while (f(&*r, &pivot) == NSOrderedDescending) r--;
            if (l <= r) {
                CGRect t = *l;
                *l++ = *r;
                *r-- = t;
            }
        } while (l <= r);
        quick(left, r, f);
        quick(l, right, f);
    }
}

static void CGRectSortRowsFirst(CGRect *array, int length)
{
    quick(array, array+length-1, CGRectCompareRowsFirst);
}

A: Inline is just a recommendation to the compiler, and can be ignored.  This can happen for several reasons, such as if the function is too complex to be safely inlined.  If you pass it as a parameter to a function like above, the compiler will create the non-inlined version whose address will be passed to the function.
It may be possible that the compiler could still inline the function - for instance, during code generation the compiler could utilize the inline function hint replacing the call via a function pointer to just the expanded function; I am not sure if any current compiler would do that.
Inlined and non-inlined versions can and often do co-exist within one compiled program.

A: The 'inline' keyword is simply a compiler flag that tells it to handle it differently in that it will copy the body of the function and replace it with the actual function call. This is a performance boost if you have a small function that gets reused in many locations in your code. It's a neat thing to use with accessors and modifiers. In your case, I think you could leave it as it is. You're not doing anything heavy. The difference will most likely not be noticeable.


text:
Q: Multiple ViewPagers in on Activity I am trying to implement more than one ViewPager in one activity and it is not really working. What's the best way to implement that. I am stuck!!
This is The Activity
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.widget.Button;

import com.viewpagerindicator.CirclePageIndicator;

public class NewWorkoutActivity extends Activity{

    ViewPager corePager;
    ViewPager timePager;
    ViewPager equipmentPager;
    CirclePageIndicator coreIndicator;
    CirclePageIndicator timeIndicator;
    CirclePageIndicator equipmentIndicator;
    Button startWorkoutButton;

    PagerAdapter coreAdapter;
    PagerAdapter timeAdapter;
    PagerAdapter equipmentAdapter;

     String[] timeSets;
     String[] coreTargets;
     String[] equipments;

     int[] timeImages;
     int[] coreImages;
     int[] equipmentImages;

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

         coreTargets = new String[] { "Full body", "Core",
                 "Legs", "Upper Body"};

         coreImages = new int[] { R.drawable.button_target_core,  R.drawable.button_target_core2,
                 R.drawable.button_target_core3,  R.drawable.button_target_core4};

         timeSets = new String[] { "15 Minutes", "20 Minutes",
                 "30 Minutes", "45 Minutes"};

         timeImages = new int[] { R.drawable.button_target_core,  R.drawable.button_target_core2,
                 R.drawable.button_target_core3,  R.drawable.button_target_core4};

          equipments = new String[] { "Rope", "Kette Bell",
                 "Weight", "Hat"};

         equipmentImages = new int[] { R.drawable.button_target_core,  R.drawable.button_target_core2,
                 R.drawable.button_target_core3,  R.drawable.button_target_core4};

        startWorkoutButton=(Button)findViewById(R.id.startWorkoutButton);
        corePager=(ViewPager)findViewById(R.id.corepager);
        timePager=(ViewPager)findViewById(R.id.timepager);
        equipmentPager=(ViewPager)findViewById(R.id.equipmentpager);
        coreIndicator=(CirclePageIndicator)findViewById(R.id.coreindicator);
        timeIndicator=(CirclePageIndicator)findViewById(R.id.timeindicator);
        equipmentIndicator=(CirclePageIndicator)findViewById(R.id.equipmentindicator);

           coreAdapter = new MyViewPagerAdapter(NewWorkoutActivity.this, coreTargets, coreImages);
            // Binds the Adapter to the ViewPager
            corePager.setAdapter(coreAdapter);

            timeAdapter = new MyViewPagerAdapter(NewWorkoutActivity.this, timeSets, timeImages);
            // Binds the Adapter to the ViewPager
            timePager.setAdapter(timeAdapter);

            equipmentAdapter = new MyViewPagerAdapter(NewWorkoutActivity.this, equipments, equipmentImages);
            // Binds the Adapter to the ViewPager
            corePager.setAdapter(coreAdapter);

            // ViewPager Indicators

            coreIndicator.setViewPager(corePager);
            equipmentIndicator.setViewPager(equipmentPager);
            timeIndicator.setViewPager(timePager);

    }

}

and My Adapter

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class MyViewPagerAdapter extends PagerAdapter {
    // Declare Variables
    Context context;
    String[] desc;
    int[] image;
    LayoutInflater inflater;

    public MyViewPagerAdapter(Context context, String[] desc,  int[] image) {
        this.context = context;
        this.desc = desc;
        this.image = image;
    }

    @Override
    public int getCount() {
        return desc.length;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((RelativeLayout) object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {

        // Declare Variables
        TextView desctext;
        ImageView vpimage;

        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View itemView = inflater.inflate(R.layout.body_page, container,
                false);

        // Locate the TextView in viewpager_item.xml
        desctext = (TextView) itemView.findViewById(R.id.vptext);

        // Capture position and set to the TextViews
        desctext.setText(desc[position]);

        // Locate the ImageView in viewpager_item.xml
        vpimage = (ImageView) itemView.findViewById(R.id.vpimage);
        // Capture position and set to the ImageView
        vpimage.setImageResource(image[position]);

        // Add viewpager_item.xml to ViewPager
        ((ViewPager) container).addView(itemView);

        return itemView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        // Remove viewpager_item.xml from ViewPager
        ((ViewPager) container).removeView((RelativeLayout) object);

    }
}

The logcat is telling me that the ViewPagers don't have adapter instances.

A: This works for me:
Try this code. Not much changes to it.
NOTE: The images I used are just random images.. you can use your own.
public class MainActivity extends ActionBarActivity {

    Context context;

    String[] timeSets;
    String[] coreTargets;
    String[] equipments;

    int[] timeImages;
    int[] coreImages;
    int[] equipmentImages;

    MyAdapter adapter1, adapter2, adapter3;

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

        coreTargets = new String[]{"Full body", "Core",
                "Legs", "Upper Body"};

        coreImages = new int[]{R.drawable.ic_launcher, R.drawable.abc_ab_share_pack_holo_dark,
                R.drawable.abc_ab_stacked_solid_dark_holo, R.drawable.abc_ab_bottom_solid_dark_holo};

        timeSets = new String[]{"15 Minutes", "20 Minutes",
                "30 Minutes", "45 Minutes"};

        timeImages = new int[]{R.drawable.abc_ab_share_pack_holo_light, R.drawable.abc_ab_transparent_light_holo,
                R.drawable.abc_ic_ab_back_holo_light, R.drawable.abc_spinner_ab_pressed_holo_light};

        equipments = new String[]{"Rope", "Kette Bell",
                "Weight", "Hat"};

        equipmentImages = new int[]{R.drawable.abc_ic_clear, R.drawable.abc_textfield_searchview_holo_dark,
                R.drawable.abc_spinner_ab_focused_holo_light, R.drawable.abc_ab_stacked_solid_dark_holo};

        ViewPager view1 = (ViewPager) findViewById(R.id.viewpager1);
        ViewPager view2 = (ViewPager) findViewById(R.id.viewpager2);
        ViewPager view3 = (ViewPager) findViewById(R.id.viewpager3);

        adapter1 = new MyAdapter(coreTargets, coreImages);
        adapter2 = new MyAdapter(timeSets, timeImages);
        adapter3 = new MyAdapter(equipments, equipmentImages);

        view1.setAdapter(adapter1);
        view2.setAdapter(adapter2);
        view3.setAdapter(adapter3);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

The Adapter
    private class MyAdapter extends PagerAdapter {

        String[] desc;
        int[] image;

        public MyAdapter(String[] desc, int[] image) {

            super();
            this.desc = desc;
            this.image = image;

        }

        @SuppressLint("NewApi")
        @Override
        public void finishUpdate(ViewGroup container) {
            // TODO Auto-generated method stub
            super.finishUpdate(container);

        }

        @Override
        public int getCount() {

            return desc.length;

        }

        @Override
        public boolean isViewFromObject(View collection, Object object) {

            return collection == ((View) object);
        }

        @Override
        public Object instantiateItem(View collection, int position) {

            // Inflating layout
            LayoutInflater inflater = (LayoutInflater) collection.getContext()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            // Setting view you want to display as a row element
            View view = inflater.inflate(R.layout.items, null);

            TextView itemText = (TextView) view.findViewById(R.id.textViewMain);

            ImageView imageView = (ImageView) view.findViewById(R.id.imageViewmain);

            try {

                itemText.setText(desc[position]);

                imageView.setImageResource(image[position]);
            } catch (Exception e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            ((ViewPager) collection).addView(view, 0);
            return view;

        }

        @Override
        public void destroyItem(View collection, int position, Object view) {
            ((ViewPager) collection).removeView((View) view);

        }

    }
}

The layout looks like this :
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.mike.app.MainActivity$PlaceholderFragment"
    android:background="#ffc42823">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <android.support.v4.view.ViewPager
            android:layout_width="fill_parent"
            android:layout_height="200dp"
            android:id="@+id/viewpager1"
            android:background="#333333"
            />

        <View
            android:layout_width="fill_parent"
            android:layout_height="3dp"
            android:background="#FFFFFF"></View>

        <android.support.v4.view.ViewPager
            android:layout_width="fill_parent"
            android:layout_height="200dp"
            android:id="@+id/viewpager2"
            android:background="#333333" />

        <View
            android:layout_width="fill_parent"
            android:layout_height="3dp"
            android:background="#FFFFFF">></View>

        <android.support.v4.view.ViewPager
            android:layout_width="fill_parent"
            android:layout_height="200dp"
            android:id="@+id/viewpager3"
            android:background="#333333" />

    </LinearLayout>

</ScrollView>

The Items layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.mike.app.MainActivity$PlaceholderFragment"
    android:background="#ff10c7c6"
    android:orientation="horizontal"
    android:gravity="center">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher"
        android:id="@+id/imageViewmain" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:text="Some Text"
        android:textSize="25sp"
        android:id="@+id/textViewMain"
        android:gravity="center" />

</LinearLayout>

Is this what you are looking for ? If yes, this works for me.. Lemme know if this works.


text:
Q: How to combine GROUP BY and JOIN statements in MySQL? I am trying to combine a query I have run on one table with some columns on another table. The query I ran calculates the total of something for me by this:
SELECT security.Loan_id
     , SUM(security.SecMktValue) AS TotalSecMktValue
  FROM security
 GROUP
    BY Loan_id
 ORDER
    BY loan_id ASC;

I then tried to join this query with columns from another table by:
SELECT loans.Loan_id, loans.TotalLoanAmt
FROM loans
JOIN(SELECT SUM(security.SecMktValue) AS TotalSecMktValue,security.Loan_id
FROM security
GROUP BY Loan_id ASC)
ON loans.Loan_id = security.Loan_id;

However, this wont run as it says there is an error with my SQL syntax even though nothing is underlined in red. Does anyone know why that is?

A: You're missing an alias:
SELECT loans.Loan_id, loans.TotalLoanAmt
FROM loans
JOIN(
    SELECT SUM(security.SecMktValue) AS TotalSecMktValue,security.Loan_id
    FROM security
    GROUP BY Loan_id ASC
    ) security -- <-- here
ON loans.Loan_id = security.Loan_id;

A: MySQL requires an alias to be assigned to the derived table (i.e. a correlation name associated with the inline view). The qualifier security is out of scope outside the inline view i.e. it's not a valid reference in the outer query.)
Here's an example, assigning the alias t to the derived table. Notice that in the outer query, references to columns from the inline view are qualified with t.
SELECT l.loan_id
     , l.totalloanamt
     , t.totalsecmktvalue
  FROM loans l
  LEFT
  JOIN (
         SELECT s.loan_id
              , SUM(s.secmktvalue) AS totalsecmktvalue
           FROM security s
          GROUP
             BY s.loan_id
       ) t
    ON t.loan_id = l.loan_id
 ORDER
    BY l.loan_id

A: If i got you question right then this should work  :)
SELECT security.Loan_id,SUM(security.SecMktValue) AS TotalSecMktValue
  FROM security security
  JOIN loans loan
  ON loans.Loan_id = security.Loan_id
  GROUP BY Loan_id ASC


text:
Q: BNF grammar using loop statements Write a simple BNF grammar for a subset of C that supports multiple statements including assignment, if-else, and while statements without block statements.  Use meaningful names for your nonterminals (vs. cryptic letters).  Assume variables are represented by single letters and are integers.  Assume that the standard precedence rules apply for the operators *, /, +, -, and parentheses.  Make sure to include relational operators (==, !=, <, >, >=, and <=).    The following is a valid program for your grammar:
 a = -35;while (b > a);a = a + b;if (a >= 10);c = a;else c = b;

Can you expand your BNF to properly handle a C block statement as part of a while or if or else?  Revise your productions to support:
    while (b > a)
    a = a + b;
    printf("in loop");
using the above grammar I came up with
<statement> ::=  a=-35
<while> ::= while (b>a)
<assign>::= a = a + b;
<if>::= if (a >= 10)
<assign> ::= c=a;
<else>
<assign> ::= c = b;

<while>::= while (b>a)
<assign>:= a = a + b;
<statement>::= printf ("in loop");

Is this a valid bnf grammar ?

A: No. What you are writting are more examples than a grammar. A grammar explains how to produce all the valid constructs of the language.
For example
 <while> ::= while <expression> <block>

Then, you define <expression> in a way that allows to write any expression in the language, and <block> as a block of statements (a simple statement or several statement grouped by brackets).
http://en.wikipedia.org/wiki/Backus%E2%80%93Naur_Form


text:
Q: How to remove values from text file with conditions I am trying to make a function to convert srt to vtt so I specified the differences between the two files:
srt
1
    00:00:05,795 --> 00:00:09,832
    Are you alright?

vtt
00:00:05.795 --> 00:00:09.832
Are you alright?

The difference is in the number above every line which increases by 1 in every line and the , in the time.
I made a function to replace , with . but I don't know how to remove all numbers from the file. I am thinking about removing the lines that is 5 letters length but maybe there is another option?
Here is what I have done:
function srttovtt($file){
    $str = implode("\n", file($file));
    $name = basename($file, '.srt');
    $fp = fopen('uploads/subs/' . $name . '.vtt', 'w');

    $str = str_replace(',', '.', $str); // replace comma

    fwrite($fp, $str, strlen($str));
    return $fp;
}

A: regex to the rescue
$text = preg_replace('~\d+\s*(\d{2}):(\d{2}):(\d{2}),(\d{3})\s*-->\s*(\d{2}):(\d{2}):(\d{2}),(\d{3})~', '\1:\2:\3.\4 --> \5:\6:\7.\8', $text);

the first \d+ is the number that's got to go and the \s* following is every whitespace after it.
next we have the times we want modified, so we keep the numeric values in parenthesis, so we can use it later on with \1, \2 etc in the format we want.
I should have included a \s* at the start too, but then I would need a newline at the start of the formatted text, which I could not find how to insert. \n didn't seem to do the job. If anyone knows how, please edit. Though it's only visual and you don't really care for that in a subtitles file.


text:
Q: C++/CLI I can't add a class to my collection I am attempting to simply add a FilterInfo class to my FilterInfo collection.  I'm having a terrible time trying to understand why the following code keeps throwing the error:

System::Collections::Generic::List::Add'
  : cannot convert parameter 1 from
  'Ziz::FilterInfo *' to
  'Ziz::FilterInfo'

I'm only learning C++/CLI, as I'm a C# developer, and I'm sure it's something simple, but I sure could use some pointers.  My stripped code is as follows:
     public value class FilterInfo
    {
        public:
            char* Address;
    };

    public ref class Ziz
    {
    private:
        List<FilterInfo>^ _blockList;

    public:
        // Constructor
        Ziz(){
            _blockList = gcnew List<FilterInfo>();
        }

        List<FilterInfo>^ GetBlockList()
        {

            for each(_IPFILTERINFO ip in _packetFilter->GetBlockList())
            {
                // _IPFILTERINFO is the native C++ struct.
                FilterInfo* f = new FilterInfo();
                _blockList->Add(f);
            }
            return _blockList;
        }

A: You declared _blockList as
List<FilterInfo>^ _blockList;

but you are trying to add
FilterInfo* f

to it. It cannot work since one is a pointer and the other one is a reference.
I'm not sure how "value" fits in but in
public value class FilterInfo
{
    public:
        char* Address;
};

You are derefore declaring an unmanaged class
to make it managed, you should use
public ref class FiterInfo

This will allow you to use FilterInfo* without having to manage memory explicitely.
Finally, char* is not so great in C++/CLI, I would recommend using System::String

A: _blockList->Add(*f);

A: You have to construct your FilterInfo with gcnew as well. You can't really mix and mash these together without marshaling.

A: FilterInfo is not FilterInfo*. If you want a List of pointers to FilterInfo, you need to say that List<FilterInfo*>. Since FilterInfo is a value class here though you'll likely just want to skip the new.
     FilterInfo fi;
     _blockList->Add(fi);

A: public ref class A

{
    };
int main(array<System::String ^> ^args)
{
      Console::WriteLine(L"Hello World");
      ICollection<A^>^ oCollection = gcnew List<A^>();
      oCollection->Add(gcnew A());
      return 0;
}


text:
Q: HTTP 404 with PUT request in REST service I am using the WCF REST template in VS 2010 to build RESTful web services for my app. I've completed all the GETs but am now trying to handle updates, and I keep getting 404 on the PUT even though it shows up in the help file.
Truncated web.config:
<system.webServer>
  <modules runAllManagedModulesForAllRequests="true">
    <add name="UrlRoutingModule"
         type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
  </modules>
  <validation validateIntegratedModeConfiguration="true" />
  <handlers>
    <add name="UrlRoutingHandler" preCondition="integratedMode" verb="*" path="UrlRouting.axd" />
  </handlers>
</system.webServer>
<system.serviceModel>
  <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  <standardEndpoints>
    <webHttpEndpoint>
      <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true" />
    </webHttpEndpoint>
  </standardEndpoints>
</system.serviceModel>

As you can see, all verbs are enabled for the UrlRoutingHandler. What am I missing?
(Note that I am using IIS 7, but I'm forced to run the app pool in classic mode in order to emulate the behavior of the release server, which is on IIS 6.)

A: After much troubleshooting the combination of the following two config changes seems to have fixed it.

*

*Remove the WebDAV handler

*Add PUT and DELETE verbs for ExtensionlessUrlHandler

(this is a placeholder to enable markdown code view below)
<handlers>
  <remove name="WebDAV" />
  <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
  <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
  <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE"
       modules="IsapiModule" scriptProcessor="c:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll"
       resourceType="Unspecified" requireAccess="Script" preCondition="classicMode,runtimeVersionv4.0,bitness32"
       responseBufferLimit="0" />
  <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE"
       modules="IsapiModule" scriptProcessor="c:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll"
       resourceType="Unspecified" requireAccess="Script" preCondition="classicMode,runtimeVersionv4.0,bitness64"
       responseBufferLimit="0" />
</handlers>


text:
Q: Semi transparent image hanging out of a semi transparent div I'm trying to build a website header that is semi transparent, and contains a semi transparent image that hangs outside the of the header div, like in the image linked below.

Because of overlapping opacities, I can't simply put a semi transparent image in to a semi transparent div and add a negative margin to the image. The best I could come up with was taking the height of the header image, and cutting that bit of the logo image, like in image attached. However that's not ideal, as doesn't play nice responsively etc etc.

Any ideas of how I might achieve this look?
Thanks in advance.

A: If you know the height of your menu then you can place both the logo and the menu inside of a container. Then position the logo with the top value equalling the height of the menu.
.header-bg {
    background: rgba(225, 225, 225, 0.5);
    position: relative;
    height: 60px;
}

.header-bg .logo {
    width: 90px;
    height: 90px;
    background: rgba(225, 225, 225, 0.5);
    position: absolute;
    top: 60px;
    left: 10%;
}

See this fiddle: http://jsfiddle.net/3kxBt/1/
Hope that helps in some way.

A: You can use rgba color format for background of both the .logo and the header to achieve your desired effect. However, you have to give position: absolute; to your .logo class because it needs to come right below the header. If you put your .logo on top of your header, then colors will overlap and won't look right. So, it needs to starts at the bottom of the header.
The header should have position: relative; so that your .logo is positioned relatively to the header. This way, you don't even need to know the height of your header because when you define top position of your .logo, you can simply use top: 100% so that it always starts right below your header. You don't have to hardcode that top value.
Now, you need to shift your actual logo (image) inside your .logo on top because its appearing below the header right now. For that you can simply push the image by giving it negative margin-top value.
SEE THE DEMO
The code would look like this:
HTML

CSS
header {
  background: rgba(255,255,255, 0.7);
  position: relative;
}

.logo {
  position: absolute;
  top: 100%;
  background: rgba(255,255,255, 0.7);
}

.logo img {
  margin-top: -50px;
}

A: This is an interesting problem and there are a couple ways to solve it; two come immediately to my mind.
The first is your method; carefully position things so that you don't have multiple translucent sections overlapping. This wouldn't be too difficult; if you go with this method I would recommend breaking the header into sections left and right of the image and using absolute positioning.
The second and easier way is to create a version of the picture with the semi-transparent white overlay you desire already applied. Then you can use that as the background for the menu and image. The only tricky thing here is you have to make sure the images line up by either using fixed positioning or calculated pixel offsets. This approach has been around for a long time and you can see any early example (2001-ish) of it here.

A: My take on it is to create a :before pseudo-element.  It has its problems, including what if the logo changes in size at some point, but overall it works.
HTML

CSS
nav a.logo {
  position: relative;
  ...
  display: inline-block;
  line-height: 0.0001em;
  font-size: 0.0001em;
}

nav a.logo img {
  position: relative; /* for z-index issues.  giving the image a relative
                         position automatically will place it above the
                         absolutely positioned :before element.  This is
                         because the before element is rendered before the
                         image */
}

nav a.logo:before {
  content: '';
  position: absolute;
  display: block;
  width: 100%;
  height: 71px;
  bottom: 0;
  left: 0;
  background: rgba(0,0,0,0.4);
  ...
}

Demo: http://jsfiddle.net/ZP6LQ/1/show
Source: http://jsfiddle.net/ZP6LQ/1/


text:
Q: Позиционирование ячейки таблицы Добавляю через js в конец еще один td с position: absolute. Сам tr имеет position: relative, но этот последний td позиционируется от общего окна, а не от tr.
Как все же сделать так, что бы эта ячейка позиционировалась от своего родительского tr?

        <button type="button" class="btn_accept" data-id="1098">ACCEPT</button>
        <button type="button" class="btn_decline" data-id="1098">DECLINE</button>

A: Все на месте:

tr {
  position: relative;
}

.add {
  position: absolute;
}

            Lorem
            Lorem
            Lorem

              <button type="button" class="btn_accept" data-id="1098">ACCEPT</button>
              <button type="button" class="btn_decline" data-id="1098">DECLINE</button>

         add

A: В вашем случае нужно добавить для tr свойство display:block.

A: Согласно уже данным ответам:

This is because according to CSS 2.1, the effect of position: relative
  on table elements is undefined.
  Что по сути означает, что мы не можем к нашему display: table добавлять этот параметр.


text: Q: How to display HTML help file in WPF I have a help file, in HTML format, that I need to display within my MVVM Application in WPF.  I don't want to use anything WinForms related and I don't want any dependency on ActiveX or IE.  Is there not a simple and out-of-the-box way to do this in WPF?  Do I need to go through the hassel of writing converters and other unwanted code?


text:
Q: Why do I need to specify window variable scope in backbone route filter? I'm using the backbone route filter, https://github.com/fantactuka/backbone-route-filter, in my backbone.js app. It's a one page app, so I was trying to record pageviews using a KissMetrics event tracking snippet. Here is the code:
before: {
    '*any': function(fragment, args) {

    }
  },

  after: {
    '*any': function(fragment) {

      var _kmq = window._kmq || [];
      _kmq.push(['record', 'Viewed ' + fragment]);
    }
  },

The question is, the event wasn't tracking unless I specified the 'window' scope of the _kmq variable. Why? In my index.html, or the one page with all my js code, I have:
var _kmq = _kmq || [];

which I thought would make the variable at the global level automatically...this is the link to a typical implementation: http://support.kissmetrics.com/apis/javascript/index.html In every case I've seen prior the common api method worked, without setting the scope to window: http://support.kissmetrics.com/apis/javascript/javascript-specific/index.html
Why did I need to specify 'window._kmq' rather than just '_kmq'?

A: This looks like an issue of local versus global scoping (see What is the scope of variables in JavaScript? for some examples of this).
Since you're including the Kiss Metrics Javascript on the page, it will be looking in the global (that is window._kmq) variable for event updates. To make sure you are pushing your event into that globally accessible variable, you need to specify that it lives in the global context (ie, window._kmq) versus a local context (ie, _kmq).
In your Javascript code that lives directly on the page, the default scope is inside window, so var _kmq = ... is the same as window._kmq = ....
In your Backbone router, this isn't the case: the scope inside there is isolated (that is, if you set var _kmq = ... inside the router, it isn't accessible anywhere except in that same block of code).


text:
Q: how do I create a const URL in Dart? A (constructor) method (FirebaseOptions) in Dart expects a constant String.
Simply passing a string results in a URISyntaxException (even though it's a perfectly fine URL), so apparently I have to encode the String.
But the String has to be const and the Uri encoder doesn't return a const String.
mucking about

A: It is not possible with Uri implementation due constructor of the Uri class is not constant.
By the way you are able to create own, constant implementation of Uri interface:
class MyConstUri implements Uri {
  const MyConstUri();

  //... implement or generate all necessary methods
}

const Uri reallyConstUri = MyConstUri();


text:
Q: What is the relationship between a SPID and a Connection in SQL server? Can a SPID be used by two connections, while both connections are open?
If a connection is returned to a connection pool, will it hold on to the SPID?

A:
Can a SPID be used by two connections,
  while both connections are open?

No, each open connection will have its own SPID.

If a connection is returned to a
  connection pool, will it hold on to
  the SPID?

Yes, as long as the connection is open, it will be associated with one SPID.
You can test this yourself by querying sys.sysprocesses.  Rebooting a client machine should clear its connection pool.


text:
Q: restart number for img class using jquery I've lot of images and I want to add class for all images and for the first 7 images it should name as "img1, img2, img3, img4, img5, img6, img7" and again after that this should be named as previous "img1, img2, img3, img4, img5, img6, img7"
So I tried this but not working its naming img1 for all images after first 7 images
$('#someid img').addClass(function(idx){
    if(idx > 6){
    idx = 0;
    }
    return "img" + (idx + 1)
});

A: It doesn't work because idx is not a counter but the actual index of the element.
Use the modulo operator instead:
$('#someid img').addClass(function(idx){
    return "img" + (idx % 7 + 1)
});


text:
Q: Deleted Cloudformation Stack, now unable to recreate new ones due to resources already existing I ran into a condition that caused my stack to become unrecoverable and I had no choice but to delete it. Using the exact same template, I went ahead and created another stack with the same name.
The following resource(s) failed to create: [AdminPanelCDNAccessIdentity,
BackendLogGroup, BackendLoadBalancerSecurityGroup, AdminPanelCertificate,
EnvironmentCertificate, AdminPanelBucket, BackendECSTaskRole,
BackendECSTaskBitbucketAccess2RunTask, BackendLoadBalancerTargetGroup]. The
following resource(s) failed to update: [FrontEndBucket].

Do I really need to delete all these resources manually and rebuild them from scratch? That seems like a terrible option.
Here's a sample snippet of my template code
Resources:
FrontEndBucket:
Type: 'AWS::S3::Bucket'
Properties:
  BucketName: !If
    - IsProduction
    - 'Fn::ImportValue': !Sub '${LandscapeStack}-DNSDomain'
    - 'Fn::Sub':
        - '${EnvironmentSubdomain}.${LandscapeDomain}'
        - LandscapeDomain:
            'Fn::ImportValue': !Sub '${LandscapeStack}-DNSDomain'
  AccessControl: Private
  Tags:
    - Key: landscape
      Value: !Ref Landscape
    - Key: environment
      Value: !Ref EnvironmentName
  WebsiteConfiguration:
    IndexDocument: index.html
Metadata:
  'AWS::CloudFormation::Designer':
    id: 53eb6c3a-767f-46fb-a719-2846f1fd6bdd
FrontEndBucketPolicy:
Type: 'AWS::S3::BucketPolicy'
Properties:
  Bucket: !Ref FrontEndBucket
  PolicyDocument:
    Statement:
      - Effect: Allow
        Action:
          - 's3:PutObject'
          - 's3:GetObject'
          - 's3:DeleteObject'
        Resource: !Sub 'arn:aws:s3:::${FrontEndBucket}/*'
        Principal:
          AWS:
            'Fn::ImportValue': !Sub '${CIResourcesStack}-BitbucketFrontEndPipelineUser'
      - Effect: Allow
        Action:
          - 's3:ListBucket'
        Resource: !Sub 'arn:aws:s3:::${FrontEndBucket}'
        Principal:
          AWS:
            'Fn::ImportValue': !Sub '${CIResourcesStack}-BitbucketFrontEndPipelineUser'
      - Effect: Allow
        Action:
          - 's3:GetObject'
        Resource: !Sub 'arn:aws:s3:::${FrontEndBucket}/*'
        Principal:
          CanonicalUser: !GetAtt FrontEndCDNAccessIdentity.S3CanonicalUserId
Metadata:
  'AWS::CloudFormation::Designer':
    id: f8d2a536-790c-4cbe-adcb-b50754c0922e

Any help on this would be greatly appreciated!!

A: You probably selected to retain all of the resources that failed to delete when you deleted the stack. CloudFormation will not adopt existing resources into the stack. You will need to manually delete all of the resources that were created by the old stack before you can deploy this exact same stack. Or you can change the names of the resources before you deploy again.


text:
Q: How to refactor EF data access code to avoid context issues I am trying to get and update EF object but I am getting error:

Additional information: An entity object cannot be referenced by
  multiple instances of IEntityChangeTracker.

I understand what is the issue.
But how to properly write data access methods to avoid issues like this?
var store = (new StoresRepository(connectionString)).GetStore(1);
// Change store object
(new StoresRepository(connectionString)).Update(store);

Data access code:
public class StoresRepository
    {
        AppDbContext context;

        public StoresRepository(string connectionString)
        {
            context = new AppDbContext(connectionString);
        }

        public Store GetStore(int storeId)
        {
            var store = context.Stores.SingleOrDefault(x=>x.StoreId == storeId);

            return store;
        }
        public void Update(Store store)
        {
            context.Stores.Attach(store);

            context.SaveChanges();
        }

A: Create a Repository object instead of creating new ones every time.
var repo = new StoresRepository(connectionString);

var store = repo.GetStore(1);

repo.Update(store);


text:
Q: How to draw multiple bar charts each one with multiple different series I want to draw a chart which includes multiples bar chart, and each one include  different series. This is what I ´ve already have. In this case Alg 1, Alg3,..., Alg 7 would be my multiple bar charts, and parameter1,2,3 would be my multiple series. But in this case all series have the same name, and I want different names series for each bar chart.
 \documentclass[border=5mm]{standalone}
 \usepackage{pgfplots}

 \begin{document}
 \makeatletter
 \pgfplotsset{
      calculate offset/.code={
        \pgfkeys{/pgf/fpu=true,/pgf/fpu/output format=fixed}
        \pgfmathsetmacro\testmacro{(\pgfplotspointmeta           *10^\pgfplots@data@scale@trafo@EXPONENT@y)*\pgfplots@y@veclength)}
        \pgfkeys{/pgf/fpu=false}
         },
    every node near coord/.style={
        /pgfplots/calculate offset,
         yshift=-\testmacro
       },
    }
   \pgfplotstableread{
    0 1 2    4
    1 7 3    10
    2 5 2    13
    3 11 7    2
    4 12 8   16
    5 7 1   2
    }\dataset
    \begin{tikzpicture}
    \begin{axis}[ybar,
           width=17cm,
           height=10cm,
           ymin=0,
           ymax=20,
           ylabel={Iterations},
           xtick=data,
           xticklabels = {
           Alg1,
           Alg3,
           Alg4,
           Alg5,
           Alg6,
           Alg7
           },
          xticklabel style={yshift=-13ex},
          major x tick style = {opacity=0},
          minor x tick num = 1,
          minor tick length=0ex,
          every node near coord/.append style={
                   anchor=east,
                   rotate=90
          }
          ]
  \addplot[draw=black,fill=black!20, nodes near coords=parameter1] table[x       index=0,y index=1] \dataset;
   \addplot[draw=black,fill=black!40, nodes near coords=parameter2] table[x    index=0,y index=2] \dataset;
   \addplot[draw=black,fill=black!60, nodes near coords=parameter3] table[x    index=0,y index=3] \dataset;
   \end{axis}
 \end{tikzpicture}

\end{document}

What I have:

What I want:

A: Here a solution I have defined a counter \mycount which is limited to six steps and produce A,B,....,F, you can also use this method Plot the \coordindex in alphabetic order to create your counter.
The counter is used inside nodes near coords to obtain the desired numbering, the name node keys holds the name of node near coords as fellows #1-\coordindex.
Your code
\documentclass[border=5mm]{standalone}
 \usepackage{pgfplots}

 \newcounter{i}
 \setcounter{i}{1}
 \def\mycount{\Alph{i}\ifnum\value{i}<6
  \stepcounter{i}
  \else
  \setcounter{i}{1}
  \fi\kern-1ex}

 \begin{document}
 \makeatletter
 \pgfplotsset{
      calculate offset/.code={
        \pgfkeys{/pgf/fpu=true,/pgf/fpu/output format=fixed}
        \pgfmathsetmacro\testmacro{(\pgfplotspointmeta           *10^\pgfplots@data@scale@trafo@EXPONENT@y)*\pgfplots@y@veclength)}
        \pgfkeys{/pgf/fpu=false}
         },
    every node near coord/.style={
        /pgfplots/calculate offset,
         yshift=-\testmacro,
       },
    name node/.style={
    every node near coord/.append style={
                   name=#1-\coordindex
                   }}
}

   \pgfplotstableread{
    0 1 2    4
    1 7 3    10
    2 5 2    13
    3 11 7    2
    4 12 8   16
    5 7 1   2
    }\dataset
    \begin{tikzpicture}
    \begin{axis}[ybar,
           width=17cm,
           height=10cm,
           ymin=0,
           ymax=20,
           ylabel={Iterations},
           xtick=data,
           xticklabels = {
           Alg1,
           Alg3,
           Alg4,
           Alg5,
           Alg6,
           Alg7
           },
          xticklabel style={yshift=-13ex},
          major x tick style = {opacity=0},
          minor x tick num = 1,
          minor tick length=0ex,
          every node near coord/.append style={
                   anchor=north,font=\scriptsize
                   }
         ]
  \addplot[draw=black,fill=black!20,name node=1,  nodes near coords=\mycount 1] table[x       index=0,y index=1] \dataset;
  \addplot[draw=black,fill=black!40,name node=2, nodes near coords=\mycount 2] table[x    index=0,y index=2] \dataset;
  \addplot[draw=black,fill=black!60,name node=3, nodes near coords=\mycount 3] table[x    index=0,y index=3] \dataset;

   \end{axis}

   \foreach \i in{1,...,3}{
   \foreach \j in{0,1,...,5}{
   \node[anchor=east,rotate=90] at (\i-\j){parameter\kern0.5ex};}}

 \end{tikzpicture}

\end{document}

Output


text:
Q: Javascript objects: use a variable's value to access a specific object I have multiple objects with identical properties:
var obj1 = { bar: "value1", foo: "value2"};
var obj2 = { bar: "value3", foo: "value4"};

I also have a variable.
var selector = "";

selector is either "obj1" or "obj2".
How can I call one of the objects using selector without knowing the object's name?
For instance, I tried:
window(["selector"][bar])

Any help is appreciated! :)

A: You have parenthesis. window is not a function. Try without the parenthesis. In addition, you need to put quotes around bar.
window[selector]["bar"]


text:
Q: Proving the smash product is homeomorphic
Prove that $X \wedge Y \cong Y \wedge X$

I am trying to prove the smash product is homeomorphic but am not sure how to go about this?
Rewriting as $X \wedge Y = (X \times Y)/(X \vee Y)$, I know and have previously proved that $X \times Y \cong Y \times X$ but am not sure what rules apply to the quotient if anyone has any guidance?


text:
Q: Como percorrer um elemento por um em um array JS Fala pessoal, boa tarde.
Eu estou a fazer uma funcao que tem a mesma utilidade do ANY.
Qual é a ideia, é saber se tem algum numero menor que o dado na funcao dentro do array, independente se ele esta na primeira ou na ultima posição do array.
Se exister retorna TRUE, se não, retorna FALSE
O codigo ta assim:

const numerosFora = [1];

function qualquer (num1, func){
 for(let i = 0; i < num1.length; i++){
   for(let i = 0; i < func.length; i++){
     if(num1[i] < func[i]){
        return true
      } else {
         return false
      }

      }
    }

}

console.log(qualquer([1,0],numerosFora))

Porem ele so retorna se o numero estiver na primeira posicao, no caso 0.

A: Se precisar fazer testes em um array para saber se algum de seus elementos satisfazem uma condição use o método Array.prototype.some().
O método some() aceita uma função callback e a evoca uma vez para cada elemento da array até o momento que essa função callback  retorne true.

/**
 * Procura em um array por um valor menor que o valor indicado.
 * @param {Array} arr - O array cujo os elementos serão testados contra val.
 * @param {number} val - O valor a ser testado contra os elementos de arr.
 * @returns {boolean} retorna true quando encontrar em arr um elemento menor que val caso o contrário retorna false.
 */
function menorQue(arr, val) {
  return arr.some((e) => {
    return e < val;
  });
}

let lista = [2, 3, 4, 5, 6];

console.log(menorQue(lista, 10));

console.log(menorQue(lista, 2));

Outra interpretação para o sua pergunta, devido a essa declaração const numerosFora = [1];, seria fazer a comparação entre dois arrays e retornando true caso seja encontrado no primeiro array um elemento menor que no segundo.

/**
 * Procura em arr1 por um elemento que seja menor que um dos valores de arr2.
 * @param {Array} arr1 - Array cujo os elementos serão testados.
 * @param {Array} arr2 - Array cujo os elementos serão testados.
 * @returns {boolean} retorna true quando encontrar em arr1 um elemento menor que qualque um dos elementos de arr2.
 */
function algumMenorQue(arr1, arr2) {
  return arr1.some((e) => {
    return arr2.some((e1) => {
      return e < e1;
    })
  });
}

let lista = [2, 3, 4, 5, 6];

console.log(algumMenorQue(lista, [7, 8, 9]));

console.log(algumMenorQue(lista, [0, 1]));

A: Os seus for possuem problema porque os dois usam a mesma variável i, logo, na comparação num1[i] < func[i], os i serão sempre do último for.
Outra coisa, quando você coloca um return, o laço termina, ou seja, os itens restantes da array que por ventura deveriam ser percorridos, não serão mais.
Como você quer apenas verificar se retorna true e parar o laço quando isso acontecer, deixe apenas o return true no laço (e altere a variável do segundo for):

const numerosFora = [1];

function qualquer (num1, func){
  for(let i = 0; i < num1.length; i++){
    for(let x = 0; x < func.length; x++){
      if(num1[i] < func[x]){
        return true;
      }else{
        console.log(false); // apenas como exemplo para mostrar no console
      }
    }
  }
}

console.log(qualquer([1,0],numerosFora))

A: Em JavaScript ES6 seria algo assim:
const qualquer = (a, b) => {
  return a.map(item1 => b.map(item2 => item1 < item2 ? true : false));
}

console.log(qualquer([1, 2, 3, 4], [1, 3, 5]));

   //Resultado
   //0: (3) [false, true, true]
   //1: (3) [false, true, true]
   //2: (3) [false, false, true]
   //3: (3) [false, false, true]


text:
Q: R digest of closure changes after repeated call I was trying to memoise an R function that operates on a reasonably complicated closure and found that repeated calls to the memoised function would compute the result twice before retrieving the cached result, instead of only computing it on the first call.
I think there's a few things going on that cause it, but this question focuses on the first problem I'm trying to understand.
My closure is essentially a list of functions:
foo <- function() {
  bar <- function() NULL
  list(bar = bar)
}

Creating an instance of foo, and running digest:
f <- foo()
digest::digest(f)
[1] "5a54945202730e8c997aa41a27d23dd5"

Instantiating f again results in a different output for digest:
f <- foo()
digest::digest(f) # different hash
[1] "180471cb687f12271c8ba7800d02695c"

But doing it a third time shows the result has "stabilised":
f <- foo()
digest::digest(f) # no change in hash
[1] "180471cb687f12271c8ba7800d02695c"

I've been reading a lot about how environments work with closures (creating shared mutable state, limiting references visible in the enclosed environment etc.) but am still scratching my head at this seemingly simple problem!
Why does digest produce different output on the second call?

A: A friend helped me resolve this.
This behaviour is a result of the byte code compiler operating on the closure on the second call of foo().
Explicitly compiling the function before the first call resolves the problem:
bar <- compiler::cmpfun(foo)


text:
Q: Windows alert method inside function triggers twice I'm learning JavaScript, while doing so I'm exploring the Google Maps API. My .htm script below runs as intended (for now) except for a bothersome Window alert method that seems to trigger twice upon execution of that part of the script. I have no idea why - any explanation or clarification on this would be much welcome. I have a feeling it may have something to do with the structure of my script.
<!DOCTYPE html>

       <title>GPS coordinates to map TEST</title>

Click below to get your coordinates and display your current position on a map:

     <input type="button" id="btn" onclick="get_location()" value="Where am I?">

Or provide coordinates to display the position entered on a map:

     Latitude: <input type="number" id="in_lat"> Longitude: <input type="number" id="in_lon">

<input type="button" id="btn_2" onclick="find_location()" value="Show">

A: It is a typo in your code.  You are adding the "click" event listener to the button twice.
Once in the HTML:
<input type="button" id="btn" onclick="get_location()" value="Where am I?">

Once in the JavaScript:
google.maps.event.addDomListener(z, "click", get_location);

That makes the get_location function fire twice for each click on the button.  Remove one of them and it will work as you expect.
code snippet:

<!DOCTYPE html>

  <title>GPS coordinates to map TEST</title>

Click below to get your coordinates and display your current position on a map:

  <input type="button" id="btn" onclick="get_location()" value="Where am I?">

Or provide coordinates to display the position entered on a map:

  Latitude: <input type="number" id="in_lat"> Longitude: <input type="number" id="in_lon">

<input type="button" id="btn_2" onclick="find_location()" value="Show">


text:
Q: How does Erlang locate a module I not sure or I'm unaware of the conventional way that erlang locates a module which isn't located in the default directories. I understand it will look in the compiled folder and erlang's system folders or the folders that - lists:foreach(fun (E) -> io:fwrite("Path: ~s~n", [E]) end, code:get_path()) will produce.
Path: .
Path: /usr/lib64/erlang/lib/kernel-2.16.3/ebin
Path: /usr/lib64/erlang/lib/stdlib-1.19.3/ebin
Path: /usr/lib64/erlang/lib/xmerl-1.3.4/ebin
Path: /usr/lib64/erlang/lib/tv-2.1.4.10/ebin
Path: /usr/lib64/erlang/lib/tools-2.6.12/ebin
Path: /usr/lib64/erlang/lib/syntax_tools-1.6.11/ebin
Path: /usr/lib64/erlang/lib/sasl-2.3.3/ebin
Path: /usr/lib64/erlang/lib/odbc-2.10.17/ebin
Path: /usr/lib64/erlang/lib/observer-1.3.1.1/ebin
Path: /usr/lib64/erlang/lib/hipe-3.10.2.1/ebin
Path: /usr/lib64/erlang/lib/eunit-2.2.5/ebin
Path: /usr/lib64/erlang/lib/erts-5.10.3/ebin
Path: /usr/lib64/erlang/lib/edoc-0.7.12.1/ebin
Path: /usr/lib64/erlang/lib/dialyzer-2.6.1/ebin
Path: /usr/lib64/erlang/lib/debugger-3.2.12/ebin
Path: /usr/lib64/erlang/lib/compiler-4.9.3/ebin

But what's the conventional method for adding additional folders to the default paths or how do you inform a module that it must look elsewhere for a module that isn't included in the default paths?

A: You can set the ERL_LIBS environment variable in your system to look for additional library files.

A: Check out code:add_path(Directory) to append a directory to the module load paths. Also see http://erldocs.com/current/kernel/code.html?i=1&search=code:add#add_path/1 for other related functions for adding code paths.
You can also tell Erlang where to find modules by exporting the ERL_LIBS environment variable with a colon-separated list of directories. Each directory should point to an OTP project with an ebin directory where the compiled .beam files are located.


text:
Q: Multi tenancy ASP.NET core I'm trying to build ASP.NET core api where I have a few group of users. These groups have a common database, but from there they can only see the records assigned to them.
For example the user XYZ calling the controller returning the values from the Products table sees only those that were assigned to his group. And the same when he adds a new Product, only the users of his group see it, and other groups do not know about the existence of this Product.
I would like to ask you to explain to me how to do it in ASP.NET core, what libraries I could use, because unfortunately I don't know how to do it.
Thank you in advance for your help.

A: I don't think you need to search for a library or a framework to build this out, you can do the implementation as follows,

*

*Create a table that reads as ProductPermissions

*Make an entry for recordid, groupid, roleid in this table

*After a user is assigned a group, the relevant tables should have the values like UserDetails, UserGroups, UserRoles etc

*When I want to see the list of products that are accessible to me, I make a request to the GetProducts API.

*The API gets my userid from the authentication process, roles and group ids

*Now, you have to join the products table and the ProductPermissions table with the keys and filter by the groupid that I have been assigned.

*The same logic applies for all the entity operations that I do, any action will be validated against the ProductPermissions table.

Note
In order to get a generic table than redundant ProductPermissions, you can have the table as EntityPermissions and then have the entityId (ex: Product, Category etc) as a column and that will be used a filter during joining so that you have a single table for all entities.


text:
Q: What is the correct format for an NServiceBus connection to an Azure Topic? I'm trying to subscribe to messages on an Azure topic using NServiceBus, but I'm struggling to structure my connection string.
The particular website states my connection string should look as follows:
Endpoint=sb://myNameSpace.servicebus.windows.net/;SharedSecretIssuer=owner;SharedSecretValue=123123123123123123

However, I have no idea who the the 'ShadedSecretIssuer' is, and there is no 'SharedAccessKeyName' as required by Azure. This is what Azure says my connection string should look like:
Endpoint=sb://myNameSpace.servicebus.windows.net/;SharedAccessKeyName=MY_SAS_NAME;SharedAccessKey=123123123123123123123123123=

If I use Azure's format though, I get the following error on startup of my NServiceBus host:

The remote server returned an error: (401) Unauthorized.
  InvalidSignature: The token has an invalid signature.

Can somebody point me in the right direction?


text:
Q: Query for count the total number of orders and sent orders per customer (return 0 if none) I have two tables Order with columns:
orderId(int), name(varchar), customerId(int), sent(bool), deleted(bool)

And Customer with columns:
customerId(int), name(varchar), address(varchar), deleted(bool)

I need to return all Customer columns, with additional TotalOrders count and TotalSentOrders count columns (for each customer) for the Customers and Orders that deleted = false and count 0 if there are no orders or sent orders.
Expected Outcome:
|customerId|name|address|deleted|TotalOrders|TotalSentOrders|
|     1    |John| A St. | false |     0     |       0       |
|     2    |Jack| B St. | false |     5     |       1       |
|     3    |Luke| C St. | false |     4     |       0       |

I'm doing this in PostgreSQL 9.6

A: demo:db<>fiddle
SELECT
    c.*,
    COUNT(*) FILTER (WHERE o.orderId IS NOT NULL),    -- 3
    COUNT(*) FILTER (WHERE o.sent = true)             -- 4
FROM customer c
LEFT JOIN orders o ON c.customerId = o.customerId     -- 1
WHERE c.deleted = false AND o.deleted = false         -- 2
GROUP BY c.customerId, c.name, c.address, c.deleted

*

*LEFT JOIN both tables, to keep Johns data

*Remove all deleted

*GROUP BY customer and COUNT the remaining records. Because John is still in the result set, he would be counted as well. To ensure you only count the orders you could use the FILTER clause to adjust the aggregate function.

*Use the FILTER clause once more to COUNT only the sent orders.


text:
Q: Powershell Json object manipulation I am hitting a Rest API and collected a gnarly block of Json. I'm running convertfrom-json on that to get a powershell object which I would like to manipulate. Essentially I need to prune a number of field/values.
Its no issue to 'get' the fields I want to remove from the object as I can just drill down to the field and collect the value thats easy, where I am stuck is how to trim off that field from the posh object. Would appreciate any assistance. Thanks.
Example:
$sample_json = @"
{
    "fields": {
        "field_one": 1,
        "field_two": 2,
        "field_three": "three",
        "field_four": "remove_me",
        "field_five": 5
    }
}
"@
Clear-Host
$json_object = ConvertFrom-Json -InputObject $sample_json
$json_object

Gives:
fields
------
@{field_one=1; field_two=2; field_three=three; field_four=remove_me; field_five=5}

So the question is how can I remove "field_four" key, and it's value, from $json_object ? Apologies if this is crazy simple; I'm a bit out of touch with Powershell these last few years.

A: You can remove "field_four" with the Remove method from PSObject.Properties:
$json_object.fields.PSObject.Properties.Remove("field_four")

A: Use the following statement
$json_object.fields.PSObject.Properties.Remove("field_four")


text:
Q: Qt's QDir: File Names Dropping Non-Ascii Characters I am having issues with QDir losing Non-Ascii characters from my file names.
I have files with names like testingöäüß.txt or exampleΦ.shp and when trying to use Qt utilities like QDir and QFile they simply show up as testing.txt and example.shp. Seems as though I cannot tell those classes what kind of encoding to use. I'm trying QDirIterator and the QDir function entryInfoList:
   QDir someDir("/home/blah");  //contains testingöäüß.txt

   QDirIterator dirIter(someDir.absolutePath(), QDir::NoDotAndDotDot | QDir::Dirs | QDir::Files);
   while(dirIter.hasNext())
   {
      QString fileName1 = QFile::decodeName(dirIter.next().toUtf8());
      std::cout << "QDirIterator Name " << fileName1.toStdString().c_str() << std::endl;
   }

   QFileInfoList fileInfoList = someDir.entryInfoList(QDir::NoDotAndDotDot | QDir::Dirs | QDir::Files);
   foreach(QFileInfo fileInfo, fileInfoList)
   {
      QString fileName1 = QFile::decodeName(fileInfo.fileName().toUtf8());
      std::cout << "entryInfoList Name " << fileName1.toStdString().c_str() << std::endl;

      QString fileName2 = QFile::decodeName(fileInfo.absoluteFilePath().toUtf8());
      std::cout << "entryInfoList Name2 " << fileName2.toStdString().c_str() << std::endl;

      QString fileName3 =  QString::fromUtf8(dirIter.fileInfo().absoluteFilePath().toStdString().c_str());
      std::cout << "entryInfoList Name3 " << fileName3.toStdString().c_str() << std::endl;
   }

Every one of those prints will lack the non-ascii characters. Seems like as soon as you try to grab the file names to loop over they will be ascii only. Anyone have any ideas on this? Or can Qt simply not handle this? Thanks!

A: I know this is an old question, but I just ran into the same problem. The same exact Qt code would work fine on my development VM, but when I transferred it to an embedded Linux system (running on x86 so literally the same executable) my directory names just silently got their non-ASCII characters dropped.
Turned out the QTextCodec::codecForLocale on my dev VM was set to UTF-8, and on the embedded box it was System. If I manually changed the locale to UTF-8 before doing any filesystem operations (by calling QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"))), everything started working fine.
So why was this happening in the first place? My suspicion is that in the process of slimming down the embedded system's root filesystem I might have accidentally deleted some locale-related files that Qt was using to try to auto-detect the locale. When it couldn't determine it was on UTF-8, it fell back to System, which for whatever reason is broken (maybe for the same reason it couldn't detect UTF-8 in the first place).
I need to eventually fix whatever is causing it to not auto-detect, but in the short-term just manually setting a UTF-8 locale should work if you are experiencing this same issue.
Note that this has nothing to do with whether the console can display UTF-8, or anything to do with manual conversion of UTF-16 to UTF-8! So Felix's answer to this question is not correct, at least for this particular issue. To completely remove the capability of the console from the equation, I was also simply printing the number of UTF-16 characters in the string, and every non-ASCII character actually made the returned path and filename strings from QDir::entryInfoList have one less UTF-16 character. Additionally, the dead giveaway is that the characters were simply stripped out, not just replaced with garbage or question marks or whatever.

A: Qt can handle filenames with special characters. You just make them disappear somewhere in that string conversion stuff. (Which is completly unnecessary) Try it this way:
#include <QDebug>
//...
QFileInfoList fileInfoList = someDir.entryInfoList(QDir::NoDotAndDotDot | QDir::Dirs | QDir::Files);
foreach(QFileInfo fileInfo, fileInfoList)
{
    qDebug() << fileInfo.fileName();//uses qdebug
    std::cout << fileInfo.fileName().toStdWString() << std::endl;//uses a 16Bit string on normal cout
}

If you still don't see them, it's because your console settings do not allow to display them. Try to write them to a file or display them in a gui - or simply try to open a file with that name, it will work.


text:
Q: How can I get animation from PPTX by using Apache POI API I'm converting PPT and PPTX file to HTML.
I can get background pictures,text,layout and so on.But I can't get custom shape and animation.
Some code of my project:
public static void getPic(XMLSlideShow ppts) throws Exception {

    for (XSLFPictureData data : ppts.getPictureData()) {
        String index = data.getIndex()+1 + "";
        String ext = data.getType().extension;

        FileOutputStream fileout = new FileOutputStream(path + "imgPPTX\\" + index + ext);
        InputStream pIs = data.getInputStream();
        if (ext.equals(".wmf")) {
            Wmf2Svg.convert(path + index + ext);
            ext = ".svg";
        }
        // System.out.println(pict.getHeader().toString());
        img.put(data.getFileName(), index + ext);

        fileout.write(data.getData());
        fileout.close();
        pIs.close();
    }

}

public static void getBg(XSLFSlide ppt) throws Exception {
    System.out.println(ppt.getSlideNumber() + ":  " + ppt.getSlideLayout().getTheme().getName() + "   " + ppt.getSlideLayout().getName());
    XSLFBackground bg = ppt.getBackground();
    CTBackground xmlBg = (CTBackground) bg.getXmlObject();
    if (xmlBg.getBgPr().getBlipFill() != null) {
        String relId = xmlBg.getBgPr().getBlipFill().getBlip().getEmbed();

        XSLFPictureData pic = (XSLFPictureData) ppt.getRelationById(relId);
        htmlins.insertImg(img.get(pic.getFileName()), "[x=0,y=0,w="+pageSize.getWidth()+",h="+pageSize.getHeight()+"]");
        // System.out.println("backg: " + pic.getFileName());
    } else {
        // System.out.println("backg: no background");
    }
    for (XSLFShape shape : ppt.getSlideLayout().getShapes()) {
            dealBGShape(shape);
    }
}


text:
Q: Should network DTC be enabled for oracle transactions I have a WCF based web service hosted in windows sever 2003 machine. The database is Oracle 10G on solaris. The web service uses transactionscope extensively and ado.net transactions in some places. Most of the transactions involve only one resource (multiple oracle stored proc calls). Some of them are two resources (MSMQ and oracle stored proc).
Given this does network DTC has to be enabled on the windows machine. It already has MSDTC service started.
There is no transaction flow from web service client to the web service.
It seems to work without network DTC enabled but I want to be sure.
The platform is .Net 2.0 SP1 + 3.0 (for WCF). Oracle driver is ODP.Net v11.1.0.6

A: My beleive is that Network DTC doesn't need to be enabled. The only requirement is that both MSDTC and OracleMTSRecoveryService services are started. I can view transactions happening using the DTC component services viewer control panel app.

A: If the client transactions are not flowing or if there are no multiple durable resources the transaction manager the transaction will not be promoted to distributed transaction.
You can check the transaction identifiers by accessing the TransactionInformation property of the Transaction class.
This class has DistributedIdentifier property.  DistributedIdentifier would be Guid.Empty if the transaction is not promoted to a distributed transaction.


text:
Q: How to use PublishBuildArtifacts for publishing one file without directory-tree? My Build-Pipeline builds my artefact to $(Pipeline.Workspace)\s\out\make\squirrel.windows\x64\simSetup-1.0.0.exe.
I want to publish this file as a pipeline-artifact.
For this, I have craeted this two tasks in my pipeline:
- task: CopyFiles@2
  displayName: 'Copy Files to: $(Build.ArtifactStagingDirectory)'
  inputs:
    SourceFolder: '$(Pipeline.Workspace)'
    Contents: '**/simSetup-*.exe'
    TargetFolder: '$(Build.ArtifactStagingDirectory)'

- task: PublishBuildArtifacts@1
  displayName: 'Publish Artifact: sim'
  inputs:
    ArtifactName: simSetup

This is working but it will include the whole directory-tree in the published zip-file. How can I only include the file simSetup-1.0.0.exe?

A: I think this should achieve your requirements:
trigger:
- none

pool:
  vmImage: ubuntu-latest

steps:
- task: CopyFiles@2
  inputs:
    SourceFolder: '$(Pipeline.Workspace)'
    Contents: '**/simSetup-*.exe'
    TargetFolder: '$(Build.ArtifactStagingDirectory)'
    flattenFolders: true

- task: PublishBuildArtifacts@1
  displayName: 'Publish Artifact: sim'
  inputs:
    ArtifactName: simSetup

This is my folder structure:

Successfully clean the tree structure during pipeline run via the setting:


text:
Q: Trying to bind datatable with listbox...something wrong Please help...what am I doing wrong here? Trying to bind listbox to datatable. After debugging, i see data rows in the table but some how it is not binding to listbox.
FYI. _this is the name of my current window...
            <ListBox Grid.Column="1" ItemsSource="{Binding ElementName=_this, Path=MainCategoriesTable}" HorizontalAlignment="Center" BorderBrush="Transparent" Background="Transparent" x:Name="lbMainCategories">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <RadioButton Grid.Column="0" Content="{Binding Path=main_category_name}" VerticalAlignment="Center" GroupName="grpMainCategory" x:Name="rdbEnableDisable" />
                            <Label Grid.Column="1" Width="30" Background="Transparent" />
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

Below is the property trying to bind with...
    public DataTable MainCategoriesTable
    {
        get { return _dtMainCategory; }
        set { _dtMainCategory = value; }
    }

A: For XAML to set the data context tocode behind this is what works for me
  DataContext="{Binding RelativeSource={RelativeSource Self}}"

in code behind
  this.DataContext = this;

But I used _this like you have used it successfully.
Set Presentation.Trace = High in the all XAML binding.  That is not the exact syntax but if you start with Presentation it should be obvious.
Why no binding on label.
main_category_name is a public property?  I notice it is in lower case.

A: DataTable works like a dictionary, not like an object. It doesn't expose your columns as properties, but each DataRow exposes an indexer that can be used to get the cell value. Therefore, you need to use indexer syntax:
<RadioButton Grid.Column="0" Content="{Binding Path=[main_category_name]}" VerticalAlignment="Center" GroupName="grpMainCategory" x:Name="rdbEnableDisable" />

UPDATE
Another thing that bothers me is that your MainCategoriesTable property doesn't notify about changes. If it's changed after all Bindings have been initialized, it won't work (while DependencyProperty will, because it always notifies about changes). To make it work, your context class must implement INotifyPropertyChanged interface and your property must look like this:
public DataTable MainCategoriesTable
{
    get { return _dtMainCategory; }
    set
    {
      if(value == _dtMainCategory)
      {
        return;
      }

      _dtMainCategory = value;
      var h = this.PropertyChanged;
      if(h != null)
      {
        h(this, new PropertyChangedEventArgs("MainCategoriesTable"));
      }
    }
}


text:
Q: Automatically export/deployment for Eclipse plugins We are working on an Eclipse plugin project. All of our deliverables are 25 plug-in files (yes, you can also say that they are 25 jar files or 25 OSGi bundles).
Every time we export those files by File → Export → Plug-in Development → Deployable plug-ins and fragments. It costs about 30 minutes to export all those files. The export way sounds like out-of-date but not so inconvenient.
And I have some doubts about the exporting/deployment:

*

*If we use a build tool (such as ANT or Maven) to build these jar files automatically, will the build tool reduce the whole exporting time ?

*The PDE can generate a ant build file by Plug-in Tools → Create Ant Build File, so can we use those generated files directly, even without start up the elipse IDE? Since they seem to be eclipse-related.

*Its better if you have suggestions on what I'm saying.

Tks in advance.

A: Maybe tycho is what you need. Tycho is a maven plugin for building osgi bundles(and eclipse plugins)

A: While eclipse plugins can be shared and delivered, they are not meant to be used as deliverables. Instead you should create an eclipse feature, which combines the plugins into one single installable unit.


text:
Q: Capistrano initial deployment failed I have trouble while deploying Rails 3 project with Capistrno to the linode VDS. Error looks like:
lifecoder@lifecoder-VirtualBox:~/projects/ruby/avtolife$ cap deploy:update
  * executing `deploy:update'
 ** transaction: start
  * executing `deploy:update_code'
    updating the cached checkout on all servers
    executing locally: "git ls-remote git@bitbucket.org:lifecoder/avtolife.git master"
    command finished in 2964ms
  * executing "if [ -d /srv/avtolife/shared/cached-copy ]; then cd /srv/avtolife/shared/cached-copy && git fetch -q origin && git fetch --tags -q origin && git reset -q --hard aec5c7f44151ca74d8eb384c478d6707719ee680 && git clean -q -d -x -f; else git clone -q git@bitbucket.org:lifecoder/avtolife.git /srv/avtolife/shared/cached-copy && cd /srv/avtolife/shared/cached-copy && git checkout -q -b deploy aec5c7f44151ca74d8eb384c478d6707719ee680; fi"
    servers: ["original-parts.net"]
    [lifecoder@original-parts.net] executing command
 ** [original-parts.net :: err] Host key verification failed.
 ** [original-parts.net :: err] fatal: The remote end hung up unexpectedly
    command finished in 1401ms
*** [deploy:update_code] rolling back
  * executing "rm -rf /srv/avtolife/releases/20120620203352; true"
    servers: ["original-parts.net"]
    [lifecoder@original-parts.net] executing command
    command finished in 588ms
    failed: "rvm_path=$HOME/.rvm/ $HOME/.rvm/bin/rvm-shell '1.9.2' -c 'if [ -d /srv/avtolife/shared/cached-copy ]; then cd /srv/avtolife/shared/cached-copy && git fetch -q origin && git fetch --tags -q origin && git reset -q --hard aec5c7f44151ca74d8eb384c478d6707719ee680 && git clean -q -d -x -f; else git clone -q git@bitbucket.org:lifecoder/avtolife.git /srv/avtolife/shared/cached-copy && cd /srv/avtolife/shared/cached-copy && git checkout -q -b deploy aec5c7f44151ca74d8eb384c478d6707719ee680; fi'" on lifecoder@original-parts.net

I need an idea on how to trace where the particular error is done. I'm pretty new in *nix and rails so some parts of config looks like magic for me :(

A: When something go wrong with Capistrano deployment - run scenario commands one by one on the remote server. My trouble was with the target server - local Ubuntu asked for remote IP address acceptance and die when have no answer from cap script. After acceptance same script runs fine.


text:
Q: Sets order isomorphic to $[\omega_0, \omega_1)$ Let $\omega_0$ be the first countable ordinal and $\omega_1$ be the first uncountable ordinal. Use $[0, \omega_1)$ to denote the set of all countable ordinals and hence $\omega_1 = [0, \omega_1)$. Could someone construct a set (other than the set of ordinals) that is order isomorphic to the set $[\omega_0, \omega_1)$. In this post, Arthur (in the top post) provided an example, which is the following:
For each $\alpha\in[0, \omega_1)$, let $X_{\alpha}$ be the set of subsets of $\mathbb{Q}$ , each of which is order isomorphic to $\alpha$, and define $X_{\alpha} < X_{\beta}$ iff $\alpha < \beta$. Then it is claimed that the following set $A$, equipped with the order "<"
$$A = \{X_{\alpha}\,\vert\,\alpha\in[0, \omega_1)\}\hspace{1cm}(\subseteq\mathcal{P}[\mathcal{P}(\mathbb{Q})])$$
is order isomorphic to $[0, \omega_1)$. If we can find a uncountable family of sets (ideally not subsets of the set of ordinals) so that the supremum is not in the family and no countable union of elements will be equal to the supremum, will that work for this question?

A: The map $f(x) = \omega_0 + x$ is an order isomorphism $[0, \omega_1) \to [\omega_0, \omega_1)$.
First, let's prove that it's a bijection. Note that in general, if we have ordinals $a \geq b$, then there exists a unique $c$ such that $a = b + c$. So for all ordinals $a \in [\omega_0, \omega_1)$, there exists a unique $c$ such that $\omega_0 + c = a$. This proves that $f$ is a bijection.
From here, we must show that $f$ is an order isomorphism. Suppose that $x \leq y$. Then write $y = x + z$. Then $f(y) = \omega_0 + y = \omega_0 + x + z = f(x) + z$, so $f(x) \leq f(y)$. The fact that both are total orders proves it's an order isomorphism and not just order-preserving.
Obviously, this result generalises a lot.


text:
Q: Homomorphism in Van Kampen Theorem I am having difficulty understanding the first homomorphism in the van Kampen Theorem (see Hatcher pp 42-43).  I will illustrate my confusion with the simple example of an annulus ($X$), which will be covered by two subsets ($A$ and $B$), each of which include the central opening and constructed so that their intersection is path connected, and so that each contains the base point.
The fundamental group of both $A$ and $B$ is $\mathbb{Z}$.  The free product of the fundamental groups of $A$ and $B$ is the argument of the homomorphism, and this free product is $\mathbb{Z}\star\mathbb{Z}$.
Now, my question:  How does the homomorphism map $\mathbb{Z}\star\mathbb{Z}$ to $\mathbb{Z}$, the fundamental group of the annulus?
If I understand the definitions correctly, a word $g_1g_2$ in the argument will be mapped to $g_1g_2$.  But the range of the homomorphism is $Z$, the fundamental group of $X$, and $g_1g_2$ is not in $Z$.
(P.S. I see, of course, that words like $g_1g_2$ can be reduced with the knowledge that there is only one hole in $X$, and so there never were two loops after all.  But this presupposes an understanding of the structure of $X$.  And, if one already understands $X$, there is no reason to resort to the van Kampen Theorem in the first place.)

A: Here is a step-by-step execution of your example:
Seifert-van Kampen (as in Hatcher, adapted). If $X$ is the union of path-connected open sets $A$ and $B$ each containing the basepoint $x_0 \in X$ and if $A\cap B$ is path-connected, then the homomorphism $\Phi : \pi_1(A)∗\pi_1(B)\to\pi_1(X)$ is surjective. The kernel of $\Phi$ is the normal subgroup $N$ generated by all elements of the form $i_{AB}(\omega)i_{BA}(\omega)^{−1}$ for $\omega\in \pi_1(A\cap B)$, and hence $\Phi$ induces an isomorphism $\pi_1(X) \cong  \pi_1(A)∗\pi_1(B)/N$.
Here, $i_{AB}$ is the homomorphism induced by the inclusion of $A\cap B$ into $A$, and similar for $i_{BA}$.
(Note that the second sentence originally has the condition that the triple intersections are path-connected, which is trivial here.)
In general, this is good news because for example, when your intersection is simply connected, your $i_{AB}$ and $i_{BA}$ must be trivial maps, so $N$ must be trivial. What you have to know is not $\pi_1(X)$ here, but rather $\pi_1(A\cap B)$. In your example, these are isomorphic, whence it is actually not too exciting for that special case.
Now to the particulars: What we have to know is $\pi_1(A)\cong \mathbb{Z}$, $\pi_1(B)\cong \mathbb{Z}$, $\pi_1(A\cap B)\cong \mathbb{Z}$. Let $a$ be a generator of $\pi_1(A)$, $b$ a generator of $\pi_1(B)$. These can be thought as fixed loops, as Michael described, say counterclockwise. Then the elements of $\pi_1(A)*\pi_1(B)$ look like, for instance, $\emptyset$, $aaabbba$, $abbaba$, $a^-b^-aab$, etc. Here with $a^-$ I denote $(-1)a$ (inverse), and if you feel more comfortable, you may write $a^3$ instead of $aaa$, etc.
Now the question is: What does $i_{AB}:\pi_1(A\cap B)\to\pi_1(A)$ do? All loops in $A$ are homotopic to some loop in $A\cap B$ relative endpoint (again, sort of boring because $A$ and $A\cap B$ look "too alike" for it to be interesting), so this map is an isomorphism. Take $\omega$ to be the preimage of $a$. We can easily see that $i_BA(\omega)=b$ (here we "use the knowledge" from $B$ and not from $X$!) So, the same applies for $i_{BA}$ and $\pi_1(B)$, except now we are taking the inverse of $i_{BA}(\omega)$ into account. when calculating $N$. $N$ is generated by $ab^-$, so we will "shorten" by $ab^-=0$, which you can basically think of as not differentiating between $a$ and $b$ (since $a=ab^-b\simeq b$). Then evidently, the free group modulo this identification is $\cong \mathbb{Z}$, given by word length after the identifications.
Summary: You indeed need to know the fundamental group structures of your two subsets that cover your space, and of their intersection. In this particular example, it is tempting to think that we are using the whole space's knowledge where we actually always use that of either one part, or the intersection. But all those groups/spaces were really similar here, so Seifert - van Kampen would be a real overkill. :)

A: Let $g_1, g_2$ be the generators of $\pi_1(A)$, $\pi_1(B)$ given by counterclockwise loops around the central hole, and let $h$ be the generator of $\pi_1(X)$ given by a counterclockwise loop around the central hole. Then the map $\pi_1(A)\ast\pi_1(B) \to \pi_1(X)$ induced by the inclusions $A \hookrightarrow X$ and $B \hookrightarrow X$ is given by $g_1 \mapsto h$, $g_2 \mapsto h$. Therefore, the word $g_1g_2$ is mapped to $h^2$.