text:
Q: Has many through, self related, and polymorphic for STI models saving STI parent class name instead of STI child class name guys we are building a sort of address book, we have Users, Contacts and a parent Table called UserEntity. We want to relate them in a many-to-many association through a table called Relationship, this relations have to be in a self related in UserEntity table.
One User has many Contacts and one Contact has many Users.
Later on we need relate new models with Users so the Relationship model must be polymorphic. We already built this:
class UserEntity < ActiveRecord::Base
  self.table_name = "users"
end

class User < UserEntity
  has_many :relationships, as: :relatable
  has_many :contacts, through: :relationships, source: :relatable, source_type "Contact"
end

class Contact < UserEntity
  has_many :relationships, as: :relatable
  has_many :users, through: :relationships, source: :relatable, source_type "User"
end

class Relationship < ActiveRecord::Base
  belongs_to :user
  belongs_to :relatable, polymorphic: true
end

but when we try to save the association user.contacts << contact the relatable_type field saves "UserEntity" value and not "Contact" or "User" value. We already tried to do this without any favorable results http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#label-Polymorphic+Associations
How can we make that relatable_type value saves the model name ("Contact" || "User") and not the STI parent model name ("UserEntity")?

A: This is something known as STI base class, whereby Rails will save the Parent class, even though you've called the subclass. We have experience with it:

The above should have Node as Company...

I spent some time last year looking over this; there's a gem called store_sti_base_class:

Notice that addressable_type column is Person even though the actual class is Vendor.
Normally, this isn't a problem, however it can have negative performance characteristic in certain circumstances. The most obvious one is that a join with persons or an extra query is required to find out the actual type of addressable.

The way around it - at least from the perspective of the gem - is to extend ActiveRecord so that it will save the actual class of the model, not its parent.
The only code I have - which is out of date - is as follows:
#config/initializers/sti_base.rb
ActiveRecord::Base.store_base_sti_class = false

#lib/extensions/sti_base_class.rb
module Extensions
  module STIBaseClass #-> http://stackoverflow.com/questions/2328984/rails-extending-activerecordbase
    extend ActiveSupport::Concern

    included do
      class_attribute :store_base_sti_class
      self.store_base_sti_class = true
    end
  end

  # include the extension
  ActiveRecord::Base.send(:include, STIBaseClass)

  ####

  module AddPolymorphic
    extend ActiveSupport::Concern

    included do #-> http://stackoverflow.com/questions/28214874/overriding-methods-in-an-activesupportconcern-module-which-are-defined-by-a-cl
      define_method :replace_keys do |record=nil|
        super(record)
        owner[reflection.foreign_type] = ActiveRecord::Base.store_base_sti_class ? record.class.base_class.name : record.class.name
        Rails.logger.info record.class.base_class.name
      end
    end
  end

  ActiveRecord::Associations::BelongsToPolymorphicAssociation.send(:include, AddPolymorphic)
end

As I need to get this working, it might be worth bantering something around.

A: You must set UserEntity as abstract class:
class UserEntity < ActiveRecord::Base
  self.table_name = "users"
  self.abstract_class = true
end

Then value relatable_type can be User or Contact.
By default RoR save in relatable_type value of base_class method in your case:
class UserEntity < ActiveRecord::Base
end

class User < UserEntity
end

class Contact < UserEntity
end

irb(main):010:0> User.base_class.name
=> "UserEntity"

irb(main):011:0> Contact.base_class.name
=> "UserEntity"

When you make UserEntity as abstract class:
class UserEntity < ActiveRecord::Base
  self.abstract_class = true
end

class User < UserEntity
end

class Contact < UserEntity
end

irb(main):010:0> User.base_class.name
=> "User"

irb(main):011:0> Contact.base_class.name
=> "Contact"

Here defined method which store class name (https://github.com/rails/rails/blob/master/activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb#L14):
def replace_keys(record)
  super
  owner[reflection.foreign_type] = record ? record.class.polymorphic_name : nil
end

def polymorphic_name
  base_class.name
end


text:
Q: YouTube video playing after closing the overlay I am using below script for opening the overlay but when i close the overlay the iframe video is still playing in background.
HTML

            ×

A: As its not clear that how you are using youtube video in your code, I am assuming you are suing the most used way, which is by embed iframe.
So
There is many ways to do it, best is to use stopVideo(); function from youtube player API.
if you have youtube player object in your code,
something like this
player = new YT.Player();

just use this function on your close button click.
player.stopVideo();

or you can do this
$('#parentSelectorOfYourIframe').children('iframe').attr('src', '');

try to go through once to youtube official player API documentation
after your question update, I have created this codePen for you.
I hope this is exactly what you need, if need something else, please let me know.
Points to keep in mind..

*

*add this vpaframeter in your youtube video link as I did  ?version=3&enablejsapi=1 and then you can play around with your YT player.

A: Apparently the problem is that you hide the frame and not destroy it.
inspect your page and you'll see that the frame always exist and is juste in
display:"none"

I have tried to replace
$(id).style.display ='none';

by
$(id).innerHTML  = "";

but you don't have your frame anymore
or you can do that to
$(id).innerHTML  = '
×
';

=>you replace your frame with herself but with display:none in it

redpajama_set_name: RedPajamaStackExchange


text:
Q: Heat-map-style plot showing modal value for grid region (via stat_summary_2d?) I have a set of 2D points with category labels, and want to visualize which category dominates each cell of a grid super-imposed over the 2D plane.
I imagined I would be able to use stat_summary_2d with a function that selects the most frequent value as shown below, but I got different plots for three variations that should be identical except for the legend labels.
Am I misusing stat_summary_2d? Is there a better way to generate this plot?
library(ggplot2)
set.seed(12345)
x = runif(1000)
y = runif(1000)
lab = rep(c("red", "blue", "green", "yellow"), 250)

df = data.frame(x=x, y=y, lab=factor(lab, labels=c("red", "blue", "green", "yellow")))
df$val = as.numeric(df$lab)

#Attempt 1
ggplot(df, aes(x=x, y=y)) +
  stat_summary_2d(aes(z=lab),
                  fun=function(z) names(which.max(table(z))),
                  binwidth=.1)

#Attempt 2
ggplot(df, aes(x=x, y=y)) +
  stat_summary_2d(aes(z=val),
                  fun=function(z) names(which.max(table(z))),
                  binwidth=.1)

#Attempt 3
ggplot(df, aes(x=x, y=y)) +
  stat_summary_2d(aes(z=as.numeric(lab)),
                      fun=function(z) names(which.max(table(z))),
                      binwidth=.1)

A: Add group = 1 to Attempt 1 & you'll see the same distribution of panels as the subsequent two attempts.
Specify the fill palette appropriately, & all three will look the same:
library(ggplot2)

#Attempt 1
p1 <- ggplot(df, aes(x=x, y=y, group = 1)) +
  stat_summary_2d(aes(z=lab),
                  fun=function(z) names(which.max(table(z))),
                  binwidth=.1) +
  scale_fill_manual(values = c("red" = "red",
                               "blue" = "blue",
                               "green" = "green",
                               "yellow" = "yellow"),
                    breaks = c("red", "blue", "green", "yellow")) +
  ggtitle("Attempt 1") + theme(legend.position = "bottom")

#Attempt 2
p2 <- ggplot(df, aes(x=x, y=y)) +
  stat_summary_2d(aes(z=val),
                  fun=function(z) names(which.max(table(z))),
                  binwidth=.1) +
  scale_fill_manual(values = c("red", "blue", "green", "yellow")) +
  ggtitle("Attempt 2") + theme(legend.position = "bottom")

#Attempt 3
p3 <- ggplot(df, aes(x=x, y=y)) +
  stat_summary_2d(aes(z=as.numeric(lab)),
                  fun=function(z) names(which.max(table(z))),
                  binwidth=.1) +
  scale_fill_manual(values = c("red", "blue", "green", "yellow")) +
  ggtitle("Attempt 3") + theme(legend.position = "bottom")

gridExtra::grid.arrange(p1, p2, p3, nrow = 1)

Explanation: If you examine the underlying data of the first plot, you'll notice that there are 379 rows of data, each corresponding to one tile in the heatmap. If we total up the number of different colours within each bin, we'll get 379 as well, so there's in fact multiple tiles at each bin position. (In contrast, the underlying data for the second and third plots have 100 rows each.)
Based on this, we know that ggplot had interpreted each factor level in "lab" to be a separate group, and performed stat_summary_2d() separately for each level. Adding group = 1 to the aesthetic mapping forced all levels to be considered together.
p1.original <- ggplot(df, aes(x=x, y=y)) +
  stat_summary_2d(aes(z=lab),
                  fun=function(z) names(which.max(table(z))),
                  binwidth=.1)

View(layer_data(p1.original))


text:
Q: refetch data from API using react hooks I'm a complete beginner in react and I have written a fetch component which returns data from an API using a usefetch function . In my app I can manually change the input to get different data from the API but what I want is to have an input field and a button that when it is clicked it returns the new data from the API . With my code below I can fetch data only once when the component mounts and if i give input nothing happens .
import React , {useState ,useEffect} from 'react';
import useFetch from './fetch'; //fetch api  code imported
import SearchIcon from '@material-ui/icons/Search';
import InputBase from '@material-ui/core/InputBase';
import Button from '@material-ui/core/Button';

  function City(){

    const searchStyle = {
      display:"flex",
      justifyContent:"flex-start",
      position:"absolute",
      top:"400px",
      left:"40%",
    }

    const [inputVal , setInputVal]  = useState(''); //store input value
    const [place,setPlace] = useState('london');  //get london data from api by manually changing value new data is succesfully dislayed
    const {loading , pics}  = useFetch(place); //fetch data
    const [images , setImages] = useState([]); //store fetched imgs

    const removeImage = (id) =>{
      setImages((oldState)=>oldState.filter((item)=> item.id !== id))
    }

    useEffect(()=>{
      setImages(pics);
    } , [pics] )

    //load and display fetched images
    return (

      {
        !loading ?

          (images.length>0 && images.map((pic) =>{
            return

                     removeImage(pic.id)} >

                          ×

                        From :
                         {pic.photographer}

          })

        ):
 Loading

      }

            <SearchIcon />
             //when input changes store it
            <InputBase onChange={(e)=>setInputVal(e.target.value)}   placeholder="Enter input" style= {{backgroundColor:"lightgrey"}}/>
            //new fetch data based on input by clicking on button nothing happens onclick
            <Button onClick= {()=>setPlace(inputVal)} color="primary" variant = "contained" > Find </Button>

);
  }

export default City;

fetch.js my code to connect to api :
import { useState, useEffect } from 'react';

function useFetch(url){

  const [loading ,setLoading] = useState(false);
  const [query,setQuery] = useState(url);
  const [pics,setPics]  = useState([]);

  const getPics = async()=>{
    setLoading(true);
      const response = await fetch(
        `https://api.pexels.com/v1/search?query=${query}&per_page=4`,
        {
          method:"GET",
          headers:{
            Accept:"application/json",
            Authorization:key
          }
        }
      );
    const result = await response.json();
    setPics(result.photos ?? []);
    setLoading(false);
  }

  useEffect(()=>{
    getPics();
  },[query]);

  return {loading , pics ,query  ,setQuery , getPics};

}

