text:
Q: what is the standard ada include path Im using gnat4.6 on Ubuntu installed using apt-get. I need to know where to install downloaded libraries like APQ. What should I set my ADA_INCLUDE_PATH and ADA_OBJECTS_PATH to?

A: The beauty of Ada support in Debian (on which Ubuntu is based) is that you don't need to mess with ADA_INCLUDE_PATH and friends; supported libraries are installed where the GNAT Project Manager expects to find them. Say gnatls -v to see the default values.
To use the system as intended, you will find it much simpler to use the GNAT Project Manager; you'd say, in your my_project.gpr file,
with "apq";
project My_Project is
   ...

and build with
$ gnatmake -P my_project

There's online documentation for GPR, but I wouldn't call it particularly user-friendly. There's a set of Youtube videos (I haven't looked at them in any detail; their stated interest is large systems, but hang in there).

A:
I use gnatmake to build; how do I cite my build paths in a correct way?

The relevant options are shown in 6.2 Switches for gnatmake: Source and library search path switches.
Addendum: The development package is libapq3.2.0-dev.

*

*The manual is in /usr/share/doc/libapq3.2.0-dev/manual.pdf.gz

*An example and corresponding .gpr file are in /usr/share/doc/libapq3.2.0-dev/examples. As @Simon suggested, the .gpr file begins:
with "apq.gpr";
project APQ.Samples is

*The Ada include files are in /usr/share/ada/adainclude/apq.

*The libraries are in /usr/lib.

$ dpkg -L libapq3.2.0-dev
/.
/usr
/usr/share
/usr/share/ada
/usr/share/ada/adainclude
/usr/share/ada/adainclude/apq
/usr/share/ada/adainclude/apq/apq_helper.ads
/usr/share/ada/adainclude/apq/apq_helper.adb
/usr/share/ada/adainclude/apq/apq.adb
/usr/share/ada/adainclude/apq/apq.ads
/usr/share/ada/adainclude/apq.gpr
/usr/share/doc
/usr/share/doc/libapq3.2.0-dev
/usr/share/doc/libapq3.2.0-dev/copyright
/usr/share/doc/libapq3.2.0-dev/manual.pdf.gz
/usr/share/doc/libapq3.2.0-dev/examples
/usr/share/doc/libapq3.2.0-dev/examples/apq-samples.adb
/usr/share/doc/libapq3.2.0-dev/examples/apq-samples.ads
/usr/share/doc/libapq3.2.0-dev/examples/apq-samples.gpr
/usr/lib
/usr/lib/libapq.a
/usr/lib/ada
/usr/lib/ada/adalib
/usr/lib/ada/adalib/apq
/usr/lib/ada/adalib/apq/apq_helper.ali
/usr/lib/ada/adalib/apq/apq.ali
/usr/share/doc/libapq3.2.0-dev/changelog.Debian.gz
/usr/lib/libapq.so


text:
Q: Exporting 3D eps figures with transparent background I am attempting to export a 3D plot from mathematica with no background, but I seem to be unable to find a way.
ParametricPlot3D[{{Cos[x], Sin[x], x}, {Sin[x], Cos[x], x}}, {x, 0,
  1}, PlotLegends -> {a, b}, Background -> None]
Export["test.eps", %, Background -> None]

The background of the legend is transparent, but not that behind the figure. I am able to do it in the case of 2D plots.

A: With version 10.4.1 I get the plot rasterized (but not the legend) with your code. As a workaround you can use the Jens' trick:
Export["myFig2.eps", Graphics[Inset[pl, Automatic, Automatic, Scaled[1]]]];

Here is how the exported EPS file looks when opened by Adobe Acrobat 11 (I have selected a number on the frame in order to show that it is a selectable text):

Not ideal but at least it is in vectors and has no background (the following is a screenshot of a MS Word 2003 document where I imported the EPS figure):

redpajama_set_name: RedPajamaStackExchange


text:
Q: Fixing Pagination with Custom Taxonomy Archive I've been trying to set up a way to write posts in a series on my site.  The idea is that each post can belong to a different series in a custom taxonomy.  I've gotten just about everything set up the way I want it ... with one exception.
Registering the Taxonomy
This part is working.  I've dropped the following code into a plug-in:
function jdm_build_series_taxonomy() {
    $labels = array(
        'name' => _x('Series Labels', 'taxonomy general name'),
        'singular_name' => _x('Series Label', 'taxonomy singular name'),
        'search_items' => __('Search Series Labels'),
        'popular_items' => __('Popular Series Labels'),
        'all_items' => __('All Series Labels'),
        'parent_item' => __('Parent Series Label'),
        'parent_item_colon' => __('Parent Series Label:'),
        'edit_item' => __('Edit Series Label'),
        'update_item' => __('Update Series Label'),
        'add_new_item' => __('Add New Series Label'),
        'new_item_name' => __('New Series Label Name')
    );

    register_taxonomy(
        'series',
        'post',
        array(
            'hierarchical' => true,
            'label' => __('Series'),
            'labels' => $labels,
            'query_var' => true,
            'rewrite' => true
        )
    );
}

add_action( 'init', 'jdm_build_series_taxonomy', 0 );

This adds "Series Labels" to the Posts dropdown menu and gives me a "Series Labels" box on the post edit screen.  Everything's working, and I can mark posts as a part of a series perfectly.  The problem lies in the next section ...
Listing items in the Taxonomy
My goal is to allow readers to walk through a series one post at a time, starting with the oldest post and moving forwards chronologically.  This is different than a typical archive page, because I have 10 posts per page for my archives, but I obviously want only one post per page for my series archive.
I've created a taxonomy-series.php file inside my template.  And it half works.  The first page will work just fine - http://localhost/wp/series/my-test-series/ displays the first article in the series with the "Next Entry »" link on the bottom of the page.  So far, so good ...
But when you click "Next Entry »" and go to the next page (http://localhost/wp/series/my-test-series/page/2/) it's a) the wrong article and b) the wrong template!
However, if I set "Blog pages show at most:" to "1" on the Reading page (it's normally set to 10) then things work just fine.  Page 2 displays the second article, page 3 displays the third, etc.
So ... what do I need to double check to force the taxonomy archive page to display only one post on each page?  I've tried the following:
$new_query = wp_parse_args(
    $query_string,
    array(
        'posts_per_page' => 1,
        'paged' => $paged
    )
);

query_posts($new_query);

and
query_posts($query_string.'&posts_per_page=1&paged='.$paged);

to no avail ... ideas?  Tips?  Suggestions?

A: Hi @EAMann:
I cringe anytime I need to do something creative with URLs in WordPress as the URL system is in my opinion by far the most inelegant aspect of WordPress. I always feel like I'm having to fight WordPress to get it to do what I want, and that WordPress is actively fighting me back related to URLs. So with that opener...
Thinking through your issue I'm going to make a suggestion which isn't exactly what you asked for. If you don't find it to be what you are looking for that's okay just please don't anyone down-vote because I'm just trying to help.
Taxonomy Isn't Single Increment and Has No Meta
One of the problems with what you are trying to do is the taxonomy system doesn't a single increment ordering and it doesn't have meta. For example in a 3 post series you might find terms with IDs of 373, 411 and 492; you can figure that 373 = #1, 411 = #2 and 492 = #3 but that's all happenstance and relative to each other. It's like trying to location the root of your WordPress site in plugin code but you don't know how many levels deep your code will be stored. Of course can write code to figure it all out and map them but that gets tricky and I'm not sure you'd get much value out of trying to figure it out instead of using a different approach.
Explicitly Assign Your Page Numbers
So the first thing I would suggest is that you explicitly assign your page numbers for each post in your series using post meta/custom fields (I picked the term installment instead of page because it made more sense to me but clearly you could use any term that fits for your use-case.)
Assigning page/installment numbers has the benefit of you being in complete control and that way you'll know what to fix when somethings out of whack and if you want to reorder you can do so just by changing the numbers. I'm assuming you'll have a edit metabox for a custom field name _installment for selecting the installment numbers (and it could even manage/juggle installment numbers via AJAX if you want to get creative so that you never have pages out of sync.)
Use $wp_rewrite->add_rule() to Explicitly Assign Your URL
I won't go in depth since I know you've generally got mad WordPress skilz so I'll just point
out that $wp_rewrite->add_rule() is the cruz of getting this all to work. Everything else is just providing support around that function's result.  Use the init hook assign your URL rule:
<?php
add_action('init', 'add_series_installment_url');
function add_series_installment_url() {
  global $wp,$wp_rewrite;
  $wp->add_query_var('series');
  $wp->add_query_var('installment');
  $wp_rewrite->add_rule('series/([^/]+)/(installment-\d+)','index.php?series=$matches[1]&installment=$matches[2]','top');
  $wp_rewrite->flush_rules(false);  // This should really be done in a plugin activation
}

Use parse_query hook to Translate URL to Query Vars
The 2nd half of this solution uses the parse_query hook which I know you much be familiar with. In general we capture the query_vars defined in init and captured via the URL rule and convert them into what we need to query WordPress posts with taxonomy+term handling your series and meta_key+meta_value handling the explicitly assigned installment/page:
<?php
add_action('parse_query', 'apply_series_installment_to_query');
function apply_series_installment_to_query(&$query) {
  if (isset($query->query['series']) && isset($query->query['installment']) &&
     preg_match('#^installment-(\d+)$#',$query->query['installment'],$match)) {
    $query->query_vars['post_type'] = 'post';
    $query->query_vars['taxonomy'] = 'series';
    $query->query_vars['term'] = $query->query['series'];
    $query->query_vars['meta_key'] = '_installment';
    $query->query_vars['meta_value'] = $match[1];
    unset($query->query_vars['series']);            // You don't need this
    unset($query->query_vars['installment']);       // or this
    unset($query->query_vars['name']);              // or this
  }
}

Summary
Normally I would have gone into a lot more depth explaining an answer but it's late, I've had too little sleep in the past 48 hours, and most importantly I know you can figure it out, you probably just needed one thing I mentioned here.
So I hope you like this solution. Even if you don't the two parts with init and parse_query and the $wp_rewrite->add_rule() and the $query->query_vars[] respectively are what you need even if you want to stick with your original architecture. Good luck and looking forward to seeing it when you have it done and online!
Anyway,
Hope this helps.

A: Here is code I use to modify number of posts on archive pages of categories and tags:
query_posts( array_merge( array(
'posts_per_page' => 1
), $wp_query->query ) );

If you can't make this work with custom taxonomy try with native (categories, tags) to check if problem is with code itself, with taxonomy or something else entirely.
Also I am not sure if you missed this or left out, but $paged is not global variable. It must be fetched as get_query_var( 'paged' )

A: Once I have faced problem about this and passed hard times  hrs to hrs by pulling hair. I googled and didn't found any specific solution about the topics. I found several talents' article but they weren't satisfying my problems. Actually custom taxonomy archive page pagination is depends on some settings of arguments of related functions. So I am actually going here sharing my thoughts of solving the taxonomy archive pagination problem.
Five things you need for custom taxonomy archive page pagination working perfectly:
( 1 ) Don't put exclude_from_search parameter key as register_post_type argument parameter or set it 'exclude_from_search' => false. By default it is set false.
( 2 ) The taxonomy that will be use with the custom post type set 'taxonomies' => 'custom_taxonomy_name' as register_post_type argument parameter or use register_taxonomy_for_object_type() directly. Custom taxonomies still need to be registered with register_taxonomy().
( 3 ) While querying within new WP_Query ($args)
i ) If not set in admin static front page use before new WP_Query($args)
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;

and use $query = new WP_Query( array( 'paged' => $paged ) );
ii ) If set in admin static front page use before 'new WP_Query($args)':
  $paged = ( get_query_var('page') ) ? get_query_var('page') : 1;

