Q: How to show and hide div on the basis of radio button selection I have two radio button on the selection of radio button it's should display div and hide div. Below is my script I don't understand why it's not working.
JavaScript

$(document).ready(function() {
  $(".text").show();
  $(".text1").hide();
  $("#r1").click(function() {
    $(".text").show();
    $(".text1").hide();
  });

  $("#r2").click(function() {
    $(".text1").show();
    $(".text").hide();
  });

});

HTML

Show textboxes
  <input type="radio" name="radio1" id="r1" checked value="Show" onClick="getResults()">Do nothing
  <input type="radio" name="radio1" id="r2" onClick="getResults()" value="Show">

 Wonderful textboxes:

Textbox #1
    <input type="text" name="text" id="text" maxlength="30">

Textbox #2
    <input type="text" name="text" id="text" maxlength="30">

Textbox #3
    <input type="text" name="text1" id="text1" maxlength="30">

Textbox #4
    <input type="text" name="text2" id="text1" maxlength="30">

here is jsfiddle link

A: Use change() event handler to handle the change event and toggle the element state using toggle() method with a boolean argument.

$(document).ready(function() {
  // attach change event handler
  $("#r1,#r2").change(function() {
    // toggle based on the id
    $(".text").toggle(this.id == 'r1');
    $(".text1").toggle(this.id == 'r2');
    // trigger change event to hide initially
  }).first().change();
});

Show textboxes
  <input type="radio" name="radio1" id="r1" checked value="Show">Do nothing
  <input type="radio" name="radio1" id="r2" value="Show">

 Wonderful textboxes:

Textbox #1
    <input type="text" name="text" maxlength="30">

Textbox #2
    <input type="text" name="text" maxlength="30">

Textbox #3
    <input type="text" name="text1" maxlength="30">

Textbox #4
    <input type="text" name="text2" maxlength="30">

FYI : The attribute should be unique on the page, for a group of elements use class attribute otherwise only the first element with the id get selected while using id selector.

A: Your Code is looking fine. make it sure that you add JQuery Properly
like

A: your code is working fine after added the jquery reference.

A: use toggle method for hide and show go to following link
https://www.w3schools.com/jquery/eff_toggle.asp


Q: How do you merge dataframes in pandas with different shapes? I am trying to merge two dataframes in pandas with large sets of data, however it is causing me some problems. I will try to illustrate with a smaller example.
df1 has a list of equipment and several columns relating to the equipment:
Item ID Equipment     Owner Status   Location
1       Jackhammer    James Active   London
2       Cement Mixer  Tim   Active   New York
3       Drill         Sarah Active   Paris
4       Ladder        Luke  Inactive Hong Kong
5       Winch         Kojo  Inactive Sydney
6       Circular Saw  Alex  Active   Moscow

df2 has a list of instances where equipment has been used. This has some similar columns to df1, however some of the fields are NaN values and also instances of equipment not in df1 have also been recorded:
Item ID Equipment     Owner Date       Location
1       Jackhammer    James 08/09/2020 London
1       Jackhammer    James 08/10/2020 London
2       Cement Mixer  NaN   29/02/2020 New York
3       Drill         Sarah 11/02/2020 NaN
3       Drill         Sarah 30/11/2020 NaN
3       Drill         Sarah 21/12/2020 NaN
6       Circular Saw  Alex  19/06/2020 Moscow
7       Hammer        Ken   21/12/2020 Toronto
8       Sander        Ezra  19/06/2020 Frankfurt

The resulting dataframe I was hoping to end up with was this:
Item ID Equipment     Owner Status   Date       Location
1       Jackhammer    James Active   08/09/2020 London
1       Jackhammer    James Active   08/10/2020 London
2       Cement Mixer  Tim   Active   29/02/2020 New York
3       Drill         Sarah Active   11/02/2020 Paris
3       Drill         Sarah Active   30/11/2020 Paris
3       Drill         Sarah Active   21/12/2020 Paris
4       Ladder        Luke  Inactive NaN        Hong Kong
5       Winch         Kojo  Inactive NaN        Sydney
6       Circular Saw  Alex  Active   19/06/2020 Moscow
7       Hammer        Ken   NaN      21/12/2020 Toronto
8       Sander        Ezra  NaN      19/06/2020 Frankfurt

Instead, with the following code I'm getting duplicate rows, I think because of the NaN values:
data = pd.merge(df1, df2, how='outer', on=['Item ID'])

Item ID Equipment_x  Equipment_y Owner_x Owner_y Status   Date       Location_x  Location_y
1       Jackhammer   NaN         James   James   Active   08/09/2020 London      London
1       Jackhammer   NaN         James   James   Active   08/10/2020 London      London
2       Cement Mixer NaN         Tim     NaN     Active   29/02/2020 New York    New York
3       Drill        NaN         Sarah   Sarah   Active   11/02/2020 Paris       NaN
3       Drill        NaN         Sarah   Sarah   Active   30/11/2020 Paris       NaN
3       Drill        NaN         Sarah   Sarah   Active   21/12/2020 Paris       NaN
4       Ladder       NaN         Luke    NaN     Inactive NaN        Hong Kong   Hong Kong
5       Winch        NaN         Kojo    NaN     Inactive NaN        Sydney      Sydney
6       Circular Saw NaN         Alex    NaN     Active   19/06/2020 Moscow      Moscow
7       NaN          Hammer      NaN     Ken     NaN      21/12/2020 NaN         Toronto
8       NaN          Sander      NaN     Ezra    NaN      19/06/2020 NaN         Frankfurt

Ideally I could just drop the _y columns however the data in the bottom rows means I would be losing important information. Instead the only thing I can think of merging the columns and force pandas to compare the values in each column and always favour the non-NaN value. I'm not sure if this is possible or not though?

A:
merging the columns and force pandas to compare the values in each column and always favour the non-NaN value.

Is this what you mean?
In [45]: data = pd.merge(df1, df2, how='outer', on=['Item ID', 'Equipment'])

In [46]: data['Location'] = data['Location_y'].fillna(data['Location_x'])

In [47]: data['Owner'] = data['Owner_y'].fillna(data['Owner_x'])

In [48]: data = data.drop(['Location_x', 'Location_y', 'Owner_x', 'Owner_y'], axis=1)

In [49]: data
Out[49]:
    Item ID     Equipment    Status        Date   Location  Owner
0         1    Jackhammer    Active  08/09/2020     London  James
1         1    Jackhammer    Active  08/10/2020     London  James
2         2  Cement Mixer    Active  29/02/2020   New York    Tim
3         3         Drill    Active  11/02/2020      Paris  Sarah
4         3         Drill    Active  30/11/2020      Paris  Sarah
5         3         Drill    Active  21/12/2020      Paris  Sarah
6         4        Ladder  Inactive         NaN  Hong Kong   Luke
7         5         Winch  Inactive         NaN     Sydney   Kojo
8         6  Circular Saw    Active  19/06/2020     Moscow   Alex
9         7        Hammer       NaN  21/12/2020    Toronto    Ken
10        8        Sander       NaN  19/06/2020  Frankfurt   Ezra

(To my knowledge) you cannot really merge on null column. However you can use fillna to take the value and replace it by something else if it is NaN. Not a very elegant solution, but it seems to solve your example at least.
Also see pandas combine two columns with null values

A: Generically you can do that as follows:
# merge the two dataframes using a suffix that ideally does
# not appear in your data
suffix_string='_DF2'
data = pd.merge(df1, df2, how='outer', on=['Item_ID'], suffixes=('', suffix_string))
# now remove the duplicate columns by mergeing the content
# use the value of column + suffix_string if column is empty
columns_to_remove= list()
for col in df1.columns:
    second_col= f'{col}{suffix_string}'
    if second_col in data.columns:
        data[col]= data[second_col].where(data[col].isna(), data[col])
        columns_to_remove.append(second_col)
if columns_to_remove:
    data.drop(columns=columns_to_remove, inplace=True)
data

The result is:
    Item_ID     Equipment  Owner    Status   Location        Date
0         1    Jackhammer  James    Active     London  08/09/2020
1         1    Jackhammer  James    Active     London  08/10/2020
2         2  Cement_Mixer    Tim    Active   New_York  29/02/2020
3         3         Drill  Sarah    Active      Paris  11/02/2020
4         3         Drill  Sarah    Active      Paris  30/11/2020
5         3         Drill  Sarah    Active      Paris  21/12/2020
6         4        Ladder   Luke  Inactive  Hong_Kong         NaN
7         5         Winch   Kojo  Inactive     Sydney         NaN
8         6  Circular_Saw   Alex    Active     Moscow  19/06/2020
9         7        Hammer    Ken       NaN    Toronto  21/12/2020
10        8        Sander   Ezra       NaN  Frankfurt  19/06/2020

On the following test data:
df1= pd.read_csv(io.StringIO("""Item_ID Equipment     Owner Status   Location
1       Jackhammer    James Active   London
2       Cement_Mixer  Tim   Active   New_York
3       Drill         Sarah Active   Paris
4       Ladder        Luke  Inactive Hong_Kong
5       Winch         Kojo  Inactive Sydney
6       Circular_Saw  Alex  Active   Moscow"""), sep='\s+')

df2= pd.read_csv(io.StringIO("""Item_ID Equipment     Owner Date       Location
1       Jackhammer    James 08/09/2020 London
1       Jackhammer    James 08/10/2020 London
2       Cement_Mixer  NaN   29/02/2020 New_York
3       Drill         Sarah 11/02/2020 NaN
3       Drill         Sarah 30/11/2020 NaN
3       Drill         Sarah 21/12/2020 NaN
6       Circular_Saw  Alex  19/06/2020 Moscow
7       Hammer        Ken   21/12/2020 Toronto
8       Sander        Ezra  19/06/2020 Frankfurt"""), sep='\s+')