export default useFetch;

I think that my place value changes when my button is clicked but my fetch function is not reloaded and I just change a value .
I would really appreciate your help .

A: You can create a new useEffect and then add the place to the useEffect dependencies to create a side effect to call the API again once the value of the place variable changes:
  // return the read function as well so you can re-fech the data whenever you need it
  const {loading , pics, readData}  = useFetch(place);

  useEffect(() => {
    readData(place);
    setImages(pics)
  }, [place]);

This will give you fresh data for each button click.

A: The problem is useFetch is storing the initial url passed into useState:
const [query,setQuery] = useState(url);

When place gets updated, useFetch never uses it and the effect is never going to be re-triggered. I think if you remove this state from useFetch completely, it ought to work as you expect:
import { useState, useEffect } from 'react';

function useFetch(url) {
  const [loading, setLoading] = useState(false);
  const [pics, setPics]  = useState([]);

  const getPics = async () => {
    setLoading(true);
    const response = await fetch(
      `https://api.pexels.com/v1/search?query=${query}&per_page=4`,
      {
        method: "GET",
        headers: {
          Accept: "application/json",
          Authorization: key
        }
      }
    );
    const result = await response.json();
    setPics(result.photos ?? []);
    setLoading(false);
  }

  useEffect(()=>{
    getPics();
  }, [url]);

  return { loading, pics, getPics };

}

export default useFetch;


text:
Q: Why can't I get my image aspectfit on rotated view of android emulator I'm a beginner with Xamarin and my code is very simple
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:XamarineTest2"
             x:Class="XamarineTest2.MainPage">

    <StackLayout>
        <Image BackgroundColor="Fuchsia"
               Aspect="AspectFit"
               Source="Juice.jpg"/>
    </StackLayout>
</ContentPage>

With the basic android emulator debugger on my visual studio 2017,
I get aspectfit image on portrait(vertical) view as expected like below.
[enter image description here][1]
But when I rotate it to landscape(horizontal) view using the button on the emulator,
I get aspectfill-like image as shown below.
[enter image description here][2]
How can I keep it aspectfit on landscape view which means the bottom of the image should not be cut off?
Thank you guys in advance.
[1]: https://i.stack.imgur.com/ddseU.jpg
[2]: https://i.stack.imgur.com/1hdDS.jpg

A: I found everything works fine if I use Grid instead of StackLayout. I don't know why, but there seems to be more such problem with StackLayout. Plz add more comment for anyone having a similar problem, since this issue is kind of very basic one in Xamarin.


text:
Q: using shortcodes in theme content I am using plugin like to read http://wordpress.org/extend/plugins/like-to-keep-reading/
problem is its using opening and closing shortcodes,when I embed them to my site http://vijaykudal.info only opening short codes displayed,can you please help me?
PS:-tried with different themes as well

A: To put shortcode within a PHP template, use do_shortcode();
<?php
echo do_shortcode( '[like_to_read]The text that is hidden from the user.[/like_to_read]' );
?>

Edit:
 <?php
    echo do_shortcode( '[like_to_read]' . get_the_content() . '[/like_to_read]' );
    ?>

A: my your theme deactived shortcodes , so
this tools save time to search about shortcode remove word in folders
so when tool got installed, click on theme file and click on grepwin then write  remove_shortcode then wait to see the resluts , and after if there's any pages contains  remove_shortcode will appear in box bellow, all u had to do is playing with codes may it works ! or simply you can user this shortcode
for example
function shortcode_content_post_url() {

    echo 'short codes is cool';
     }
add_shortcode('cool', 'shortcode_content_post_url');

and in url post type [cool]
then it will appear short codes is cool


text:
Q: Undo selecting to use partition as swap and recover data I don't know how to explain this as I don't know what has happened.
So I was trying to install Ubuntu from a Flash drive and didn't knew what to do. Somewhere during the Initial steps of Setup I Checked that "something else.."

Where it showed this..(this is not my PC) just like that sda5 one of my drive was sda3 and was about 336 GB in size which I used as "swap" (IDK what is that either).
I used sda5 as the "root file system" thingy. Now my problem is, when the installation was over and it rebooted it directly Started Windows and I saw My 336 Gb drive missing in Windows as well as Ubuntu. TBH I don't know what I have done, where this is heading..I am beyond Terrified :C . HELP!
And this is what it shows in My Windows 7 now:


text:
Q: Connection refused with ElasticSearch on Digital Ocean I install Elastic Search using this tutorial changing only version by Elastic Search.
Set network.host: 127.0.0.1 to access by terminal. But show this error when try connect:
curl: (7) Failed to connect to localhost port 9200: Connection refused

A: Check your port 9200 is open or not, then check if you're not using the UFW firewall.
In case of you are using the UFW firewall :

*

*sudo ufw allow 9200


text:
Q: Single Sign On (SSO) via 3rd party ADFS using ASP.NET WebForms We have a webforms (.net 4.5) application which uses membership for user authentication which we host ourselves. Our clients have Active Directory and ADFS which they host in their own networks, they require our software to use single sign on authenticating against their ADFS server. I'm looking for steps on how to implement this so we can continue to use our normal membership login but use SSO where available.
There's a lot of info out there and I honestly don't know where to start. Cheers.

A: I wrote up something very similar to this:
OWIN : ASP.NET MVC application with multiple authentication options
Basically, use the OWIN Identity stacks to support whatever protocols you want.
Note that this application (RP in ADFS speak) still needs to be configured on the ADFS side.


text:
Q: Add one more option to android messages long press context menu I wanted to write an app which can store some messages. Currently by doing long press on android messages some options (like "forward message", "delete message" etc) are arrived. I would like to add one more option to this (for example "store this message").
Is there a way to do this?

A: Try this code:
ListView nameList;
nameList = (ListView) findViewById(R.id.list);
nameList.setLongClickable(true);
registerForContextMenu(nameList);

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
    menu.setHeaderTitle("Delete / Miss Call Contact");
    menu.add(menu.NONE,1,menu.NONE,"Delete");
    menu.add(menu.NONE,2,menu.NONE,"call");
}

@Override
public boolean onContextItemSelected(MenuItem item) {
  final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
  position = (int)info.id;
  switch(item.getItemId()) {
    case DELETE:
       // do something
    case MISSCALL:
       // do something
  }
  return super.onContextItemSelected(item);
}


text:
Q: Localization with LocalizedStrings in Xaml - Binding value to the binding string I'm on a question-spree!
I want to know, when binding objects to an ItemsControl, how can I bind a textbox to LocalizedStrings using the current path in de ItemsSource?
Code will clarify, I hope:
<ItemsControl ItemsSource="{Binding Hours}" VerticalAlignment="Top">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Grid VerticalAlignment="Top">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="125" />
                    <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>
                    <TextBlock Grid.Column="0" Text="{Binding Path=LocalizedResources.DayName, Source={StaticResource LocalizedStrings}}" Style="{StaticResource App_Content_Grid_Bold}" HorizontalAlignment="Left" />
                <TextBlock Grid.Column="1" Text="{Binding Description}" Style="{StaticResource App_Content_Grid_Subtle}" FontSize="20" Foreground="Black" HorizontalAlignment="Right" />
            </Grid>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

The problem is, DayName does not exist in LocalizedStrings but it's value does.
How can I parse it's value into this binding context before the binding itself is applied?
Something like: {Binding Path=LocalizedResources.[DayName], Source={StaticResource LocalizedStrings}}?


text:
Q: how to clean large postgresql table contains many useless records? I have a quite large log table in my postgresql database(over 100 million records),  and many of the records are useless that I am gonna to clean to improve the IO performance.
and this work have to be done while the production db in service.
I have 2 ideas of myself:
solution 1

*

*create a new table log_new

*rename tables in a transaction: log -> log_old, log_new to log

*clean the useless records from log_old, then move the remained records into the new log

*done

solusion 2

*

*create a new table log_temp

*rename tables in a transaction: log -> log_old, log_temp -> log

*clean the useless records from log_old

*do vacuum full and reindex on log_old

*rename back the tables: log -> log_temp, log_old -> log

*move the records in log_temp to log

*done

a short time log records missing is acceptable, but log writing can not be interrupted(table name reference from applications NOT changed, log writing request NOT be blocked).

question 1: do you see any pitfalls in my solutions ?
question 2: what would be your choice, or do you have a better solution ?

A: I would:

*

*Create a new table log_temp.

*Insert into the new table all the records I want to keep.

*Truncate the old table.

*Insert the records from log_temp into the old table.

Truncating the table should be the fastest way to remove all the old records -- and it doesn't require any vacuuming.  The key is saving the right data in log_temp.  And verifying it before truncating the original table.
This method is also trigger-safe and works with many constraints.  That is, you don't have to redefine triggers if there were any on the original table.


text:
Q: Is LINQ to SQL deprecated? Back in late 2008 there was a lot of debate about the future of LINQ to SQL.  Many suggested that Microsoft's investments in the Entity Framework in .NET 4.0 were a sign that LINQ to SQL had no future.  I figured I'd wait before making my own decision since folks were not in agreement.
Fast-forward 18 months and I've got vendors providing solutions that rely on LINQ to SQL and I have personally given it a try and really enjoyed working with it.  I figured it was here to stay.
But I'm reading a new book (C# 4.0 How-To by Ben Watson) and in chapter 21 (LINQ), he suggests that it "has been more or less deprecated by Microsoft" and suggests using LINQ to Entity Framework.
My question to you is whether or not LINQ to SQL is officially deprecated and/or if authoritative entities (Microsoft, Scott Gu, etc.) officially suggest using LINQ to Entities instead of LINQ to SQL.

A: No it is not. The team are still working on improving it.

A: For all the "Linq-to-SQL is dead" folks: Scott Guthrie himself clearly mentioned at TechEd Europe that Linq-to-SQL is FULLY SUPPORTED in .NET 4, and Damien Guard posted a blog post on what changes and improvements have been made for Linq-to-SQL in .NET 4.
To quote Mark Twain: "Reports of my death have been greatly exaggerated"......

A: LINQ to SQL tools in Visual Studio

LINQ to SQL was the first object-relational mapping technology
  released by Microsoft. It works well in basic scenarios and continues
  to be supported in Visual Studio, but it's no longer under active
  development. Use LINQ to SQL when maintaining a legacy application
  that's already using it, or in simple applications that use SQL Server
  and do not require multi-table mapping. In general, new applications
  should use the Entity Framework when an object-relational mapper layer
  is required.

A: Make sure to have a look at this article posted on InfoQ.com - it's a really interesting one. Its conclusion: "[O]ver the long run LINQ to SQL and LINQ to Entities will merge. In the mean time, development work on LINQ to SQL will not end entirely."