and use $query = new WP_Query( array( 'page' => $paged ) );
Remember to use  posts_per_page and paged parameter in new WP_Query($arg) argument array.
If not set static front page, then you should use page parameter in new WP_Query ($arg) argument array.
( 4 ) Use Wordpress paginate_links( $args ) function like the example below to render pagination in archive template file.
<?php $big = 999999999; // need an unlikely integer
echo paginate_links( array(
                  'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
                  'format' => '?paged=%#%',  or   '/paged=%#%',  // if using pretty permalink
                   'current' => max( 1, get_query_var('paged') ),
                   'total' => $query->max_num_pages ) ); // Here $max_num_pages is the properties of  new WP_Query() object . It is total number of pages. Is the result of $found_posts / $posts_per_page
 ?>

( 5 ) The paginate_links() function output the ul li listing with page-numbers class.
        If you use bootstrap inject pagination class to the ul with the help of javascript or jquery and a nice fancy pagination         will be output.
Hope you can now enjoy pagination in the taxonomy archive template without any 404 problem :-)


text:
Q: What's wrong with Metal instrument simdgroup_load or simdgroup_store? OS: MacOS 12.2.1
Hardwear: MacBook Pro 2020, M1
Metal: 2.4
Xcode: 13.2.1
Here is my test computer kernel,which read input buffer with simdgroup_load adn write output buffer with simdgroup_store
kernel void fun(
const device half * Src                 [[ buffer(0) ]],
constant uint4 & SrcShape               [[ buffer(1) ]],
device half * Dst                       [[ buffer(2) ]],
constant uint4 & DstShape               [[ buffer(3) ]],
const device half * Weight              [[ buffer(4) ]],
ushort3 threadgroup_position_in_grid    [[ threadgroup_position_in_grid ]],
ushort3 thread_position_in_threadgroup  [[ thread_position_in_threadgroup ]],
ushort3 threads_per_threadgroup         [[ threads_per_threadgroup ]],
ushort3 thread_position_in_grid         [[ thread_position_in_grid ]])
{

    const int SrcSlices = (int)SrcShape[0];
    const int SrcHeight = (int)SrcShape[1];
    const int SrcWidth  = (int)SrcShape[2];
    const int DstSlices = (int)DstShape[0];
    const int DstHeight = (int)DstShape[1];
    const int DstWidth  = (int)DstShape[2];
    const int Kernel_X = 3;
    const int KernelElemNum = 3 * 3;
    const int N_Pack = 8;

   // Test only 1 thread
   if(thread_position_in_grid.z != 0|| thread_position_in_grid.y != 0|| thread_position_in_grid.x * N_Pack != 0) return;

    simdgroup_half8x8 sgMatY;
    simdgroup_load(sgMatY, Src);

    simdgroup_store(sgMatY, Dst);

}

It's a simple shader, however output buffer only save first 2 values from input buffer,the other 62 values are ALL ZERO.
Here is the result from Xcode Metal Capture

How to debug or fix it?

A: Bug fixed.
Anyone who intent to use this feature can refer in the implementation in TF-Lite:
https://github.com/alpa-projects/tensorflow-alpa/blob/ee8f6612b515ada4509fa53491c5ba5b3ef8524a/tensorflow/lite/delegates/gpu/common/tasks/conv_metal_simd.cc


text:
Q: Convert canvas image in webpage to pdf using flying saucer I am using Flying Saucer to generate pdf from webpages. I came across a problem. Problem is how to print canvas images in pdf using flying saucer. Is there any other way, i can convert canvas images to pdf ?

A: The only way to print canvas images into pdf using xhtmlrenderer, would be to convert these images into some format  FS could understand. There is a Javascript method that converts the canva images into some static format that FS could use,
please take a look at https://github.com/hongru/canvas2image
Hope this would help :)


text:
Q: Find the nodes with the most mutual connecting nodes? I'm working with a data set that contains customers, their purchases and the businesses they purchased from, and I'm trying to determine which businesses share the highest number of mutual customers. Ideally the output would be a table that lists the connected businesses and the number of mutual customers. I.e.:
| BUSINESS_1 - BUSINESS_2 | 4 |
| BUSINESS_1 - BUSINESS_5 | 3 |
| BUSINESS_3 - BUSINESS_7 | 2 |
| BUSINESS_4 - BUSINESS_9 | 2 |

I don't have much at this point, but the query I'm working with looks something like this:
MATCH (c:Customer)<-[:Trans_Cust]-(t:Transaction)-[:Trans_Business]->(b:Business)
RETURN c, t, b

Thanks in advance

A: I guess this should do the trick, maybe provide a sample dataset on http://console.neo4j.org for us to help.
MATCH (b:Business)
MATCH (b)<-[:Trans_Business]-(t:Transaction)-[:Trans_Cust]->(c:Customer)
MATCH (c)<-[:Trans_Cust]-(:Transaction)-[:Trans_Business]->(other:Business)
WHERE b <> other
WITH b, other, collect(distinct(customer)) as customers
RETURN b, other, size(customers) as sharedCustomers
ORDER BY sharedCustomers DESC


text:
Q: Setting of Parallelism-count for apache storm bolt? I'm running a 8 core machine with 4 worker slots, I had 10 bolts. As per my knowledge each bolt uses a single executor by default. I.e.: my 8 core has only eight executors. Is it Right or Wrong? If Right how to set Parallelism-count for my 10 bolts, if Wrong, what's the Right way to set Parallelism?

A: Understand it this way:
One node (server) has one supervisor.
Supervisor starts/stops workers.
Worker is a process.
Executors are threads in the worker process.
One executor can run multiple tasks.
A task is an instance of your spout or bolt.
The number of executors is always less than or equal to the number of tasks.
So now, it doesn't matter how many cores your machine has. Go ahead and create as many executors as the number of bolts you have. Storm will use a thread pool to manage the threading, so your tasks will be time shared on your processor automatically.
If you create more than 1 worker and you have a second supervisor node, then that supervisor will run maybe 5 of your 10 bolts under one worker and the first supervisor will run maybe 5 of your 10 bolts under another worker.
There is no right and wrong way to set up parallelism. It's highly dependent on what kind of logic you want to program.