Q: How to update streamProvider stream based on other providers value I want to update StreamProvider stream, based on the value of the Provider. I arrived at this solution.
return Provider<SelectedDay>.value(
          value: selectedDay,
          child: ProviderToStream<SelectedDay>(
            builder: (_, dayStream, Widget child) {
              return StreamProvider<DailyHomeData>(
                initialData: DailyHomeData.defaultValues(DateTime.now()),
                create: (_) async* {
                  await for (final selectedDay in dayStream) {
                    yield await db
                        .dailyHomeDataStream(
                            dateTime: selectedDay.selectedDateTime)
                        .first;
                  }
                },
                child: MainPage(),
              );
            },
          ),
        );

This is the providerToStream class, which i copied from here Trouble rebuilding a StreamProvider to update its current data
class ProviderToStream<T> extends StatefulWidget {
  const ProviderToStream({Key key, this.builder, this.child}) : super(key: key);

  final ValueWidgetBuilder<Stream<T>> builder;
  final Widget child;

  @override
  _ProviderToStreamState<T> createState() => _ProviderToStreamState<T>();
}

class _ProviderToStreamState<T> extends State<ProviderToStream> {
  final StreamController<T> controller = StreamController<T>();

  @override
  void dispose() {
    controller.close();
    super.dispose();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    controller.add(Provider.of<T>(context));
  }

  @override
  Widget build(BuildContext context) {
    return widget.builder(context, controller.stream, widget.child);
  }
}

And this is the error i get when i try to use it
type '(BuildContext, Stream<SelectedDay>, Widget) => StreamProvider<DailyHomeData>' is not a subtype of type '(BuildContext, Stream<dynamic>, Widget) => Widget'

Note: The code doesnt even work when i place a dummy widget inside the ProviderToStream widget.
 child: ProviderToStream<SelectedDay>(
              builder: (_, ___, Widget child) {
                return child;
              },
            ),

I also tried to force somehow the type in the builder, so that it is not dynamic, with no luck
   child: ProviderToStream<SelectedDay>(
              builder: (_, Stream<SelectedDay> dayStream, Widget child) {
                return child;
              },
            ),


Q: Locate stack/heap variables in memory I am currently trying to hot patch programs (update code and data in the program memory, according to a released patch).
Assume that we can stop a running program, and do the patch. If the patch changes some data initialization or assignment values, how could we know where the variables are, like those in stack or heap?

Example:
Before patch:
void func() {
    int a = 1;
}

After patch:
void func() {
    int a = 2;
}

When patching, how could we know the location of a in the stack (or maybe not in the stack)?

A: Unless you have a lot of knowledge of how the compiler works, you cannot know a priori where these variables are stored, or even how they are represented.  Each compiler designer makes his own rules for how/where variables are stored.
You might be able to figure out for a specific compiled program, by inspecting the generated code.


Q: $\mathfrak{sl}_2(\mathbb{Z})$'s properties as a Lie algebra over a ring I was wondering what was known about $\mathfrak{sl}_2(\mathbb{Z})$ as a Lie algebra; in particular, what is known about its representation theory? I know of some texts which treat Lie algebras generally over rings, but I haven't seen any that specifically discuss this example. It would be wonderful if there existed some analogue of a Clebsch-Gordan decomposition for tensor products of $V_n$ (by which I mean the irreps in the complex case), even if they are no longer irreducible over $\mathbb{Z}$. Thank you very much!


Q: Convert ndarray to string array Lets say there is array
values = [[ 116.17265886,   39.92265886,  116.1761427 ,   39.92536232],
          [ 116.20749721,   39.90373467,  116.21098105,   39.90643813],
          [ 116.21794872,   39.90373467,  116.22143255,   39.90643813]]

now I want to convert this to
values = [[ '116.17265886',   '39.92265886',  '116.1761427' ,   '39.92536232'],
          [ '116.20749721',   '39.90373467',  '116.21098105',   '39.90643813'],
          [ '116.21794872',   '39.90373467',  '116.22143255',   '39.90643813']]

A: Assuming you really have a numpy array (not a list of list), you can use astype(str):
values = np.array([[ 116.17265886,   39.92265886,  116.1761427 ,   39.92536232],
                   [ 116.20749721,   39.90373467,  116.21098105,   39.90643813],
                   [ 116.21794872,   39.90373467,  116.22143255,   39.90643813]])

out = values.astype(str)

output:
array([['116.17265886', '39.92265886', '116.1761427', '39.92536232'],
       ['116.20749721', '39.90373467', '116.21098105', '39.90643813'],
       ['116.21794872', '39.90373467', '116.22143255', '39.90643813']],
      dtype='<U32')

A: If it's not a numpy array and it is a list of a list of values the following code should work:
for index in range(len(values)):
   values[index] = [str(num) for num in values[index]]
print(values)

For each list it returns a list of each of the values changed to a string, this returns the following.
[['116.17265886', '39.92265886', '116.1761427', '39.92536232'],
['116.20749721', '39.90373467', '116.21098105', '39.90643813'],
['116.21794872', '39.90373467', '116.22143255', '39.90643813']]


Q: Rails_Admin - how to export specific rows My Table contains rows, each row has an account field containing the email of the current_user so that users have access only to rows containing their own data. Rails_Admin exports successfully ALL rows. How could I export ONLY the rows that belongs to the user email account.
I am new in .haml

A: You can select which fields to export by defining the export block
RailsAdmin.config do |config|
  config.model 'Highway' do
    export do
      field :number_of_lanes
    end
  end
end

Also you can configure the value of each field
  RailsAdmin.config do |config|
    config.model 'Lesson' do
      export do
        field :teacher, :string do
          export_value do
            value.name if value #value is an instance of Teacher
          end
        end
      end
    end
  end


Q: The Mathematics of Hexagonal Grids in SVG This is my first time posting on this forum, but my mathematics skills are a little weak when push comes to shove.
Here is my question:

What is a formula that maps the center-points of horizontal hexes in a cubic grid system to a specific point in an SVG plane.
  *in SVG space Y is inverted: negative Y goes up on the screen, positive Y goes down (don't ask why it just does)

Some context:
I have JavaScript implementation drawing the hex the way I want from any given center-point. This means I just need the formula to output the X coordinate and the Y coordinate
This should be possible because each X, Y, Z label is unique within any given grid whose center-point should map to a specific X, Y coordinate in 2d space.
I spent several hours thinking about this and couldn't wrap my head around how to go about describing it mathematically, so an explanation of why it works would be welcome as I'm always up for learning new things.
**
Inputs: (X, Y, Z) cubic coordinate

Always an integer

Outputs: (X, Y) SVG coordinate

Float or Integer *that is the center-point of the hex

EDIT: clarification
**I'm not mapping 3d space to 2d space. A cubic hex grid looks like the following
It's also worth mentioning that the formula will be dependent on the size of the hex. Which for the purposes of my program is measured as the length of a straight line between itself and any of its neighbors since all hexes are the same size?


Q: flutter post request with header and body anyone could help me to write flutter request post for the following header and body with the corresponding response below;
Example Post Request
Header Request:
Content-Type:application/x-www-form-urlencoded

Body Request:
grant_type: client_credentials

scope: accounts

client_assertion_type: code**

client_assertion: code**

A: Try the following,
String hostname = "myhostname";// example
String port = "1234"; //example
String url = "https://$hostname:$port/as/token.oauth2";
String body = "{'grant_type' : '$client_credentials' }" +
              "'scope' : '$accounts'" +
              //... etc etc
              "'Corresponding Response': { 'access_token': 'JWt CODE', 'expires_in': '86400', 'token_type': 'bearer', 'scope': 'payments' }"+
             "}";
var res = await http.post(Uri.encodeFull(url),
        headers: {
          "Accept": "application/json",
          "Content-Type" : "application/x-www-form-urlencoded"
        },
        body: body);


Q: Get relative links from html page I want to extract only relative urls from html page; somebody has suggest this :
find_re = re.compile(r'\bhref\s*=\s*("[^"]*"|\'[^\']*\'|[^"\'<>=\s]+)', re.IGNORECASE)

but it return  :
1/all absolute and relative urls from the page.
2/the url may be quated by "" or '' randomly .

A: Use the tool for the job: an HTML parser, like BeautifulSoup.
You can pass a function as an attribute value to find_all() and check whether href starts with http:
from bs4 import BeautifulSoup

data = """

test1
test2
test3
test4

"""
soup = BeautifulSoup(data)
print soup.find_all('a', href=lambda x: not x.startswith('http'))

Or, using urlparse and checking for network location part:
def is_relative(url):
    return not bool(urlparse.urlparse(url).netloc)

print soup.find_all('a', href=is_relative)

Both solutions print:
[test2,
 test4]


Q: How to avoid content from overlapping div border Here I have this markup:

This is short

This one is longer

Yet this one is a lot more longer

And here's the CSS:
div.cabinet{
  width:120px;
  border-right:5px solid #e7e8e1;
  white-space:nowrap;
}

I need the content not to overlap the right border of the div but instead be padded some 5px away. Here's the jsfiddle. I tried to play with z-index but it didn't help. What should I do?

A: Demo Fiddle
How about the following:
div.cabinet{
  border-right:5px solid #e7e8e1;
  white-space:nowrap;
  display:inline-block;
  padding-right:5px;
}

Use inline-block to make the div fit the content, then add padding. If you only wish the child ul to do this, simply apply those properties to div.cabinet ul instead (as well as the border).

A: Add a Padding to your UL or LI tag,
ul{padding:5px;} /** Will be applicable to all li's or you can also give it seperately **/

you can change that 5px value, but it will be enough !


Q: Find column value Excel I have a data that looks like this in Excel:
A   17  8,5 5,666666667 4,25    3,4 2,833333333 2,428571429
B   5   2,5 1,666666667 1,25    1   0,833333333 0,714285714
C   5   2,5 1,666666667 1,25    1   0,833333333 0,714285714
G   4   2   1,333333333 1       0,8 0,666666667 0,571428571

I want to find a the letter representing a specific value. For instance, if I search for "17" I want to get the output "A" and if I am looking for 0,8 I want to get "G". Can anyone help me?
(In reality I want to find sort all the values in the data from the largest to the lowest and find the corresponding letter for the value)

A: =INDEX($A$1:$A$4,AGGREGATE(14,6,ROW($B$1:$H$4)/(L3=$B$1:$H$4),1))

assuming your example data is in the A1:H4 Range
When you have duplicate value that can be found this formula will return the one in the largest row number.  If you want the value in the first row number you can change the 14 to 15.

EDIT
Option 1
=INDEX($A$1:$A$21,AGGREGATE(14,6,ROW($B$18:$L$21)/(L3=$B$18:$L$21),1))

Option 2
=INDEX($A$18:$A$21,AGGREGATE(14,6,ROW($B$18:$L$21)/(L3=$B$18:$L$21),1)-ROW($A$18)+1)

The problem you had when you moved it was most likely because of your range reference changes.  The row number that is returned from the aggregate check has to be a row within the index range.  So option one keep the index range large but matches all possible rows from the aggregate results.  Option two reduces the range to just your data and adjust the results to subtract the number of rows before your data so its really referring to which row within the index range you want to look at.
Option 3
Thanks to Scott Craner indicating the full column reference is perfectly acceptable outside the aggregate function, you could also use:
=INDEX($A:$A,AGGREGATE(14,6,ROW($B$18:$L$21)/(L3=$B$18:$L$21),1)


Q: In OpenTest, how does one run tests across multiple actors using a single template that contains a dozen tests? As it stands currently, we have a single template with a dozen tests underneath it. We have two actors, but the second actor never picks up any tests under the session using the template that was launched.
How should I structure my distributed testing to allow for the tests to be executed in parallel against the two actors?

A: As of version 1.1.4, test sessions execute sequentially, within one test session. The reason for that is to be deterministic about what happens when, so testers can make reliable assumptions about the execution flow. This is important because tests can have dependencies between them and must execute in a specific order for them to succeed. To be sure, this is a bad practice, but it's sometimes necessary for practical reasons.
To execute tests in parallel, you must create two (or more) separate test sessions, so you must split your current session template in two. In the future, OpenTest will introduce an option that will allow one single test session to execute against multiple actors, but the default will still be executing the tests sequentially.


Q: How to access in folder images in node.js? So in my project I have folder /Pictures and everything else is all over the project folder. My problem is that I can access all the CSS , JS, HTML, but it doesn't let me get this image folder as a source of the web app.
I tried this(doesn't work):
  app.get('/water.jpeg', function (req, res) {
      res.sendFile(__dirname + '/' + "Pictures" + '/' + "water.jpeg");
  });

I want all my images from the /Pictures folder to be a source for my web app.

A: if image uploads to '/uploads' folder then try like
app.use('/uploads', express.static(process.cwd() + '/uploads'))

A: __dirname gives you the directory name of entry point file. I don't know where is your entry point file in your application, but that's where you have to start.
By the way, I advise you to use the "join" function of the "path" module to concatenate the path so as it works on linux or window filesystem.

A: I found a solution by Quora here, thanks to everyone who helped :) :
link


Q: Cannot infer type for `U` I am using Rust and Diesel:
fn create_asset_from_object(assets: &HashMap<String, Assets_Json>) {
    let connection: PgConnection  = establish_connection();
    println!("==========================================================");
    insert_Asset(&connection, &assets);
}

pub fn insert_Asset(conn: &PgConnection, assests: &HashMap<String, Assets_Json>){
    use self::schema::assets;

    for (currency, assetInfo) in assests {

        let new_asset = self::models::NewAssets {
            asset_name: &currency,
            aclass:  &assetInfo.aclass,
            altname: &assetInfo.altname,
            decimals:  assetInfo.decimals,
            display_decimals: assetInfo.display_decimals,
        };

       //let result = diesel::insert(&new_asset).into(assets::table).get_result(conn).expect("Error saving new post");
       println!("result, {:#?}", diesel::insert(&new_asset).into(assets::table).get_result(conn).expect("Error saving new post"));

    }
}

Compiler error:
error[E0282]: type annotations needed
   --> src/persistence_service.rs:107:81
    |
107 |        println!("result, {:#?}", diesel::insert(&new_asset).into(assets::table).get_result(conn).expect("Error saving new post"));
    |                                                                                ^^^^^^^^^^ cannot infer type for `U`

A: I strongly recommend that you go back and re-read The Rust Programming Language, specifically the chapter on generics.

LoadDsl::get_result is defined as:
fn get_result<U>(self, conn: &Conn) -> QueryResult<U>
where
    Self: LoadQuery<Conn, U>,

In words, that means that the result of calling get_result will be a QueryResult parameterized by a type of the callers choice; the generic parameter U.
Your call of get_result in no way specifies the concrete type of U. In many cases, type inference is used to know what the type should be, but you are just printing the value. This means it could be any type that implements the trait and is printable, which isn't enough to conclusively decide.
You can use the turbofish operator:
foo.get_result::<SomeType>(conn)
//            ^^^^^^^^^^^^

Or you can save the result to a variable with a specified type:
let bar: QueryResult<SomeType> = foo.get_result(conn);

If you review the Diesel tutorial, you will see a function like this (which I've edited to remove non-relevant detail):
pub fn create_post() -> Post {
    diesel::insert(&new_post).into(posts::table)
        .get_result(conn)
        .expect("Error saving new post")
}

Here, type inference kicks in because expect removes the QueryResult wrapper and the return value of the function must be a Post. Working backwards, the compiler knows that U must equal Post.
If you check out the documentation for insert you can see that you can call execute if you don't care to get the inserted value back:
diesel::insert(&new_user)
    .into(users)
    .execute(&connection)
    .unwrap();


Q: Threejs: Disable frustum culling for some objects In order to solve the problem of z-fighting, I limited the near and far of camera to a small range.But when I want to add a larger object,it was culled by view frustum.
I tried object3d.frustumCulled property,not working as expected,the reason is as follows:
https://github.com/mrdoob/three.js/issues/12170
So,is there a way to ensure that some specific objects are not frustum culled without changing the camera near and far? THX.

A: Culling doesn't mean that an object is drawn or not. It can be either drawn or not drawn depending on where it is. It is an optimization that tries to say something like this:

Hey, i have a really cheap check (plane/sphere intersection) that i can do and tell you if you need to attempt to draw this at all.

So you do a cheap check, and if the object is guaranteed to be entirely out of the frustum, you never issue the draw call. If it intersects, you have to issue a draw call, but you may still see nothing if none of the triangles are actually in the frustum.
If you download something like specter.js and inspect your draw calls, you will infact see that with frustumCulled = false you get a draw call for every object in your scene. Your screen may be empty.


Q: How can I uncover the fraction line in beamer? I would like to uncover elements of an equation one at a time. This is easy enough usually, but in this case I'd like to progressively reveal a fraction. The problem with the way I'm doing it is that the fraction line is visible throughout, and for obvious aesthetic reasons I'd only like it to show up on the last uncover. Here's how I'm doing it now :
\documentclass[8pt,xcolor=dvipsnames,compress]{beamer}
\begin{document}
\begin{frame}
$\frac{\uncover<2->{\int} \phi(\lambda) \uncover<2->{T(\lambda) \lambda d \lambda}}{\uncover<3->{\int \phi_{S}(\lambda) T(\lambda) \lambda d \lambda}}$
\end{frame}
\end{document}

This reveals the elements I'd like to reveal when I'd like to reveal them, but as I've said keeps the fraction line throughout. Any ideas on how to only make it appear on step 3 ?

A: Here's a pretty fun non-complete solution. I've taken the \binom command and removed the parentheses. The elements are not completely unmoving though. We can probably tweak the command some more. I will look into it more later.

After @LoopSpace's kind encouragement I made a new attempt and solved it. The good thing about \binom is as @LoopSpace was discussing that it works the same way as \frac but without the fraction bar. I added a phantom of the denominator to get the correct alignment of the fraction.
However, even with the newly defined command, I couldn't get the correct horizontal alignment if the \int was within a \uncover environment, to solve this, I put the \int in the full fraction within an \uncover environment as well.
\documentclass[8pt,xcolor=dvipsnames,compress]{beamer}
\newcommand{\hidefrac}[2]{\genfrac{}{}{0pt}{0}{#1}{#2}} %new command, 0 in the fourth argument means displaystyle (change to 1 for textsize)
%taken from definition of \binom in the amsmath package

\begin{document}
\begin{frame}
$\only<1-2>{\hidefrac{\uncover<2->{\int}\phi(\lambda)\uncover<2->{T(\lambda)\lambda d\lambda}}{\phantom{\int\phi_{S}(\lambda)T(\lambda)\lambda d\lambda}}}$%
$\only<3->{\displaystyle\frac{\uncover<3->{\int}\phi(\lambda)T(\lambda)\lambda d\lambda}{\int\phi_{S}(\lambda)T(\lambda)\lambda d \lambda}}$
\end{frame}
\end{document}

And be careful with spaces. Try removing the % in the end of the first \only line to see what I mean.

A: Inspired by some of the tweaking found here, I've come up with the following solution :
\documentclass[8pt,xcolor=dvipsnames,compress]{beamer}
\begin{document}
\begin{frame}
$\uncover<2->{\int} \phi(\lambda) \uncover<2->{T(\lambda) \lambda d \lambda} \uncover<3->{\above 0.4pt} \uncover<3->{\int \phi_{S}(\lambda) T(\lambda) \lambda d \lambda}$
\end{frame}
\end{document}

Basically you just avoid the \frac command entirely by doing what it does yourself using \above, allowing you to use \uncover on the \above command.

A: Just use \pause:
$\frac{\uncover<2->{\int} \phi(\lambda) \uncover<2->{T(\lambda) \lambda d \lambda}\pause[3]}{\int \phi_{S}(\lambda) T(\lambda) \lambda d \lambda}$


Q: How to detect the screen DPI using VB.NET? I need the screen DPI so i can adjust my program accordingly.
So my question is How to detect the screen DPI using VB.NET?

A: try this:
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim g As Graphics = Me.CreateGraphics()
    MessageBox.Show("ScreenWidth:" & Screen.PrimaryScreen.Bounds.Width & " ScreenHeight:" & Screen.PrimaryScreen.Bounds.Height & vbCrLf & " DpiX:" & g.DpiX & " DpiY:" & g.DpiY)
End Sub


Q: Find the minimum of this function Let $\delta = 0.503997.$ What is the minimum of the function $h$ defined for all $\gamma \in ]0,1[$ by
$$h(\gamma):= \left(\frac{\gamma^{32}}{(\gamma^{32} - 1)}\right)\times
  \left(\frac{2}{\delta \times (1 - \gamma^2)}\right)^{16}?$$
Thanks in advance.


Q: How to continue at particular step - spookyjs? I am using spookyjs to test my application.
Question
Is there anyway to enforce the spookyJs to start at particular step?
How to force start at particular step spookyJs?
Example
SpookyJs will run step by step, Suppose some connection error happened at particular step and server got stopped, Now how can I continue the test from particular step instead of running from beginning.
Any suggestion will be grateful


Q: Helper not available in the view I am migrating from 1.3 to 2.0.6 and have the following problem:

Notice (8): Undefined variable: session [APP/View/Users/login.ctp, line 2]
Fatal error: Call to a member function flash() on a non-object in login.ctp on line 2

Why is there a problem accessing the session helper?

A: That's not how to use helpers

Notice (8): Undefined variable: session [APP/View/Users/login.ctp, line 2]
Fatal error: Call to a member function flash() on a non-object in login.ctp

Whilst it's not in the question your login.ctp template looks something like this:
<?php
echo $session>flash(); # line 2

That's not how helpers are expected to be used in CakePHP 2.x:

you can use [the helper] in your views by accessing an object named after the
  helper:
<!-- make a link using the new helper -->
<?php echo $this->Link->makeEdit('Change this Recipe', '/recipes/edit/5'); ?>

The code you're looking for is:
# echo $session->flash(); # wrong
echo $this->Session->flash(); # right

Note also that Session needs to be in the controller $helpers array.
In 1.2 and earlier versions of CakePHP helpers were expected to be variables, this changed but was still supported in 1.3. If your 1.3 CakePHP application has been using helpers in this way, it has been relying on backwards-compatibility with earlier versions. In 2.0 helpers are not variables, and only possible to access as a view class property. Be sure to read the migration guides - for more information on what has changed.


Q: How to show count for messages which are hidden below the scroll using jQuery? I need to show counter for loaded but scroll down messages in conversation screen. Suppose there are 15 messages in total but showing only 6 on browser right now. It means 9 messages are hidden in below so counter should display 9. But when I scroll up or down counter should change the value accordingly visible and hidden messages.
        function isScrolledIntoView(elem) {
         var $elem = $(elem);
        var $window = $(window);

        var docViewTop = $window.scrollTop();
            var docViewBottom = docViewTop + $window.height();

            var elemTop = $elem.offset().top;
            var elemBottom = elemTop + $elem.height();

        return ((elemBottom <= docViewBottom) && (elemTop >=        docViewTop));
        }
            var message = $('#messages');
            $(window).scroll(function() {
        if (isScrolledIntoView('#hiddenElem')) {
      message.text("Visible");
        } else {
      message.text("Invisible");
    }
  });

Check code in this JS Fiddle. Also JavaScript code written for show hidden or visible element.

A: You have to compare the position of each messages with the scrolled value.
So you need to loop throught them.
Here is something working:
var messages=$(".msg");

$(window).scroll(function(){
  var counter=0;
  for(i=0;i<messages.length;i++){
    if( messages.eq(i).offset().top < $(window).scrollTop() ){
      counter++;
    }
  }
  // Display result.
  $("#messages").html(counter);
});

Updated Fiddle


Q: addTextChangedListener Null Pointer Exception Been looking at other questions but none of them solved my problem.
I have an editText and I need to implement an addTextChangedListener to this field so i can update values of other text views in real time.
public class MainActivity extends ActionBarActivity {

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

    EditText billText = (EditText)findViewById(R.id.billValue);
    billText.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1,
                int arg2, int arg3) {
            // TODO Auto-generated method stub

        }

    });

Anything wrong in my code that I may be missing?

A: As far as I can guess, following line causing NullPointerException because your editText is null
billText.addTextChangedListener(new TextWatcher() {

May be the EditText you are trying to access here isn't in the activity_main.xml layout. So at first, make sure that the EditText with id billValue exists in the activity_main.xml.

A: You are creating a new instance of an interface not a class. Instead, you may write your activity class as
public class MainActivity extends ActionBarActivity implements TextWatcher

and add some methods to your class:
    @Override
    public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        // TODO Auto-generated method stub

    }

    @Override
    public void afterTextChanged(Editable arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1,
            int arg2, int arg3) {
        // TODO Auto-generated method stub

    }

Try it, you will not have an exception I guess.

A: Do like the following -
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    billText.addTextChangedListener(new TextWatcher()
    {
      public void onTextChanged(CharSequence s,
      int start, int before, int count)
      {
        EditText billText = (EditText) view.findViewById(R.id.billText);
        billText_val = billText.getText().toString().toLowerCase();
        //do anything with this value

      }

    public void beforeTextChanged(CharSequence s, int start, int count, int after)
    {

    }

    public void afterTextChanged(Editable s)
    {

    }
 });
}

A: You are doing that fine There Might be an Issue with the Reference of your EditText
Anyhow here is my sample code attached for this purpose.
et_email = (EditText) findViewById(R.id.et_regstepone_email);

et_email.addTextChangedListener(this);

    @Override
public void afterTextChanged(Editable s) {
    // TODO Auto-generated method stub

}

@Override
public void beforeTextChanged(CharSequence s, int start, int count,
        int after) {
    // TODO Auto-generated method stub

}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
    // TODO Auto-generated method stub

    if(count==0&&et_email.length()==0){
        et_email.setCompoundDrawables(null, null, null, null);

    }else if(count>0){

    }

}

A: I had exactly the same problem.
Check the ID of your EditText in other layout xml files of the same activity. In my case it was the xml in layout-v21. I was overriding the ID of the EditText element in it.


Q: How to compare two column values incrementally and copy entire row if the cells in those columns meet a condition I am trying to compare two columns in one workbook and based on a certain condition copy the row where that condition is met to another workbook.
This is for a "database" I am working on. I have a Master sheet and then several versions of sub-masters that are catered specifically to certain individuals.
I have tried to some success by creating two different With statements and using a delete function on the sub-sheet but it is clunky and I'm not a fan of it. Please see the example code below.
Public Sub Workbook_Open()

Dim wb1 As Workbook, wb2 As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet
Dim copyFrom As Range
Dim lRow As Long
Dim strSearch As String
Dim vrtSelectedItem As Variant

Set wb1 = Application.Workbooks.Open("C:\Users\myfolder\Desktop\Excel Master Test\ROLE BASED TRACKER DRAFT.xlsx")
Set ws1 = wb1.Worksheets("Master")

Set wb2 = ThisWorkbook
Set ws2 = wb2.Worksheets("Sheet1")

'~~> Specifies which resources info. you are retrieving
strSearch = "117"
ws2.Cells.Clear

'~~> Copying the header information and formatting.
ws1.Range("1:1").Copy
ws2.Range("1:1").PasteSpecial

With ws1

    '~~> Remove any filters
    .AutoFilterMode = False

    lRow = .Range("A" & .Rows.Count).End(xlUp).Row

    With .Range("L1:L" & lRow)
        .AutoFilter Field:=1, Criteria1:=strSearch
         Set copyFrom = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow
    End With

    .AutoFilterMode = False

End With

'~~> Destination File

With ws2
    If Application.WorksheetFunction.CountA(.Rows) <> 0 Then
        lRow = .Cells.Find(What:="*", _
                      After:=.Range("A1"), _
                      Lookat:=xlPart, _
                      LookIn:=xlFormulas, _
                      SearchOrder:=xlByRows, _
                      SearchDirection:=xlPrevious, _
                      MatchCase:=False).Row + 1
    Else
        lRow = .Range("A" & Rows.Count).End(xlUp).Row
    End If
    copyFrom.Copy .Rows(lRow)
End With

With ws2
        '~~> Remove any filters
    .AutoFilterMode = False

    lRow = .Range("A" & .Rows.Count).End(xlUp).Row

    With .Range("AD1:AD" & lRow)
        .AutoFilter Field:=1, Criteria1:=strSearch
        .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
    End With

    .AutoFilterMode = False

End With

With ws1

    '~~> Remove any filters
    .AutoFilterMode = False

    lRow = .Range("A" & .Rows.Count).End(xlUp).Row

    With .Range("AD1:AD" & lRow)
        .AutoFilter Field:=1, Criteria1:=strSearch
         Set copyFrom = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow
    End With

    .AutoFilterMode = False

End With

'~~> Destination File

With ws2
    If Application.WorksheetFunction.CountA(.Rows) <> 0 Then
        lRow = .Cells.Find(What:="*", _
                      After:=.Range("A1"), _
                      Lookat:=xlPart, _
                      LookIn:=xlFormulas, _
                      SearchOrder:=xlByRows, _
                      SearchDirection:=xlPrevious, _
                      MatchCase:=False).Row + 1
    Else
        lRow = .Range("A" & Rows.Count).End(xlUp).Row
    End If
    copyFrom.Copy .Rows(lRow)
End With

With ws2.Sort
    .SetRange Range("A2:A12000")
    .Header = xlNo
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

wb1.Save
wb1.Close
wb2.Save

End Sub

This is the code that I am trying to get work. I keep getting a Type Mismatch error on my cell comparison lines. '' If ws1.Range("AD1:AD" & lRow) <> ws1.Range("L1:L" & lRow) Then ''
Public Sub Workbook_Open()

Dim wb1 As Workbook, wb2 As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet
Dim copyFrom As Range
Dim lRow As Long
Dim strSearch As String
Dim vrtSelectedItem As Variant

Set wb1 = Application.Workbooks.Open("C:\Users\myfolder\Desktop\Excel Master Test\ROLE BASED TRACKER DRAFT.xlsx")
Set ws1 = wb1.Worksheets("Master")

Set wb2 = ThisWorkbook
Set ws2 = wb2.Worksheets("Sheet1")

'~~> Specifies which resources info. you are retrieving
strSearch = "117"
ws2.Cells.Clear

'~~> Copying the header information and formatting.
ws1.Range("1:1").Copy
ws2.Range("1:1").PasteSpecial

With ws1

    '~~> Remove any filters
    .AutoFilterMode = False

    lRow = .Range("A" & .Rows.Count).End(xlUp).Row

    If ws1.Range("AD1:AD" & lRow) <> ws1.Range("L1:L" & lRow) Then

        With .Range("AD1:AD" & lRow)
            .AutoFilter Field:=1, Criteria1:=strSearch
            Set copyFrom = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow
        End With

        .AutoFilterMode = False

    End If

End With

'~~> Destination File

With ws2
    If Application.WorksheetFunction.CountA(.Rows) <> 0 Then
        lRow = .Cells.Find(What:="*", _
                      After:=.Range("A1"), _
                      Lookat:=xlPart, _
                      LookIn:=xlFormulas, _
                      SearchOrder:=xlByRows, _
                      SearchDirection:=xlPrevious, _
                      MatchCase:=False).Row + 1
    Else
        lRow = .Range("A" & Rows.Count).End(xlUp).Row
    End If
    copyFrom.Copy .Rows(lRow)
End With

With ws1

    '~~> Remove any filters
    .AutoFilterMode = False

    lRow = .Range("A" & .Rows.Count).End(xlUp).Row

    If ws1.Range("AD1:AD" & lRow) = ws1.Range("L1:L" & lRow) Then

        With .Range("L1:L" & lRow)
            .AutoFilter Field:=1, Criteria1:=strSearch
            Set copyFrom = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow
        End With

        .AutoFilterMode = False

    End If

End With

'~~> Destination File

With ws2
    If Application.WorksheetFunction.CountA(.Rows) <> 0 Then
        lRow = .Cells.Find(What:="*", _
                      After:=.Range("A1"), _
                      Lookat:=xlPart, _
                      LookIn:=xlFormulas, _
                      SearchOrder:=xlByRows, _
                      SearchDirection:=xlPrevious, _
                      MatchCase:=False).Row + 1
    Else
        lRow = .Range("A" & Rows.Count).End(xlUp).Row
    End If
    copyFrom.Copy .Rows(lRow)
End With

With ws2.Sort
    .SetRange Range("A2:A12000")
    .Header = xlNo
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

wb1.Save
wb1.Close
' wb2.Save

End Sub

A: I just wanted to thank everyone who helped. I am going to just stick with my initial solution of filter, copy, paste, filter, delete, filter, copy, paste, sort.
See my first code block for what I am talking about. Cheers.


Q: would a css grid framework be a good fit for creating application like layouts? I have a webapp that I am making and it has some particular layout needs that are closer to an application than a website.
The layout has:

*

*a left sidebar that is fixed to the left side of the browser window and has a static width until it stacks, this sidebar will have tabs in it

*a content area that will expand to a certain max-width and then stop

*a right side bar that is fixed the the right edge of the content

I've been struggling to really determine if using a grid system, like bootstrap, would be an appropriate fit for something like this. Having some rows/columns and a collapsible grid in the content area seems like it would make sense, but in the sidebars it seems like its best to not use a grid system at all. I don't particularly like the idea doing some layout in the html with bootstrap3 and some in css.
Basically my app has the same layout as http://qz.com/ and I want similar responsive design breaks, and with that I would like to know if there is one or more css frameworks that support that type of layout with little overriding.

A: if you have some experience with resposive design and media queries, i would code it myself to avoid the thousands of lines of unnecessary code that comes with frameworks/libraries. bootstrap is great, but it also requires a bit of effort to master, and it would be a bit overkill for this one layout (if i understand you correctly).
if you just need this one layout, i would really recommend you do code it from scratch (personally i'd use something like jQuery and LESS). i hope i understood your question correctly, and sorry if this was not very hands-on.
to sum it up: in my opinion you're probably better off coding it yourself, but bootstrap and other frameworks will provide valuable insight and inspiration for how to do it.


Q: Beginner needs suggestions on map clicks and geojson I'm a beginner with programming, and javascript. I went to the FOSS4G-NA conference and was very inspired to learn more. I'm trying to learn PostGIS, and have come across a very useful tutorial for using PostGIS with Openlayers and geoserver: http://workshops.opengeo.org/postgis-spatialdbtips/
I've followed through all of the examples, but one of many things I don't understand:
The examples show how to retrieve data from the postgis database and display on the map, or show how to calculate something within a distance of the map click. What about retrieving the clicked taxlot, then using the id of that taxlot to perform other spatial queries?
For example, I'm trying to build up an example based on the concepts for the tutorial. I want the user to click a watershed (a polygon layer), and have the map return the outline of the clicked watershed, as well as highlight/send to the map any withdrawal point data contained within that watershed, and produce some summary output (such as the total number and withdrawal amounts) and place that into the iframe on the page.
My strategy would be:

*

*Have one function retrieve the clicked watershed, output the selected watershed vector to the map, and return the ID of that watershed and store it as a variable.

*That variable would then be passed to a second function where the spatial query using st_contains is performed to select all of the points within the taxlot, and then output those selected building vectors to the map.

*A third function would perform a similar query to the second function, except output the result of a summary calculation to the iframe.
Right now I'm stuck on whether this strategy is right, as I'm a bit lost on the code to both retrieve clicked attribute data and store it as a variable, as well as display it using geojson. Clicking in my map page gets me the error that my clicked_shed variable is null, in my getWatershed function. Right now I've only created a function to retrieve the ID of the clicked watershed, and a function to display those withdrawal points within that clicked watershed.
I'm so inspired by all of this I think my first task after I understand this better will be to write some easy tutorials following on to this existing tutorial for others in my position.  There can never be enough examples and tutorials in my opinion.
Can anyone provide a lowly beginner with any thoughts?
    var x = -8684372;
    var y = 4765431;
    var zoom = 10;
    var map, json_layer;

function init(){

    initMap();
    var wwms = new OpenLayers.Layer.WMS( "Opequon Sub-watersheds","/geoserver/wms?",
               {
                transparent:'true',
                layers: 'medford:subshed2',
                'format':'image/png'},
               {'reproject': true});
    var swms = new OpenLayers.Layer.WMS( "Opequon Streams",
                    "/geoserver/wms?",
               {
                transparent:'true',
                layers: 'medford:OpequonStreams',
                'format':'image/png'},
               {'reproject': true});
    map.addLayer(wwms);
    map.addLayer(swms);

    map.events.register("click", map, getWatershed);
    map.events.register("click", map, getFeatures );

    }

    function initMap() {

        // Initialize our map using Mercator as the internal units.
        // That means our bounds, center, resolution, all have to be in Mercator.
        var options = {
            projection: new OpenLayers.Projection("EPSG:900913"),
            displayProjection: new OpenLayers.Projection("EPSG:4326"),
            units: "m",
            numZoomLevels:20,
            maxResolution: 156543.0339,
            maxExtent: new OpenLayers.Bounds(-20037508, -20037508, 20037508,
            20037508.34),
            controls:[new OpenLayers.Control.MouseDefaults(),
                      new OpenLayers.Control.LayerSwitcher(),
                      new OpenLayers.Control.PanZoomBar()]
        };

        map = new OpenLayers.Map( 'map' , options );

        var gmap = new OpenLayers.Layer.Google(
            "Google Physical", // the default
            {type: G_PHYSICAL_MAP, 'sphericalMercator': true}
        );
        var gsat = new OpenLayers.Layer.Google(
            "Google Satellite",
            {type: G_SATELLITE_MAP, 'sphericalMercator': true}
        );
        map.addLayers([gmap, gsat]);
        map.setCenter(new OpenLayers.LonLat(x, y), zoom);
    }

    function getWatershed(e) {
        var geojson = new OpenLayers.Format.GeoJSON();
        // Get the mercator coordinates from the viewport
        var xy = map.getLonLatFromViewPortPx(e.xy);
        // Find the watershed ID.
        var sql  = "select st_asgeojson(the_geom), id ";
            sql += "from medford.subshed2 ";
            sql += "where st_contains(the_geom,st_transform(st_setsrid(";
            sql += "st_makepoint(" + xy.lon + "," + xy.lat + ")";
            sql += ",900913),26918))";
        var config = {
              "method":"GET",
              "url":"04-sql-to-json.jsp",
              "async":false,
              "params":{"sql":sql}
              };
        var xmlhttp = OpenLayers.Request.issue(config);
        var clicked_shed = geojson.read(xmlhttp.responseText, "FeatureCollection");
            var id = clicked_shed.attributes.id;
            getFeatures(id);
        }

    function getFeatures(id) {
        var json_url = "04-sql-to-json.jsp?sql=";
        var sql = "select st_asgeojson(st_transform(withdraw.the_geom,900913)),
            shed.id
            from medford.subshed2 shed, medford.withdrawals6_opequonUTM withdraw
            where st_contains(shed.the_geom,withdraw.the_geom)
            AND shed.id = '" + id + "'";
        json_url += escape(sql);
        if (json_layer) {
        json_layer.destroy();
            }
        jsonlayer = new OpenLayers.Layer.Vector("GeoJSON", {
                strategies: [new OpenLayers.Strategy.Fixed()],
                protocol: new OpenLayers.Protocol.HTTP({
                url: json_url,
                format: new OpenLayers.Format.GeoJSON()
                })
            });
        map.addLayer(json_layer);

    }

A: You should parse response inside success function:
OpenLayers.Request.GET({
  async: false,
  url: "./04-sql-to-json.jsp",
  params: {sql: sql},
  success: function(e){
    features = geojson.read(e.responseText, "FeatureCollection");
  }
});
id = features[0].attributes.id;

A: Without knowing the exact workings of your 04-sql-to-json.jsp file, it seems as though you are building the SQL in javascript, and using the jsp to execute the query.
This is somewhat of a security hole, see SQL injection on wikipedia


Q: Spring Transaction not working I'm having a problem with transactions, when execution reaches

taskExecutor.execute();

I get an Exception:

Caused by: org.springframework.transaction.IllegalTransactionStateException: No existing transaction found for transaction marked with propagation 'mandatory'

I know this error is self-explanatory, but I can't get it to work properly.
This is how I get the controller and make the call:
ApplicationContext context = new ClassPathXmlApplicationContext("META-INF/spring/applicationContext.xml");
BeanFactory beanFactory = context;
FacadeControler f = beanFactory.getBean("facadeController");
f.method(reservation);

This is my FacadeController:
package xxx;

import ...

@Service
public class FacadeControllerImpl implements FacadeController {

    static Logger logger = Logger.getLogger(FacadeControllerImpl.class);

    @Qualifier("executor")
    @Autowired
    private TaskExecutor taskExecutor;

    @Transactional(propagation=Propagation.REQUIRED)
    public Reservation method(Reservation reservationFromEndpoint){

    ...
    taskExecutor.execute();
    ...

    }

Here is the Executor:
@Component("executor")
public class QueueTaskExecutor implements TaskExecutor {

  final static Logger logger = LoggerFactory.getLogger(QueueTaskExecutor.class);

  @Autowired
  protected QueuedTaskHolderDao queuedTaskDao;

  @Autowired
  protected Serializer serializer;

  @Override
  @Transactional(propagation=Propagation.MANDATORY)
  public void execute(Runnable task) {

      logger.debug("Trying to enqueue: {}", task);

      AbstractBaseTask abt;
      try {
          abt = AbstractBaseTask.class.cast(task);
      } catch (ClassCastException e) {
          logger.error("Only runnables that extends AbstractBaseTask are accepted.");
          throw new IllegalArgumentException("Invalid task: " + task);
      }

      // Serialize the task
      QueuedTaskHolder newTask = new QueuedTaskHolder();
      byte[] serializedTask = this.serializer.serializeObject(abt);
      newTask.setTriggerStamp(abt.getTriggerStamp());

      logger.debug("New serialized task takes {} bytes", serializedTask.length);

      newTask.setSerializedTask(serializedTask);

      // Store it in the db
      this.queuedTaskDao.persist(newTask);

      // POST: Task has been enqueued
  }

}
Here is my applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:task="http://www.springframework.org/schema/task"
   xmlns:tx="http://www.springframework.org/schema/tx"
   xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/task
 http://www.springframework.org/schema/task/spring-task-3.0.xsd
 http://www.springframework.org/schema/tx
 http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

<!-- Where to look for Spring components -->
<context:annotation-config />
<context:component-scan base-package="com.xxx"/>

<!-- @Configurable with AspectJ -->
<context:spring-configured/>

<!-- A task scheduler that will call @Scheduled methods -->
<!--     <task:scheduler id="myScheduler" pool-size="10"/> -->
<!--     <task:annotation-driven scheduler="myScheduler"/> -->

<!-- DataSource -->
<bean class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" id="myDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/bbdd"/>
    <property name="username" value="user"/>
    <property name="password" value="pass"/>
</bean>

<!-- JPA Entity Manager -->
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="myEntityManagerFactory">
    <property name="dataSource" ref="myDataSource" />
    <property name="jpaVendorAdapter">
             <bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter"></bean>
    </property>
    <property name="persistenceUnitName" value="comm_layer" />
    <property name="jpaPropertyMap">
        <map>
            <entry key="eclipselink.weaving" value="false"/>

            <entry key="eclipselink.ddl-generation" value="create-or-extend-tables"/>
            <entry key="eclipselink.logging.level" value="INFO"/>
        </map>
    </property>
</bean>

 <!-- Transaction management -->
<tx:annotation-driven mode="aspectj" />
<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
    <property name="jpaDialect">
        <bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaDialect" />
    </property>
    <property name="entityManagerFactory" ref="myEntityManagerFactory"/>
</bean>

<bean id="facadeController" class="xxx.FacadeControllerImpl">


Q: Is there a way to ask a context in EF how big its tracking set is? I'm running into what appears to be a fairly typical problem in EF.  As I continue accessing my context, the number of items it tracks and enumerates over in detect changes increases.  Eventually, everything slows to a crawl.  Here's what I'm currently doing to address the problem:
public class ContextGenerator
{
    private IContext _context;
    private string _connString;
    private int accessCount;

    public ContextGenerator(string conn)
    {
        _connString = conn;
    }

    public IContext Instance
    {
        get
        {
            if (accessCount > 100)
            {
                Dispose();
            }
            if (_context == null)
            {
                var conn = EntityConfigurationContext.EntityConnection(_connString);
                _context = new MyDbContext(conn);
                accessCount = 0;
            }
            ++accessCount;

            return _context;
        }
    }

    public void Dispose()
    {
        _context.Dispose();
        _context = null;
    }
}

This mostly works to prevent my context from getting too unwieldy, as it disposes and creates a new one every 100 accesses, but it seems very clunky and messy.  Furthermore, 100 was chosen arbitrarily and there's no guarantee that somebody won't insert a million things with only one access.  Is there a way to instead ask the context itself if it's gotten "too big"?
Or if anyone has a better idea for tackling this problem, I'm open to suggestions.

A: Each context should be a single Unit of Work, therefore I would highly recommend you have 1 context per operation (unless you relly have to).
For more info on what EF is currently tracking checkout Context.ChangeTracker


Q: XML xquery retrieve the descendent nodes value from a xml string I'm reading a XML document using XQuery in SQL Server. This is my XML:
  declare @xml as xml='
  <contactdata>
    <contacts>
      <groupkey>24</groupkey>
      <groupname>Test Group One</groupname>
      <contact>
        <contactkey>100</contactkey>
        <contactname>Test Contact One</contactname>
      </contact>
      <contact>
        <contactkey>111</contactkey>
        <contactname>Test Contact Two</contactname>
      </contact>
    </contacts>
    <contacts>
      <groupkey>26</groupkey>
      <groupname>Test Group Two</groupname>
       <contact>
        <contactkey>101</contactkey>
        <contactname>Test Contact Six</contactname>
      </contact>
    </contacts>
  </contactdata>';

In order to retrieve the each contact details under every group, I'm using this XQuery syntax
select
    c.value('(groupkey)[1]','int'),
    c.value('(groupname)[1]','nvarchar(max)'),
    c.value('(contact/contactkey)[1]','int'),
    c.value('(contact/contactname)[1]','nvarchar(max)')
from
@xml.nodes('contactdata/contacts') as Contacts(c)

But this will return only the first contact under each group.

But I need this output

Please help.

A: Just change your query to this:
select
    c.value('(../groupkey)[1]','int'),
    c.value('(../groupname)[1]','nvarchar(max)'),
    c.value('(contactkey)[1]','int'),
    c.value('(contactname)[1]','nvarchar(max)')
from
    @xml.nodes('contactdata/contacts/contact') as Contacts(c)

You need to get a list of all <contact> elements - and then extract that necessary data from those XML fragments. To get the groupkey and groupname, you can use the ../ to navigate "up the tree" one level to the parent node.


Q: GCM Notification not register for token and not receiving notifications This is my appdelegate where is my notification implementations goes on. Sometimes I register with token and token is received. But not receiving notifications. But some time there is no registration with token at all. This is my code below.

import UIKit
import UserNotifications
import RxSwift
//import Firebase
//import Messages

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    let gcmMessageIDKey = "gcm.message.shopflow.key"
    var window: UIWindow?
    let userdefaults = Foundation.UserDefaults.standard

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
//        FirebaseApp.configure()

        // [START set_messaging_delegate]
//        Messaging.messaging().delegate = self
        // [END set_messaging_delegate]
        UNUserNotificationCenter.current().delegate = self
        registerForPushNotifications()
        checkReachability()
        checkRegisterdUser()

        // Check whether the app has opened from a notification or a normal launch
        //crashing code
//        let remoteNotif = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? NSDictionary
//        if remoteNotif != nil {
//            let notifName = remoteNotif?["aps"] as! String
//            print("Notification: \(notifName )")
//        }else{
//            print("Not remote")
//        }

        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        checkReachability()
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        checkReachability()
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        checkReachability()
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

    // check connectivity
    func checkReachability(){
        if ReachabilityHelper.shared.checkNetworkReachability(){

        }else{
            showNetworkAlert()
        }
    }

    // show network alert
    func showNetworkAlert(){

        let alertController = UIAlertController(title: "Connection Error", message:"An active internet connection is needed to use this app.Please make sure you are connected and try again.", preferredStyle: .alert)

        let okAction = UIAlertAction(title:  NSLocalizedString("Retry", comment: ""), style: UIAlertActionStyle.default) {
            UIAlertAction in

            if ReachabilityHelper.shared.checkNetworkReachability(){
                //print("Connected")

            }else{
               // print("Not connected")
                self.showNetworkAlert()
            }

        }

        alertController.addAction(okAction)
        window!.rootViewController?.present(alertController, animated: true, completion: nil)
    }

    func checkRegisterdUser(){

       // let storyBoard = UIStoryboard(name: storyboardIdentifier., bundle: <#T##Bundle?#>)

        if UserDefaults.standard.bool(forKey: Key.loginStatus){
            let vc = UIStoryboard(name: storyboardIdentifier.home.rawValue, bundle: nil).instantiateViewController(withIdentifier: viewControllerIdentifiers.tabBar.rawValue) as! UITabBarController
            Constants.AppObjects.appDelegate.window?.rootViewController = vc

           // self.present(vc, animated: true, completion: nil)
        }
    }

    func registerForPushNotifications() {

//        if #available(iOS 10.0, *) {
//          // For iOS 10 display notification (sent via APNS)
//          UNUserNotificationCenter.current().delegate = self
//
//          let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
//          UNUserNotificationCenter.current().requestAuthorization(
//            options: authOptions,
//            completionHandler: {_, _ in })
//        } else {
//          let settings: UIUserNotificationSettings =
//          UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
//            UIApplication.shared.registerUserNotificationSettings(settings)
//        }
//
//        UIApplication.shared.registerForRemoteNotifications()

                    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
                        (granted, error) in
                        print("Permission granted: \(granted)")

                        guard granted else { return }
                        self.getNotificationSettings()
                    }

    }

    func getNotificationSettings() {
        UNUserNotificationCenter.current().getNotificationSettings { (settings) in
            print("Notification settings: \(settings)")
            guard settings.authorizationStatus == .authorized else { return }
            DispatchQueue.main.async(execute: {
                UIApplication.shared.registerForRemoteNotifications()
            })
        }
    }

//    private func application(_ application: UIApplication, didRegister notificationSettings: UNNotificationSettings) {
////        if notificationSettings. != UIUserNotificationType() {
//        application.registerForRemoteNotifications()
////      }
//    }

    // This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
    // If swizzling is disabled then this function must be implemented so that the APNs token can be paired to
    // the FCM registration token.
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
        userdefaults.set("NA", forKey: "DEVICE_TOKEN")
        userdefaults.synchronize()
      print("Registration failed!")
    }

    func application(_ application: UIApplication,
                     didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        // With swizzling disabled you must set the APNs token here.
        // Messaging.messaging().apnsToken = deviceToken

        let tokenParts = deviceToken.map { data -> String in
            return String(format: "%02.2hhx", data)
        }

        let token = tokenParts.joined()
        print("Device Token: \(token)")
        userdefaults.set(token, forKey:"DEVICE_TOKEN")
        userdefaults.synchronize()

        _ = HomeViewModel().deviceToken().subscribe(onNext:{ message in

            if message == response.success.rawValue{
                //print("Signup done")
                print("new Device Token device registation")
            }else if message != ""{
               print("shopErrors:fail Device Token device registation")
                //print(alertMessage)
            }

        }).disposed(by: DisposeBag())

    }

//    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
//
//        if let remoteNotification = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as! [NSObject : AnyObject]? {
//
//        }
//    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
      // If you are receiving a notification message while your app is in the background,
      // this callback will not be fired till the user taps on the notification launching the application.
      // TODO: Handle data of notification

      // With swizzling disabled you must let Messaging know about the message, for Analytics
      // Messaging.messaging().appDidReceiveMessage(userInfo)

      // Print message ID.
      if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
      }

      // Print full message.
      print(userInfo)
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                     fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
      // If you are receiving a notification message while your app is in the background,
      // this callback will not be fired till the user taps on the notification launching the application.
      // TODO: Handle data of notification

      // With swizzling disabled you must let Messaging know about the message, for Analytics
      // Messaging.messaging().appDidReceiveMessage(userInfo)

      // Print message ID.
      if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
      }

      // Print full message.
      print(userInfo)

      completionHandler(UIBackgroundFetchResult.newData)
    }

    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
      // Let FCM know about the message for analytics etc.