A: Last I checked, this very site uses (or used to use) Linq To SQL. Joel Spolsky mentions this in his GoogleTechTalk: http://www.youtube.com/watch?v=NWHfY_lvKIQ.
When speaking of software, "dead" is a figurative modifier (software doesn't die in any literal, biological sense), so this debate can linger on as long as the involved parties refuse to define in any literal sense what it means for "Linq To Die". Or, LTD for short. Hence, as of this moment, the LTD debate has lingered for two years. All because of a little linguistic ambiguity.
Those who say that "L2S is dead" are generally referring to the fact that L2S isn't going to receive too many (if any) new features. Updates to Linq (like the updates mentioned in Damien Guard's post) are likely to be confined to performance, usability, and stability updates. Of course, some developers might actually argue that this is a good thing (probably the same developers who are a wee bit angry about the new dynamic type).
Those who say that "L2S is not dead" are generally referring to the fact that L2S isn't going to be cut altogether from .Net (at least not anytime soon). Think: ADO. It may lose some of its traction amongst practicing developers (and that may be the unspoken desire of those crafty folks at Microsoft), but that doesn't mean that you won't be able to use L2S if you want to. It just means that Microsoft isn't trying to tantalize the masses with it.
When starting a project, I actually think it's great that I have a choice between EF and L2S. As Bill Wagner points out, there's a time and a place for both.

A: I am late to this discussion, but I wanted to point out that as far back as 2008, the Link to SQL Project Manager (Tim Mallalieu) made this announcement in his blog post,

"As of .NET 4.0, LINQ to Entities [rather than LINQ to SQL] will be the recommended data access solution for LINQ to relational scenarios."

I have found no other more recent announcements to the contrary.

A: i guess it's inevitsble that they'll merge. EF is really an enterprise level implementation of LINQ over db objects. linq2sql was to all intents a proof of concept(and a lot more) that actually grew legs but fuelled many of the ideas that we now see in EF. at the end of the day, the DAL layer (nhibernate, EF, l2s, subsonic etc) should be pretty far down the chain so as to negate any differences in the client BO code that implents the LINQ service - hot swappable would be the end game via DI.


text:
Q: monitoring a node.js server I am looking for a way to get some sort of monitoring, statistic or management data out of a node.js server instance - not sure what to search for or where to start. Any advice appreciated.
Stats would be requests processed (if applicable) - number of connections and so on.

A: Don't know if it will fit your needs, but you can try to look at node-monitor. Also Joyent is doing some advanced real-time performance analysis stuff, but it's probably only for their cloud services.

A: Nodetime can monitor different metrics, such as HTTP Response time, CPU time, OS Load, etc. It is also possible to set up email Alerts based on these metrics. More in the blog post Monitoring Node.js Application Performance.


text:
Q: Java Concurrent Modification Error HashMap Fun question here. Why does the first version of this throw a concurrent modification error, while the second does not. Should this happen?
Map<String,Integer> map = new HashMap<>();
... // Populate the map
for(String key : map.keySet()){
    if(map.get(key) < 50){
        map.remove(key);
    }
}

Map<String,Integer> map = new HashMap<>();
... // Populate the map
for(String key : new ArrayList<String>(map.keySet())){
    if(map.get(key) < 50){
        map.remove(key);
    }
}

A: The first example throws an exception because you modify the map while you are iterating over it. That is expected.
In the second example, you create an ArrayList containing all the strings in the map. Here you iterate over that newly created ArrayList, so your second example don't throw an example because you iterate over the ArrayList, not over the map

A: This
for(String key : map.keySet()){
    if(map.get(key) < 50){
        map.remove(key);
    }
}

will always throw a ConcurrentModificationException because you remove items while you iterate. What you need is an Iterator which has the remove operation:
for(Iterator<Map.Entry<String, Integer>> it = map.entrySet().iterator(); it.hasNext(); ) {
    Map.Entry<String, Integer> entry = it.next();
    if(entry.getValue() < 50) {
      it.remove();
    }
}

There is also the ConcurrentHashMap which supports concurrent operations and only locks buckets if you need it.

A: In the first case you get a concurrentModificationException because there's a modification count associated with iteration in terms of internal implementation. If the modification count changes during iteration a concurrentModificaitonException is thrown.
The solution is to use iterator.remove() instead of removing an element directly from the map.
In the second case, you are iterating not the map but a different collection while removing an element from the map. In this case, the modification count never changes during iteration because you are iterating a different collection.
Also, in a multithreaded environment always use synchronized on a collection that represents shared mutable state in a class before iterating it otherwise you can get a concurrentModificationException .
In a multithreaded environment, your second solution would not be correct because you haven't synchronized the statement where you transfer the keyset of the original map to a new collection. So there's potential to get a concurrentModificationException. Use a ConcurrentHashMap in a multithreaded environment while knowing that not every operation or set of operations on a ConcurrentHashMap is threadsafe by default.


text:
Q: REGEX para remover sites, e-mails Quero remover os endereços de sites, e-mails, etc...
url_regex = re.compile(r'(?i)(<|\[)?(https?|www)?(.*)?\.(.*){2,4}')
mail_regex = re.compile(r'(?i)(<|\[)?@(.*)\.(.*){2,3}')

Desta forma, eu poderia remover por exemplo:

http://www.google.com.br

http://www.twitter.com
[image.jpeg]
www.facebook.com
[www.amazon.com]
MARIN@blabla.jp
vairegex@python.br
...

Quando testadas em um texto, essas regex fazem match com o texto todo e nao apenas com os endereços site/emails.

A: O problemas dessas expressões regulares estão no operador .*. O operador * é guloso, ou seja, ele vai tentar casar com o máximo possível de caracteres da string.
O ideal é sempre que possível, construir uma expressão regular que tenha um critério de parada. Por exemplo, uma URL ou um endereço de e-mail podem ter espaço em branco? Se não puderem, o seu critério de parada é o carácter em branco. Ou então um e-mail ou URL só podem ter letras, números e alguns caracteres (., -, _). Então você pode casar com todos até encontrar um carácter que não seja um desses.
Vamos definir que um e-mail tem apenas letras, números e alguns caracteres (., -, _) e tem um @ no meio. Uma expressão regular para validar e-mail é beemm mais complexa que isso, mas essa aceita 98% dos e-mails existentes.
mail_regex = re.compile('([a-z0-9_.-]+@[a-z0-9_.-]+)', re.IGNORECASE)