text:
Q: Linq to Entity Framework Model - How To Switch Views Programmatically I am using the entity framework model to query my database and have put in a few views that I would like to use that all have the same query parameters. Rather than write a big list of case-switch statements I am wondering how to do this programmatically by passing through the view object as a parameter to my main method. In sql I would do this like:
public void Tables(string TableName)
{
    using(EntityModel entity = new EntityModel()){
      string sql = "select * from " + TableName;
      etc....
}

However I just can't see how to do a similar thing with the entity framework model i.e.
public void Tables(Type TableName)
{
    using(EntityModel entity = new EntityModel()){
      ObjectQuery<Users> oq = new ObjectQuery<Users>("EntityModel.Users", EntityModel);
      var q = (from p in oq select p);
}

That's fine if you know what type of table or view you need (i.e. Users), but you can't pass a type as a parameter because ObjectQuery can't accept variables, typeof() or anything that isn't hard-coded. Anyone have any ideas if this is at all possible?

A: You can do this with Entity SQL, but you would still need to know the return type of the query. If the query always returned the same type of entity, then I think you would not be passing in a "TableName." So what is it that you actually want out of the query? Some scalar value? Scalars, after all, are all you would get out of your SQL example. You can do that with Entity SQL, specify the entity set name as a string, and get scalar results back. See: http://msdn.microsoft.com/en-us/library/cc716751.aspx

A: Use a generic method to pass the type
public void Tables<TTableType>(string TableName)
{
     using (EntityModel entity = new EntityModel())
     {
            ObjectQuery<TTableType> oq = new ObjectQuery<TTableType>("EntityModel." + TableName, entity);
            var q = (from p in oq select p);
        }
    }


text:
Q: p:graphicImage disappears after a while in google chrome I use p:graphic image component of prime faces in jsf 2.0 project with pf 3.3. I implemented it as BalusC explained in severeal questions like this. It orks fine on internet explorer and firefox but in google chrome the image disappears leaving  a broken image link behind.
In internet explorer; when i save as the image it's named untitled.png and it's ok.
In internet explorer; when i save as the image it's named dynamiccontent.xhtml.png and it's ok.
But in google chrome its named dynamiccontent.xhtml and even if i change the extension the image is not visible.
I create the image with java graphics library as
BufferedImage bufferedimage = new BufferedImage(_width, _height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = bufferedimage.createGraphics();
....
g2d.dispose();

ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(bufferedimage, "png", os);

return os;

And my xhtml is like:
<p:graphicImage value="#{imagesBean.image}">
    <f:param name="lilw" value="#{reportsLoadSheetBean.loadedIndexLandingWeight}" />
    <f:param name="litow" value="#{reportsLoadSheetBean.loadedIndexTakeOffWeight}" />
    <f:param name="lizfw" value="#{reportsLoadSheetBean.loadedIndexZeroFuelWeight}" />
    <f:param name="tl" value="#{reportsLoadSheetBean.topLimit}" />
    <f:param name="zfwf" value="#{reportsLoadSheetBean.zeroFuelWeightForward}" />
    <f:param name="zfwa" value="#{reportsLoadSheetBean.zeroFuelWeightAfter}" />
    <f:param name="towf" value="#{reportsLoadSheetBean.takeOffWeightForward}" />
    <f:param name="towa" value="#{reportsLoadSheetBean.takeOffWeightAfter}" />
    <f:param name="lwf" value="#{reportsLoadSheetBean.landingWeightForward}" />
    <f:param name="lwa" value="#{reportsLoadSheetBean.landingWeightAfter}" />
    <f:param name="width" value="600" />
    <f:param name="height" value="200" />
</p:graphicImage>

and lastly the Application scoped bean that gets the image and sends it to the interface:
public StreamedContent getImage() throws IOException {
    FacesContext context = FacesContext.getCurrentInstance();

    if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
        // So, we're rendering the view. Return a stub StreamedContent so
        // that it will generate right URL.
        return new DefaultStreamedContent();
    } else {
        String lilw = context.getExternalContext().getRequestParameterMap().get("lilw");
        String litow = context.getExternalContext().getRequestParameterMap().get("litow");
        String lizfw = context.getExternalContext().getRequestParameterMap().get("lizfw");
        String tl = context.getExternalContext().getRequestParameterMap().get("tl");
        String zfwf = context.getExternalContext().getRequestParameterMap().get("zfwf");
        String zfwa = context.getExternalContext().getRequestParameterMap().get("zfwa");
        String towf = context.getExternalContext().getRequestParameterMap().get("towf");
        String towa = context.getExternalContext().getRequestParameterMap().get("towa");
        String lwf = context.getExternalContext().getRequestParameterMap().get("lwf");
        String lwa = context.getExternalContext().getRequestParameterMap().get("lwa");

        List<Number> zeroFuelWeightIntervals = new ArrayList<Number>();
        List<Number> takeOffWeightIntervals = new ArrayList<Number>();
        List<Number> landingWeightIntervals = new ArrayList<Number>();

        zeroFuelWeightIntervals.add(Double.valueOf(zfwf));
        zeroFuelWeightIntervals.add(Double.valueOf(zfwa));
        zeroFuelWeightIntervals.add(Double.valueOf(tl));

        takeOffWeightIntervals.add(Double.valueOf(towf));
        takeOffWeightIntervals.add(Double.valueOf(towa));
        takeOffWeightIntervals.add(Double.valueOf(tl));

        landingWeightIntervals.add(Double.valueOf(lwf));
        landingWeightIntervals.add(Double.valueOf(lwa));
        landingWeightIntervals.add(Double.valueOf(tl));

        int width = Integer.parseInt(context.getExternalContext().getRequestParameterMap().get("width"));
        int height = Integer.parseInt(context.getExternalContext().getRequestParameterMap().get("height"));

        IdealIntervalPointDiagram diagram = new IdealIntervalPointDiagram(
                "ZFL", Double.valueOf(lizfw), zeroFuelWeightIntervals,
                "TOW", Double.valueOf(litow), takeOffWeightIntervals,
                "LAW", Double.valueOf(lilw), landingWeightIntervals,
                width, height);

        ByteArrayOutputStream os = new ByteArrayOutputStream();

        try {
            os = diagram.paint();

        } catch (IOException e) {
            e.printStackTrace();
        }

        return new DefaultStreamedContent(new ByteArrayInputStream(os.toByteArray()), "image/png");
    }

May it be a bug about primefaces?

A: I found the problem. It's about the google chrome checking the content-length header strictly in the response including the image and because the server compresses the image; the actual content size and the size written on the header does not match. Other mainstream browser ignore this mismatching but google chrome not. so i called
FacesContext.getCurrentInstance().getExternalContext().setResponseContentLength(os.size());

before returning the image and now it also works fine in google chrome.


text:
Q: Android: How to remove the Wifi Network by using removeNetwork() correctly (Android 5.0 Asus Zenfone ) First, I'm using the addNetwork() to add a SSID to the Configuration list. Everything is okay(SSID has been added to the Configuration list successfully).
Second, I'm using removeNetwork() to remove the configured network. When I execute this method, everything acts as it should. The wifi disconnects and the SSID doe not appear in the list of configured netowrks...
But, when I using the addNetwork() to add the same SSID to the Configuration list again.
I always get the return value(networkId) -1.
The only way to solve this problem is to restart the WiFi function.


text:
Q: Fatal error in Yii immediately after adding eager-loading I've got 3 CActiveRecord models:

*

*A

*B

*C

Relationships:

*

*A has many B.

*A has many C.

*B belongs to A.

*C belongs to A.

In AController's actionHome($id), I'm retrieving the single row of A from the database. Just like the default actionView($id).
In my View for actionHome(), I also list all instances of B and C that belong to that A.
public function actionHome($id)
{
  $this->render('home', array('a' => A::model()->findByPk($id)));
}

In actionHome(), I want to use eager loading of A's relationships.
But, when I add with() to the findByPk() function, I immediately get a fatal error.
public function actionHome($id)
{
  $this->render('home', array('a' => A::model()->with('bs','cs')->findByPk($id)));
}

Fatal error: Call to a member function label() on a non-object in my home.php view file.
label() is a public static function I have within my A model class.
So, since I've added eager loading, this causes the function to be unavailable.
Can someone please assist?
Why would this function no longer be available?
label() is called in my view home.php like so:
$this->breadcrumbs = array(
  CHtml::encode($a->label(2)) => array('index'),
  CHtml::encode($a->name),
);

label() is defined as follows in my model:
public static function label($n = 1)
{
  if ( $n == 0 ) $n = 1;
  return Yii::t('app', 'A|As', $n);
}

If I comment-out the call to label() within the view (or change the call to A::label(2)), then the next line just triggers an error too,.. that "name" is not a property of non-object.
Obviously, for some reason, $a is no longer an object.
Update 1:
Adding with() causes findByPk($id) to return NULL, therefore $a is NULL in my view, so I'm trying to find why. Lazy loading doesn't have this issue.

A: The findByPk() is returning NULL because the relation cs is empty. Yii is doing an INNER JOIN from A to B and because there are no B's that belong to A, the resultset is empty.
Lazy-loading didn't have this problem because it doesn't do the query until data from B is needed.


text:
Q: Compile as static and dynamic library Is it possible to create two configurations for a Visual Studio Project where one configuration compiles the code into a static, the other one into a dynamic library?
If yes, how is it done?

A: Yes, just create a new configuration in the Configuration Editor for all platforms, and name it accordingly. Then set that configuration up to build a static library manually.


text:
Q: [Batch ]How to remove unwanted text using CMD/PowerShell I've been searching for a while now for a solution to this problem:
This is the content from the beginning of the textfile output.txt (ofc there follow many more lines of servernames):

Current query set
                    name: srv-comms-xx;
                    name: easrv00xxx;
                    name: ealxsrv00xxx;

I would need a batch script that:

*

*removes the first line of this file

*removes everything from other lines except the servernames
So output of example would be:

srv-comms-xx
easrv00xxx
ealxsrv00xxx

I expiremented with findstr but without success.

A: You can use the -replace operator to remove everything other than the name, using regular expressions:
# Read the file into an array with Get-Content
$Lines = Get-Content .\output.txt
# Use Where-Object to filter away lines not containing "name:"
$Lines = $Lines |Where-Object {$_ -match 'name:'}
# Use -replace to capture the servername
$Names = $Lines -replace '^\s+?name:\s(\S+);\s*$','$1'

You can combine these statements into a single pipeline:
$Names = Get-Content .\output.txt |Where-Object {$_ -match 'name:'} |ForEach-Object {$_ -replace '^\s+?name:\s(\S+);\s*$','$1'}

A: I like the previous answers, but wanted to show you an easier way available, if you can install WMF/PowerShell version 5.
This release adds a super powerful new tool called ConvertFrom-String. This uses FlashExtract (found in Excel) and an input example file to intelligently pull out values from any given input.
If you wanted to write some really succinct code, you could use this approach.  To make an input example file, just copy and paste your expected output into notepad.
Current query set
                name: srv-comms-xx;
                name: easrv00xxx;
                name: ealxsrv00xxx;

Next, note the values you want to select, (in our case, the server names).  Now, for the first few server names in the list put curly braces, the name you'd like to call this extracted value, and then a close brace at the end of what you want.  Here's an example.
Current query set
                    name: {name*:srv-comms-xx};
                    name: {name*:easrv00xxx};
                    name: ealxsrv00xxx;

Note the *, which tells ConvertFrom-String to make new objects everytime we see this value.
So, that's our example file.  Now save it somewhere (in my example T:\Example.txt), and call it using Convertfrom-String.
Get-Content .\output.txt | ConvertFrom-String -TemplateFile T:\example.txt

Output
name
----
srv-comms-xx
easrv00xxx
ealxsrv00xxx

Note that we only provided two examples, but PowerShell was smart enough to recognize the pattern and extract the final server name too.  Even if our input  had thousands of names, we'd only need an example of the first three or four lines to give PowerShell enough hints as to what we want to do.
If you wanted to scrape the file and ONLY return the server names, just pipe into Select -Expand Name, like this:
Get-Content .\output.txt | ConvertFrom-String -TemplateFile T:\example.txt |
  Select-Object -ExpandProperty Name

A: Here is a cmd solution:
for /F "usebackq skip=1 tokens=2 delims=:; " %I in ("output.txt") do echo %I

To write the output into a new file, say output_new.txt, use redirection:
> "output_new.txt" (for /F "usebackq skip=1 tokens=2 delims=:; " %I in ("output.txt") do echo %I)

To use all this in a batch script, double the % signs:
> "output_new.txt" (for /F "usebackq skip=1 tokens=2 delims=:; " %%I in ("output.txt") do echo %%I)

Type for /? in command prompt for more information about parsing text files with for /F.


text:
Q: How to package README.md in a Debian git source repository? I'm trying to create a brand new Debian-ish package (mostly for private use but I'm thinking about publishing it on GitHub) based on a third-party program that doesn't currently have a Debian package.
I have all the basics sorted out (it builds packages and it works) but I've run into some snags while trying to make a git repository out of it.
I've used git-buildpackage to create a repository from my .dsc and using the basic build options it works fine.  I'm now trying to use pbuilder to do some extended sanity checking and it's run into a problem with the README.md file.
Upstream doesn't provide a README.md file.  I want to have one in the root of my repository so that people browsing GitHub will see the information automatically.
dpkg-source gets annoyed if I add the file without also adding a patch to debian/patches.
But it seems like the recommended way to use a git repository (at least with git-buildpackage) is to have the master branch not have patches pre-applied (which makes a certain amount of sense since it'd be duplication -- especially due to the way that applied patches are tracked via the .pc subdir) -- but if I unapply all patches, then the README.md file vanishes, which defeats the point.

I've now added a debian/source/options file that contains:
extend-diff-ignore="README\.md$"

And not including a patch to create the file.  This accomplishes both goals (master is the unpatched source but contains a README.md file and dpkg-source doesn't get upset about this during the build).  The downside is that this file doesn't appear anywhere in the generated source package (orig.tar.gz and debian.tar.xz) files either.
I can live with this as the file isn't terribly exciting (mostly just a description and some instructions how to build it from git), but it means the Git repository is "different" from the source package.  Is this the right way to do it?  Is there a better way?


text:
Q: Firefox keeps failing to verify certain apps Here's the problem.  I get a message that pops up that says, "one or more extensions cannot be verified and have been disabled".  I know a temporary fix to get these apps working again but the apps always break after so much time.  What I do is go in my extensions for my Firefox profile (which is a JSON file) and I use Wordpad to change all the instances of appDisabled": true to appDisabled": false.  I also change all the instances of signedState":-1 to signedState":2.  The problem is that it keeps changing the false back to true and the 2's back to -1's.  I am using Firefox version 56.0.2.  Is there any permanent fix that can keep these changes under the current version that I am using?  I am getting sick and tired of having to make these changes every day.  Also, a couple of key add-ons that I use which are Classic Theme Restorer and unblock Origin keep getting disabling from this issue.  I value these add-ons and I would love it if you knew any command prompt that I could put into Wordpad that would make Firefox stop trying to verify add-ons or whatever it does that causes Firefox to disable the add-ons.  I welcome any other fix as well.  I do want to keep my current version of Firefox and I know the Greasemonkey I use wouldn't work on later versions.
I already tried using Wordpad to change all instances of appDisabled": true to false and signedState":-1 to 2.  It would work for a while and then everything reverted back to how it was.
...
appDisabled":true

...
signedState":-1

When appDisabled is true and signedState switches to -1, I get the message saying, "one or more extensions cannot be verified." It also disables the incompatible apps.


text:
Q: Getting ClusterBlockException while running queries using node client My elasticsearch cluster(version 2.0) is started and the node client is built successfully, but  for some reason I'm getting the following error while running queries using node client.
20:15:15.479 [Pool:entitytaskscheduler: Thread#1] DEBUG c.b.o.e.t.c.DataCollectorStatusUpdateTask - collectors updated due to agent reconnected:{}
ClusterBlockException[blocked by: [SERVICE_UNAVAILABLE/1/state not recovered / initialized];]
        at org.elasticsearch.cluster.block.ClusterBlocks.globalBlockedException(ClusterBlocks.java:154)
        at org.elasticsearch.cluster.block.ClusterBlocks.globalBlockedRaiseException(ClusterBlocks.java:144)
        at org.elasticsearch.action.search.type.TransportSearchTypeAction$BaseAsyncAction.<init>(TransportSearchTypeAction.java:116)
        at org.elasticsearch.action.search.type.TransportSearchQueryThenFetchAction$AsyncAction.<init>(TransportSearchQueryThenFetchAction.java:73)
        at org.elasticsearch.action.search.type.TransportSearchQueryThenFetchAction$AsyncAction.<init>(TransportSearchQueryThenFetchAction.java:67)
        at org.elasticsearch.action.search.type.TransportSearchQueryThenFetchAction.doExecute(TransportSearchQueryThenFetchAction.java:64)
        at org.elasticsearch.action.search.type.TransportSearchQueryThenFetchAction.doExecute(TransportSearchQueryThenFetchAction.java:53)
        at org.elasticsearch.action.support.TransportAction.execute(TransportAction.java:70)
        at org.elasticsearch.action.search.TransportSearchAction.doExecute(TransportSearchAction.java:99)
        at org.elasticsearch.action.search.TransportSearchAction.doExecute(TransportSearchAction.java:44)
        at org.elasticsearch.action.support.TransportAction.execute(TransportAction.java:70)
        at org.elasticsearch.client.node.NodeClient.doExecute(NodeClient.java:58)
        at org.elasticsearch.client.support.AbstractClient.execute(AbstractClient.java:347)
        at org.elasticsearch.action.ActionRequestBuilder.execute(ActionRequestBuilder.java:85)
        at org.elasticsearch.action.ActionRequestBuilder.execute(ActionRequestBuilder.java:59)
        at com.hidden.ppp.management.dc.DataCollectorPollStatusDAOESImpl.findDCIdsUpdatedInTime(DataCollectorPollStatusDAOESImpl.java:151)
        at com.hidden.ppp.engine.taskexecutor.cptaskexecs.DataCollectorStatusUpdateTask.execute(DataCollectorStatusUpdateTask.java:199)
        at com.hidden.ppp.engine.taskexecutor.cptaskexecs.DataCollectorStatusUpdateTaskRunner.run(DataCollectorStatusUpdateTaskRunner.java:27)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)
20:15:15.558 [Pool:entitytaskscheduler: Thread#1] WARN  c.b.o.m.d.DataCollectorPollStatusDAOESImpl - blocked by: [SERVICE_UNAVAILABLE/1/state not recovered / initialized];
20:15:15.558 [Pool:entitytaskscheduler: Thread#1] DEBUG c.b.o.e.t.c.DataCollectorStatusUpdateTask - collectors for which polls updated after epoc time:1453128243336 - dcids: []
ClusterBlockException[blocked by: [SERVICE_UNAVAILABLE/1/state not recovered / initialized];]
        at org.elasticsearch.cluster.block.ClusterBlocks.globalBlockedException(ClusterBlocks.java:154)
        at org.elasticsearch.cluster.block.ClusterBlocks.globalBlockedRaiseException(ClusterBlocks.java:144)
        at org.elasticsearch.action.search.type.TransportSearchTypeAction$BaseAsyncAction.<init>(TransportSearchTypeAction.java:116)
        at org.elasticsearch.action.search.type.TransportSearchQueryThenFetchAction$AsyncAction.<init>(TransportSearchQueryThenFetchAction.java:73)
        at org.elasticsearch.action.search.type.TransportSearchQueryThenFetchAction$AsyncAction.<init>(TransportSearchQueryThenFetchAction.java:67)
        at org.elasticsearch.action.search.type.TransportSearchQueryThenFetchAction.doExecute(TransportSearchQueryThenFetchAction.java:64)
        at org.elasticsearch.action.search.type.TransportSearchQueryThenFetchAction.doExecute(TransportSearchQueryThenFetchAction.java:53)
        at org.elasticsearch.action.support.TransportAction.execute(TransportAction.java:70)
        at org.elasticsearch.action.search.TransportSearchAction.doExecute(TransportSearchAction.java:99)
        at org.elasticsearch.action.search.TransportSearchAction.doExecute(TransportSearchAction.java:44)
        at org.elasticsearch.action.support.TransportAction.execute(TransportAction.java:70)
        at org.elasticsearch.client.node.NodeClient.doExecute(NodeClient.java:58)
        at org.elasticsearch.client.support.AbstractClient.execute(AbstractClient.java:347)
        at org.elasticsearch.action.ActionRequestBuilder.execute(ActionRequestBuilder.java:85)
        at org.elasticsearch.action.ActionRequestBuilder.execute(ActionRequestBuilder.java:59)
        at com.hidden.ppp.management.dc.DataCollectorPollStatusDAOESImpl.findDCIdsNotUpdatedInTime(DataCollectorPollStatusDAOESImpl.java:182)
        at com.hidden.ppp.engine.taskexecutor.cptaskexecs.DataCollectorStatusUpdateTask.execute(DataCollectorStatusUpdateTask.java:204)
        at com.hidden.ppp.engine.taskexecutor.cptaskexecs.DataCollectorStatusUpdateTaskRunner.run(DataCollectorStatusUpdateTaskRunner.java:27)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)

I've even disabled the "multicast" as per this post - still no luck. Surprisingly, I could access the elasticsearch from sense. Any clues on what is going wrong ?

A: I faced the same error message and was not able to understand the problem first. I was developing a node client Java application on my laptop, using an Elasticsearch data node on a remote server. For production use, I needed to deploy the Java application on this remote server.
I configured the Java application to talk to the local host only (being on the same host now):
elasticsearch.discovery.zen.ping.unicast.hosts=127.0.0.1

And got the same exception
ClusterBlockException[blocked by: [SERVICE_UNAVAILABLE/1/state not recovered / initialized];]

Looking at the logs I also found this entry:
[WARN] [TP-Processor2] DiscoveryService.waitForInitialState -> [cerbera] waited for 30s and no initial state was set by the discovery

So basically, the question was: Why doesn't it find the Elasticsearch data node? I changed port ranges and also played with the multicast setting - without success.
Finally, I checked elasticsearch.yml and found the data node not listening to localhost (127.0.0.1), but instead on the ethernet interface 192.168.1.2.
network.host: 192.168.1.2
http.port: 9200

The final change was simple, I just needed to reconfigure the node client configuration to talk to the correct interface
elasticsearch.discovery.zen.ping.unicast.hosts=192.168.1.2

Now my node client is talking to elasticsearch via the correct interface. Job done.

A: I had the same problem (using k8s ) I finally replaced my elastic image and the issue was solved...
moved from 6.5.4-debian-9-r41 to 6.8.16-debian-10-r5 (using bitnami images)
I know it is not the best answer - but I really tried suggested answers and nothing worked for me. so my recommendation is to update to a newer better version. (docker makes that easy:) )


text:
Q: prevent preloading of images? The website I'm working on has a list ul with above a 100 (li) bullet points. Each of them links to another html-site.
I would like to show an image preview, whenever you hover over one of the links. The image should slowly slide in from the left.
As each preview image is up to 40kb in size, I actually don't want to preload the images.
What would be the best way to prevent it?
I would like to do this only via CSS, without JS, if possible.
My ideas:
a) default-state: <img>-tag with display:none; hover-state: set it to display:inline . Problem: transition does not work with display :(.
b) simply use a div instead and write a CSS-rule for every li, so that on hover the corresponding background-image with the preview-image is assigned to it.
Does this prevent the preloading of the image?

A: If you add it as a background image, but only show it on hover the image won't load until the user hovers over whatever has the style. You should be able to set the background image inline instead of outputting the image file as an IMG

A: You can't do this with just CSS because your browser will load all contents (regardless of display:none). I would recomend javascript or server side like php.
Maby jquery load could be something?
http://api.jquery.com/load/


text:
Q: Memory Tracker in C++ going into infinite loop during vector initialization I am trying to write memory tracker in C++ by overloading new and delete operator. But it is going into loop and calling new again and again. Following is my code.
#ifndef MEMORY_TRACKER_H_
#define MEMORY_TRACKER_H_

#pragma warning( disable : 4290 )
#pragma comment(lib, "Dbghelp.lib")

#include <Windows.h>
#include <malloc.h>
#include <map>
#include <iostream>
#include <DbgHelp.h>
#include <sstream>
#include <vector>

static const int MAX_TRACES     = 62;
static const int MAX_LENGTH     = 256;
static const int BUFFER_LENGTH  = (sizeof(SYMBOL_INFO) + MAX_LENGTH * sizeof(wchar_t) + sizeof(ULONG64) - 1) / sizeof(ULONG64);
static bool SYSTEM_INITIALIZED  = false;

typedef struct record_t {
    std::string symbol;
    std::string address;
    std::string filename;
    std::string linenumber;
} record;

typedef std::vector<record>              record_vec_t;
typedef std::pair<size_t, record_vec_t>  record_entry_t;
typedef std::map<size_t, record_entry_t> memory_record_t;

memory_record_t gMemoryRecord;

static record_vec_t GetCallStackDetails(const void* const* trace, int count ) {
    record_vec_t callStackVector;

    for (int i = 0; i < count; ++i) {
        ULONG64 buffer[BUFFER_LENGTH];
        DWORD_PTR frame           = reinterpret_cast<DWORD_PTR>(trace[i]);
        DWORD64 sym_displacement  = 0;
        PSYMBOL_INFO symbol       = reinterpret_cast<PSYMBOL_INFO>(&buffer[0]);
        symbol->SizeOfStruct      = sizeof(SYMBOL_INFO);
        symbol->MaxNameLen        = MAX_LENGTH;
        BOOL has_symbol           = SymFromAddr(GetCurrentProcess(), frame, &sym_displacement, symbol);
        DWORD line_displacement   = 0;
        IMAGEHLP_LINE64 line      = {};
        line.SizeOfStruct         = sizeof(IMAGEHLP_LINE64);
        BOOL has_line             = SymGetLineFromAddr64(GetCurrentProcess(), frame, &line_displacement, &line);

        record curr_rec;
        curr_rec.symbol = "(No Symbol)";

        std::stringstream formatter;
        if (has_symbol) {
            curr_rec.symbol = symbol->Name;
            formatter.clear();
            formatter << " [0x" << trace[i] << "+" << sym_displacement << "]";
            curr_rec.address = formatter.str();
        } else {
            formatter.clear();
            formatter << " [0x" << trace[i] << "]";
            curr_rec.address = formatter.str();
        }
        if (has_line) {
            formatter.clear();
            formatter << line.FileName;
            curr_rec.filename = formatter.str();

            formatter.clear();
            formatter << line.LineNumber;
            curr_rec.filename = formatter.str();
        }
        callStackVector.push_back(curr_rec);
    }
    return callStackVector;
}

static void addRecord(void *ptr, size_t size) {
    if ( SYSTEM_INITIALIZED == false ) {
        SymSetOptions(SYMOPT_DEFERRED_LOADS | SYMOPT_UNDNAME | SYMOPT_LOAD_LINES);
        if (SymInitialize(GetCurrentProcess(), NULL, TRUE)) {
            SYSTEM_INITIALIZED = true;
        } else {
            SYSTEM_INITIALIZED = false;
            return;
        }
    }
    void* trace[MAX_TRACES];

    int count            = CaptureStackBackTrace(0, MAX_TRACES , trace, NULL);
    record_vec_t record  = GetCallStackDetails( trace, count);
    record_entry_t entry = std::make_pair( size, record);

    gMemoryRecord.insert(std::make_pair((size_t)ptr, entry));
}

static void deleteRecord(void *ptr ) {
    memory_record_t::iterator itr = gMemoryRecord.find((size_t)ptr);
    if ( itr != gMemoryRecord.end()) {
        gMemoryRecord.erase(itr);
    }
}

void dumpUnfreedMemory() {
    for ( memory_record_t::iterator itr = gMemoryRecord.begin(); itr != gMemoryRecord.end(); ++itr ) {
    }
}

// Overloading new operator
void* operator new ( size_t size ) throw ( std::bad_alloc ) {
    std::cout << " Overloaded new is called " << std::endl;
    void *ptr = (void *)malloc(size);
    addRecord(ptr, size);

    return ptr;
}

// Overloading delete Operator
void operator delete ( void* ptr ) throw () {
    std::cout << " Overloaded delete  is called " << std::endl;
    deleteRecord(ptr);
    free ( ptr );
}

#endif

following is the test file
#include "MemoryTracker.h"
int main ( int argc, char **argv) {
    int *ptr = new int;
    return 0;
}

it is going into loop on call of GetCallStackDetails, platform is windows

A: You're overloading the global operator new, and std::vector<record> uses the default allocator, which calls operator new to allocate the memory.  Which then calls your GetCallStack, which allocates a new vector ....
One solution is to use a custom allocator in your vector, which pulls from a separate pool of memory, so that it doesn't call your GetCallStack.


text:
Q: Is there a limit on how many values an Entity in Wit.Ai can have? I created a Wit.AI entity with about 10k values. When I input a message that is exactly one of the the possible values, Wit.AI doesn't seem to be able to pick that up. I tried this with an entity that has only a few values and it worked. Is this because of the amount of values that the entity has?

A: If your Wit app has stories, the stories may be taking precedence over any other training data you have provided (e.g. entities and their values), because Wit intentionally overfits on stories.
Make sure you delete any stories if you want your AI to be sensitive to a large training dataset.


text:
Q: Avoiding CamelCasePropertyNamesContractResolver for a specific method I have web api controllers and I am using this method of configuration in WebApiConfig file for camel casing my results for all controllers.
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

Now I have a controller's method which is giving data to Angularjs translation provider and all translation strings are not in camelcase in my html, thats why I need results of that method to be not in CamelCase. How to avoid camel casing serialization behavior for this specific controllers' method.

A: you can use ApiController.Json method.
just return like this from your controller method
return Json(data, new JsonSerializerSettings { ContractResolver = new DefaultContractResolver() });


text:
Q: Which is a better way: retrieve images from AWS S3 or download it and store locally in a temp folder to be displayed? Problem: Retrieve image from S3 and load into UIButton.
I'm currently doing my research on this issue and can't seem to make up my mind. Which is a better way to do it in terms of performance and security issue?
Also, do I need to do caching or store these images in Core Data?
Thanks!

A: It depends on how you use them. If your app is going to retrieve the images similiar to instagram, or twitter, it's good to download them as the user requested the images via the app.
If once the images are retrieved, the application going to use the images again and again multiple times, it's a good idea to store the images after they are downloaded.
For example, let's think about an application about "social networking" concept, and this app, let's say, has a chat interface which is functional after users add each other. As the users add each other, you download the images of the users and store them on the device, then you can use the profile images of the users by retrieving the locally stored images rather than retrieving them from the server, thus, each time they chat each other, you dont use the bandwidth for nothing. And you should also use a push notification or something that has a similiar functionality for the scenario, when a user changes his profile pictures, all of his/her friends should also be notified (I mean the app is going to be notified by the server) to retrieve and update their local profile image with the newly added ones.
As I said, it depenends on the scenarios of your application/server relationship. If the images you are storing on the AWS S3 are only going to be used only once, then storing them is useless. And If the user is going to use some of the images frequently (like app is a social networking app, friendship app and the friends are going to see each other's photo or uploaded images frequently), then storing them is a good idea, only for some of the users that who has subscribed to each other.


text:
Q: how to create class file for a java file which has only package statement and annotations? I have a file which has only two statements in it
@javax.xml.bind.annotation.XmlSchema(namespace = "XXXXX", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package sample;

want to create class file which has same name as filename is Package-info.java

A: package-info.java is not meant to be compilable. It is used by javadoc.
See http://docs.oracle.com/javase/7/docs/technotes/tools/solaris/javadoc.html#packagecomment for more info:
Package Comment Files
Each package can have its own documentation comment, contained in its own "source" file, that the Javadoc tool will merge into the package summary page that it generates. You typically include in this comment any documentation that applies to the entire package.
To create a package comment file, you have a choice of two files to place your comments:

*

*package-info.java - Can contain a package declaration, package annotations, package comments and Javadoc tags. This file is generally preferred over package.html.

*package.html - Can contain only package comments and Javadoc tags, no package annotations.
A package may have a single package.html file or a single package-info.java file but not both. Place either file in the package directory in the source tree along with your .java files.
package-info.java - This file can contain a package comment of the following structure -- the comment is placed before the package declaration:
File: java/applet/package-info.java
/**
 * Provides the classes necessary to create an
 * applet and the classes an applet uses
 * to communicate with its applet context.
 * <p>
 * The applet framework involves two entities:
 * the applet and the applet context.
 * An applet is an embeddable window (see the
 * {@link java.awt.Panel} class) with a few extra
 * methods that the applet context can use to
 * initialize, start, and stop the applet.
 *
 * @since 1.0
 * @see java.awt
 */
package java.lang.applet;


text:
Q: loop generate plots for variables in a data frame So I have a data frame, set up a bit like this:
Sample V1  V2 V3  Group1 Group2
bob    12  32  12  G1      G2
susan  43  23  54  G2      G2
mary   23  65  34  G1      G2

I am able to do a grouped boxplot of each variable (V1, V2, V3) individually, grouped by Group1 and Group2 variables, but my real dataset has WAY more variables, and will be tedious to code individually. Is there a way that I can loop the process, and automate plot generation and export? For loops are still a bit of an obscure topic for me.
Here is the code I use to generate an individual plot:
png(filename= "filename.jpg")
ggplot(aes(y=data$V1, x=data$Group1, fill=data$Group2), data=data) + geomboxplot()
dev.off()

Thanks!

A: Here are several approaches for you. I'm guessing there is a duplicate, but if you're just starting out it's not always easy to apply those answers to your data.
library(reshape2)
library(ggplot2)
###create some data
set.seed(100)
n = 500

dat <- data.frame(sample = sample(LETTERS[1:10],n,T),
                  V1 = sample(50,n,T),
                  V2 = sample(50,n,T),
                  V3 = sample(50,n,T),
                  Group1 = paste0("G",sample(3,n,T)),
                  Group2 = paste0("G",sample(5,n,T)))

approach 1: melt and facet
dat_m <- melt(dat,measure.vars = c("V1","V2","V3"))

p1 <- ggplot(dat_m, aes(x = Group1,y = value,fill = Group2))+
  geom_boxplot() + facet_wrap(~variable)
p1

As you can see, this is not feasible when you have too many grouping variables.
approach 2: different plots/images per variable, still using the long data. I have split the long data by variable, and created a plot for each chunk. The current code plots to the console; file-saving code is commented out.
lapply(split(dat_m, dat_m$variable), function(chunk){
  myfilename <- sprintf("plot_%s.png", unique(chunk$variable))

  p <- ggplot(chunk, aes(x = Group1,y = value,fill = Group2)) +
    geom_boxplot() + labs(title = myfilename)
  p
#   #png(filename = myfilename)
#   print(p)
#   dev.off()

})

And a third approach is to use the strings of columns you're interested in:
#vector of columns you want to plot
mycols <- c("V1","V2","V3")

#plotting for each column. Not that I've put the 'fixed' variable
#inside aes in the main call to ggplot, and the 'varying' variable
#inside aes_string in the call to boxplot

lapply(mycols, function(cc){
  myfilename <- sprintf("plot_%s.png",cc)
  p <- ggplot(dat, aes(x = Group1,fill = Group2)) +
    geom_boxplot(aes_string(y = cc)) + labs(title = myfilename)
  p
  #   #png(filename = myfilename)
  #   print(p)
  #   dev.off()
})


text:
Q: How to run multiple python function pairs in parallel with different array as input? In f0.py,I generate a parameter list, then I save them into an shape-(1000,M,L,N) array:
np.save('../data/seed_S.npy',S)

I have to use one element of the above array S in another two functions f1.py and f2.py, I use:
S = np.load('../data/seed_S.npy')
array_x = S[0]

in both f1.py and f2.py,
and then I can do the related calculations with S[0].
Similarly, to run the two functions f1.py and f2.py a second time, I use the second element of S:
S = np.load('../data/seed_S.npy')
array_x = S[1]

in both f1.py and f2.py,
and then I can do the related calculations with S[1].
and so on.
My question is: I want to run the functions f1.py and f2.py N times (N=1000), I always have to change my functions f1.py and f2.py. Is it possible to implement the same running without changing the functions themselves?  I want run f1.py--f2.py function pairs 1000 times in parallel. Besides, I also tried to implement the idea without function f0.py, but at each run, f1.py generate and save the array_x, and the corresponding f2.py read and use this array_x. Which method may be better? Could anyone provide me a suggestion?  Thanks!
I have tried an implementation as follows.
# f1.py
import numpy as np
from modules import *

class system1:
    def __init__(self,N,M,L):
        # store the parameters in the system1
        self.M = int(M)
        self.L = int(L)
        self.N = int(N)
        self.S = init_S(M,L,N)
        self.T = 7
        # The array
        self.S_traj = np.zeros((self.T, self.M, self.L+1, self.N))

# Main
if __name__=='__main__':
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('-M', nargs='?', const=10, type=int, default=10, \
                        help="the number of samples.")
    parser.add_argument('-L', nargs='?', const=5, type=int, default=5, \
                        help="the number of hidden layers.")
    parser.add_argument('-N', nargs='?', const=8, type=int, default=8, \
                        help="the number of nodes per layer.")
    args = parser.parse_args()
    M,N,L = args.M, args.N, args.L
    # Preparing parameters for using in f2.py
    parameter_list = np.array([M,L,N])
    # Initilize an instance of system1
    o = system1(N,M,L)
    #=================================
    #Save the seed for f2.py
    #=================================
    np.save('../data/para_list.npy', parameter_list)
    np.save('../data/seed_S_M{:d}_L{:d}_N{:d}.npy'.format(M,L,N),o.S)
    # Run some calculation ...
    o.S_traj[0,:,:,:] = o.S # Note that self.S_traj will independent of self.S from now on.
    for index in range(o.T):
        print("Runing f1...")
        print("Done.")

# f2.py
import numpy as np
from modules import *

class system2:
    def __init__(self):
        # f2.py accept the same intial configurations as f1.py.

        # to obtain the basic parameters: M, L, N
        para_list = np.load('../data/para_list.npy')
        M = para_list[0]
        L = para_list[1]
        N = para_list[2]
        # then store these parameters
        self.M = M
        self.L = L
        self.N = N
        self.T  = 7
        #arrays
        self.S_traj = np.zeros((self.T, self.M, self.L+1, self.N))
        self.S = np.load('../data/seed_S_M{:d}_L{:d}_N{:d}.npy'.format(self.M,self.L,self.N))
# Main
if __name__=='__main__':
    import argparse
    # Initilize an instance of system2.
    o = system2()
    # run calculation ...
    o.S_traj[0,:,:,:] = o.S
    for index in range(o.T):
        print("Running f2...")
        print("Done.")

and the modules.py is:
# modules.py
import numpy as np

# Functions
def init_S(M,L,N):
    S = np.ones((M,L+1,N))
    for i in range(M):
        for j in range(L+1):
            S[i,j,:] = generate_coord(N)
    return S
def generate_coord(N):
    """Randomly set the initial coordinates."""
    v = np.ones(N)
    list = [-1,0]
    for i in range(N):
        v[i] = np.random.choice(list)
    return v

A: If you are running them as different files then you need to give them arguments from outside the script. You can do this simply with sys.argv or in a more verbose way with the argparse module. For instance if your f1.py has something like:
import sys
print(sys.argv[1])

Running python3 f1.py hello would print hello. You will probably want to convert the input to int before using it.
This should allow you to run it in a loop from another script with subprocess.run


text:
Q: Convert JSON object to array using javascript I have a jQuery ajax request which returns data in json format, how can we convert it and push in to an array. TIA.
[{"Day":"Nov 03","Saavor Kitchen":null,"Home Kitchen":2,"Restaurant":null},
{"Day":"Nov 06","Saavor Kitchen":null,"Home Kitchen":1,"Restaurant":1},
{"Day":"Nov 07","Saavor Kitchen":null,"Home Kitchen":null,"Restaurant":1},
{"Day":"Nov 08","Saavor Kitchen":null,"Home Kitchen":2,"Restaurant":null},
{"Day":"Nov 09","Saavor Kitchen":null,"Home Kitchen":4,"Restaurant":null},
{"Day":"Nov 10","Saavor Kitchen":null,"Home Kitchen":3,"Restaurant":null},
{"Day":"Nov 11","Saavor Kitchen":null,"Home Kitchen":4,"Restaurant":null},
{"Day":"Nov 13","Saavor Kitchen":null,"Home Kitchen":4,"Restaurant":1},
{"Day":"Nov 14","Saavor Kitchen":null,"Home Kitchen":2,"Restaurant":1},
{"Day":"Nov 15","Saavor Kitchen":null,"Home Kitchen":5,"Restaurant":null},
{"Day":"Nov 16","Saavor Kitchen":null,"Home Kitchen":5,"Restaurant":null},
{"Day":"Oct 30","Saavor Kitchen":null,"Home Kitchen":null,"Restaurant":2},
{"Day":"Oct 31","Saavor Kitchen":null,"Home Kitchen":2,"Restaurant":3}]

Desired output :-
    [
      ['Day', 'Saavor Kitchen', 'Home Kitchen', 'Restaurant '],
      ['Nov 03',  1000,      400, 50],
      ['Nov 04',  1170,      460, 90],
      ['Nov 05',  660,       1120, 58],
      ['Nov 06',  1030,      540, 88]
    ]

A: You can do it like below  (using .map and .unshift):-

var json = '[{"Day":"Nov 03","Saavor Kitchen":null,"Home Kitchen":2,"Restaurant":null},{"Day":"Nov 06","Saavor Kitchen":null,"Home Kitchen":1,"Restaurant":1},{"Day":"Nov 07","Saavor Kitchen":null,"Home Kitchen":null,"Restaurant":1},{"Day":"Nov 08","Saavor Kitchen":null,"Home Kitchen":2,"Restaurant":null},{"Day":"Nov 09","Saavor Kitchen":null,"Home Kitchen":4,"Restaurant":null},{"Day":"Nov 10","Saavor Kitchen":null,"Home Kitchen":3,"Restaurant":null},{"Day":"Nov 11","Saavor Kitchen":null,"Home Kitchen":4,"Restaurant":null},{"Day":"Nov 13","Saavor Kitchen":null,"Home Kitchen":4,"Restaurant":1},{"Day":"Nov 14","Saavor Kitchen":null,"Home Kitchen":2,"Restaurant":1},{"Day":"Nov 15","Saavor Kitchen":null,"Home Kitchen":5,"Restaurant":null},{"Day":"Nov 16","Saavor Kitchen":null,"Home Kitchen":5,"Restaurant":null},{"Day":"Oct 30","Saavor Kitchen":null,"Home Kitchen":null,"Restaurant":2},{"Day":"Oct 31","Saavor Kitchen":null,"Home Kitchen":2,"Restaurant":3}]';

var columns = ['Day', 'Saavor Kitchen', 'Home Kitchen', 'Restaurant'];

var result = JSON.parse(json).map(function(obj) {
  return columns.map(function(key) {
    return obj[key];
  });
});
result.unshift(columns);
console.log(result);
console.log(Object.keys($.parseJSON(json)[0]));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

To get keys dynamically:-
console.log(Object.keys($.parseJSON(json)[0]));

Since you already used dataType:'json' in your ajax code, so do:-
console.log(Object.keys(json[0]));

A: A simple combination of Object.values() with an Array.map() will do the trick here:
var res = arr.map(function(item) {
  return Object.values(item);
});

Demo:

var arr = [{
    "Day": "Nov 03",
    "Saavor Kitchen": null,
    "Home Kitchen": 2,
    "Restaurant": null
  },
  {
    "Day": "Nov 06",
    "Saavor Kitchen": null,
    "Home Kitchen": 1,
    "Restaurant": 1
  },
  {
    "Day": "Nov 07",
    "Saavor Kitchen": null,
    "Home Kitchen": null,
    "Restaurant": 1
  },
  {
    "Day": "Nov 08",
    "Saavor Kitchen": null,
    "Home Kitchen": 2,
    "Restaurant": null
  },
  {
    "Day": "Nov 09",
    "Saavor Kitchen": null,
    "Home Kitchen": 4,
    "Restaurant": null
  },
  {
    "Day": "Nov 10",
    "Saavor Kitchen": null,
    "Home Kitchen": 3,
    "Restaurant": null
  },
  {
    "Day": "Nov 11",
    "Saavor Kitchen": null,
    "Home Kitchen": 4,
    "Restaurant": null
  },
  {
    "Day": "Nov 13",
    "Saavor Kitchen": null,
    "Home Kitchen": 4,
    "Restaurant": 1
  },
  {
    "Day": "Nov 14",
    "Saavor Kitchen": null,
    "Home Kitchen": 2,
    "Restaurant": 1
  },
  {
    "Day": "Nov 15",
    "Saavor Kitchen": null,
    "Home Kitchen": 5,
    "Restaurant": null
  },
  {
    "Day": "Nov 16",
    "Saavor Kitchen": null,
    "Home Kitchen": 5,
    "Restaurant": null
  },
  {
    "Day": "Oct 30",
    "Saavor Kitchen": null,
    "Home Kitchen": null,
    "Restaurant": 2
  },
  {
    "Day": "Oct 31",
    "Saavor Kitchen": null,
    "Home Kitchen": 2,
    "Restaurant": 3
  }
];

var res = arr.map(function(item) {
  return Object.values(item);
});

console.log(res);

A: Create an array of keys (the header) to use as the 1st row, and to get the values from the objects.
Parse the json, and iterate it with Array#map. On each iteration, map the array of keys, and extract the values from the object.
Concat the keys array as the 1st array.

var json = '[{"Day":"Nov 03","Saavor Kitchen":null,"Home Kitchen":2,"Restaurant":null},{"Day":"Nov 06","Saavor Kitchen":null,"Home Kitchen":1,"Restaurant":1},{"Day":"Nov 07","Saavor Kitchen":null,"Home Kitchen":null,"Restaurant":1},{"Day":"Nov 08","Saavor Kitchen":null,"Home Kitchen":2,"Restaurant":null},{"Day":"Nov 09","Saavor Kitchen":null,"Home Kitchen":4,"Restaurant":null},{"Day":"Nov 10","Saavor Kitchen":null,"Home Kitchen":3,"Restaurant":null},{"Day":"Nov 11","Saavor Kitchen":null,"Home Kitchen":4,"Restaurant":null},{"Day":"Nov 13","Saavor Kitchen":null,"Home Kitchen":4,"Restaurant":1},{"Day":"Nov 14","Saavor Kitchen":null,"Home Kitchen":2,"Restaurant":1},{"Day":"Nov 15","Saavor Kitchen":null,"Home Kitchen":5,"Restaurant":null},{"Day":"Nov 16","Saavor Kitchen":null,"Home Kitchen":5,"Restaurant":null},{"Day":"Oct 30","Saavor Kitchen":null,"Home Kitchen":null,"Restaurant":2},{"Day":"Oct 31","Saavor Kitchen":null,"Home Kitchen":2,"Restaurant":3}]';

var keys = ['Day', 'Saavor Kitchen', 'Home Kitchen', 'Restaurant'];
var result = keys.concat(JSON.parse(json).map(function(o) {
  return keys.map(function(key) {
    return o[key];
  });
}));

console.log(result);

A:

let res = [{"Day":"Nov 03","Saavor Kitchen":null,"Home Kitchen":2,"Restaurant":null},{"Day":"Nov 06","Saavor Kitchen":null,"Home Kitchen":1,"Restaurant":1},{"Day":"Nov 07","Saavor Kitchen":null,"Home Kitchen":null,"Restaurant":1},{"Day":"Nov 08","Saavor Kitchen":null,"Home Kitchen":2,"Restaurant":null},{"Day":"Nov 09","Saavor Kitchen":null,"Home Kitchen":4,"Restaurant":null},{"Day":"Nov 10","Saavor Kitchen":null,"Home Kitchen":3,"Restaurant":null},{"Day":"Nov 11","Saavor Kitchen":null,"Home Kitchen":4,"Restaurant":null},{"Day":"Nov 13","Saavor Kitchen":null,"Home Kitchen":4,"Restaurant":1},{"Day":"Nov 14","Saavor Kitchen":null,"Home Kitchen":2,"Restaurant":1},{"Day":"Nov 15","Saavor Kitchen":null,"Home Kitchen":5,"Restaurant":null},{"Day":"Nov 16","Saavor Kitchen":null,"Home Kitchen":5,"Restaurant":null},{"Day":"Oct 30","Saavor Kitchen":null,"Home Kitchen":null,"Restaurant":2},{"Day":"Oct 31","Saavor Kitchen":null,"Home Kitchen":2,"Restaurant":3}];

//console.log((res))
let keys = [];
let day = [];
let saavor = [];
let homeKitch = [];
let restaurant = [];
let allData = [];

res.map((obj) => {
  if (keys.length ==0)  keys.push(Object.keys(obj))
  day.push(obj["Day"]);
  saavor.push(obj["Saavor Kitchen"]);
  homeKitch.push(obj["Home Kitchen"]);
  restaurant.push(obj["Restaurant"]);
})

allData[0] = keys;
allData.push(day);
allData.push(saavor);
allData.push(homeKitch);
allData.push(restaurant);

console.log(allData)

A:     var json = '[{"Day":"Nov 03","Saavor Kitchen":null,"Home Kitchen":2,"Restaurant":null},{"Day":"Nov 06","Saavor Kitchen":null,"Home Kitchen":1,"Restaurant":1},{"Day":"Nov 07","Saavor Kitchen":null,"Home Kitchen":null,"Restaurant":1},{"Day":"Nov 08","Saavor Kitchen":null,"Home Kitchen":2,"Restaurant":null},{"Day":"Nov 09","Saavor Kitchen":null,"Home Kitchen":4,"Restaurant":null},{"Day":"Nov 10","Saavor Kitchen":null,"Home Kitchen":3,"Restaurant":null},{"Day":"Nov 11","Saavor Kitchen":null,"Home Kitchen":4,"Restaurant":null},{"Day":"Nov 13","Saavor Kitchen":null,"Home Kitchen":4,"Restaurant":1},{"Day":"Nov 14","Saavor Kitchen":null,"Home Kitchen":2,"Restaurant":1},{"Day":"Nov 15","Saavor Kitchen":null,"Home Kitchen":5,"Restaurant":null},{"Day":"Nov 16","Saavor Kitchen":null,"Home Kitchen":5,"Restaurant":null},{"Day":"Oct 30","Saavor Kitchen":null,"Home Kitchen":null,"Restaurant":2},{"Day":"Oct 31","Saavor Kitchen":null,"Home Kitchen":2,"Restaurant":3}]';

    $.each($.parseJSON(json), function(idx, obj) {
      $("#demo").html(obj.Day);
    });


text:
Q: putc skips an index putchar does not? I have an a method that reads input and prints ascii characters to a file stream.
Originally it didn't need to print to a file so I used putchar and it worked fine
but now that I use putc or fputc it prints every other input.
Example:
input = test
Output = t s
    int readFile(char* input,FILE* inputFile)
{
    int anyChanges = 1;
    int iochar = 0;
    int i = 0;

    //credit Foster Chapter 2
    while (( iochar = getc(inputFile) ) != EOF )
    {
        //Returns 1 if no changes made, return 0 if any changes have been made.
        // printf("\t character --> %c",iochar);
        //printf("\nGot to first while loop\n");

        if(iochar != '\n')
        {
            // printf("Got to second loop\n");
            int printedColumns =0;
            input[i] = iochar;
            printf("input array ---> %c\n",input[i]);
            i++;
            printf("i:%d\n",i);
            printf("iochar:%d\n",iochar);
            //This if statement checks for normal ascii characters.
            //If the output is less than 72 it prints it and increments printedColumns.
            if (( ' ' <= iochar ) && ( iochar <= 126 ) )
            {
                fputc(input[i],inputFile);
            }
        }
    }
}

A: did you mean to fputc iochar instead of input[i] (since you already incremented i)?
http://www.cplusplus.com/reference/cstdio/fputc/ states that the position indicator is incremented.

A: Here for getc & putc you are using same Stream pointr i.e. inputFile , you want to read and write onto same file ??


text:
Q: Prevent D3 graph from scaling I am using this as my base project which is scrollable and scalable in both x and y axis. I have modified it to only be scrollable and scalable in x axis. Now, I want to prevent it from being scalable (i.e the x-scale should not change) while keeping it scrollable (i.e click the graph and dragging it slides it to the left or right)
I have tried doing scale(1) where there's transformation to keep the scale from not changing but that doesn't help. Here's the snippet for that:
g.append("svg:rect")
              .attr("class", "zoom x box")
              .attr("width", width - margin.left - margin.right)
              .attr("height", height - margin.top - margin.bottom)
              .attr("transform", "translate(" + 0 + "," + 0 + ")")
              .style("visibility", "hidden")
              .attr("pointer-events", "all")
              .call( d3.behavior.zoom().on("zoom", function(){
                  g.attr("transform", "translate(" + d3.event.translate + ") scale(1)")
              }) ).append("g");

And here's the full code:

<!DOCTYPE html>

    <title>Simpe Single Axis Zoom</title>

Any sort of help is greatly appreciated. Thanks.

A: I found out that there was an easy fix for this. In the d3.behaviour.zoom() function, all I needed to add was .scaleExtent([1,1]), which doesn't scale anything more than 1 and hence preventing the zoom.
An example: https://jsfiddle.net/x97k4snj/1/

<!DOCTYPE html>

    <title>Simpe Single Axis Zoom</title>


text:
Q: Getting Outputs of Resources from Reused Modules I have the following code that will call a module and make target groups for me based off of the information I pass it in the locals variables.  This works just fine, my issue being trying to get the arn of each target group it creates in an output.
locals {
  targetgroups_beta = {
    targetgroup1 = {
      name = "example",
      path = "/",
      environment = "Beta"
    }
    targetgroup2 = {
      name = "example2",
      path = "/",
      environment = "Beta"
    }
    }
  }

module "target-groups"{
  for_each = local.targetgroups_beta
  source = ".//modules/targetgroups"
  name-beta = each.value.name
  path-beta = each.value.path
  environment-beta = each.value.environment
  vpc-id = "${module.vpc.vpc_id}"
}

The resource name in the module it is calling is target-group, so based off of what I read I should be able to refer to it by something like this:
output{
     value = "${aws_lb_target_group.target-group[0].arn}"
}

When I try this I receive the following when running a terraform plan:
"Because aws_lb_target_group.target-group does not have "count" or "for_each" set, references to it must not include an index key. Remove the bracketed index to refer to the single instance of this resource."
My understanding of this is the module that the for_each is calling isn't running a for_each, so I cannot reference the resources in this way.  If I do ""${aws_lb_target_group.target-group.arn}" that reference works technically, but includes the arn for every target group and I plan on adding a lot more.  Is there a way to take each of these arns out of this list as its own output?
Code in the module that it is calling for reference:
resource "aws_lb_target_group" "target-group" {
  name     = "example-${var.name-beta}"
  port     = 80
  protocol = "HTTP"
  vpc_id   = var.vpc-id
  deregistration_delay = 5

  tags = {
    Environment = "${var.environment-beta}"
  }

  health_check{
  healthy_threshold = 2
  unhealthy_threshold = 2
  timeout = 10
  interval = 15
  path = var.path-beta
  }
}

A: If I correctly understand, you are using for_each in your target-groups module. If so to get the outputs, you would have to use something like the following in your main.tf file:
module.target-groups[*].arn

The for_each will create multiple modules, not multiple resources in a single module.
Here is good info on using for_each and count with modules in terraform 0.13.
Update for one module
If you want to use only one module, you can do the following:
module "target-groups"{

  target_groups_to_create = local.targetgroups_beta

  source = ".//modules/targetgroups"
  name-beta = each.value.name
  path-beta = each.value.path
  environment-beta = each.value.environment
  vpc-id = "${module.vpc.vpc_id}"
}

Then in the module:
variable "target_groups_to_create" {}

resource "aws_lb_target_group" "target-group" {

  for_each = var.target_groups_to_create

  name     = "example-${each.value.name}"
  port     = 80
  protocol = "HTTP"
  vpc_id   = var.vpc-id
  deregistration_delay = 5

  tags = {
    Environment = "${each.value.environment}"
  }

  health_check{
  healthy_threshold = 2
  unhealthy_threshold = 2
  timeout = 10
  interval = 15
  path = each.value.path
  }
}


text:
Q: Laravel format datetime I have in my database the date of birth of a user, but I want to format that to something like 27 March 2000. I already have the date of registered and I can format that, but if I try to format the date of birth it gives me the following error:
Call to a member function format() on string
This code I used to show and format the date of birth of a user:
{{ucfirst(Auth::user()->created_at->format("M d Y"))}}

I tried to use this code for the date of birth because it is in a table with all the users:
{{ucfirst($user->birthdate->format("M d Y"))}}

This is the database structure:
 http://i.stack.imgur.com/Agchg.png

A: You need to tell Laravel that your birthdate field is a date, otherwise Laravel will just fetch it as-is and not touch it at all. You do that by adding a protected $dates to the model-class which is an array of all fields which Laravel should treat as dates.
class MyModel extends [...] {
    protected $dates = ['bithdate'];
}

This will tell Laravel that birthdate is a date and Laravel will convert it to a instance of Carbon.


text:
Q: Expectation on drawing card from a deck. Suppose I keep drawing cards from a deck of cards(with replacement, meaning after I draw a card, I switch a new deck of cards but keep the card I draw) until I have drawn both a 1 and a 2. Then What is the expected number of times I would have to draw cards until I can stop?
I have no clue about how to compute such expectation numbers.

A: If you try something with probability $p>0$ of succeeding, you'll have to try on average $1/p$ times before succeeding (cf https://en.wikipedia.org/wiki/Geometric_distribution )
Thus, with $n\ge2$ cards in the deck, you'll draw the first 1 or 2 in  $\frac{n}{2}$ tries and the second one in $n$ tries, so $\frac{3n}{2}$ is the answer

A: Assuming a 52-card deck with 4 1s (aces) and 4 2s, this is relatively simple to calculate.
Each draw there is a 2/13 chance you will draw either a 1 or a 2. After you have drawn either a 1 or 2, you have a 1/13 chance of drawing whatever the other number you need to draw is.
IDK but according to WNG (the other answerer) it takes 1/p times on average before succeding. So 13/2 + 13/1 = 21.5
Apparently it will take on average 21.5 draws to get both a 1 and a 2. Seems kindof high to me so IDK if this is right :(
Edit: 13/2 + 13/1 is actually 19.5


text:
Q: Apache stops functioning for no particular reason I have been experiencing this issue for about a year now with Ubuntu 16.04  & LAMP stack. Basically the server sort of gives out after a few months of usage. After checking every log I can think of on the server, there is nothing indicating any problems, but simply stops working about 50% of the time.

*

*Its not out of memory

*No errors in logs

*Plenty of disk space & inodes

*Apparmor not getting in the way

*Server not under load

Its running PHP 7.0 with Apache2, off the shelf stuff, nothing fancy.
Pretty consistently happens after several months. Not sure exact duration as its working fine, then one day just goes haywire.
I would put phpinfo() here, but I can't even get it to load :|
Any input, or other things I can check other than the obvious syslog/apache logs/etc would be immensely appreciated.

A: I seemed to have rectified the issue by simply disabling the PHP module using a2dismod php7.0; a2enmod php7.0;
Now for the real question - what could that process have done? Reset some cache? Reset settings? Any ideas?


text:
Q: draw custom view then add to xml I have LinearLayout in my xml file that I am trying to add a custom view to. Here is my xml code:
        <LinearLayout android:id="@+id/amenitycontent"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="@color/background_color">

            <com.mypackage.util.AmentiesView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>

        </LinearLayout>

This code is inside a TabHost (not sure if this makes a difference).
and here is my custom view:
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

public class AmentiesView extends View{

Bitmap image;
String title;
private final Paint paint = new Paint();

public AmentiesView(Context context) {
    super(context);
    image = BitmapFactory.decodeResource(getResources(), R.drawable.checkcircle);

}
public AmentiesView(Context context, AttributeSet attrs) {
    super(context, attrs);
    image = BitmapFactory.decodeResource(getResources(), R.drawable.checkcircle);

}

public void setTitle(String _title){
    title = _title;
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.drawBitmap(image, 0, 0, paint);
    canvas.drawText(title, image.getWidth() + 10, 0, paint);
    canvas.drawColor(Color.RED);
}

}

When I run the code, nothing is shown. Any ideas?

A: Try setting some fixed numbers for width and height of your view - i.e 300x200. There's a good chance that since you're setting the width and height to wrap_content and your view basically has no content(nothing added in it) the canvas you're getting in onDraw is empty.


text:
Q: MySql - Add comma delimiter Is there a way for adding commas for values for IN clause? e.g. if my query
 SELECT * FROM Persons WHERE Id IN(.....)

and I've copied from csv file, example:
12
23
58
55

I tried to put the cursor on the left of 12 and hold down Alt + Shift,  click the down key for as many numbers as you have, I saw the line and I released the keys (Alt + Shift) I pressed comma (,) but it's applied on just one line, what I did wrong?

A: Are you using Google Chrome/FireFox and development tool enabled (Press F12 to show it)?
You can go to console and paste this code
let lines = `
Paste text from csv here
`;
let lineText = lines.split('\n').filter(x => x.trim().length > 0).map(x => x.trim())
console.log(` SELECT * FROM Persons WHERE Id IN(${lineText.join(', ')})`)

Then you can paste the text copied from csv to Paster text from csv here
Then enter. You will get the sql script in the console. Then copy the sql and paste to mysql command executor.

Hope this helps!

A: Certainly, Alt+Shift adds several cursors in MySQL Workbench but (for whatever the reason) they don't behave as such. The editor, however, supports regular expressions to search and replace so you can use that:

*

*Select all lines but the last one.

*Go to Edit/ Find/ Find and Replace (Ctrl+H).

*Set the Regular Expression mode from the tiny  icon:

*Search for $ (end of line) and replace with , (comma).

*Hit Replace All.

Disclaimer: my copy of Workbench for Windows freezes everytime I try. If yours does too, you may want to just switch to another MySQL client; this regexp syntax is pretty much universal across editors.


text:
Q: Как сделать подписанный хэшем JSON? Помогите пожалуйста. Я не могу понять как создать транзакцию и отправить POST запрос И вообще как работать с этим API. Я прочитал документацию но ничего не понял. Пожалуйста помогите - проект стоит
Вот API - https://docs.cityhub.com.ua/introduction.html
Думаю на земле еще есть хорошие люди.

A: В целом, в документации всё написано, хотя и немного непоследовательно.

*

*Формируем массив в указанном формате, с пустой строкой на месте хэша

*Сортируем так чтобы ключи шли в алфавитом порядке

*Делаем JSON encode

*Формируем хэш MD5 из строки вида джейсон + токен

*Подставлям хэш в массив

*Делаем JSON encode и полученный джейсон отправляем

Дальше это все надо просто написать на РНР
$token = 111;

$data = [
    'auth' => [
        'point' => '33_44',
        'hash' => '',
    ],
    'locale' => 'ru',
    'service_id' => 999,
    'amount' => 1000,
    'fields' => [
        'account' => '1112233',
    ],
];
ksort($data);
$json = json_encode($data);
$hash = md5($json . $token);
$data['auth']['hash'] = $hash;
$json = json_encode($data);

и дальше отправлем полученный джейсон.
Токен должны выдать при регистрации


text:
Q: Resource Timing API not showing correct resources in Selenium I have geckodriver latest version installed and I am running latest Firefox version. I wrote a selenium script to just open a URL in firefox and keep the browser open (I am not calling driver.close() or driver.quit())
Here is what the script looks like
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("https://www.nrk.no/")

The number of resources reported by Resource Timing API is > 100 for this website.

Now, the website is just reloaded again, so that the resources are fetched from cache.
NOTE: I refreshed by just pressing enter in the address bar
The number of resources reported by Resource Timing API is < 40. Same is the discrepancy with the number of resources in Developer Tools in Networks tab. This is happening for every website.

This is not happening if I just run plain Firefox and refresh the page in the same way. The resources number match always, irrespective of the number of times I refresh the web page.


text:
Q: foreach value from input form please help me. i have a problem with my code.
This is code input.php :
<form method="POST" action="simpan.php">
NIM : <input type="text" required placeholder="input NIM" name="nim"/>

Name : <input type="text" required placeholder="input name" name="nama"/>

score : <input type="number" required placeholder="input score between 0-100" name="score"/>
<input type="submit" value="OK"/>

This is code simpan.php :
<?php
    session_start();
    $_SESSION['nim'][] = $_POST['nim'];
    $_SESSION['nama'][] = $_POST['nama'];
    $_SESSION['nilai'][] = $_POST['score'];

    header("location:index.php")
?>

and This is code show.php :
    <?php
    session_start();
    foreach($_SESSION as $key)
    {
            foreach($key as $data => $value)
            {
            echo "NIM : ",$value." ", "Name : ",$value." ", "Score : ",$value." ";
            }
    }
?>

the result :
enter image description here
And the problem is I want to show the input with format
Nim:
Name:
score:
example = nim:01 name: john score:90
What should I change in show.php in order to appear according to the above format?
thanks :)

A: @Arif Maulana just change your show.php to like below hope this is what you want:
<?php
    session_start();
    $echoString = "";
    foreach($_SESSION as $key => $sessionArr){
            if($key == "nama"){
                $echoString .= "name : ";
            }
            else if($key == "nilai"){
                $echoString .= "score : ";
            }
            else{
                $echoString .= $key." : ";
            }

            foreach($sessionArr as $value)
            {
                $echoString .= $value." ";
            }
    }
    echo $echoString;
?>

A: Please check the below example i did https://3v4l.org/CcOOK
 <?php

 $_POST['nim'] = 'Hrllo';
 $_POST['nama'] = 'Data';
 $_POST['score'] = '33';

$_SESSION['nim'][] = $_POST['nim'];
$_SESSION['nama'][] = $_POST['nama'];
$_SESSION['score'][] = $_POST['score'];

$string = '';
foreach($_SESSION as $main_key => $key)
    {
            foreach($key as $data => $value)
            {
             $string .= $main_key . ":" . $value . ' ';
            }

    }
    $string = rtrim($string, ' ');
    echo $string;


text:
Q: How to make turtles move at the same time? I'm modeling a bus stations with passengers. When all the passengers of a bus station are boarded, I want the bus (a turtle) to drive away. This should happen at the same time, however it is not at the moment. The buses leave after each other. Does anyone know what I'm doing wrong? Thanks in advance!

A: It still all happens in the same tick, so that is pretty much simultaneous since they don't have any effect on eachother. The only effect "leaving together" would have here is visual. If you really want them to move together you should use a link to group them together and then use tie so that their movement is linked, or create a loop with them all taking very small steps in succession.
Some more remarks:

*

*By the way what is the purpose of the time parameter? Why not just use ticks?

*You are calling tick twice. Once in go and once in drive.

*The if usage still feels really weird in your check-in procedure, especially since you combined it with move-to.

*The neighbor usage is also still weird. Why not a construction with patch-here?

*Constructions like one-of patches with [pxcor = 3 and pycor = 8] could be rewritten much more conveniently as patch 3 8

*I still suggest making a separate breed for your passengers.

*The naming of the bus breed still feels very off, since you are using the singular bus as plural
(I am deliberately not giving any actual code as answer since this series of posts feels very much like a school project)


text:
Q: Web application firewall (WAF) rules validation by javascript WAF Rules applied to web application which is already developed. To overcome WAF blocking inputs , need to convert format of input or encode input before form submitting  got failed. If any possibility to validate WAF rules using javascript , pls guide me to how it is possible.
if any JS library or api available pls mention.

A: I'm assuming the rule set your App Gateway is using is the OWASP rule set. This comes down to securing your code from vulnerabilities.  The WAF will enforce more secure and potentially better practices in your coding.  Here is a list of ways to secure your Javascript site, specifically node.js, for the OWASP top 10.  I'd start tackling the Rules one by one as once one is resolved it may trigger an additional one in the chain of inspection.  There might be cases where some WAF rules may need to be disabled as they are false positives. These can be disabled in the portal or via ARM


text:
Q: Separate the values in dictionary into two column. Python and Django I've a program which will read data from text file.
There are 3 types of data that I need to read from text file.

*

*visual id

*time

*tname_pb

Problem
I have 3 columns and need to separate output into different columns.
But, visual id is working perfectly, but time and tname_pb are combined together.

Question
How can I separate time and tname_pb into two different column.
Current views.py based on the picture
with open(path) as input_data:

for line in input_data:
    if line.startswith('2_visualid_'):
        visual_key = line.lstrip('2_visualid_').rstrip()
        data.update({visual_key: []})

    if 'time' in tokens:
        if search_time in line and visual_key in data:
            data[visual_key].append(next(input_data).lstrip('2_mrslt_').rstrip())

    if 'tname_pb' in tokens:
        if tname_pb in line and visual_key in data:
            data[visual_key].append(next(input_data).lstrip('2_mrslt_').rstrip())

Current template based on the picture

                Visual ID

            Time Delay Index

            Tname PB

        {% for key, values in output.items %}

            {{ key }}

            {% for value in values %}

            {{value}}

            {% endfor %}

        {% endfor %}

NOTE
I have tried few examples from Google, but I get errors with them.
I will post them here if they help clarify my question. I left them out because I don't want my question to be confusing.

A: You have a new table row going on here for each value.
{% for value in values %}

       {{value}}

{% endfor %}

Instead of this, you need to make a new table cell for each value.

                    Visual ID

                    Time Delay Index

                    Tname PB

        {% for key, values in output.items %}

                {{ key }}

                {% for value in values %}
                    {{ value }}
                {% endfor %}

        {% endfor %}


text:
Q: Applescript: Notification centre alert with specific Icon I understand that there is a very limited number of options to do with the Applescript notification alert call, but I am curious as to whether alerts can be called with icons or specified images to better identify them?
I ask this as i have seen it employed by other Applications which use the Notification Centre, and each Application has its notifications heralded by its own Application Icons.
Example:

Thanks in Advance.

A: Basically it's not possible to change the icon programatically.
A workaround is to save the script as application and change the icon (applet.icns) in the Resources folder of the package.