//        Messaging.messaging().appDidReceiveMessage(userInfo)
      // handle your message
    }

}

@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {

  // Receive displayed notifications for iOS 10 devices.
  func userNotificationCenter(_ center: UNUserNotificationCenter,
                              willPresent notification: UNNotification,
    withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let userInfo = notification.request.content.userInfo

    // With swizzling disabled you must let Messaging know about the message, for Analytics
    // Messaging.messaging().appDidReceiveMessage(userInfo)

    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
      print("Message ID: \(messageID)")
    }

    // Print full message.
    print(userInfo)

    // Change this to your preferred presentation option
    completionHandler([.alert, .sound, .badge])
  }

  func userNotificationCenter(_ center: UNUserNotificationCenter,
                              didReceive response: UNNotificationResponse,
                              withCompletionHandler completionHandler: @escaping () -> Void) {
    let userInfo = response.notification.request.content.userInfo
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
      print("Message ID: \(messageID)")
    }

    // Print full message.
    print(userInfo)

    completionHandler()
  }

  func registerForPushNitfication(){
    registerForPushNotifications()
  }
}

//extension AppDelegate: MessagingDelegate{
//    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
//        let dataDic: [String: String] = ["token": fcmToken]
//        NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDic)
//
//        userdefaults.set(dataDic["token"], forKey:"DEVICE_TOKEN")
//        userdefaults.synchronize()
//
//        _ = HomeViewModel().deviceToken().subscribe(onNext:{ message in
//
//            if message == response.success.rawValue{
//                //print("Signup done")
//                print("shopErrors:new Device Token device registation")
//            }else if message != ""{
//               print("shopErrors:fail Device Token device registation")
//                //print(alertMessage)
//            }
//
//        }).disposed(by: DisposeBag())
//    }
//
//}