Nessa expressão regular, temos 2 partes, uma que aceita 1 ou mais caracteres de a a z, números e os 3 caracteres especiais que definimos. Esperamos depois disso um carácter @ e depois a segunda parte, onde aceitamos as mesmas coisas da primeira parte.
Para casar com uma url é a mesma coisa, a diferença é que nossa ancora está no começo do texto (http://, www ou [).
url_regex  = re.compile('((http://|www|\[)[a-z0-9_.-]+]?)', re.IGNORECASE)

Nessa expressão regular, olhamos primeiro para o começo do texto para ver se tem http://, www ou [. Caso tenha, olhamos se tem letras, números e afins. A única diferença aqui é que também olhamos o ultimo caractere, se não é ], no caso da URL ser cercada por colchetes.
Finalmente, rodando essas expressões no texto que você postou, temos o seguinte resultado:
print (mail_regex.sub('E-MAIL', text))
http://www.google.com.br

http://www.twitter.com

[image.jpeg]

www.facebook.com

[www.amazon.com]

E-MAIL

E-MAIL

E nas urls:
print (url_regex.sub('URL', text))
URL

URL

URL

URL

URL

MARIN@blabla.jp

vairegex@python.br


text:
Q: EF- Result of Lambda Expression to List(of Class) I have the following class:
Public Class CodeList
    Public Code As String
End Class

I am using Entity Framework.
I have the following table in a generated class:
Partial Public Class ContentTable
    Public Property ID As Long
    Public Property Type As Nullable(Of Integer)
    Public Property Code As String
    Public Property Active As Nullable(Of Boolean)
End Class

I am using this lambda expression to select distinct Code from ContentTable
Dim db As New ModelCodeEntities
Dim result = db.ContentTables.Select(Function(m As ContentTable) m.Code).Distinct().ToList

I want to convert the result of this lambda to a List(of CodeList)
Any help would be appreciated.

A: Dim result As List(Of CodeList)=db.ContentTables.Select(Function(item) item.Code).Distinct().Select(Function(code) new CodeList with{.Code=code}).ToList()


text:
Q: Replacing glPush/PopMatrix I do realize that glPush/Pop matrix functions are not supported by many platforms (so don't shoot me) but does anyone knows how should I replace them without breaking my existing code base?

A: Its actually pretty simple.  Each time you push a matrix you are just multiplying it with the one that was one down the stack.  You could VERY simply write your own push/pop matrix stack.  Literally a stack of matrices for ModelView, Projection and Texture(s) and then each time you call push matrix just push Mprev * Mcurr to the top of the stack.  When you pop you are just going back to the previous matrix.

A: Since these funcs are deprecated along with fixed function on many platforms and new core versions, you have to supply the matrices to your own shader (mandatory) as uniforms.
gl_ModelViewMatrix, gl_ModelViewProjectionMatrix and other builtin uniforms are removed from GLSL along with fixed function in all new OpenGL (core) versions aswell, regardless the platform.
Therefore, the decision should not be based on platforms, since all new core profiles don't have those functions anymore. Replacing this requires some effort, but will improve portability to all platforms and more importantly, (forward) compatibility to the new ones.
Implementing a client side matrix stack is not that hard either.
EDIT: See this C++ example template, which mimicks the OpenGL matrix stack. It lacks the matrix math implementations, does not use the STL stack due to reasons not visible here, but shows the math operations to be done:
EDIT 2: added error check (1 element is the minimum stack size)
template<typename T>
class MatrixStack
{
public:
    typedef T matrix_type;

private:
    std::vector<matrix_type> stack;

public:
    MatrixStack(void)
    {
        stack.push_back(matrix_type::identity());
    }

    void clear(void)
    {
        stack.clear();
        stack.push_back(matrix_type::identity());
    }

    size_t size(void) const
    {
        return stack.size();
    }

    void push(void)
    {
        matrix_type tmp = stack.back(); //required in case the stack's storage gets reallocated
        stack.push_back(tmp);
    }

    bool pop(void)
    {
        if (size() > 1)
        {
            stack.pop_back();
            return true;
        }
        else
        {
            return false;
        }
    }

    void load(const matrix_type& matrix)
    {
        stack.back() = matrix;
    }

    void loadIdentity(void)
    {
        load(matrix_type::identity());
    }

    void loadTransposed(const matrix_type& matrix)
    {
        load(transpose(matrix));
    }

    void mult(const matrix_type& matrix)
    {
        load(stack.back() * matrix);
    }

    void multTransposed(const matrix_type& matrix)
    {
        load(stack.back() * transpose(matrix));
    }

    const matrix_type& get(void) const
    {
        return stack.back();
    }
};


text:
Q: I need an interval of 3 seconds to execute each mysql_query I'm doing a simple chat and everything is working well, but everybody can flood the chat sending how many messages they want to...
PHP:

<input type="text" autocomplete="off" maxlength="50" placeholder="Type your message..." id="message" size="87%" checked="yes">
<input type="button" id="message" onClick="sendMessage()" value="Send">

JAVASCRIPT:
function sendMessage() {
var message = $('#message').val();
$.post('postMessage.php', { message: message } , function() { } );
}

postMessage.PHP:
session_start();
include ("chats/connect.php");
$timname = $_SESSION['username'];
if (isset($_POST['message'])) {
mysql_query("INSERT INTO chat VALUES ('', '".$timname."', '".$_POST['message']."', '".time()."', NOW(), '');");
}

I need to set a interval to send each message like 3 seconds...
Any information will be helpful!

A: Try Jquery to refresh specific page. Try something like below code
setup.js
var autorefresh=setInterval(
function()
{
    $("query.php").load('query.php');
    e.preventDefault();
},3000);

query.php
session_start();
include ("chats/connect.php");
$timname = $_SESSION['username'];
if (isset($_POST['message'])) {
mysql_query("INSERT INTO chat VALUES ('', '".$timname."', '".$_POST['message']."', '".time()."', NOW(), '');");
}

Here 3000 in setup.js is time in miliseconds you want to refresh.


text:
Q: Custom sort objects in an array in swift Needed to sort Objects (Class/Datatype), Alphabetically.
UnSorted Array::
[main.Apple, main.Zoo, main.IceCream, main.Apple, main.IceCream]

Sorted Array:: Alphabetically Type @ the Front
[main.Apple, main.Apple, main.IceCream, main.IceCream, main.Zoo]

A: This is one of the solutions that I have found till now:

*

*Make use of sortInPlace function and dynamicType to check for class names e.g.:- String(firstDataType.dynamicType).componentsSeparatedByString(".").last! this retrieves the class name for the Object.
unsortedArray.sortInPlace({(firstDataType,secondDataType) in
return String(firstDataType.dynamicType).componentsSeparatedByString(".").last!
    .localizedStandardCompare(String(secondDataType.dynamicType).componentsSeparatedByString(".").last!) == NSComparisonResult.OrderedAscending

})
Demo Link


text:
Q: Writing 3D array in c++ and reading with numpy (without using reshape) I'm debugging some volumetric data in c++ and would like to visualise it.
Say I have a double array in c++, how can I write it as a binary file and read it from numpy as a 3D array? I'd like to stick to the standard c++ library.
double myArr[1000];
// ...Set values of myArr

std::ofstream outFile;
std::open("myfile.bin");
for (int i = 0; i < 10; i++) {
    for (int j = 0; j < 10; j++) {
        for (int k = 0; k < 10; k++) {
            outFile << myArr[k + j*10 + i*100];
        }
        outFile << "some way to declare the next slice";
    }
    outFile << "some way to declare the next slice";
}
outFile.close();

In python I would like to read this array like this so it would appear as a 3D array:
numpy.fromfile("myfile.bin", dtype=np.float)

I read this Writing binary in c++ and read in python which works for 1d int but not sure how to create 3D double. ie. what do I need to write to the array to tell it to shift by 1 along each dimension? I don't want to use numpy to reshape the array as the dimension output by c++ can vary.


text:
Q: AttributeError: 'function' object has no attribute 'connect' I'm trying to insert data into my already created sqlite3 database. The data is able to be inputted. However, when trying to connect to my database and save I receive an error saying "  AttributeError: 'function' object has no attribute 'connect'"
My code fragment is listed below:
def data_entry():
    option_choice=0
    call("clear")
    print"\t","\n"*4
    print"\t","-"*45
    print"\t","\t-- Data Entry --"

    ID = raw_input("what is your user ID?")
    Name = raw_input("What is your name?")
    Age = raw_input("how old are you?")
    incidents = raw_input("How many incidents have you been involved in?")
    physical_ability = raw_input("what is your physical driving state?")
    Address = raw_input("what is your address?")
    Tel = raw_input("what is your phone number?")
    datestamp = raw_input("What is today's date?")
    keyword = raw_input("What is the make of your vehicle?")
    monthly_salary = raw_input("How much do you earn each month?")

    conn = db.connect('Insurance_Shark.db')
    cursor = conn.cursor()
    cursor.execute("INSERT INTO customerdatabase VALUES(?, ?, ?, ?, ?, ?)",
        (ID, Name, Age, incidents, physical_ability, Address, Tel, datestamp, keyword, monthly_salary))

A: You haven't shown how the db variable is defined, but it looks like it is a function, because:
>>> def db():
...     pass
...
>>> db.connect()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'function' object has no attribute 'connect'

The connect() function is available directly from the sqlite3 module:
>>> import sqlite3
>>> sqlite3.connect("test.db")
<sqlite3.Connection object at 0x10d922a28>


text:
Q: Why do we use pointer of object when we create a object? Why do we use a pointer of object when we want to create a new object like this?
employee *Steve = new employee();

In this case, I want to create an object named Steve.
#include <iostream>
#include <string.h>
using namespace std;

class employee{
private:
    char name[40];
    int salary;
public:
    employee(){
        strcpy(name, "unnamed");
        salary = 0;
    }
    char *getName(){
        return name;
    }
};

int main(){
    employee *Steve = new employee();
    cout<<"Name: "<< Steve->getName();
}

A: We do not use pointers when we do not need pointers. When we want to create an object we call a constructor to create an object, but we do not use new nor raw pointers.
employee Steve;
std::cout << "Name: " << Steve.getName() << "\n";

If we dynamically allocate the object then we still do not use new or raw poitners, but container or smart pointers.
In bad tutorials and questionable teaching they use pointers a lot. Often that is because they do not actually aim to teach C++, but rather to teach pointers. In modern C++ the use of raw pointers is limited to rare cases.
There would be more to say about the code you wrote, but I'll leave it at that and refer you to The Definitive C++ Book Guide and List.


text:
Q: Error when doing a project transfer from oracle repo to eapx file I am running a Sparx EA Project transfer from a oracle Repo to a EAPX file for a backup.. While it runs I get the error below.
Is this something I should be concerned about ? Is there anyway to fix the underlying cause of the error ?

Thanks
Rob


text:
Q: Searching any word using Linq In my winform app I have a form where user can search for product by typing any text in search field. For example the product description might be stored as "Adidas aftershave 100Ml" . But user can type any thing like 100 Ml Aftershave. So I would like to query using linq to get all records where description contains any of these word(100 Ml Aftershave).
So far I have done something like this:
List<string>txtList =  txtSearchTerm.Text.Split(' ').ToList();
return dbContext.productRepo.Where(t => txtList.Any(b =>
                   t.ProductDescription.StartsWith(b)
                   || t.ProductDescription.EndsWith(b)
                   || t.ProductDescription.Contains(b)

                 )).Select(x => x.ProductDescription).ToList();

Any other way of achieving this in better way ,making it more quick or any other improvement.
Thanks

A: Well, you are testing if the description starts, ends and contains something. The first two are already redundant because Contains "contains" them:
var matchingDescriptions = dbContext.productRepo
    .Where(x => txtList.Any(x.ProductDescription.Contains))
    .Select(x => x.ProductDescription));

Another easy optimization(for Linq-To-Objects), I would order the words by length first:
var txtList = txtSearchTerm.Text.Split(' ').OrderBy(s => s.Length).ToList()

A: One thing you can straightaway improve is to remove StartsWith and EndsWith , Becuase you are already doing t.ProductDescription.Contains(b) .
List<string>txtList =  txtSearchTerm.Text.Split(' ').ToList();
       return dbContext.productRepo.Where(t => txtList.Any(b =>
               t.ProductDescription.Contains(b)
             )).Select(x => x.ProductDescription).ToList();


text:
Q: Bash string manipulation with/without whitespaces Consider having a String in bash holding a list of items:
# BLUBB="item foobar blubb bar"

Further consider having an exclude list of items:
# EXCLUDE="item bar blubb"

What would be the easiest way to resolve this to a list holding BLUBB w/o EXCLUDE. My first approach was:
# for i in $EXCLUDE; do BLUBB=${BLUBB//$i/}; done

But this additionally removes the bar from foobar. So it seems, one has to look for whitespace or nothing before and after the $i. How is the syntax for this?

A: Something like this can be done:
#/bin/bash
BLUBB="item foobar blubb bar"
EXCLUDE="item bar blubb"
for word in ${BLUBB} ${EXCLUDE} ${EXCLUDE}; do
    echo ${word}
done | sort | uniq -u

A: I'd do this in bash with an associative array:
$ BLUBB="item foobar blubb bar"
$ EXCLUDE="item bar blubb"
$ declare -A h
$ for word in $BLUBB; do h[$word]=1; done
$ declare -p h
declare -A h='([blubb]="1" [bar]="1" [foobar]="1" [item]="1" )'
$ for word in $EXCLUDE; do unset "h[$word]"; done
$ declare -p h
declare -A h='([foobar]="1" )'
$ words="${!h[*]}"
$ echo "$words"
foobar

If any of the "words" in BLUBB or EXCLUDE contain whitespace, you have to use indexed arrays to hold them:
$ BLUBB=(item foobar blubb bar "word with spaces")
$ EXCLUDE=(item bar blubb with)
$ declare -A h
$ for elem in "${BLUBB[@]}"; do h["$elem"]=1; done
$ for elem in "${EXCLUDE[@]}"; do unset "h[$elem]"; done
$ declare -p h
declare -A h='(["word with spaces"]="1" [foobar]="1" )'


text:
Q: Installing Ruby - Failed to build gem native extension I don't know anything about the stuff that you write here :) I tried to search for answers online, as I usually do, but unfortunately, couldn't find anything specific.
I am trying to install Ruby on Rails, according to a description from here Rails Tutorial
I have installed Bash on Ubuntu on Windows. Could you tell me what have I done wrong? Or how can I fix it to install it properly?
when I check ruby version it shows me:
ruby 2.3.1p112 (2016-04-26) [x86-64-linux-gnu]

However an error appears:
ERROR: Failed to build gem native extension.

current directory: /var/lib/gems/2.3.0./gems/nio4r-2.1.0/ext/nio4r/usr/bin/ruby2.3 -r ./siteconf20170726-93-g151dm.rb extconf.rb
mkmf.rb can't find header files for ruby at /usr/lib/ruby/include/ruby.h

extconf failed, exit code 1

Gem files will remain installed in /var/lib/gems/2.3.0/gems/nio4r-2.1.0 for inspection.
Results logged to /var/lib/gems/2.3.0/extensions/x86_64-linux/2.3.0/nio4r-2.1.0/gem_make.out

I have also done:
apt-get install make
apt-get install ruby-dev

And now something different appeared:
    ERROR: Failed to build gem native extension.

    current directory: /var/lib/gems/2.3.0./gems/nio4r-2.1.0/ext/nio4r/usr/bin/ruby2.3 -r ./siteconf20170726-530-13b2fuh.rb extconf.rb
checking for unistd.h...***extconf.rb failed ***

Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers. Check the mkmf.log file for more details. You may need configuration option.

The rest of the code can be found in the file - too much things to write by hand. :) Ruby 2- command line pict
Please help!! I want to learn Ruby :) :)
Plus, is there a way to copy command line and to paste it somehow or do I have to put it here letter by letter? :)