I register for APNs and enable push notifications and also background notification fetch capability. But I couldn't resolve this. Anyone can find an answer?


Q: Unable to configure Swagger in Spring project, getting File not found exception I am trying to configure swagger for my spring application. Below is the configuration. However, getting an error
[springfox/documentation/spring/web/SpringfoxWebMvcConfiguration.class] cannot be opened because it does not exist
Spring version - 4.0.4
Springfox version - 2.9.2
It's NOT a maven project, I have all the required jar files added to the classpath.
Spring-context.xml
<bean id="Swagger" class="skt.test.SwaggerConfig" />

<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/"/>

    <mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>

Swagger config class
package skt.test;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
@EnableWebMvc
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
          .select()
          .apis(RequestHandlerSelectors.any())
          .paths(PathSelectors.any())
          .build();

    }

}

Jar files included
https://i.imgur.com/sYaYnrY.png
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to load bean class: skt.test.SwaggerConfig; nested exception is java.io.FileNotFoundException: class path resource [springfox/documentation/spring/web/SpringfoxWebMvcConfiguration.class] cannot be opened because it does not exist
    at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:160)
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:299)
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:243)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:254)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:94)
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:609)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4682)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5143)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1384)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1374)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:909)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:841)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1384)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1374)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:909)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:421)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:932)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:633)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:344)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:475)
Caused by: java.io.FileNotFoundException: class path resource [springfox/documentation/spring/web/SpringfoxWebMvcConfiguration.class] cannot be opened because it does not exist
    at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:172)
    at org.springframework.core.type.classreading.SimpleMetadataReader.<init>(SimpleMetadataReader.java:50)
    at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:82)
    at org.springframework.core.type.classreading.CachingMetadataReaderFactory.getMetadataReader(CachingMetadataReaderFactory.java:102)
    at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:77)
    at org.springframework.context.annotation.ConfigurationClassParser.asSourceClass(ConfigurationClassParser.java:551)
    at org.springframework.context.annotation.ConfigurationClassParser$SourceClass.getRelated(ConfigurationClassParser.java:760)
    at org.springframework.context.annotation.ConfigurationClassParser$SourceClass.getAnnotationAttributes(ConfigurationClassParser.java:741)
    at org.springframework.context.annotation.ConfigurationClassParser.collectImports(ConfigurationClassParser.java:366)
    at org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:340)
    at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:249)
    at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:206)
    at org.springframework.context.annotation.ConfigurationClassParser.processImports(ConfigurationClassParser.java:426)
    at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:249)
    at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:206)
    at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:174)
    at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:156)
    ... 39 more

A: You need below library ,
     <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.5.0</version>
    </dependency>

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

If you are not using pom just download it from
https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui/2.5.0
https://mvnrepository.com/artifact/io.springfox/springfox-swagger2/2.5.0
To get more insight you can follow here
https://github.com/mayurbavisiya/Spring4Swagger
In your spring file you need to write
<mvc:resources mapping="/swagger-ui.html" location="classpath:/META-INF/resources/swagger-ui.html"/>

Hope this will help you out.


Q: ResourceReferenceKeyNotFoundException on NotifyIcon I'm using WPF NotifyIcon, and actually I'm trying to learn how to display a simple NotifyIcon in the system tray. Actually In the MainWindow I put this code:
 private TaskbarIcon tb;

 public MainWindow()
 {
      InitializeComponent();
 }

 private void MetroWindow_StateChanged(object sender, EventArgs e)
 {
      if (WindowState == WindowState.Minimized)
      {
          tb = (TaskbarIcon)FindResource("TestNotifyIcon");
      }
 }

essentially when the main window is minimized the tb should show the Icon declared in a Dictionary like this:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:local="clr-namespace:PrimoCalendarExport.Utils.Resources.UIDictionary"
                xmlns:tb="http://www.hardcodet.net/taskbar">

<tb:TaskbarIcon x:Key="TestNotifyIcon"
              IconSource="/Utils/Images/Test.ico"
              ToolTipText="hello world" />