A: Try these commands:
sudo apt-get install build-essential patch
sudo apt-get install ruby-dev zlib1g-dev liblzma-dev
Hope it will help!
I also recommend you to install RVM.
Then run rvm install your_version to install an essential ruby version. You can choose any version you need. For instance rvm install 2.4.1
After those steps, run following commands:
gem install bundler
gem install rails

A: You need ruby development files to build (& install) native extensions
sudo apt-get install ruby-dev


text:
Q: krbtgt password expiration policy I am asking about krbtgt password in Active directory which is used to encrypt tickets issued by KDC,what i know is that this krbtgt account has a security issue that it's password is rarely changed.
but when i run net user krbtgt /domain i found that it's password expires after 45 days,i wonder is this policy changes recently and what's is the default password expiration date for this account in windows 2016 and 2012 ?

A: Password expiration only applies to accounts that logon. The krbtgt account is disabled and does not logon, so password expiration would not apply.
If you want to change the password, which you should do periodically, you can do it using AD Users and Computers. The actual password you supply will not be used as AD assigns a random  password to the account. The password also needs to be changed twice, with the second password change occurring the following day.
More information:
https://support.microsoft.com/en-us/help/2549833/changing-the-krbtgt-password-may-fail-when-a-custom-password-filter-is
https://adsecurity.org/?p=1441


text:
Q: Unable access to opportunity object fields in apex classes and trigger?  Unable to access opportunity object fields in apex classes and in triggers also .even in the standard way of creating apex classes. getting an error as variable doesn't Exist, even field is available.
please help me out on this

A: This happens when your organization has a class named as Opportunity.
Check in your list of classes which is named as Opportunity and rename it to something else.
Compiler searches for Amount property in your custom made Opportunity class which if doesn't exist, then it gives an compilation error.
Compile all your classes post renaming and then try saving your changes.
You can compile all classes by navigating from Setup > Develop > Apex Classes > Click on Compile all classes
Note : You should never create classes with the names which are already being used by the platform.


text:
Q: Running JAR from BAT file cannot find natives path I am running my JAR from a BAT file on Windows 7 x64 machine. Lately I added native .dll files to project, so now I need to add the path to the BAT. My project is exported to "C:/dist" and folder with native libs called "natives" placed alongside, that is "C:/dist/natives".
The problem is that for some reason the path is ignored, or cannot be found, or it seems something else is wrong in the BAT. This is my BAT code:
@ECHO OFF
java -XX:+UseG1GC -Xmx1G -server -Djava.library.path="C:/dist/natives" -jar data.jar
@if %errorlevel% neq 0 pause

When I run my project from the NetBeansIDE all works fine as expected. It is only when I try to run the compiled file from the BAT file it seems it cannot find the native libs when they are needed ending up with error.
I also tried add the path to the native libs programaticaly like this:
//PROGRAMATICALLY SET THE PATH TO NATIVE LIBRARIES
System.setProperty("java.library.path", "natives");
Field fieldSysPath = ClassLoader.class.getDeclaredField("sys_paths");
fieldSysPath.setAccessible(true);
fieldSysPath.set(null, null);

It works as it should in NetBeansIDE but not once the jar is compiled and run via BAT file.

A: This might have the same problem I mentioned at the beginning  of this post of mine, namely one of these:

*

*unnecessary jar files in your project (they might cause problems similar to yours)

*mixing different versions of LWJGL jar files (might cause problems similar to yours)

*mixing different versions of LWJGL native .dll files (might cause problems similar to yours)

*using unneeded native .dll files (sometime unnecessary ones may cause errors like yours)


text:
Q: Setting dynamic min and max date witt jquery datetimepicker Based on earlier posts, I have setup the following custom binding for datetimepicker
ko.bindingHandlers.datetimepicker = {
    init: function (element, valueAccessor, allBindingsAccessor) {
        //initialize datepicker with some optional options
        var options = allBindingsAccessor().datetimepickerOptions || {};
        $(element).datetimepicker(options);

        //handle the field changing
        ko.utils.registerEventHandler(element, "change", function () {
            var observable = valueAccessor();
            try {
                observable($(element).datetimepicker("getDate"));//****
            }
            catch(ex) {}
        });

        //handle disposal (if KO removes by the template binding)
        ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
            $(element).datetimepicker("destroy");
        });

    },
    update: function (element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor()),
            current = $(element).datetimepicker("getDate");

        if (value - current !== 0) {
            $(element).datetimepicker("setDate", value);
        }
    }
};

And dynamic min and max date custom binding handlers
ko.bindingHandlers.minDate = {
    update: function(element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor()),
        current = $(element).datetimepicker("option", "minDate", value);
    }
};

ko.bindingHandlers.maxDate = {
    update: function(element, valueAccessor) {
    var value = ko.utils.unwrapObservable(valueAccessor()),
        current = $(element).datetimepicker("option", "maxDate", value);
    }
};

I have two datetimepickers which limits each other in terms of min and max dates. The problem is that both datetimepicker closes immediately after an action (selecting a date or manipulating the slider). Removing the min-max handlers from the markup also removes the problem. Any suggestions on how to fix this? Thanks.

A: I am not sure that you can alter min-max value of a datepicker while it is opened!
Changing the values of one probably fires observable update which forces an update on mix-max value of datepickers. I would check in your bindings the new value of min or max and if that has not changed i wouldn't alter the value of the datepicker.
This is probably the problem...


text:
Q: How to retrieve the state to be consumed in corda I need to update a state in Corda, once after it is created. I am using LinearState class for this, which have a LinearID field of type UniqueIdentifier. I am facing an issue in how to pass the UniqueIdentifier of the state to be consumed to the constructor of the UpdateFlow in the node's terminal. The code for my Update Flow is as follows:
@InitiatingFlow
@StartableByRPC
public static class UpdateOffer extends FlowLogic<SignedTransaction> {
        private final ProgressTracker.Step GENERATING_TRANSACTION = new ProgressTracker.Step("Generating transaction.");
        private final ProgressTracker.Step ADDING_NEW_OFFER = new ProgressTracker.Step("Adding the New Offer State.");
        private final ProgressTracker.Step VERIFYING_TRANSACTION = new ProgressTracker.Step("Verifying contract constraints.");
        private final ProgressTracker.Step SIGNING_TRANSACTION = new ProgressTracker.Step("Signing transaction with our private key.");
        private final ProgressTracker.Step GATHERING_SIGS = new ProgressTracker.Step("Gathering the counterparty's signature.") {
            @Override
            public ProgressTracker childProgressTracker() {
                return CollectSignaturesFlow.Companion.tracker();
            }
        };
        private final ProgressTracker.Step FINALISING_TRANSACTION = new ProgressTracker.Step("Obtaining notary signature and recording transaction.") {
            @Override
            public ProgressTracker childProgressTracker() {
                return FinalityFlow.Companion.tracker();
            }
        };

        private final ProgressTracker progressTracker = new ProgressTracker(
                GENERATING_TRANSACTION,
                ADDING_NEW_OFFER,
                VERIFYING_TRANSACTION,
                SIGNING_TRANSACTION,
                GATHERING_SIGS,
                FINALISING_TRANSACTION
        );

        @Override
        public ProgressTracker getProgressTracker() {
            return progressTracker;
        }

        //Class Variables
        private final UniqueIdentifier linearID;
        private final String sender;
        private final String receiver;
        private final String policyID;
        private final double faceValue;
        private final double offeredAmount;

        public UpdateOffer(UniqueIdentifier linearID, String sender, String receiver, String policyID, double faceValue, double offeredAmount) {
            this.linearID = linearID;
            this.sender = sender;
            this.receiver = receiver;
            this.policyID = policyID;
            this.faceValue = faceValue;
            this.offeredAmount = offeredAmount;
        }

        @Override
        public SignedTransaction call() throws FlowException {
            List<UUID> listOfLinearIds = new ArrayList<>();
            listOfLinearIds.add(linearID.getId());
            QueryCriteria queryCriteria = new QueryCriteria.LinearStateQueryCriteria(null, listOfLinearIds);

            // 2. Get a reference to the inputState data that we are going to settle.
            Vault.Page results = getServiceHub().getVaultService().queryBy(OfferState.class, queryCriteria);
            StateAndRef inputStateAndRefToTransfer = (StateAndRef) results.getStates().get(0);
            OfferState inputStateToTransfer = (OfferState) inputStateAndRefToTransfer.getState().getData();

            AccountService accountService = getServiceHub().cordaService(KeyManagementBackedAccountService.class);
            //Owner Account
            AccountInfo lspAccountInfo = accountService.accountInfo(sender).get(0).getState().getData();
            PublicKey lspKey = subFlow(new NewKeyForAccount(lspAccountInfo.getIdentifier().getId())).getOwningKey();
            AnonymousParty lspAccount = subFlow(new RequestKeyForAccount(lspAccountInfo));

            //Insurance Company Account
            AccountInfo sellerAccountInfo = accountService.accountInfo(receiver).get(0).getState().getData();
            AnonymousParty sellerAccount = subFlow(new RequestKeyForAccount(sellerAccountInfo));

            final Party notary = getServiceHub().getNetworkMapCache().getNotaryIdentities().get(0);
            final OfferState output = new OfferState(inputStateToTransfer.getLinearId(), lspAccount,sellerAccount,policyID,faceValue,offeredAmount, true);

            progressTracker.setCurrentStep(GENERATING_TRANSACTION);
            TransactionBuilder builder = new TransactionBuilder(notary);

            progressTracker.setCurrentStep(ADDING_NEW_OFFER);
            builder.addInputState(inputStateAndRefToTransfer);
            builder.addOutputState(output,OfferContract.ID);
            builder.addCommand(new OfferContract.Commands.Send(), Arrays.asList(lspKey,sellerAccount.getOwningKey()));

            progressTracker.setCurrentStep(SIGNING_TRANSACTION);
            builder.verify(getServiceHub());
            SignedTransaction locallySignedTx = getServiceHub().signInitialTransaction(builder,Arrays.asList(getOurIdentity().getOwningKey(),lspKey));

            progressTracker.setCurrentStep(GATHERING_SIGS);
            FlowSession session  = initiateFlow(sellerAccountInfo.getHost());
            List<TransactionSignature> accountToMoveToSignature = (List<TransactionSignature>) subFlow(new CollectSignatureFlow(locallySignedTx,
                    session,sellerAccount.getOwningKey()));
            SignedTransaction signedByCounterParty = locallySignedTx.withAdditionalSignatures(accountToMoveToSignature);

            progressTracker.setCurrentStep(FINALISING_TRANSACTION);
            return subFlow(new FinalityFlow(signedByCounterParty, session));
        }
 }

Can anyone help me with this? I have been stuck here for more than a week now.