</ResourceDictionary>

this dictionary of resource is located inside a folder, in particular:
Project name
   \Utils
       \Resources
          \Dictionary
             \InlineToolTip.xaml

Now the problem's that when I minimize the main window I get this error:

ResourceReferenceKeyNotFoundException

so seems that the TestNotifyIcon can't be located in the project. I don't know what am I doing wrong, I followed all the steps of the tutorial, someone maybe know my mistake? Thanks.

A: It appears you are looking in the wrong place for the resource. You are looking in the XAML of the metro window however you should be looking in the main window XAML specify to the program where to look using something like this: (I am not currently on visual studio)
 private void MetroWindow_StateChanged(object sender, EventArgs e)
 {
      if (WindowState == WindowState.Minimized)
      {
          tb = (TaskbarIcon)this.FindResource("TestNotifyIcon");
      }
 }

or
 private void MetroWindow_StateChanged(object sender, EventArgs e)
 {
      if (WindowState == WindowState.Minimized)
      {
          tb = (TaskbarIcon)MainWindow.FindResource("TestNotifyIcon");
      }
 }


Q: How to remove figure caption prefix "figure" in beamer I am trying to remove the caption prefix, "Figure", for my figures in beamer. I tried doing this but it made no difference.
Heres a minimum working example:
As you can see, I have included the caption package.
\documentclass{beamer}