A: *

*Instead of having a UniqueIdentifier input parameter in your flow's constructor, use a String:
public UpdateOffer(String linearID...

*Then inside your flow you can query like this:
LinearStateQueryCriteria linearCriteria = new LinearStateQueryCriteria()
                    .withExternalId(Collections.singletonList(linearId));

*Since your input parameter is now a String, you can easily pass it from the terminal.


text:
Q: How to install GTK2-notif2 theme? Here is the link: http://gnome-look.org/content/show.php?content=18886&foo=6
I'm using Ubuntu 11.10 64-bit.

A: Ubuntu 11.10 is based on Gnome 3, which means it uses GTK 3 and the theme you want to apply is GTK 2. This means that even if you do apply it will only affect GTK 2 apps and not GTK 3 apps, which will create a major rajor theme inconsistency.
I suggest you use a GTK 3 theme. You can find a lot of themes here:

*

*http://gnome-shell.deviantart.com/gallery/29380653
Or you can add the following PPAs:

*

*https://launchpad.net/~kokoto-java/+archive/omgubuntu-stuff

*https://launchpad.net/~webupd8team/+archive/themes

*https://launchpad.net/~satyajit-happy/+archive/themes
If you don't know how to use PPAs please read this:
What are PPAs and how do I use them? and if you don't know how to install themes manually in Ubuntu 11.10 read this: How to change GTK+ theme?

A: If you are using Gnome Shell, you can't, Gnome Shell is GTK3, this theme is GTK2 only and would not render correctly if at all.
If you are using Unity, this is a duplicate post:
How do I change window theme in 11.10?
You should be able to use the gtk2 theme in Unity.
edit: perhaps I am wrong though, as it would seem unity uses gtk3 as well.


text:
Q: How to handle comma in url in c# My url string is
"https://MyCom.Produect.App.ResourcePath/ts?Customer_Account=A B C\, LLC,D E F\, LLC&Billing_Code=11,12&fromDateTime=2013-05-13&toDateTime=2013-06-13"
If I copy it in IE and run, it will return some data.
However the same string in c# gives me a bad request exception.
Here is my c# code for this,  I think I must miss something. Thanks
    public void GetDataAsyn(string m_strUrl)
    {
        var username = m_strEmail;
        var password = m_strPassword;

        var uri = new Uri(m_strUrl);

        var credentialCache = new CredentialCache();
        credentialCache.Add(uri, "Basic", new NetworkCredential(username, password));
        var httpRequest = (HttpWebRequest)WebRequest.Create(uri);
        httpRequest.Method = "GET";
        httpRequest.ContentType = "application/json";
        httpRequest.UseDefaultCredentials = true;
        httpRequest.Accept = Constants.CONTENT_TYPE_TEXT_CSV;
        httpRequest.UserAgent = Helper.GetUserAgent();
        Helper.SetProxyIfNeeded(httpRequest, uri);
        httpRequest.Headers.Add("Authorization", Helper.GetAuthHeader(username, password));

        ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
        httpRequest.BeginGetResponse(GetResponseCallback, new object[] { httpRequest });
    }

    private void GetResponseCallback(IAsyncResult asyncResult)
    {
        try
        {
            var obj = (object[])asyncResult.AsyncState;
            var request = (HttpWebRequest)obj[0];
            var response = request.EndGetResponse(asyncResult);
            Stream responseStream = response.GetResponseStream();
            if (responseStream != null)
            {
                var streamReader = new StreamReader(responseStream);
                ReturnedData = streamReader.ReadToEnd();
            }

            ....do something with ReturnedData
        }
        catch (Exception ex)
        {
            Helper.LogError(ex);
        }
    }

A: I am going to take a shot in the dark here as you didn't show us how you are assigning your URL to m_strUrl.
Most likely you are getting the bad request because a \ character in C# is an escape.
To correct problems like this you either have to escape the \ like this \\
Or a much cleaner way to handle this would be to use the @ sign and make the string a literal.
If the \ in the example you provided are part of the url (not escape characters) the following is your literal url string:
    string m_strUrl =  @"https://MyCom.Produect.App.ResourcePath/ts?Customer_Account=A%20B%20C\,%20LLC,D%20E%20F\,%20LLC&Billing_Code=11,12&fromDateTime=2013-05-13&toDateTime=2013-06-13";

If you are already trying to escape the commas with the \ your string would look like this.
    string m_strUrl = @"https://MyCom.Produect.App.ResourcePath/ts?Customer_Account=A%20B%20C,%20LLC,D%20E%20F,%20LLC&Billing_Code=11,12&fromDateTime=2013-05-13&toDateTime=2013-06-13";


text:
Q: Making requests to NASA website using requests module I want to download Apollo images from Nasa website using requests module in Python.
This is my beginning code-
>>> import requests

>>> url = "https://images.nasa.gov/search-results?q=Apollo"

>>> headers = {'User-Agent' : 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:77.0) Gecko/20100101 Firefox/77.0'}

>>> res = requests.get(url, headers=headers)
>>> res.status_code

>>> len(res.content)
>>> print(res.content)

200
2868
b'<!doctype html>    <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1"> <meta name="pinterest" content="nopin"> <meta name="google-site-verification" content="ZKpcXLqaBX3jND8Fybkvr3MaaOpC_6MRjXBYm0XNkJQ"> <meta name="theme-color" content="#ffffff"> <base href="/">  <meta property="og:title" content="{{ngMeta.title}}"> <title ng-bind="ngMeta.title"></title> <meta property="og:description" content="{{ngMeta.description}}"> <meta ng-if="ngMeta[\'url\']" property="og:url" content="{{ngMeta.url}}"> <meta ng-if="ngMeta[\'image\']" property="og:image" content="{{ngMeta.image}}"> <meta ng-if="ngMeta[\'imageWidth\']" property="og:image:width" content="{{ngMeta.imageWidth}}"> <meta ng-if="ngMeta[\'imageHeight\']" property="og:image:height" content="{{ngMeta.imageHeight}}"> <meta ng-if="ngMeta[\'fbAppId\']" ng-if="ngMeta[\'fbAppId\']" property="fb:app_id" content="{{ngMeta.fbAppId}}"> <meta ng-if="ngMeta[\'type\']" property="og:type" content="{{ngMeta.type}}">  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png?v=eEa2MLRaNk"> <link rel="icon" type="image/png" href="/favicon-32x32.png?v=eEa2MLRaNk" sizes="32x32"> <link rel="icon" type="image/png" href="/favicon-16x16.png?v=eEa2MLRaNk" sizes="16x16"> <link rel="manifest" href="/manifest.json?v=eEa2MLRaNk"> <link rel="mask-icon" href="/safari-pinned-tab.svg?v=eEa2MLRaNk" color="#0d3d92"> <link rel="shortcut icon" href="/favicon.ico?v=eEa2MLRaNk"> <link rel="stylesheet" href="styles/vendor.100c511f.css">  <link href="https://fonts.googleapis.com/css?family=Titillium+Web:300,400" rel="stylesheet">  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/pretty-checkbox@3.0/dist/pretty-checkbox.min.css"> <link rel="stylesheet" href="styles/main.8534951e.css">

    '

However, the website can detect that I am not using my browser.
I have tried with other headers also, but it does not work
What can I do to surpass this?
Please tell

A: When you make an HTTP GET request to https://images.nasa.gov/search-results?q=Apollo using the requests module, you get back exactly the resource you requested from the server: that HTML file. Nothing else. When you make the same request with a browser, the browser knows to parse that HTML file to execute scripts, make ajax requests / XHR requests, make requests based on meta data / links / stylesheets in the HTML, etc. It's this action by the browser that completely renders a given page the way it's meant to be seen by human eyes. When you make a simple HTTP GET request to a page, like what you're doing, you just get back the barebones template, where the DOM hasn't been populated yet, since this is typically meant to happen asynchronously at a later point in time.
You can still use the requests module, but you'll just use it differently: Instead of making an HTTP GET request to a webpage, you make an HTTP GET request to NASAs RESTful image asset API, which is the same API your browser makes requests to when populating the page. This is ideal because you won't have to scrape a page using BeautifulSoup or anything like that, you just imitate the same request your browser would make, and you get back JSON:
def main():

    import requests

    url = "https://images-api.nasa.gov/search"

    params = {
        "q": "apollo",
        "page": "1",
        "media_type": "image",
        "year_start": "1920",
        "year_end": "2020"
    }

    response = requests.get(url, params=params)
    response.raise_for_status()

    images = response.json()["collection"]["items"]
    for image in images:
        thumbnail_url = image["links"][0]["href"]
        image_url = thumbnail_url[:thumbnail_url.rfind("~")] + "~orig.jpg"
        print(image_url)

    return 0

if __name__ == "__main__":
    import sys
    sys.exit(main())

Output:
https://images-assets.nasa.gov/image/APOLLO 50th_FULL COLOR_300DPI/APOLLO 50th_FULL COLOR_300DPI~orig.jpg
https://images-assets.nasa.gov/image/s69-35505/s69-35505~orig.jpg
https://images-assets.nasa.gov/image/S69-35503/S69-35503~orig.jpg
https://images-assets.nasa.gov/image/7995383/7995383~orig.jpg
https://images-assets.nasa.gov/image/S69-16402/S69-16402~orig.jpg
https://images-assets.nasa.gov/image/S69-34968/S69-34968~orig.jpg
https://images-assets.nasa.gov/image/S69-34969/S69-34969~orig.jpg
https://images-assets.nasa.gov/image/PIA13058/PIA13058~orig.jpg
https://images-assets.nasa.gov/image/PIA14003/PIA14003~orig.jpg
https://images-assets.nasa.gov/image/S69-60662/S69-60662~orig.jpg
https://images-assets.nasa.gov/image/S69-34313/S69-34313~orig.jpg
https://images-assets.nasa.gov/image/S69-33999/S69-33999~orig.jpg
https://images-assets.nasa.gov/image/S69-27915/S69-27915~orig.jpg
https://images-assets.nasa.gov/image/S68-56002/S68-56002~orig.jpg
https://images-assets.nasa.gov/image/200907200097HQ/200907200097HQ~orig.jpg
https://images-assets.nasa.gov/image/S68-26890/S68-26890~orig.jpg
https://images-assets.nasa.gov/image/S68-26958/S68-26958~orig.jpg
https://images-assets.nasa.gov/image/S68-27041/S68-27041~orig.jpg
https://images-assets.nasa.gov/image/S68-27076/S68-27076~orig.jpg
https://images-assets.nasa.gov/image/S68-27161/S68-27161~orig.jpg
https://images-assets.nasa.gov/image/S68-26936/S68-26936~orig.jpg
https://images-assets.nasa.gov/image/S69-27089/S69-27089~orig.jpg
https://images-assets.nasa.gov/image/200907200096HQ/200907200096HQ~orig.jpg
https://images-assets.nasa.gov/image/200907200094HQ/200907200094HQ~orig.jpg
https://images-assets.nasa.gov/image/200907200095HQ/200907200095HQ~orig.jpg
https://images-assets.nasa.gov/image/NHQ201812110018/NHQ201812110018~orig.jpg
https://images-assets.nasa.gov/image/NHQ201812110017/NHQ201812110017~orig.jpg
https://images-assets.nasa.gov/image/NHQ201812110027/NHQ201812110027~orig.jpg
https://images-assets.nasa.gov/image/S69-25478/S69-25478~orig.jpg
https://images-assets.nasa.gov/image/S69-25861/S69-25861~orig.jpg
https://images-assets.nasa.gov/image/S69-25862/S69-25862~orig.jpg
https://images-assets.nasa.gov/image/S69-25881/S69-25881~orig.jpg
https://images-assets.nasa.gov/image/KSC-20190716-PH_FWM04_0104/KSC-20190716-PH_FWM04_0104~orig.jpg
https://images-assets.nasa.gov/image/200907200098HQ/200907200098HQ~orig.jpg
https://images-assets.nasa.gov/image/S67-50903/S67-50903~orig.jpg
https://images-assets.nasa.gov/image/S69-19983/S69-19983~orig.jpg
https://images-assets.nasa.gov/image/as17-162-24050/as17-162-24050~orig.jpg
https://images-assets.nasa.gov/image/NHQ201812110008/NHQ201812110008~orig.jpg
https://images-assets.nasa.gov/image/NHQ201812110019/NHQ201812110019~orig.jpg
https://images-assets.nasa.gov/image/NHQ201812110042/NHQ201812110042~orig.jpg
https://images-assets.nasa.gov/image/NHQ201812110009/NHQ201812110009~orig.jpg
https://images-assets.nasa.gov/image/NHQ201812110010/NHQ201812110010~orig.jpg
https://images-assets.nasa.gov/image/S68-26668/S68-26668~orig.jpg
https://images-assets.nasa.gov/image/Maura_test_s69-36593/Maura_test_s69-36593~orig.jpg
https://images-assets.nasa.gov/image/S69-36593/S69-36593~orig.jpg
https://images-assets.nasa.gov/image/200907200015HQ/200907200015HQ~orig.jpg
https://images-assets.nasa.gov/image/KSC-20190716-PH_FWM04_0123/KSC-20190716-PH_FWM04_0123~orig.jpg
https://images-assets.nasa.gov/image/as09-23-3596/as09-23-3596~orig.jpg
https://images-assets.nasa.gov/image/S67-49447/S67-49447~orig.jpg
https://images-assets.nasa.gov/image/S69-35099/S69-35099~orig.jpg
https://images-assets.nasa.gov/image/S69-26148/S69-26148~orig.jpg
https://images-assets.nasa.gov/image/KSC-20190716-PH_KLS02_0062/KSC-20190716-PH_KLS02_0062~orig.jpg
https://images-assets.nasa.gov/image/KSC-20190716-PH_FWM04_0063/KSC-20190716-PH_FWM04_0063~orig.jpg
https://images-assets.nasa.gov/image/jsc2007e034221/jsc2007e034221~orig.jpg
https://images-assets.nasa.gov/image/9309375/9309375~orig.jpg
https://images-assets.nasa.gov/image/NHQ201812110004/NHQ201812110004~orig.jpg
https://images-assets.nasa.gov/image/0102627/0102627~orig.jpg
https://images-assets.nasa.gov/image/200907200091HQ/200907200091HQ~orig.jpg
https://images-assets.nasa.gov/image/200907200093HQ/200907200093HQ~orig.jpg
https://images-assets.nasa.gov/image/NHQ201812110006/NHQ201812110006~orig.jpg
https://images-assets.nasa.gov/image/NHQ201812110007/NHQ201812110007~orig.jpg
https://images-assets.nasa.gov/image/NHQ201812110041/NHQ201812110041~orig.jpg
https://images-assets.nasa.gov/image/NHQ201812110034/NHQ201812110034~orig.jpg
https://images-assets.nasa.gov/image/NHQ201812110036/NHQ201812110036~orig.jpg
https://images-assets.nasa.gov/image/NHQ201812110037/NHQ201812110037~orig.jpg
https://images-assets.nasa.gov/image/NHQ201812110030/NHQ201812110030~orig.jpg
https://images-assets.nasa.gov/image/NHQ201812110040/NHQ201812110040~orig.jpg
https://images-assets.nasa.gov/image/NHQ201812110016/NHQ201812110016~orig.jpg
https://images-assets.nasa.gov/image/NHQ201812110002/NHQ201812110002~orig.jpg
https://images-assets.nasa.gov/image/NHQ201812110025/NHQ201812110025~orig.jpg
https://images-assets.nasa.gov/image/NHQ201812110035/NHQ201812110035~orig.jpg
https://images-assets.nasa.gov/image/NHQ201812110014/NHQ201812110014~orig.jpg
https://images-assets.nasa.gov/image/NHQ201812110015/NHQ201812110015~orig.jpg
https://images-assets.nasa.gov/image/NHQ201812110038/NHQ201812110038~orig.jpg
https://images-assets.nasa.gov/image/S69-35507/S69-35507~orig.jpg
https://images-assets.nasa.gov/image/S69-35504/S69-35504~orig.jpg
https://images-assets.nasa.gov/image/S71-37963/S71-37963~orig.jpg
https://images-assets.nasa.gov/image/as17-152-23272/as17-152-23272~orig.jpg
https://images-assets.nasa.gov/image/0101493/0101493~orig.jpg
https://images-assets.nasa.gov/image/6761216/6761216~orig.jpg
https://images-assets.nasa.gov/image/6870605/6870605~orig.jpg
https://images-assets.nasa.gov/image/KSC-20190716-PH_FWM04_0144/KSC-20190716-PH_FWM04_0144~orig.jpg
https://images-assets.nasa.gov/image/0101140/0101140~orig.jpg
https://images-assets.nasa.gov/image/KSC-20170127-PH_KLS02_0005/KSC-20170127-PH_KLS02_0005~orig.jpg
https://images-assets.nasa.gov/image/s69-32614/s69-32614~orig.jpg
https://images-assets.nasa.gov/image/s69-34039/s69-34039~orig.jpg
https://images-assets.nasa.gov/image/S69-62224/S69-62224~orig.jpg
https://images-assets.nasa.gov/image/S72-50438/S72-50438~orig.jpg
https://images-assets.nasa.gov/image/9309295/9309295~orig.jpg
https://images-assets.nasa.gov/image/as14-67-09364/as14-67-09364~orig.jpg
https://images-assets.nasa.gov/image/KSC-20190716-PH_FWM04_0085/KSC-20190716-PH_FWM04_0085~orig.jpg
https://images-assets.nasa.gov/image/KSC-20190716-PH_FWM04_0204/KSC-20190716-PH_FWM04_0204~orig.jpg
https://images-assets.nasa.gov/image/KSC-20190716-PH_FWM04_0393/KSC-20190716-PH_FWM04_0393~orig.jpg
https://images-assets.nasa.gov/image/S69-18569/S69-18569~orig.jpg
https://images-assets.nasa.gov/image/S66-36742/S66-36742~orig.jpg
https://images-assets.nasa.gov/image/jsc2007e045377/jsc2007e045377~orig.jpg
https://images-assets.nasa.gov/image/KSC-20190716-PH_FWM04_0088/KSC-20190716-PH_FWM04_0088~orig.jpg
https://images-assets.nasa.gov/image/KSC-20190716-PH_FWM04_0053/KSC-20190716-PH_FWM04_0053~orig.jpg
https://images-assets.nasa.gov/image/KSC-20190716-PH_FWM04_0018/KSC-20190716-PH_FWM04_0018~orig.jpg
https://images-assets.nasa.gov/image/KSC-20190716-PH_FWM04_0316/KSC-20190716-PH_FWM04_0316~orig.jpg
>>>

What I've done here is a little naive, because to get the original sized image, all I did was purge the ~thumb.jpg at the end of each thumbnail URL, and replaced it with ~orig.jpg - this assumes that the original has a JPEG extension. The better solution would be to look at image["href"], which is a URL to another JSON file, which contains URLS for all the different versions / dimensions of a given image. You'd simply make another request to that JSON file, and then a request to one of the URLs contained within that JSON.

A: We have docs for the API right in the footer of images.nasa.gov:
https://images.nasa.gov/docs/images.nasa.gov_api_docs.pdf
Check it out, you should be able to do everything with it that we do with the web application: our front-end is just Angular which talks to the API -- you can do the same thing with requests. Just connect to
https://images-api.nasa.gov/
instead of the web front-end.
The docs include examples using Curl, which you should be able to translate to requests. We use requests, ourselves, for writing utilities to manipulate the API.
Have fun!


text:
Q: How to recognize an area in an canvas via javascript This image is loaded in an html5 canvas.
If a user presses at any point inside the square, I want to fill this area with a color. But just inside, the color stops at the black lines. You can think about the fill tool like in Windows Paint.
How can I solve this? Are there libraries for javascript for such a function to start with?

A: What you are looking for is called a flood fill algorithm. Which basically will take the color of the pixel you clicked on as a seed. It will check for all the pixels that are connected to the seed pixel that have the same color of the seed and fill them to a desired color. There are two types of this algorithm: 8-directional and 4-directional. Where the neighbours are defined as such ( S = Seed, X = Connected ):
4-directional
----------------
|    |  X |    |
----------------
|  X |  S |  X |
----------------
|    |  X |    |
----------------

8-directional
----------------
|  X |  X |  X |
----------------
|  X |  S |  X |
----------------
|  X |  X |  X |
----------------

The recursive algorithm is like so (From Wikipedia):
Flood-fill (node, target-color, replacement-color):
 1. If target-color is equal to replacement-color, return.
 2. If the color of node is not equal to target-color, return.
 3. Set the color of node to replacement-color.
 4. Perform Flood-fill (one step to the west of node, target-color, replacement-color).
    Perform Flood-fill (one step to the east of node, target-color, replacement-color).
    Perform Flood-fill (one step to the north of node, target-color, replacement-color).
    Perform Flood-fill (one step to the south of node, target-color, replacement-color).
 5. Return.

A: You might want to use the CanvasRenderingContext2D.isPointInPath()

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.clicked = false;

function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.save();
  ctx.rotate(45);
  ctx.beginPath();
  ctx.rect(100, -100, 100, 100);
  if (ctx.clicked) {
    ctx.fillStyle = "blue";
    ctx.fill()
  }
  ctx.stroke();
  ctx.restore();
}
draw();
canvas.addEventListener('click', function(e) {
  var bounds= canvas.getBoundingClientRect();
  var mouseXY = [e.clientX-bounds.left, e.clientY-bounds.top]
  ctx.clicked = ctx.isPointInPath(mouseXY[0], mouseXY[1]);
  draw();
});
canvas {
  border: 1px solid
}
<canvas id="canvas" height="500" width="500"></canvas>