\usepackage{graphicx}
\usepackage{subfigure}
\usepackage{subfig}
\usepackage{epstopdf}
\usepackage{hyperref}
\usepackage{amsmath}
\usepackage[labelformat=empty]{caption}
\usepackage{setspace}
\usepackage[T1]{fontenc}
\usepackage[super,numbers,sort&compress]{natbib}
\usepackage[labelformat=empty]{caption}

% \usepackage{makeidx}
% \usepackage{sidecap}

\setbeamertemplate{footline}[page number]
%\setbeamercolor{structure}{bg=yellow, fg=black}
\usetheme{CambridgeUS}

\logo{%
\includegraphics[scale=0.25]{logo1}%
\hspace{\dimexpr\paperwidth-4cm}
\includegraphics[height=1cm]{logo2}%
}%

\begin{document}

\title[PT]{Presentation Title}
\author[Author1]{List of Authors}
\institute[Univ]{University Name}

\begin{frame} % Cover slide
\titlepage
\end{frame}

\frame{
\frametitle{Evaporating liquid film, G=0.0, S=100, M=35.1, Pr=7.02, E=0.0001, R=0}

\begin{figure}
 \begin{center}
   \includegraphics[scale=0.21]{/home/userid/Research/Dissertation/wigner/montage_evap/Evap_zg_2wl}
    \caption{Wavenumber k=2}
 \end{center}
\end{figure}

}

A: I've been having trouble with the caption package in Beamer, and the options above using this package weren't working for me.
However, this in the preamble seemed to do the trick:
\setbeamertemplate{caption}{\insertcaption}

A: You can use the caption package:
\documentclass{beamer}

\usepackage{caption}
\captionsetup[figure]{labelformat=empty}% redefines the caption setup of the figures environment in the beamer class.

\begin{document}
\frame{
\begin{figure}
\caption{Test}
\end{figure}

\begin{table}\caption{test}
\centering
\begin{tabular}{|c|c|}
c&c
\end{tabular}
\end{table}}
\end{document}

Notice that since I am only redefining the caption style for figures the rest are left intact as defined by the beamer class.

A: The solution is very simple. Just put the caption below the \includegraphics... command with a double left slash. You don't need to use the caption command, only if you need to number figures, which is note very common in a presentation:
\centering
\includegraphics...
\\ <your caption here>

A: I use the caption* command instead of caption, which removes the prefix in the Beamer slides.

A: None of the answers worked for me, I had the same problem. I tried this one in the preamble and it does the job requested:
\captionsetup{labelformat=empty,labelsep=none}

A: Renew caption template
\documentclass{beamer}

\begin{document}
\setbeamertemplate{caption}{\raggedright\insertcaption\par}

\frame{
\begin{figure}
\rule{5cm}{5cm}
\caption{Test}
\end{figure}
}

\end{document}

No need to load any other packages. You may even add some fancy stuff like a
\setbeamertemplate{caption}{%
\begin{beamercolorbox}[wd=.5\paperwidth, sep=.2ex]{block body}\insertcaption%
\end{beamercolorbox}%
}

Which basically gives you a colored box around the caption (when a color-theme is used).
You can use :
\setbeamertemplate{caption}[default]

if you want to switch back the parameter to its default value, for example if you want the change to be only local.

A: Do not use the commands \begin{figure}, \caption and \end{figure}.
Just use \includegraphics[scale=0.4]{fig.eps}


Q: How to post values of each item in model from view to controller as a List or Array? example of view priority list of orders
i have a orders model, i need the user to arrange orders in order of priority by numbers.
for each order a different number of priority and post to the controller the id of the order and the priority number that he selected for the order.
post it to the controller as a list/array of pairs (id, position).
and also how to receive in the actionResult a list/array of value pairs.
this is my PackerController:
    public ActionResult SetByCity(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        var supplier = db.Suppliers.Where(s => s.Id == id).FirstOrDefault();

        var mySupplierOrders = db.Orders.Where(o => o.SupplierId == supplier.Id && o.SupplierApproval == 1).Include(o => o.Clients).Include(o => o.Suppliers);
        return View(mySupplierOrders.OrderBy(o => o.Clients.BusinessAddress).ToList());
    }

and this is the view for "SetByCity":
    @foreach (var item in Model)
    {

                @Html.DisplayFor(modelItem => item.Id)

                @Html.DisplayFor(modelItem => item.Clients.BusinessName)

                @Html.DisplayFor(modelItem => item.Clients.BusinessAddress)

                @Html.DisplayFor(modelItem => item.CreateDate)

                @Html.DisplayFor(modelItem => item.PayDate)

                @Html.DisplayFor(modelItem => item.Discount)

                @Html.DisplayFor(modelItem => item.TotalPrice)

                <form method="post" action="@Url.Action("SetOrdersPosition", "Packer")" id="editform">
                    <input type="hidden" name="Id" value="@item.Id">
                    <input type="number" name="Position" min="1" max="@Model.Count()">@*i need to put all the positions and id's of all the items in a pairs list and send it to the controller*@
                </form>

    }

<input type="submit" value="send" form="editform" />

and this is the receiving actionResult "SetOrdersPosition" in the PackerController:
    [HttpPost]
    public ActionResult SetOrdersPosition(List<id,position>)
    {
        //does something...
    }

i don't know what to put in the parameters that the SetOrdersPosition gets...

A: Hope you are using the Model name called "Suppliers".
So in get method pass that into view.
You needs to do come little changes accordingly to use Begin Form in your view, so that you can directly post your model data to controller.
Use this item inside body.
Don't forget to declare the model which you are using in the view page like below.
@model MVC.Models.Suppliers
@using (Html.BeginForm("SetOrdersPosition", "Packer", FormMethod.Post))
    {

        @foreach (var item in Model)
           {

            @Html.DisplayFor(modelItem => item.Id)

            @Html.DisplayFor(modelItem => item.Clients.BusinessName)

            @Html.DisplayFor(modelItem => item.Clients.BusinessAddress)

            @Html.DisplayFor(modelItem => item.CreateDate)

            @Html.DisplayFor(modelItem => item.PayDate)

            @Html.DisplayFor(modelItem => item.Discount)

            @Html.DisplayFor(modelItem => item.TotalPrice)

            <input type="submit" value="Submit"/>

     }

}

Controller Code [HttpPost]
 public ActionResult SetOrdersPosition(Suppliers _suppliers)
  {
    //does something...
  }


Q: Expanding to consumer to cater for each producer? I have the following socket connection codes. Where for every connection is one new thread. After receiving the data which is done via the producer then I put into a queue for next database processor which is the consumer. This works fine but the moment the queue gets build up it can hang or even take even hours to clear cause is like so many producers and just one single consumer. I am thinking is it possible for me to have one consumer handles one producer meaning each message goes into its own queue gets process and that it. What changes can I do to handle it or must I build a thread pooling ?
public class cServer {
   private LinkedBlockingQueue<String> databaseQueue = new LinkedBlockingQueue<String>();
   class ConnectionHandler implements Runnable {

    private Socket receivedSocketConn1;
    ConnectionHandler(Socket receivedSocketConn1) {
      this.receivedSocketConn1=receivedSocketConn1;
    }
      // gets data from an inbound connection and queues it for databse update
      public void run() { // etc

         // you already have most of this in your existing code.
         // it uses the shared databaseQueue variable to queue message Strings
         BufferedWriter w = null;
         BufferedReader r = null;
          String message="";
          try {

             PrintStream out = System.out;
             BufferedWriter fout = null;
             w =  new BufferedWriter(new OutputStreamWriter(receivedSocketConn1.getOutputStream()));
             r = new BufferedReader(new InputStreamReader(receivedSocketConn1.getInputStream()));

             int m = 0, count=0;
             int nextChar=0;

             while ((nextChar=r.read()) != -1)
             {

                  message += (char) nextChar;

                  if (nextChar == '*')
                  {

                     databaseQueue.add(message);
                     message="";
                  }
                 }
              }
              catch (IOException ex)
              {
                   System.out.println("MyError:IOException has been caught in in the main first try");
                   ex.printStackTrace(System.out);
              }
              finally
              {
                try
                {

                    if ( w != null )
                    {
                        w.close();
                    }
                    else
                    {
                        System.out.println("MyError:w is null in finally close");
                    }
                }
                catch(IOException ex){
                   System.out.println("MyError:IOException has been caught in w in finally close");
                   ex.printStackTrace(System.out);
                }

              }
      }

   }

   class DatabaseProcessor implements Runnable {

      // updates databaase with data queued by ConnectionHandler
      Connection dbconn = null;
      Statement stmt = null;
      Statement stmt1 = null;
      Statement stmt2 = null;
      Date connCreated = null;
      public void run()
      { // this is just like the QueueProcessor example I gave you
         // open database connection
         //createConnection();
             while (true)
             {

                try
                {
                    int count=0;
                    String message = "";
                    message = databaseQueue.take();
                    if (message.equals(null)) {
                       System.out.println("QueueProcessor is shutting down");
                    break; // exit while loop, ends run() method
                    }
                    System.out.println("Message taken from queue is :"+message);

                }
                catch (Exception e)
                {
                e.printStackTrace();
                }
            }//while true
           //closeConnection();
     }//run
   }

   public static void main(String[] args) {
      new cServer();
   }
   cServer() { // default constructor
      new Thread(new DatabaseProcessor()).start();
      try
      {
               final ServerSocket serverSocketConn = new ServerSocket(5000);
               while (true)
                    {
                        try
                        {
                                Socket socketConn1 = serverSocketConn.accept();
                                new Thread(new ConnectionHandler(socketConn1)).start();
                        }
                        catch(Exception e)
                        {
                            System.out.println("MyError:Socket Accepting has been caught in main loop."+e.toString());
                            e.printStackTrace(System.out);
                        }
                    }
      }
      catch (Exception e)
      {
         System.out.println("MyError:Socket Conn has been caught in main loop."+e.toString());
         e.printStackTrace(System.out);
         //System.exit(0);
      }
      databaseQueue.add(null);
   }
}