text:
Q: writing around the square I hope there was no similar thread (at least I wasn't able to find). I have problem in writing such a thing in latex:

I would be grateful for any hint. Thanks in advance!

A: This is a commutative diagram, for which the Xy package is particularly useful.
\documentclass{article}
\usepackage{amsmath}
\usepackage[all]{xy}
\begin{document}
\[
\xymatrix{
    X_n\ar[r]^{\text{a.s.}} \ar@{=}[d]^D & X\ar@{=}[d]^D\\
    Y_n                                  & Y
}
\]
\end{document}

The package is really versatile for drawing commutative diagrams; check out the documentation for all of the things you can do to decorate objects and arrows.

A: Another option is tikz-cd:
\documentclass{article}
\usepackage{amsmath}
\usepackage{tikz-cd}

\begin{document}

\[
\begin{tikzcd}
X_n \arrow[r,"\text{a.s.}"]
    \arrow[d,shift right=.15em,equal,"D"] &
  X \arrow[d,equal,"D"]\\
Y_n & Y
\end{tikzcd}
\]

\end{document}

The argument to \arrow (in brackets) has the direction, possible options like equal for getting an "equals sign" instead of an arrow, or swap for changing the side of the label (default is the left side looking in the direction of the target); with shift right we can move it to the right in order to correct the visual effect induced by the presence of the subscripts; finally, between double quotes, the label.

A: A demo of what can be done with pstricks and with tikz-cd:
\documentclass{article}
\usepackage{amsmath}
 \usepackage{pst-node}
\usepackage{tikz-cd}
\usepackage{auto-pst-pdf}

\begin{document}
%
 \[ \psset{arrows=->, arrowinset=0.15, linewidth=0.5pt, nodesep=3pt, labelsep=2pt, rowsep=0.6cm, colsep = 1.1cm, shortput=nab}
 \everypsbox{\scriptstyle}
 \begin{psmatrix}
%%%nodes
 \smash[b]{X_n} & X \\%
 Y_n & Y
 %%% arrows
 \ncline{1,1}{1,2}^{a. s.}
\psset{arrows=none, doubleline, doublesep=1.4pt}
 \ncline{1,1}{2,1}>{D}
 \ncline{1,2}{2,2}>{D}
 \end{psmatrix}
 \]

\[ \begin{tikzcd}
X_n \arrow{r}{a. s.} \arrow[equal]{d}{D} & X \arrow[equal]{d}{D} \\%
Y_n & Y
\end{tikzcd}
\]
\end{document}

A: A Tikz solution
\documentclass{standalone}

\usepackage{tikz}
\usetikzlibrary{positioning}

\begin{document}

\begin{tikzpicture}
    [%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        node distance =.7cm
    ]%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
     \node (A)               {$\textbf{X}_{\textbf{n}}$};
     \node (B) [right=of A]  {$\textbf{X}$};
     \node (C) [below=of B]  {$\textbf{Y}$};
     \node (D) [below=of A]  {$\textbf{Y}_{\textbf{n}}$};

    \draw[->,thick] (A) -- node[above] {a.s.} (B);
    \draw[double,thick] (A) -- node[right] {D}(D);
    \draw[double,thick] (B) -- node[right] {D}(C);
\end{tikzpicture}
\end{document}

The result is

A: This is only a sketch. Some tuning probably needed. (I am assuming, that it is about probability, not commutative diagrams).
\documentclass{article}

\usepackage{graphicx}

\begin{document}

\def\eqD{\stackrel{D}{=}}
\def\roteqD{\rotatebox{-90}{$\eqD$}}

\[
\begin{array}{c@{}c@{}c}
X_n&\;\stackrel{\mathrm{a.s.}}{=}\;&X\\[-7pt]
\roteqD &&\roteqD\\[5pt]
Y_n&&Y
\end{array}
\]

\end{document}


text:
Q: In Rebol How to get the Object Path Name (String)? Let's say I have
list: [system/history system/prompt]

I want to convert to
list-string: ["system/history" "system/prompt"]

This may be an obvious answer but I can't see any :)
Thanks.

A: Or
>> list: [system/history system/prompt]
>> map-each v list [form v]
== ["system/history" "system/prompt"]

A: There's many simple ways to do this in Rebol. It's interesting to use parse:
>> list: [system/history system/prompt]
== [system/history system/prompt]
>> parse list [(list-string: copy []) some [set path path! (append list-string mold path)]]
== true
>> list-string
== ["system/history" "system/prompt"]

A: Another way, that updates the existing list block:
list: [system/history system/prompt]
== [system/history system/prompt]

forall list [list/1: mold list/1]

probe list
== ["system/history" "system/prompt"]

A: Assuming you never have spaces in the original list (as is true in your example)
parse form list none
== ["system/history" "system/prompt"]


text:
Q: GET min over multiple columns Can someone give me some advice on how I can get the min of values over multiple colums?
I'd like to do this without using a subquery if possible.
Thanks in advance!
something like the function 'least'.

A: least seems to be exactly what you need:
SELECT LEAST(MIN(col1), MIN(col2), MIN(col3)) AS minium_of_three_columns
FROM   my_table


text:
Q: error on booting desktop pc (asus MoBo) Each time i boot my desktop PC, the boot process stops and i am confronted with the following message
(My desktop MoBo is an asus M3N78 EM (AMD cpu and chipset)
NEW CPU IS INSERTED IN YOUR SYSTEM !
PRESS F1 TO RUN SETUP
PRESS F2 TO LOAD DEFAULT VALUES AND CONTINUE
I have done the following

*

*changed the cmos battery cell

*i have NOT changed the cpu ever

*pulled out the only hardware add-on (a PCIe card)

*reinstalled the bios

Hitting F2 will continue the boot process to my Windows 10 desktop
Would anyone have an idea why this is happening and what can be done ??


text:
Q: How to return a value from a Scala def I am new to Scala, but have some experience with Haskell. I did the following:
import scala.io.Source

val fileContent = Source.fromFile(filename).getLines.toList
val content = fileContent.map(processLine)

def processLine(line: String){
    val words = line.split("\\s+")
    println((words(0), words(1)))
}

Here processLine doesn't return anything so content is now a list of empty return values for all items. I thought the solution would be to include a return value in processLine, but Scala doesn't like that:
warning: enclosing method processLine has result type Unit: return value discarded

So how can I modify processLine so that it can be used to create a list of non-empty tuple values in content? how would it be to declare a lambda function with more than one line?
Thanks to helpful info in this thread, I could also have written it with a lambda expression:
var nonLinearTrainingContent = fileContent.map(x=> {
        val words = x.split("\\s+")
        (words(0), words(2))
        })

A: There are two things that prevent a result being returned:

*

*println returns Unit

*Your function defintion is a shorthand for a method returning Unit
This would give you the result you expected:
def processLine(line: String) : (String,String) = {
  val words = line.split("\\s+")
  val result = (words(0), words(1))
  println(result)
  result
}

As asked the same expressed as a function:
val processLineFun : String => (String, String) = line => {
  val words = line.split("\\s+")
  val result = (words(0), words(1))
  println(result)
  result
}

A: Make the tuple (words(0), words(1)) the last line of processLine function:
def processLine(line: String) = {
  val words = line.split("\\s+")
  println((words(0), words(1)))
  (words(0), words(1))
}

Edit: use curly braces for multiline lambda function or separate operators with ';' for one-line lambda
Edit2: fixed return type


text:
Q: How to find irreducible representation of a group from reducible one? I was reading this document to answer my question. But after teaching me hell lot of jargon like subgroup, normal subgroup, cosets, factor group, direct sums, modules and all that the document says this,

You likely realize immediately that this is not a particularly easy
  thing to do by inspection. It turns out that there is a very
  straightforward and systematic way of taking a given representation
  and determining whether or not it is reducible, and if so, what the
  irreducible representations are. However, the details of how this can
  be done, while very interesting, are not necessary for the agenda of
  these notes. Therefore, for the sake of brevity, we will not pursue
  them.

(>_<)
I want to learn to do this by hand and then write a program. Please don't ask me to learn GAP or any other software instead.
How to find irreducible representation of a group from reducible one? What is that straightforward and systematic way?

A: I do not believe that there is a straightforward way of doing what you want for complex representations. Probably the best way is to first compute the character table of the group. There are algorithms for that, such as Dixon-Schneider, but it is not something you can just sit down and program in an afternoon. Then you can use the orthogonality relations to find the irreducible constituents of your representation. There are then algorithms you could use to construct the matrices of the representations from its character - there is one due to Dixon, for example. This method is indirect in that you are not computing the irreducible constituents directly, but you are using the full chaarcter table, but I don't know any better way of doing it.
Strangely, this problem is a little easier for representations over finite fields, where there is a comparatively simple algorithm known as the "MeatAxe" for finding the irreducible constituents directly. (But programming it efficiently would still take a lot fo effort.)

A: (This might get more traction on math.stackexchange.com, rather than physics.stackexchange.com)
One can easily answer some of these questions with the concept of the character of a representation.
A (linear) representation is a homomorphism from group elements to linear transformations of a vector space.  The character of a representation is a map from group elements to the trace of this linear transformation.  A representation that is a direct sum of other representations has a character that is the ordinary sum of the characters of these other representations.
One can define an inner product on characters $x$ and $y$ by doing a normalized sum or integral of $\overline{x(g)} y(g)$.  Irreducible characters are orthonormal. This lets you test for irreducibility -- the character of the representation must have an inner product of 1 with itself.  If you have a list of the irreducible characters (which may be easier to construct than the list of irreducible representations), you can use this inner product to count how many times each irreducible character appears in a given character (and hence how many times an irreducible representation appears in a representation).
Of course, you do need the list of irreducible characters and representations to do this.  For finite groups, simple counting arguments plus orthogonality can get you an exhaustive list of irreducible characters, which will then tell you quite a bit about the corresponding representations. For continuous groups, other techniques are required.

A: 0) Find all irreducible representations of the group. Better learn GAP or another computer algebra system specially designed for algebra (in mathematical, not common sense). Or use character tables if you have well-known finite group.
1) Find a number of irreducible representations in the one you have using orthogonality relations for the characters (sum over group of the product of characters of elements from two representations equal to number of elements multiplied by number "times one representation may be find in another")
2) Now, if you want to derive a connection between your reducible representation and irreducible ones, you should find Clebsch-Gordan coefficients. Just pick any algorithm  -- it is hard to find a good description of one, I could not actually.
If you want to take reducible representation and by some diagonalization-like procedure turn it into irreducible ones, there is no such algorithm.


text:
Q: How to get current frame of RTSP using C /C++language? How to get current frame of RTSP using C /C++language?
I know there is many Python solution:
Read Frames from RTSP Stream in Python
If we can not use command (such as ffmpeg ..), just using c/c++ code.
I am try libvlc or openCV. How can I do? Thank you.

A: Use libvlc_video_set_callbacks() for libvlc 3.x.
There is another, faster, API in libvlc 4.x which uses the GPU.
Docs: https://www.videolan.org/developers/vlc/doc/doxygen/html/group__libvlc__media__player.html#ga612605f2e5c638d9f4ed59021d714bf0