text:
Q: How can I hide the loading spinner when the HTTP call is finished? I have a simple HTTP get call with angularJS
  $http({
        method: 'GET',
        url: 'Dashboard/GetDashboard'
    }).then(function successCallback(response) {
        $scope.dashboard = response.data;
    }, function errorCallback(response) {
        console.log(response);
    });

Sometimes the performance is very low when the dashboard is loading and I want to use a loading spinner from font-awesome. This is my HTML code on the index.

I know I have to use ng-hide for it but I don't know what expression I have to use.
When the HTTP call is finished I want to hide the loading spinner.
Can someone point me in the right direction?
Kind regards

A: so here is the solution assign a scope variable
$scope.loading = false;

when you do server call make this value true like
$scope.loading = true;

and after your results come make it to $scope.loading = false;
and in HTML use

so whenever loading is true this  tag will be visible.

A: Use some boolean variable and put it before your call and on success make it true like below :
    Using ng-hide
    $scope.isSpinnerHidden = false;
    $http({
            method: 'GET',
            url: 'Dashboard/GetDashboard'
        }).then(function successCallback(response) {
            $scope.dashboard = response.data;
            $scope.isSpinnerHidden = true;
        }, function errorCallback(response) {
            console.log(response);
        });

OR
Use ng-show like below
$scope.isSpinnerHidden = true;
    $http({
            method: 'GET',
            url: 'Dashboard/GetDashboard'
        }).then(function successCallback(response) {
            $scope.dashboard = response.data;
            $scope.isSpinnerHidden = false;
        }, function errorCallback(response) {
            console.log(response);
        });

Hope it helps !!


text:
Q: How to use listagg in hibernate I am trying to use listagg function to generate a list of users.
Consider the following table
 ROLE_ID    ENAME
---------- ----------
       4    CLARK
       4    KING
       4    MILLER
       7    ADAMS
       9    FORD
       9    JONES

On using the following query in the SQL Developer
SELECT ROLE_ID,
       LISTAGG(ENAME, ',') WITHIN GROUP (ORDER BY ENAME) AS EMPLOYEES
FROM USERS
GROUP BY ROLE_ID;

will result in the following in the console output
ROLE_ID EMPLOYEES
-----------------------------
4        CLARK,KING,MILLER
7        ADAMS
9        FORD, JONES

My goal is try doing this in hibernate but I am not sure how to proceed.
Any help is appreciated.

A: For anyone having problems using listagg as part of a formula, registering the "within" keyword with Hibernate solved the problem for me. (Using Hibernate 5.0.7.)
public class CustomOracleDialect extends Oracle10gDialect {
    public CustomOracleDialect() {
        super();

        registerKeyword("within");
    }
}

Prior to this, Hibernate would break the query by attempting to prefix the "within" keyword with the outer table's alias. Once the keyword was registered the following works:
@Formula("(select (listagg(l.serial_number, ', ') within group(order by d.serial_number))\n"
        + "from order_lines l\n"
        + "where l.order_id = id\n"
        + "group by l.order_id)")
private String serialNumbers;

Note that if you try to assign an alias to the listagg expression it still breaks the query, as Hibernate tries to prepend it with the table's alias as well. This of course is not an issue with formula queries, but if using listagg as part of a named query you may need to omit the alias and reference the column by position within the result set.

A: We found a good solution.
@Formula("(select (listagg(l.serial_number, ', ') \00within group(order by d.serial_number))\n"
    + "from order_lines l\n"
    + "where l.order_id = id\n"
    + "group by l.order_id)")
private String serialNumbers;

Just append the \00 before WITHIN keyword.
And you don't need to extends anything.
Cheers.

A: Hibernate doesn't understand sql function be default. Try registering in hibernateDialect.
registerFunction("listAgg", new StandardSQLFunction("listAgg", Hibernate.STRING));

A: Registering of listagg method is not working in hibernate dialect .              Try with registering wm_concat method , it worked for me ..
Find below code ..
public class ServiceAppOracle10gDialect extends Oracle10gDialect {
     public ServiceAppOracle10gDialect() {
            super();
            //registerFunction("LISTAGG", new StandardSQLFunction("LISTAGG", StandardBasicTypes.STRING));
            registerFunction("wm_concat", new StandardSQLFunction("wm_concat", StandardBasicTypes.STRING));
        }
}

And make sure that u have changed your hibernate.dialect property ..
<!--                <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop> -->
                <prop key="hibernate.dialect">com.apple.sc.analytics.utils.ServiceAppOracle10gDialect</prop>

A: After a lot struggle i found this solution. I think it will help you all.You can register LISTAGG function like below
registerFunction("LISTAGG", new SQLFunctionTemplate( StandardBasicTypes.STRING,"LISTAGG(?1,',') WITHIN GROUP(ORDER BY ?1)"));

and you can use LISTAGG(<columnname>) in your hibernate query

A: To use listagg in hibernate query

*

*First register listagg function in Hibernate Dialect by extending Oracle10gDialect(in case you are using Oracle) or MySQLDialect(for MySQL)

public class CustomOracle10gDialect extends Oracle10gDialect {
     public CustomOracle10gDialect() {
         super();
         registerFunction("LISTAGG", new SQLFunctionTemplate(StandardBasicTypes.STRING,"LISTAGG(?1,',') WITHIN GROUP(ORDER BY ?1)"));
    }
}

*Update your config file to use custom dialect.
spring.jpa.database-platform=com.abc.CustomOracle10gDialect
or
com.abc.CustomOracle10gDialect

*Use LISTAGG()
Example -
select c.id, listagg(firstName) from Contacts c where  GROUP BY c.id

redpajama_set_name: RedPajamaStackExchange


text:
Q: Horizontal center variable width div within div, mouse events beside must pass through? How can I horizontally center a variable-width div within another div with a specific offset from the top (or vertically centered as well)? An extra condition is that only the visible part of the div must intercept mouse events -- this limits some of the options.
+--------------+
|  outer div   +
|   <innner>   +
+--------------+

inner contains clickable elements and must be at the top of the stacking order. The outer div is clickable as well, thus the area around inner must pass mouse events to the underlying div. inner is a variable width. inner must have some offset from the top of outer.
I know there are a lot of related centering questions, but the mouse events aspect here makes this different.

A: Let's say you have an outer div with the class outer, and inside it there's another div having class="inner".
The centering can be achieved by css:
.outer {
    height: 100px;
    width: 200px;
    line-height: 100px;
    border: 1px solid red;
    text-align: center;
}

.inner {
    height: 50px;
    line-height: 50px;
    display: inline-block;
    vertical-align: middle;
    text-align: center;
    border: 1px solid blue;
}

I added click events to the outer div, and for the button inside the inner div. The button click will propagate to the outer div by default.
Demo: http://jsfiddle.net/er144/bh3V9/


text:
Q: How to write php code inside jquery I tried all possible ways to write php code inside a jquery code. Here is my code snippet:
 $('body').on('click', '.add_more', function(){
     var plugin_dir = "<?php plugins_url(); ?>";
     console.log(plugin_dir);
 });

Even I tried as follows:
$('body').on('click', '.add_more', function(){
    var plugin_dir = <?php plugins_url(); ?>;
    console.log(plugin_dir);
});

I am writing this code inside a wordpress plugin php file. I apologize if this question is duplicate. It kills my day. Any idea?

A: Instead of assigning value that way you can use wp_localize_script() or wp_add_inline_script() and create a plugin configuration JS object to use that everywhere.
PHP file
add_action( 'wp_enqueue_scripts', function() {
    wp_enqueue_script(
        'script-handle',
        'your-script-uri/script.js',
        array( 'jquery' ),
        'version',
        true
    );

    wp_localize_script(
        'script-handle',
        'pluginNameSpace',
        array(
            'url' => plugins_url()
        )
    );
} );

JS file
$('body').on('click', '.add_more', function(){
    console.log( pluginNameSpace.url );
});

A: You just need to echo the plugins_url()
$('body').on('click', '.add_more', function(){
     var plugin_dir = "<?php echo plugins_url(); ?>";
     console.log(plugin_dir);
 });


text:
Q: how to keep text box and button in the same line in html I want to keep text box and button in the same line, but it's coming in two different lines:

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">

    <button class="btn btn-primary" onclick="AddEditExpenses(0)">Add Expense</button>
    <button class="btn btn-success" onclick="ReportExpense()">Expense Report</button>

    <form asp-controller="Expense" asp-action="Index" class="form-group">

            <input class="form-control" type="text" name="SearchString" placeholder="Search">
            <button type="submit" class="btn btn-default btn-info">Filter</button>

    </form>

A: Make your parent element, containing the input and button element a flex box. I used the bootstrap utility classes to achieve this. I added a small margin to the input element as well, also using a bootstrap utility class.

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">

    <button class="btn btn-primary" onclick="AddEditExpenses(0)">Add Expense</button>
    <button class="btn btn-success" onclick="ReportExpense()">Expense Report</button>

    <form asp-controller="Expense" asp-action="Index" class="form-group">

        <input class="form-control mr-1" type="text" name="SearchString" placeholder="Search">
        <button type="submit" class="btn btn-default btn-info">Filter</button>

    </form>

A: Probably the best way to achieve exactly what you want is something like this

      <button class="btn btn-primary" onclick="AddEditExpenses(0)">Add Expense</button>
      <button class="btn btn-success" onclick="ReportExpense()">Expense Report</button>

    <form asp-controller="Expense" asp-action="Index" class="form-group col-sm-4 d-flex">
      <input class="form-control" type="text" name="SearchString" placeholder="Search">
      <button type="submit" class="btn btn-default btn-info">Filter</button>
    </form>

A: The "Filter" button goes in the second line since Bootstrap's form-control class has display: block and width: 100%. Change display: inline-block and reduce width: 50%.

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">

    <button class="btn btn-primary" onclick="AddEditExpenses(0)">Add Expense</button>
    <button class="btn btn-success" onclick="ReportExpense()">Expense Report</button>

    <form asp-controller="Expense" asp-action="Index" class="form-group">

        <input class="form-control" type="text" name="SearchString" placeholder="Search" style="display: inline-block; width: 50%;">
        <button type="submit" class="btn btn-default btn-info">Filter</button>

    </form>

A:

 <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>

     <button class="btn btn-primary" onclick="AddEditExpenses(0)">Add Expense</button>
     <button class="btn btn-success" onclick="ReportExpense()">Expense Report</button>

     <form asp-controller="Expense" asp-action="Index" class="form-group">

             <input class="form-control" type="text" name="SearchString" placeholder="Search">
             <button type="submit" class="btn btn-default btn-info ml-2">Filter</button>

     </form>


text:
Q: Unsupported sampling flex/actionscript In action script i need
  Loading configuration file /opt/flex/frameworks/flex-config.xml
  t3.mxml(10): Error: unsupported sampling rate (24000Hz)

        [Embed(source="music.mp3")]

     t3.mxml(10): Error: Unable to transcode music.mp3.

        [Embed(source="music.mp3")]

The code is
         <?xml version="1.0"?>
   <!-- embed/EmbedSound.mxml -->
  <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">

  <mx:Script>
    <![CDATA[

        import flash.media.*;

        [Embed(source="sample.mp3")]
        [Bindable]
        public var sndCls:Class;

        public var snd:Sound = new sndCls() as Sound;
        public var sndChannel:SoundChannel;

        public function playSound():void {
            sndChannel=snd.play();
        }

        public function stopSound():void {
            sndChannel.stop();
        }
    ]]>
</mx:Script>

<mx:HBox>
    <mx:Button label="play" click="playSound();"/>
    <mx:Button label="stop" click="stopSound();"/>
</mx:HBox>
</mx:Application>

A: From livedocs:

"Flash can import either 8- or 16-bit sounds at sample rates of 11, 22, or 44 kHz. Sounds recorded in formats that are not multiples of 11 kHz (such as 8, 32, or 96 kHz) are resampled when imported into Flash. Flash can convert sounds to lower sample rates on export."

Flex Builder will not do it for you so you need to downsample the "music.mp3" file to 22kHz manually before using it.
Edit:
I can't find proper documentation but here it says:

"Sound Sample Rate - measured in Hz, this is fixed when the sound file is first recorded, and Flash .SWF files only allow four rates.
The Flash SWF format has sampling rates of:
5500 Hz
11025 Hz
22050 Hz
44100 Hz (preferred setting)"

A: You can remove the ID3v2 tag, and it should work.  I think it's the APIC.
So anyone who is facing problems embedding MP3 files, download ID3 Remover: http://sourceforge.net/projects/id3remover/files/id3remover/v1.2/ID3Remover_1_2.zip/download .


text:
Q: What aspects should I be wary of when choosing a web development framework? I am a relatively new to the world of software development and I've used the Ruby on Rails framework to develop relatively simple applications before. I know that frameworks can be extremely useful in terms of getting applications up and running quite quickly.
However I also know about the well documented problems that Rails had in terms scalability, and I was wondering if there were any other factors that I should be wary of before deciding to use a web frameworks in general aside from scalability, particularly when designing non-trivial business applications.

A: First and foremost, I would look for a framework that

*

*has an active, helpful community

*is well-documented

*is written in a way you understand

*has a history of responding quickly to bugs in general and security problems in particular

It is important that you understand what the framework does. While a framework helps you to avoid boilerplate code and also often gives you a hand up with structuring your application, like any abstraction layer, you still need to understand how it works and what that means for your application (in regards to structure, performance, security...). So look for a framework you feel comfortable with and that does not look like lots of voodoo magic to you.


text:
Q: How to create reusable custom modal component in React? I have a problem with the concept of modals in React. When using server side rendered templates with jQuery I was used to have one empty global modal template always available (included in base template that was always extended). Then when making AJAX call I just populated modal..something like this:
$('.modal-global-content').html(content);
$('.modal-global').show();

So how do I make this concept in React?

A: There are a few ways of doing this. The first involves passing in the modal state from a parent component. Here's how to do this - first with the parent App.js component:
// App.js

import React from "react";

import Modal from "./Modal";

const App = () => {
  const [showModal, updateShowModal] = React.useState(false);

  const toggleModal = () => updateShowModal(state => !state);

  return (

Not a modal

      <button onClick={toggleModal}>Show Modal</button>
      <Modal canShow={showModal} updateModalState={toggleModal} />

  );
}

export default App;

And here's the Modal.js child component that will render the modal:
// Modal.js

import React from "react";

const modalStyles = {
  position: "fixed",
  top: 0,
  left: 0,
  width: "100vw",
  height: "100vh",
  background: "blue"
};

const Modal = ({ canShow, updateModalState }) => {
  if (canShow) {
    return (

I'm a Modal!

        <button onClick={updateModalState}>Hide Me</button>

    );
  }

  return null;
};

export default Modal;

This way is perfectly fine, but it can get a bit repetitive if you're reusing the modal in many places throughout your app. So instead, I would recommend using the context API.
Define a context object for your modal state, create a provider near the top of your application, then whenever you have a child component that needs to render the modal, you can render a consumer of the modal context. This way you can easily nest your modal deeper in your component tree without having to pass callbacks all the way down. Here's how to do this - first by creating a context.js file:
// context.js

import React from "react";

export const ModalContext = React.createContext();

Now the updated App.js file:
// App.js

import React from "react";

import { ModalContext } from "./context";
import Modal from "./Modal";

const App = () => {
  const [showModal, updateShowModal] = React.useState(false);

  const toggleModal = () => updateShowModal(state => !state);

  return (
    <ModalContext.Provider value={{ showModal, toggleModal }}>

Not a modal

        <button onClick={toggleModal}>Show Modal</button>
        <Modal canShow={showModal} updateModalState={toggleModal} />

    </ModalContext.Provider>
  );
}

export default App;

And lastly the updated Modal.js file:
// Modal.js

import React from "react";

import { ModalContext } from "./context";

const modalStyles = {
  position: "fixed",
  top: 0,
  left: 0,
  width: "100vw",
  height: "100vh",
  background: "blue"
};

const Modal = () => {
  return (
    <ModalContext.Consumer>
      {context => {
        if (context.showModal) {
          return (

I'm a Modal!

              <button onClick={context.toggleModal}>Hide Me</button>

          );
        }

        return null;
      }}
    </ModalContext.Consumer>
  );
};

export default Modal;

Here's a Codesandbox link with a working version using context. I hope this helps!

A: One way you can solve this problem by using css and JSX.
this is the app and i can have anything like a button a link anything
Lets assume we have a link (react-router-dom) which redirects us to
a DeletePage
The Delete Page renders a Modal
You will provide the title and the actions of the Modal as props
const App = () => {
  return(
    <Link to="/something/someid">SomeAction</Link>
  )
}

const DeletePage = () => {
  return(
    <Modal
      title="Are you sure you want to delete this"
      dismiss={() => history.replace("/")}
      action={() => console.log("deleted") }
      />
  )
}

Modal

const Modal = (props) => {
  return(

{props.title}

        <button onClick={props.dismiss}>Cancel</button>
        <button onClick={props.action}>Delete</button>

    )
}

*

*set the z-index of the modal a high number

*position: fixed of the modal component

*when the user will click on the background the model will go away (
many ways to implement that like with modal state, redirect, etc i
have taken the redirect as one of the ways )

*cancel button also has the same onClick function which is to dismiss

*Delete button has the action function passed through props

this method has a flaw because of css because if your parent component
has a position property of relative then this will break.
The modal will remain inside the parent no matter how high the z-index is

To Save us here comes React-Portal

React portal creates a 'portal' in its own way

The react code you might have will render inside DOM with id of #root ( in most cases )

So to render our Modal as the top most layer we create another
DOM element eg

 in the public index.html file

The Modal react component code will slightly change

const Modal = (props) => {
  return ReactDOM.createPortal(

{props.title}

        <button onClick={props.dismiss}>Cancel</button>
        <button onClick={props.action}>Delete</button>

    ),document.querySelector("#modal")
}

rest is all the same

A: Using React-Portal and Modal Generator
I have been toiling my days finding a good, standard way of doing modals in react. Some have suggested using local state modals, some using Modal Context providers and using a function to render a modal window, or using prebuilt ui libraries like ChakraUI that provides it's own Modal component. But using these can be a bit tricky since they tend to overcomplicate a relatively easy concept in web ui.
After searching for a bit, I have made peace with doing it the portal way, since it seems to be the most obvious way to do so. So the idea is, create a reusable modal component that takes children as props and using a local setState conditionally render each modal. That way, every modal related to a page or component is only present in that respective component.
Bonus:
For creating similar modals that uses the same design, you can use a jsx generator function that takes few colors and other properties as its arguments.
Working code:
// Generate modals for different types
// All use the same design
// IMPORTANT: Tailwind cannot deduce partial class names sent as arguments, and
// removes them from final bundle, safe to use inline styling
const _generateModal = (
  initialTitle: string,
  image: string,
  buttonColor: string,
  bgColor: string = "white",
  textColor: string = "rgb(55 65 81)",
  buttonText: string = "Continue"
) => {
  return ({ title = initialTitle, text, isOpen, onClose }: Props) => {
    if (!isOpen) return null;
    return ReactDom.createPortal(

            <RxCross2
              className="absolute top-0 right-0 mr-5 mt-5 cursor-pointer text-2xl"
              onClick={() => onClose()}
            />

{title}

              {text}

            <button
              onClick={() => onClose()}
              className="rounded-full px-16 py-2 text-xl text-white"
              style={{ backgroundColor: buttonColor }}
            >
              {buttonText}
            </button>

,
      document.getElementById("modal-root") as HTMLElement
    );
  };
};

export const SuccessModal = _generateModal(
  "Success!",
  checkimg,
  "rgb(21 128 61)" // green-700
);
export const InfoModal = _generateModal(
  "Hey there!",
  infoimg,
  "rgb(59 130 246)" // blue-500
);
export const ErrorModal = _generateModal(
  "Face-plant!",
  errorimg,
  "rgb(190 18 60)", // rose-700
  "rgb(225 29 72)", // rose-600
  "rgb(229 231 235)", // gray-200
  "Try Again"
);


text:
Q: Why is python sklearn feature selection chi square (chi2) test not symmetric? The chi2 function from the sklearn feature selection package returns the chi-square statistic and the p-value. It should be symmetric in the sense that the chi-square statistic is the same regardless of the order in which the variables are given, but it doesn't seem to be.
Here is a code example:
import numpy as np
import pandas as pd
import sklearn.feature_selection as fs

#creating two correlated normal variables
n = 100
cov = [[1.0, 0.75],
       [0.75, 1.0]]
x = np.random.multivariate_normal([0,0], cov, n)

x1 = x[:,0]
x2 = x[:,1]

#turning them into discrete values (with the pandas quantile function)
#I am using two different number of categories for the two variables,
#which makes the effect I am talking about much more pronounced
x1_q = pd.qcut(x1, q=5, labels=False)
x2_q = pd.qcut(x2, q=15, labels=False)

#need to turn one of them into a two dimensional array
#in order to use the chi2 function

x2_m = x2_q.reshape(n, 1)
chi2_1 = fs.chi2(y=x1_q, X=x2_m)

#now I reverse the order
x1_m = x1_q.reshape(n, 1)
chi2_2 = fs.chi2(y=x2_q, X = x1_m)

My question:
why are chi2_1 and chi2_2 not the same? The example uses random numbers. But as an example  I get a chi-square statistic for chi2_1 of 89.59 and for chi2_2 of 37.92 in one of my runs. Any idea what I am missing here?


text:
Q: Flickr API returns duplicate photos I'm trying to extract geo-tagged photos using by python from Flickr API.
But, it returns duplicate photos.
when it extracting over 41 pages, returns same photo URL.
Here is my code,
# !/usr/bin/python
# coding=utf-8
from flickrapi import FlickrAPI
import json, time, os
import pymongo

client = pymongo.MongoClient("localhost",27017)
db = client.flickr
coll = db.flickr_a

API_KEY = "xxx"
SEACRET_KEY = "xxx"

flickr = FlickrAPI(API_KEY, SEACRET_KEY, format="parsed-json")
extras="url_c,url_l,url_o,geo,date_taken,owner_name"

for page in xrange(1,550):
    disney = flickr.photos.search(bbox="139.867,35.613,139.914,35.645",
per_page=100,extras=extras,page=page)
    photos = disney["photos"]
    coll.insert(photos)

Please give me advice or sample code.
Thanks.

A: A quick fix would be to store the photo urls in a python list and remove duplicates by turning it into a set.
at the beginning
coll = []

to add
coll.append(photos)

and at the end (I'm guessing your insert command here)
for p in set(coll):
    db.flickr_a.insert(p)


text:
Q: Need a suggestion in UI design i need give the two options to users when they come to my site(like the following) even before loding the main pages of the site.

*

*Daily deals

*discount and Coupon codes

based on the user selection, i need to display the respective pages.
Now my query is "how to give these two option to users for their selection?"... Please suggest how this can be handled... is this same kind of thing is implemented in any of the website to have a better idea.

A:
i need give the two options to users
  when they come to my site(like the
  following) even before loading the
  main pages of the site

Are you looking for a message-box styled window(similar to feedback message-box on some websites) or a pop-up window?
Another Option
You can create a page which is displayed to the user when the user visits the site.
From there you can then link to the main page of the website or load the page the user selects from the options.

A: Don't make them choose. Decide on a default (based on which one is most often what users want) then make it easy to switch. This way, instead of annoying all the users all the time you only slightly annoy some of the users some of the time.
Also, make both pages bookmarkable (eg: example.com/deals and example.com/codes). This way the user can bookmark the variation they want.

A: This is a very common design, many car dealerships show that as well.  As soon as you visit the landing page, it has a pretty picture, and two BIG buttons: New Cars and Old Cars.  Depending upon which button you click, you go to the two main pages.
So your website can have something like:

*

*gourav/splash_page  with two big buttons

*gourav/daily_deals

*gourav/couponsetc

One trick to use is that when you find a cookie from one of the two main pages, you can automatically load that page.  But this means that user should be able to switch between the two main sites using a top level menu.


text:
Q: How to check SOAP webservice connectivity I'm developing an android application using SOAP webservice. In this app, I need check the connectivity of the webservice, because if the connection is available i have to show the data in online mode and  if the connection is not available i have to show the data in offline mode ie. I'm using SQLlite database to store the data from the webservice
How can my application test for availability of the server, to control whether the application runs in online or offline mode?

A: At design time you can point a web browser at the webservice and examine the response. It you don't get a response, or not what you expect, you can get more detail using Fiddler
At run-time you can simply attempt to access the server in a try/catch exception handler. Define a public bool IsOnline on something that's visible with appropriate scope, and set it true after successful execution and set it false in the exception handler. It's been decades since I used Java but this is the same approach you would use in practically any OO semiprocedural language, like C# or C++ or Java or for that matter VB.

A: For this , I followed this method

*

*I create a Pogo Function (web-method) in my web-service (server) to to check
connectivity

*Create a method to in client side to call the web-method . While i Enter into the app for first time ,I call this client method
from the phone using client function .Then wait for the response.The client method should be surrounded by try-catch block

*If any exception or timed out happened the response will be null and go to exception stage.So
buy checking the response . I set a flag (boolean or integer variable) on base of the state of
response (null or not null) to decide off-line or on-line
mode
Example with code
    public class CallSOAP {

private String SOAP_ACTION="your action url";
private String OPERATION_NAME="";//The web method OR web service you are going to call
private final String WSDL_TARGET_NAMESPACE=SOAP_ACTION;
private  final String SOAP_ADDRESS=Configuration.WEB_SERVICE_URL;//ip-address of serever where you host your service
private Exception exception;
private String ErrorMsg="";
private String TERST_URL="" ;
public Object call(String MethodeName,ArrayList<PropertyInfo> Parameters){
  this.OPERATION_NAME=MethodeName;
  SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE, OPERATION_NAME);
 if(Parameters != null && Parameters.size()>0){
   for(PropertyInfo propertyInfo : Parameters){
      request.addProperty(propertyInfo);
 }
}

SoapSerializationEnvelope  envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet= true;
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransport =null;
if(!this.TERST_URL.equals(""))
  httpTransport = new HttpTransportSE(this.TERST_URL);
else
  httpTransport = new HttpTransportSE(SOAP_ADDRESS);
 Object Response =null;
 try{
    httpTransport.call(SOAP_ACTION+OPERATION_NAME, envelope);
    Response=envelope.getResponse();
  }
 catch (SocketTimeoutException ex) {
     this.ErrorMsg="Unable to connect";
      Response=null;
     this.exception=ex;
  }
  catch (IOException ie) {
   this.ErrorMsg="Unable to connect";
  Response=null;
   this.exception=ie;
  }
   catch (Exception e) {
    this.ErrorMsg="Unable to connect";
    Response=null;
    this.exception=e;
 }
      return Response;
   }
}

In the code ErrorMsg="Unable to connect"; shows the connection is not available now .So i set the response to null and you can pass this response to activity and check it over there
Refer this


text:
Q: Obtaining a national total from total of some cities We are interested in estimating a total of a variable $x$ on the national range. If the country is divided in cities $C_1,\cdots,C_5$ and the population frame has units in all the five cities, and we decide to sample only from units existing in the big cities $C_1$ and $C_2$ by a SRS to obtain an estimation of the population total $T$ of the cities $C_1$ and $C_2$. How can we then obtain the population total $T'$ of all the five cities? Thank you foryour help or giving a reference where to read on this!
Can I do the following: Let $\bar T= \dfrac{T}{N_1+N_2}$ then
$$T'=T+ N_3*\bar T + N_4*\bar T+ N_5*\bar T$$
Where $N_i$ is the population number of units in the city $i$, ($i=1..5$).


text:
Q: ServiceStack with mono on linux I know nothing about linux or mono. I have web app that I am building in WebMatrix. I've set up simple service with ServiceStack and a cshtml test page. All runs fine on Windows but when I move the files to linux box my pages work but the RESTful calls to ServiceStack service bringing back 404 no found. Is there something I'm missing here? Does mono on linux read the web.config and global.asax the same?
Thanks

A: Yes, it reads them the same.
But...
Linux uses case-sensitive file-systems.
So if you type:
http://localhost.com/whatever.aspx
and your site is actually called whatever.aspx, then it will work.
However, if you type Whatever.aspx, that will get you a 404.
Also, if your site's codebehind is called Master.cs (with class Master), and you reference it on a aspx file with master.cs (such as the default visual Studio web application template), you will get a "not found" error.
Additionally, if you run mono on mod-mono with Apache, i think it runs on port 8080 or 8082 by Default, so you have to type http://localhost.com:8080/whatever.aspx.
A better idea might be to run servicestack on nginx via fastcgi-mono-server4.

A: It sounds like casing - you should fix that for performance reasons, but in the meantime you can get Mono to ignore-case by setting the MONO_IOMAP environment variable as follows before starting your mono process e.g. I use the following in my service script:
export MONO_IOMAP=all
${MONOSERVER} /applications=${WEBAPPS} /socket=tcp:127.0.0.1:9000 &

It's documented here:
http://www.mono-project.com/IOMap


text:
Q: Height of binary search tree without building it I have a few million consecutive numbers e.g. {3, 1, 2, ...}. In the same order as  they are, numbers are inserted into a binary search tree. I need to found what is the height of the tree.
Is there any method to determine a height of the tree, without build a whole tree?

A: If it is balanced as a part of the build, it is log2(n) where n is the count of numbers. Otherwise, that is a best case and worst case is n.

A: I am not aware of any algorithm. Quick thought is that it could go along the lines - first element is root, tree height is 1, then check next two elements and depending on what they are height h = 2 or 3, then check next 4 elements and depending on what they are h = h + (1 or 2 or 3 or 4) then check next 8 elements and h = h + (f(elements) - function which returns how much those elements increase tree height) etc... This is just very simplified example on what I would try to pursue. Not even sure if it would be faster than simply building tree and saving height information along the line, but at least it would be performed in place if you mananage to write that function. That is interesting problem BTW.


text:
Q: Using Jsoup to extract single value from page source I need to extract just a single value from a web page. This value is a random number which is generated each time the page is visited. I won't post the full page source but the string that contains the value is:
            Expecting 937117

The "937117" is the value I'm after here. Thanks
Update
Here is what I've got so far:
    Document doc = Jsoup.connect("www.mywebsite.com).get();
    Elements value = doc.select("*what do I put in here?*");

    System.out.println(value);

A: can you not use javascript regular expression syntax?  If you know the element you are interested in, extract it as a string $stuff from jsoup, then just do
$stuff.match( /Expecting (\d*)/ )[1]

A: Everything is described clearly in following snippet. I had created a HTML file with a similar SPAN tag inside. Use Document.select() to select elements with specific class name that you want.
import java.io.File;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Entities.EscapeMode;
import org.jsoup.select.Elements;

public static void main(String[] args) {
    String sourceDir = "C:/Users/admin/Desktop/test.html";
    test(sourceDir);
}

private static void test(String htmlFile) {
    File input = null;
    Document doc = null;
    Elements classEles = null;

    try {
        input = new File(htmlFile);
        doc = Jsoup.parse(input, "ASCII", "");
        doc.outputSettings().charset("ASCII");
        doc.outputSettings().escapeMode(EscapeMode.base);

        /** Find all SPAN element with matched CLASS name **/
        classEles = doc.select("span.label.label-info.pull-right");

        if (classEles.size() > 0) {
            String number = classEles.get(0).text();
            System.out.println("number: " + number);
        }
        else {
            System.out.println("No SPAN element found with class label label-info pull-right.");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

A:         public void yourMethod() {

          try {
                Document doc = connect("http://google.com").userAgent("Mozilla").get();
                Elements value = doc.select("span.label label-info pull-right");

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


text:
Q: Can't boot up laptop. Screen glitches out My dad's  Dell 1525 Laptop screen goes all glitchy and freezes after about 20 seconds after boot.
This a video showing what happens
https://www.youtube.com/watch?v=NtoTpDAEzMY
I've tried the following:

*

*Reset Bios  to default settings

*Ran full diagnostics from Bios which came back with no errors

*Ran LCD diagnostics which was fine.  It showed all colors and bars correctly

*Replace RAM with RAM from another laptop that I know works

*Replace hardrive with hard drive from another laptop I know works

*Try to boot without battery in

*Boot up from Ubuntu DVD. Screen glitches and freezes just like in Windows

*I don't hear any beeps to from the machine to suggest a motherboard issue

Any ideas on what the issue is or other things I can investigate?

A: Try to restart the laptop in SAFE MODE
If the same thing does not happen then it is pointing towards a hardware VGA issue.
How to start Windows in Safe Mode or Safe Mode with Networking


text:
Q: Argparse pattern where input filenames are given through a file or a list of filenames on the command line Does argparse support a pattern such as:
foo.py {-f list_of_filenames.txt|file [file ...]}

I achieve this at the moment with the following argparse definition:
parser = argparse.ArgumentParser()
parser.add_argument("--file", "-f")
parser.add_argument("files", nargs="*")

and performing the mutual exclusivity + required check in my code rather than letting argparse do the check.
Can argparse handle a pattern of this sort?

A: argparse takes fromfile-prefix-chars parameter
https://docs.python.org/3.4/library/argparse.html#fromfile-prefix-chars
So if the filenames are in a file, one name per line
>>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
>>> parser.add_argument('files', nargs='*')
>>> parser.parse_args(['@filenames.txt'])

Will read the names from the file.  It puts them in the sys.argv list just as though you had entered them on the command line.


text:
Q: Base de datos phpMyAdmin subir a mi dominio Tengo una base de datos con phpMyAdmin, cuando lo utilizo con mi localhost funciona perfecto, pero si quiero subir la base de datos a mi dominio, como se cual es el host, usuario y contraseña?
Gracias

A: Si lo que deseas es subir tu base de datos a tu host, tiene que irte al apartado de base de datos, tu host te pedirá que definas nombre y contraseña de usuario que tendrá acceso a esa base de datos, esos son los que usaras para tu conexión.
En el apartado de host en tu archivo de conexión podrás dejar localhost, si es que tus archivos están almacenados en el mismo host, en caso de que desees hacer una conexión externa a tu base de datos tendrás que usar la ip de tu host.
Espero te sea de ayuda.


text:
Q: Recursively sorting two separate lists Define a recursive function named sort; it is passed any unordered list; it returns a new list (not mutating the argument) that contains every value in the argument list, but in non-descending order.
For example, calling sort([4,5,3,1,6,7,2]) would call sort recursively on the lists [4,5,3]and [1,6,7,2], returning the lists [3,4,5] and [1,2,6,7] respectively, which when merged would be return the list [1,2,3,4,5,6,7].
Note when the length of the list is even, both sublists will have the same
size; when the length of the list is odd, it is natural to divide it into two lists, the first of which has one fewer values than the second.
The function starts like this:
def sort(l):

I know how to separate l into two list, for example [4,5,3,1,6,7,2], I separate them into [4,5,3] and [1,6,7,2]. But I really don't know how to recursively sorting each half when the sort function only has one argument l.
Can someone please tell the way to do this? Thank you.

A: I gave it a go and it seems to work. Like TobiasR said, it's a merge sort. If you want a better explanation of how it works, I'd check out this video on merge sorts by Harvard University.
Anyway, this is the code for it:
def sort(l):
    if len(l)==2:
        if l[0]<l[1]:
            return l #return list as it is
        return l[::-1] #return reversed list
    elif len(l)==1:
        return l
    l_1=sort(l[:len(l)//2]) # cut the list in half
    l_2=sort(l[len(l)//2:])
    l_out=[]
    while True:
        if not l_1: #check l1 isn't empty
            l_out+=l_2
            break;
        elif not l_2: #check l2 isn't empty
            l_out+=l_1
            break;
        if l_1[0]<l_2[0]: #put the smallest item in the list
            l_out.append(l_1.pop(0))
        else:
            l_out.append(l_2.pop(0))
    return l_out


text:
Q: How to pass value of paragraph to controller I have a paragraph tag that is manipulated using jquery. I have a list of checkboxes which changes the value of the paragraph everytime a new checkbox is selected. I would like to know if it is possible to pass that value across to the controller.

My checkboxes:
<input type="checkbox" class="slectOne" data-id="R @item.standard_400.00 (per day)" />
<input type="checkbox" class="slectOne" data-id="R @item.super_400.00 (per day)" />

My paragraph tag:

Please choose cover to continue

A: You can... but you probably don't want to. Instead you would post the value of the checkboxes that influence the paragraph...
If you do need to, you can get it as:
$(".result").val();

and post either using AJAX, or by appending a <input type='hidden'> to a form and then posting it.


text:
Q: RefineryCMS 2.1.0 and Zurb 4 Top menu with dropdown navigation I'm trying to use Zurb foundation to style an app built with the latest version of refinery. I began by following this guide
http://blog.flatironschool.com/post/54511602806/build-a-blog-based-site-with-refinerycms
but the latest version of refinery uses "menu-presenter" to layout the menu.
I have got this far:
module ApplicationHelper

   def zurb_menu
      menu_items = Refinery::Menu.new(Refinery::Page.in_menu)

      presenter = Refinery::Pages::MenuPresenter.new(menu_items, self)
      presenter.css = "top-bar-section"
      presenter.dom_id = nil
      presenter.menu_tag = :section
      presenter.list_tag = "ul class='left'"
      presenter
   end
end

This sort of works, However the elements aren't quite right and the main problem is that the I don't know how or where to add the dropdown class to make the child elements dropdown. With the code above the child elements are just expanded all the time.
Thanks for your help

A: instead of in_menu if you use fast_menu, then you will be able to reorder pages. menu_pages works, but you it will not render pages in the same order as they are in admin. hope this helps someone.
menu_items = Refinery::Menu.new(Refinery::Page.menu_pages)
menu_items = Refinery::Menu.new(Refinery::Page.fast_menu)

A: This is my version...  Tested; and it works for me at least.
I used the code for Bootstrap I found on another question (link in the comments above). But instead of replacing the entire menu presenter I override only the methods we need for this.
Create a Zurb menu presenter file:
app/presenters/refinery/pages/zurb_menu_presenter.rb
module Refinery
  module Pages
    class ZurbMenuPresenter < MenuPresenter

    config_accessor :list_dropdown_css, :list_item_dropdown_css, :list_first_css

    MenuPresenter.menu_tag = :section
    MenuPresenter.css = "top-bar-section"
    self.list_dropdown_css = "dropdown"
    self.list_item_dropdown_css = "has-dropdown"
    self.list_first_css = nil

      def render_menu_items(menu_items)
        if menu_items.present?
          content_tag(list_tag, :class => menu_items_css(menu_items)) do
            menu_items.each_with_index.inject(ActiveSupport::SafeBuffer.new) do |buffer, (item, index)|
              buffer << render_menu_item(item, index)
            end
          end
        end
      end

      def check_for_dropdown_item(menu_item)
        ( menu_item != roots.first ) && ( menu_item_children( menu_item ).count > 0 )
      end

      def menu_items_css(menu_items)
        css = []

        css << list_first_css if (roots == menu_items)
        css << list_dropdown_css if (roots != menu_items)

        css.reject(&:blank?).presence

      end

      def menu_item_css(menu_item, index)
        css = []

        css << list_item_dropdown_css if (check_for_dropdown_item(menu_item))
        css << selected_css if selected_item_or_descendant_item_selected?(menu_item)
        css << first_css if index == 0
        css << last_css if index == menu_item.shown_siblings.length

        css.reject(&:blank?).presence
      end

      def render_menu_item(menu_item, index)

          if check_for_dropdown_item(menu_item)
              menu_item_class = list_item_dropdown_css
          else
              menu_item_class =  menu_item_css(menu_item, index)
          end

          content_tag(list_item_tag, :class => menu_item_class) do
              @cont = context.refinery.url_for(menu_item.url)
              buffer = ActiveSupport::SafeBuffer.new
              buffer << link_to(menu_item.title, context.refinery.url_for(menu_item.url))
              buffer << render_menu_items(menu_item_children(menu_item))
              buffer
          end
      end

    end
  end
end

I have a helper in app/helpers/application_helpers.rb:
module ApplicationHelper
    def zurb_menu
        menu_items = Refinery::Menu.new(Refinery::Page.menu_pages)
        presenter = Refinery::Pages::ZurbMenuPresenter.new(menu_items, self)
        presenter
    end
...

Then just call zurb_menu from the _header.  I'm doing the Navbar stuff explicitly in my header function, which may or may not be right; you could roll that into the ZurbMenuPresenter class, and I may well do so:
app/views/refinery/_header.html.erb

Home

Menu

<%=
    zurb_menu.to_html
%>

A: You'll need to override the MenuPresenter. Specifically, you'll need to add the appropriate classes to the children of the top-level menu with the render_menu_item function. I'm not too familiar with Zerb Foundation, but this should get you started.
Note: untested code, I just switched in some class names from my own Bootstrap menu solution to get you started, you might have to do a bit more work. I'm also adding your helper code to the overridden presenter, so you can just call it in a view like this: <%= Refinery::ZerbMenuPresenter.new(refinery_menu_pages, self).to_html %>
app/presenters/refinery/zerb_menu_presenter.rb

module Refinery
  class ZerbMenuPresenter < ::Refinery::MenuPresenter
    self.css = "top-bar-section"
    self.dom_id = nil
    self.menu_tag = :section
    self.list_tag = "ul class='left'"
    def render_menu_item(menu_item, index)
      content_tag(list_item_tag, :class => menu_item_css(menu_item, index)) do
        buffer = ActiveSupport::SafeBuffer.new
        if menu_item_children(menu_item).present?
          buffer << link_to("#{menu_item.title}", context.refinery.url_for(menu_item.url), :class => 'has-dropdown')
          buffer << render_menu_items(menu_item_children(menu_item), 'dropdown')
        else
          buffer << link_to(menu_item.title, context.refinery.url_for(menu_item.url))
        end
        buffer
      end
    end
  end
end


text:
Q: Is there a way to add git branch to databasechangelog table when running liquibase through jenkins job? My company is using jenkins job to run liquibase on oracle database. We want to keep track of git branch from which changesets are executed. Is there a way to add column to DATABASECHANGELOG where I can store git branch from which the jenkins liquibase job is executed?

A: I don't think you can add columns to databasechangelog table.
But I guess, when you write a changeSet, you know in what branch it's going to be executed. So you can provide a branch name in changeSet's id or inside a <comment> tag. This way, branch name will appear in databasechangelog.id and databasechangelog.comments


text:
Q: Blank spaces in large format plotter prints I keep getting a blank swath when printing large format PDF files to my plotter.
I am trying to plot a single page that is 42" (maximum width of roll for this plotter) by up to 120" in length.  The map includes vector (lines, points, labels) on an image basemap (Bing Maps Road).
The pdf prints fine for 58" then there's about 4" of gap, then the plotter resumes.  I have experienced this on numerous files made from ArcGIS Pro and made from ArcGIS Desktop 10.2.1.  The PDF files look fine on the screen.  It seems to NOT be related to corrupt files or the writing of the PDF file, but rather problems in reading the PDF or sending it to the plotter.
I create the PDF in ArcGIS Pro 2.5.1 (or ArcMap 10.2.1).  I have tried deflate and adaptive compression.
I have tried 150 and 300 DPI.  I 'compress vector graphics', Max quality, embed fonts, no georeference, PDF layers only, RGB.
I avoid Adobe Reader.  I use Adobe Acrobat 11.0.23.
I have tried printing at 'Actual size" and at "100% of actual size"
I have tried normal quality, and best quality ('more passes' and NOT 'more passes').  I have tried printing as image (150dpi and 300dpi) and NOT as image.
I send to HP designjet T1700ps (driver 61.194.11903.100).  The driver is (@ Devices//Printer Properties/Advanced/) HP DesignJet T1700ps.  (Others in that list include PCL3GUI and HPGL2).
What solution will allow me to print plotter pages in excess of 58"?

A: The above work was being done using HP DesignJet T7100ps driver.
when I changed to the HPGL2 driver things get better.
(As I understand it, the HPGL2 driver is used for vector and has a limited amount of options to play with.  Apparently those options include plotting a pdf file that contains vector data on top of an image background.)


text:
Q: Selenium web driver can't sign in to google, Update Changes, problem remain****************
cheregeckodriver_autoinstaller.install()
profile = webdriver.FirefoxProfile("/Users/Toshiba/AppData/Roaming/Mozilla/Firefox/Profiles/zq6j04pa.default")
profile.set_preference("dom.webdriver.enabled",False)
profile.set_preference("useAutomationExtension", False)
profile.update_preferences()
desired = DesiredCapabilities.FIREFOX

path = '/Users/Toshiba/Desktop/backup/PythonLearning/Learning/Selenium/geckodriver'
binary = FirefoxBinary("/Users/Toshiba/AppData/Local/Mozilla Firefox/firefox.exe")
ua = UserAgent()
user_agent = ua.random
options = webdriver.FirefoxOptions()
options.add_argument(f'user-agent={user_agent}')
# options.add_argument('-incognito')
wd = webdriver.Firefox(executable_path=path, firefox_profile=profile,     desired_capabilities=desired, firefox_binary=binary)

url = "https://docs.google.com/forms/u/0/"
wd.get(url)
# login to google
username_class = "whsOnd zHQkBf".replace(" ",".")
wd.find_element_by_class_name(username_class).send_keys(username)
time.sleep(random.uniform(1, 3))
btn_next_class = "VfPpkd-RLmnJb"
wd.find_elements_by_class_name(btn_next_class)[-1].click()

Problem

Automate testing software detected
Couldn't sign you in
This browser or app may not be secure. Learn more
Try using a different browser. If you're already using a supported browser, you can refresh your screen and try again to sign in.


text:
Q: Installer created by VS 2008 deployment project fails with error "System.BadImageFormatException" I have created an installer with Visual Studio 2008. VS project type is deployment project. This installer fails in some environments but also runs perfectly in some other environments.
For example, the installer is compiled in virtual machine that runs Windows Server 2012 R2 Standard. Of course installation succeeds there. How ever, it fails in other virtual machine running same Windows edition.
The error message is: "Error 1001. Exception occurred while initializing the installation: System.BadImageFormatException: Could not load file or assembly 'file: Custom actions.dll' or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded."
Target framework is 3.5 in all applications in the installer solution. Also the references in Custom Actions library have .NET version 2.0 or 3.5.
What is missing in the failing environment? Where to start the search?

A: Blog: Maybe check this blog quickly. Essentially: 1) bitness 32/64, 2) corrupted binary file or 3) configuration issues (app.config).
InstallUtilLib.dll: Here is a similar answer: System.BadImageFormatException: Could not load file or assembly (from installutil.exe). It links to this MSDN explanation: 64-bit managed custom actions throw a System.BadImageFormatException exception. Seems likely.

Alternatives: The real answer - IMHO - would be to avoid Visual Studio Installer projects due to a number of known problems with this type of project. The WiX toolkit is a good open source alternative. And there are other, commercial options. And there is an alternative version with more elaborate details.

Some Links:

*

*System.BadImageFormatException: Could not load file or assembly

*BadImageFormatException Class

*This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded

A: There are really only two reasons for this error:

*

*You have 32-bit (or 64-bit) code trying to call an assembly of the opposite architecture. In custom action calls you'll need to chase down the calling sequence and be careful of AnyCpu types of assembly that may be JIT compiled to the architecture of the system rather than assemblies you'll call.

*Incompatible NET architectures. In your case, the assemblies you referred to are all NET 2.0 CLR-based. If they end up running in a NET 4.0 CLR they will fail. It may help to look at the Launch Conditions to see what's going on.
I also think Visual Studio 2008 is not a good basis for a setup project. VS Community Edition is free, and will host the add-on Installer Projects. Certainly VS 2008 is unaware of NET 4.0 CLR.


text:
Q: Identifying line where thread is in debugger I am trying to debug a multithreaded application where several threads seem to stall, and then continue working minutes later or never again.
I'm sure there is  a point of contention between them that is causing this, but I don't know how to find it. Using the Parallel Stacks and Threads view in Visual Studio only provides me with the stack from of where the threads were started, not where they currently are.
I start my tasks with:
Task task = new Task((object state) => { DoWork(state).GetAwaiter().GetResult(); }, $"worker_task{i}", TaskCreationOptions.LongRunning);

They then run through a process of pulling items from a ConcurrentQueue and processing them. I used the GetAwaiter().GetResult(); else the async method they call immediately returns and the tasks show as complete even though there is still work being done.
Visual Studio Debug windows:

Thread #38880 is not actually doing any work, and I want to find out where it is getting stuck, but it only shows me where the task was started.
How can I see what line the task/thread is currently on? Am I starting my tasks in such a way that I cannot see this? If so, what should I be doing?

Context: I am running tasks that call API's via Httpclient. Because of the network latency I am running multiple tasks in parallel to maximize my cpu utilization during wait time. Calling Httpclient is an async operation, and I can't seem to await the creation of a task, so I ended up creating an anonymous function and blocking inside of that.
This is probably the wrong approach, but I don't know how else to go about it.
Method that starts the tasks:
    private static void InitWorkers()
    {
        for(int i = 0; i < max_workers; i++)
        {
            Task task = new Task((object state) => { DoWork(state).GetAwaiter().GetResult(); }, $"worker_task{i}", TaskCreationOptions.LongRunning);

            ProcessingTasks.TryAdd($"worker_task{i}", task);
            processedStats.TryAdd($"worker_task{i}", new Stat());

            task.Start();
        }
    }

A: Your problem is .GetAwaiter().GetResult(), which blocks the calling thread while waiting for the task to finish.
Don't do that.
If your method is truly async, you don't need to create a Task at all; you can just call it, and it will do its work asynchronously.
If it performs blocking or CPU-bound calls in its synchronous portion, you should use Task.Run() to run that in a background thread and wait for the resulting task.


text:
Q: Thread-safe or multithreaded CRF in Java with support for continuous variables? I want to use Mallet to run Conditional Random Fields in a Leave-One-Sequence-Out manner on a rather large data set. Therefore I need multithreaded computation to handle this computationally, either by 1) training multiple CRFs in parallel, with each CRF being trained on a single thread, or 2) training each CRF in a multithreaded manner.
In the Mallet API I found a multithreaded version of a CRF trainer, cc.mallet.fst.CRFTrainerByThreadedLabelLikelihood.java, which implements option 2. However, in my situation I need support for continuous variables, for which fst does not seem to have support and for which GRMM seems needed. With a small adjustment I managed to let GRMM handle continuous inputs. For GRMM however, as far as I was able to find, there seems to be no support for multithreaded training through option 2 like in fst.
As an alternative, I implemented option 1, in which I train the CRFs for the folds of the experiment in parallel in different threads. I use my own build of the Minmo/Mallet github version of Mallet, checked out on the 26th of August 2015. The GRMM code however seems to be not thread safe, as exceptions are thrown when I run the code in parallel while these exceptions are not thrown when I run the same code while using a single thread. Also, the prediction accuracy is significantly lower when the CRFs are trained in parallel, when I simply catch the exceptions and let the execution continue. The exception thrown when executed on multiple threads is the following:
java.lang.IndexOutOfBoundsException: Assignment does not give a value for variable I216_VAR[f=0][tm=38]
    at cc.mallet.grmm.types.Assignment.get(Assignment.java:337)
    at cc.mallet.grmm.types.Assignment.get(Assignment.java:315)
    at cc.mallet.grmm.types.LogTableFactor.rawValue(LogTableFactor.java:255)
    at cc.mallet.grmm.types.LogTableFactor.logValue(LogTableFactor.java:219)
    at cc.mallet.grmm.inference.AbstractBeliefPropagation.lookupLogJoint(AbstractBeliefPropagation.java:553)
    at cc.mallet.grmm.learning.ACRF$MaximizableACRF.computeLogLikelihood(ACRF.java:1348)
    at cc.mallet.grmm.learning.ACRF$MaximizableACRF.getValue(ACRF.java:1270)
    at cc.mallet.optimize.LimitedMemoryBFGS.optimize(LimitedMemoryBFGS.java:99)
    at cc.mallet.grmm.learning.DefaultAcrfTrainer.train(DefaultAcrfTrainer.java:207)
    at cc.mallet.grmm.learning.DefaultAcrfTrainer.train(DefaultAcrfTrainer.java:119)

Is there any way to circumvent these problems and train Conditional Random Fields with continuous variables in a multithreaded way, either by training each CRF multithreaded, or by training multiple CRFs in different threads simultaneously? Preferably by using Mallet (fst or GRMM), as that would safe me the time of switching, but I would be open to any other CRF/PGM Java library as well.

A: I've been messing around with this same problem lately, and think I came up with a decent solution. Check out this repo and let me know if it helps. By specifying that continuous features need to have a prefix that follow the regex '[A-Z]+=', I was able to set up a pipe that (loosely) sets  to the double that follows it. I think I still have some tests to do to verify, but maybe it'll give you some inspiration.


text:
Q: I am new to cypress+TS. Getting error while trying to access element inside the iframe using Cypress with Typescrpt Issue: While handling Iframe using Cypress with TS, getting an error as
TypeError
data.its is not a function

Below code in test class:
getSAveCardElement()
        .click()
        .then(() => {
          getIFrame().xpath("//*[@name='cardnumber']").type(info.stripeCardNum);
        });

Function for Iframe Handling:
export const getIframeBody = () => {
  return cy.xpath("//div[@id='cardElementpaymentModal']//iframe[contains(@name,'privateStripeFrame')]").each((data) => {
    // @ts-ignore
    data.its('0.contentDocument').its('body').should('not.be.undefined').then(cy.wrap);
  });
};

The reason to try with each loop is that getting jquery element with contentDocument only through with each loop.
PFB error's screenshot

A: Function for Iframe handling that works
  export const getIframeBody = () => {
  let $body: JQuery<HTMLElement | Document | Text | Comment>;
  getStripeCardIframe().each((data) => {
    $body = data.contents().find('body');
  });
  return cy.then(() => {
    cy.wrap($body);
  });
};


text:
Q: Incorrect number of decimal places on a specific formula I'm having an issue which I can reproduce in three completely unrelated projects in Visual Studio 2010, so I assume this has to do with the .NET framework in general.
When I set a breakpoint in the project, and type in the following text in the following text to be evaluated:
"12500 + 6217.680 + 172.24"
I receive this:
"18889.920000000002"
Note the incorrect number of decimals.
I expect to see this:
"18889.92"
I can type it into a watch window, and it evaluates correctly.  But, not in the Immediate Window.
What gives?

A: This is normal behavior for floating point math.  I recommend reading What Every Computer Scientist Should Know About Floating-Point Arithmetic.
If you want to display this with a specific precision, you should format the result using value.ToString(format) with a specified amount of precision.

A: If you use the m suffix to indicate that the numbers are decimals, not doubles, the results will be what you expect (at least in this case).
12500m + 6217.680m + 172.24m = 18889.92


text:
Q: Чем отличаются понятия "Обновиться из origin" и "Обновиться из upstream"? Обновиться из апстрима — обновить свою локальную версию форка до последней версии основного репозитория, от которого сделан форк.
Обновиться из ориджина — обновить свою локальную версию репозитория до последней удалённой версии этого репозитория.
Я нашел эти определения, но не могу понять в чем их разница. В моём понимании термин "репозиторий" - означает каталог с файлами проекта который находится на сервере GitHub. В чем разница между понятиями "локальная версия форка" и "локальная версия репозитория" если и то и другое является копией "изначального репозитория"?
Чем отличается "последняя версия основного репозитория от которого сделан форк" от "последней удаленной версии этого репозитория"? Основной репозиторий и удаленная версия этого репозитория это не одно и тоже?
Почему Upstream подразумевает изначально созданный проект, а origin подразумевает мою скопированную копию основного проекта находящуюся на github, если само слово origin указывает на изначально созданный проект, по логике, но на его месте стоит слово upstream? это сбивает с толку.

A: Для начала "репозиторий" понимается неправильно. git - это система с распределенным репозиториями. После выполнения fork на github и clone на своей машите будет целых три независимых репозитория. origin - обычно используется в репозитории на машине пользователя в качестве алиаса для того удаленного репозитория, из которого был клонирован этот и куда будут отправляться изменения. upstream - обычно используется в репозитории на машине пользователя в качестве алиаса для того удаленного репозитория, из которого был форкнут тот репозиторий, из которого клонировали этот. На практике удаленных репозиториев может быть куда больше двух, соответственно можно делать и неограниченное количество произвольных алиасов для них.


text:
Q: Построение графиков в C++ Builder Можно ли в С++ Builder 6 построить график на основании определенных данных, чтобы не использовать Excel?
Или как-то можно в программе создать, открыть и записать в файл Excel информацию, которую выдаст программа, чтобы после в файле создался график с определенными параметрами?

A: Построить график очень просто. Наверное что-то вроде
Canvas->MoveTo(StartX, StartY);
Canvas->LineTo(X, Y);

Excel понимает очень простой формат CSV. Напистаь выгрузку данных в такой формат совсем просто. А потом очень очень очень просто открыть такой файл в Excel и несколькими кликами мыши сделать график.
A: А можно использовать COM-объект Excel. Придется познакомиться с типами OleVariant.
Одно из простейших
A: Раньше был TChart. Простой способ нарисовать график.
Поиском находится на раз.


text:
Q: Call an external dynamic library using node I need to edit clips using node using one of the existing video manipulation libraries. (Note: I am aware that I could run an existing editing executable like FFMPEG, but that's not what I am after).
Question: What's the best way to call native libraries in Node?
Background information: I will need to talk to one one these libraries: Gstreamer, FFmpeg/LibAV or libVLC.
My ideal outcome is to have a nice, robust library that I use directly using node, but my lack of experience in terms of using native libraries, and the somehow fragmented world of video editing libraries.

A: You could use node-ffi which helps you call the native C++ libraries in nodejs.


text:
Q: Difficulties using AJAX to pass input value to controller I have this PHP CodeIgniter code where in the view I am getting input from a text field. Using AJAC I am trying to pass this value to the controller using GET request. The controller will then call a function from my model to retrieve a database record matching the search criteria.
For some reason it doesn't work. I tried to do a var dump in the controller to see if the value is passed by AJAX, but I am not getting anything. Any ideas what I am doing wrong and why I can't receive the form value in the controller?
View:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.13.3/jquery.min.js"</script>
<script language="Javascript">
    $(document).ready(function () {
        $('#submitbutton').click(function () {
            $.ajax({
                url: "../../index.php/testcontroller/getdatabasedata",
                data: {
                    'searchvalue' : $('#inputtext').val()
                },
                method: 'GET'
            }).done(function (data) {
                var dataarray = data.split('##');
                $('#question').html(dataarray[ 1 ]);
                $('#answer1').html(dataarray[ 2 ]);
            });
            return false;
        });
    });
</script>
</body>

Controller
public function getdatabasedata()
{
    $this->load->model('testmodel');
    $year = $this->input->get('searchvalue');
    //I TRIED TO DO A VARDUMP($YEAR) BUT I DON'T GET ANYTHING!

    $movie = $this->testmodel->findquestion($year);
    $moviesstring = implode(",", $movie);
    echo $moviesstring;
}

Model
function findquestion($searchvalue)
{
    $this->db->where('answer1', $searchvalue);
    $res = $this->db->get('questions');
    var_dump($res)
    if ($res->num_rows() == 0)
    {
        return "...";
    }
    $moviearray = $res->row_array();
    return $moviearray;
}

A: Script:
<script
  src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script language="Javascript">
$(document).ready(function ()
{
  $("#submitbutton").bind("click",function()
    {
      var target_url = '<?php echo(base_url()."testcontroller/getdatabasedata") ; ?>';
      var data = {'searchvalue' : $('#inputtext').val() };
      $.ajax ({

              url : target_url,
              type: 'GET',
              data: data,
              cache: false,
              success: function(controller_data)
                {
                  var dataarray = controller_data.split('#');
                  $('#question').html(dataarray[1]);
                  $('#answer1').html(dataarray[3]);
                },
            });
            return false;
    });
});
</script>

.bind("click",function()  - add quotes to click event.
var dataarray = controller_data.split('#'); - split
  data caracter must match character in implode function in controller.

Controller:
public function getdatabasedata(){

        $this->load->model('testmodel');
        $year = $this->input->get('searchvalue');
        $movie = $this->testmodel->findquestion($year);
        $separated = implode("#", $movie);
        echo $separated;

    }

Hope this helped.

A: I will share my usual ajax code that I use in my views , make sure your base url is correct
$("#submitbutton").bind("click",function()
        {

            var target_url = '<?php echo(base_url()."testcontroller/getdatabasedata") ; ?>';
            $.ajax
            (
            {
                url : target_url,
                type: "GET",
                // data: {'searchvalue' : $('#inputtext').val()},
                cache: false,
                success: function(data)
                {
                    alert(data);
                },
                error: function(jqXHR, textStatus, errorThrown)
                {
                    alert("error during loading ....");
                }
            });

        });// end loading via ajax

and in your controller just echo something
public function getdatabasedata()
{
    //$this->load->model('testmodel');
    //$year = $this->input->get('searchvalue');
    //I TRIED TO DO A VARDUMP($YEAR) BUT I DON'T GET ANYTHING!

    //$movie = $this->testmodel->findquestion($year);
    //$moviesstring = implode(",", $movie);
    //echo $moviesstring;
    echo "hello";
}


text:
Q: Usage of std::forward vs std::move I always read that std::forward is only for use with template parameters. However, I was asking myself why. See the following example:
void ImageView::setImage(const Image& image){
    _image = image;
}

void ImageView::setImage(Image&& image){
    _image = std::move(image);
}

Those are two functions which basically do the same; one takes an l-value reference, the other an r-value reference. Now, I thought since std::forward is supposed to return an l-value reference if the argument is an l-value reference and an r-value reference if the argument is one, this code could be simplified to something like this:
void ImageView::setImage(Image&& image){
    _image = std::forward(image);
}

Which is kind of similar to the example cplusplus.com mentions for std::forward (just without any template parameters). I'd just like to know, if this is correct or not, and if not why.
I was also asking myself what exactly would be the difference to
void ImageView::setImage(Image& image){
    _image = std::forward(image);
}

A: You have to specify the template type in std::forward.
In this context Image&& image is always an r-value reference and std::forward<Image> will always move so you might as well use std::move.
Your function accepting an r-value reference cannot accept l-values so it is not equivalent to the first two functions.

A: I recommend reading "Effective Modern C ++" by Scott Meyers, specifically:

*

*Item 23: Understand std::move and std::forward.

*Item 24: Distinguish universal references for rvalue references.

From a purely technical perspective, the answer is yes: std::forward
can do it all. std::move isn't necessary. Of course, neither function
is really necessary, because we could write casts everywhere, but I
hope we agree that that would be, well, yucky. std::move's attractions
are convenience, reduced likelihood of error, and greater clarity.

rvalue-reference
This function accepts rvalues and cannot accept lvalues.
void ImageView::setImage(Image&& image){
    _image = std::forward(image);        // error
    _image = std::move(image);           // conventional
    _image = std::forward<Image>(image); // unconventional
}

Note first that std::move requires only a function argument, while std::forward requires both a function argument and a template type argument.
Universal references (forwarding references)
This function accepts all and does perfect forwarding.
template <typename T> void ImageView::setImage(T&& image){
    _image = std::forward<T>(image);
}

A: You cannot use std::forward without explicitly specifying its template argument. It is intentionally used in a non-deduced context.
To understand this, you need to really understand how forwarding references (T&& for a deduced T) work internally, and not wave them away as "it's magic." So let's look at that.
template <class T>
void foo(T &&t)
{
  bar(std::forward<T>(t));
}

Let's say we call foo like this:
foo(42);

*

*42 is an rvalue of type int.

*T is deduced to int.

*The call to bar therefore uses int as the template argument for std::forward.

*The return type of std::forward<U> is U && (in this case, that's int &&) so t is forwarded as an rvalue.

Now, let's call foo like this:
int i = 42;
foo(i);

*

*i is an lvalue of type int.

*Because of the special rule for perfect forwarding, when an lvalue of type V is used to deduce T in a parameter of type T &&, V & is used for deduction. Therefore, in our case, T is deduced to be int &.

Therefore, we specify int & as the template argument to std::forward. Its return type will therefore be "int & &&", which collapses to int &. That's an lvalue, so i is forwarded as an lvalue.
Summary
Why this works with templates is when you do std::forward<T>, T is sometimes a reference (when the original is an lvalue) and sometimes not (when the original is an rvalue). std::forward will therefore cast to an lvalue or rvalue reference as appropriate.
You cannot make this work in the non-template version precisely because you'll have only one type available. Not to mention the fact that setImage(Image&& image) would not accept lvalues at all—an lvalue cannot bind to rvalue references.


text:
Q: Remove date on top of datetimepicker only time I have form, I want to show time when I pick it, but It show date and time
enter image description here
I want to remove it, cause no sense
My coffee:
$('#time1').datetimepicker
format: 'hh:ii'
autoclose: true
startView: 1

My slim:
#time1.input-group.date
  input.form-control type="text"
    span.input-group-addon
      span.glyphicon.glyphicon-time

Pls help me T_T

A:  # In your cofee it can be like this
 $('#time1').datetimepicker
   pickDate: false
   format: 'LT'


text:
Q: Creating SQL Server database in (or attaching from) Google Drive I tried to create a new SQL Server database in my Google Driver folder but I cannot even navigate to my GD and when I paste in the path I keep getting acces denied even when SSMS is running as Admin.
Also tried creating the DB in usual SQL Server Data folder, moving to my Gooogle Drive and attaching from there by pasting in the path because I cannot navigate to GD when trying to attache an existing DB but again I get access denied error...
Anyway, did anyone manage to create in or attach from Google Driver folders an SQL Server database or has any idea how to achieve this?

A: SSMS may be running as an admin, but the service account that SQL Server is using is the one that needs access to the folder. Can you verify that is the case


text:
Q: Как считать из файла только числа Нужно записать в файл студентов: имена и их оценки по 4 предметам, ну или же сразу написать все это в файле.

С этим проблем нет, а далее нужно вписать в другой файл имена студентов, которые имеют оценки 4 и 5.

Вот здесь проблема, не знаю, как это осуществить.

Попробовал создать целочисленную переменную и решил попробовать передавать в нее значения(ожидал, что будут передаваться только числа, но прошел отладкой, понял, что не так).

В общем как можно это сделать ?

Есть вариант искать слово "оценки:", но может есть другой
bool foo(vector<int>& name) {
    for (int i = 0; i < name.size(); i++) {
        if (name[i] < 3) {
            return false;
        }
    }
    return true;
}

int main() {
    // Фрагмент записи в файл решил не добавлять
    int x, sum = 0;
    vector<int> v;
    bool check;
    ifstream iname("read.txt");
    ofstream oname2("write2.txt");
    if (!iname.is_open()) {
        exit(0);
    }
    else {                        // Чтение
        while (!iname.eof()) { // Об этом фрагменте писал выше
            if (iname >> x) {
                v.push_back(x);
                sum++;
            }
            if (sum == 4) {
                check = foo(v);
                if (check) {
                //  oname2 << "Yes" << endl; // Это я проверял, работает или нет
                }
                sum = 0;
            }
        }
    }
    iname.close();
    oname2.close();
}

A: В общем решил сам, только пришлось создавать записи: "имя", "оценки", а уже после, на следующей строке, писать данные, хотя можно было без этого, просто представил, как все будет выглядеть и, отталкиваясь от этого, писал :
bool foo(vector<int> &n) {
    for (int i = 0; i < n.size(); i++) {
        if (n[i] < 4) {
            return false;
        }
    }
    return true;
}

int main() {
    setlocale(LC_ALL, "ru");
    int volume;
    cout << "Введите количество студентов: "; cin >> volume;
    vector<string> fio; // Вектор хранения тех, кто подходит
    vector<int> num;
    int first, second, third, fourth;
    string name;
    string str;
    string st; // имя студента
    bool mark = false;
    bool strn = false;
    ofstream oname("write.txt");
    oname << "List of students: " << endl;
    for (int i = 0; i < volume; i++) {
        cout << "Введите имя студента " << i + 1 << ": "; cin >> name;
        oname << "Name is student: " << endl << name << endl;
        cout << "Введите все оценки студента: "; cin >> first >> second >> third >> fourth;
        oname << "Assessments: " << endl << first << " " << second << " " << third << " " << fourth <<  endl; // Запись оценок в файл
    }
    oname.close();

    bool check;
    int sum = 0;
    ifstream iname("write.txt");
    if (!iname.is_open()) {
        cout << "File for reading is not open!";
    }
    else {
        while (getline(iname, str)) {
            if (strn) {
                st = str; // Хранение имени студента
                strn = false;
            }
            if (str.find("Name") != string::npos) {
                strn = true;
            }
            if (str.find("Assessments:") != string::npos) {
                mark = true;
                while (sum != 4) {
                    int x;
                    iname >> x;
                    num.push_back(x);
                    sum++;
                    if (sum == 4) {
                        check = foo(num);
                    }
                }
                if (check) {
                    fio.push_back(st);
                }
                sum = 0;
            }
        }
    }
    iname.close();

    ofstream readn("read.txt");
    for (int i = 0; i < fio.size(); i++) {
        readn << fio[i] << endl;
    }
    readn.close();

}


text:
Q: Insert multiple value from multiple table I created the below query to add users to the group in the SQL DB.
Since two columns are inserting from the Groups table, I have to provide the group name multiple times. Is there any way to simplify this query so that I need to only put the Email and group name only one time?
insert into USG (Id,RId,H) Values (
(select Id from Users where Email = 'test@domail.com'),
(select RId from groups where name = 'Market Admin'),
(select H from groups where name = 'Market Admin')
)

A: Hmmm . . . you can join the two tables like this:
insert into USG (Id, RId, H)
    select u.id, g.Rid, g.h
    from users u join
         groups g
         on u.Email = 'test@domail.com' and
            g.name = 'Market Admin';

This is not exactly the same as your query but it probably also does what you want.  Two differences:

*

*If no groups or users match your conditions, your version inserts a row with NULL values.  This will not insert anything.

*If multiple groups or users match your conditions, your version returns an error.  This inserts multiple rows.

These can both be addressed, but requires slightly complicating the query.


text:
Q: Switch from Mobile view to Desktop view by PHP session I have done the switching from mobile view to desktop view, but how do I show the menu if desktop view is on? I want to show "Switch to Mobile View"
Here is my code
<?php session_start(); ?>
<meta charset="<?php bloginfo( 'charset' ); ?>">

<?php
if($_GET['show_desktop_mode'] == 'true') {
    $_SESSION['desktopmode'] = 'true';
} else if($_GET['show_desktop_mode'] == 'false') {
    $_SESSION['desktopmode'] = 'false';
}

if($_SESSION['desktopmode'] == 'true') {
    /* DESKTOP MODE */
    ?>
    <meta name="viewport" content="width=1170">
    <?php
} else {
    // DEFAULT
    ?>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <?php
}
?>

And here Goes in my footer
<?php if($_SESSION['desktopmode'] == 'false') { ?>

Switch To Desktop Mode

<?php } elseif($_SESSION['desktopmode'] == 'true') { ?>

Switch to Mobile Mode

<?php } ?>


text:
Q: using Areas in MVC5 I am trying to achieve the routings as follow:

*

*http://example.com/Admin/Index

*http://example.com/Application/Index

*http://example.com/Customers/Index
etc...
I like the ideas of using 'Areas' and want to separate all the codes by using Areas.  So, I created my Areas structure like the following screnshot

and the code in ApplicationAreaRegistration.cs is
public override string AreaName
    {
        get
        {
            return "Application";
        }
    }

    public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRoute(
            "Application_default",
            "Application/{controller}/{action}/{id}",
            new { action = "Index", id = UrlParameter.Optional }
        );
    }

However, I cannot achieve the route I want like
http://example.com/Application/Index
In stead of that it becomes, http://example.com/Application/Application/Index
I tried to change the default routing without {controller} in AreaRegistration
context.MapRoute(
                "Application_default",
                "Application/{action}/{id}",
                new { action = "Index", id = UrlParameter.Optional }
            );

But I got, Controller is required area.
I know I can easily get http://example.com/Application/Index if I put the Controller in root Controllers Folder.  But it means I couldn't group my codes like the Areas anymore and it will be seprated across the MVC Folders.
What I would like to know is, whether I can achieve what I want by using the Areas or am I trying to do which is impossible?

A: You need to add a default controller name to the route so MVC understands what to put in the controller route value when you take it out of the URL.
public override void RegisterArea(AreaRegistrationContext context)
{
    context.MapRoute(
        "Application_default",
        "Application/{action}/{id}",
        new { controller = "Application", action = "Index", id = UrlParameter.Optional }
    );
}


text:
Q: Dynamically submit form and show the value of the input without reloading I want to create a fully dynamic chat UI  for my website,
But it reloads the whole page if a person submits the button this will directly show the div

    <?php  print $message->getName() ." : " . $chat->message . ""; ?>

Without reload msgs are save in some xml file path like example (../user/xml)
HTML
<form action="action.php" method="post">
    <input type="text" id="input" value="php echo">
    <input type="submit" value="send" onclick="showDiv()">
</form>

    <?php  print $message->getName() ." : " . $chat->message . ""; ?>

i don't know javascript/ajax well how to solve this

A: Try jquery ajax, on submit button send last msg for save into db and fetch all record and show them into chat page. so each time you send msg it will fetch all msg. if you don't know about how ajax work then let me know.

A: Begin by looking at the event on forms called 'onSubmit'. https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onsubmit
Once you understand that, you can 'event.preventDefault()' in your 'onSubmit' method handler. Or in English, keep a form's default behavior to submit to the action from occurring.
After preventing the default action, you will need to do something with the form, and the easiest in latest browsers is to use the fetch API. https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
You should be able to submit the data in the form to some endpoint that returns the HTML you wish to inject.
Once the HTML has been successfully returned, simple document.createElement methods with append (https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/append) will need to be used.
Good luck learning the web!


text:
Q: How to prove this statement? I cannot prove this proposition directly .

Let $(X,d)$ and $(Y,d')$ be metrice spaces. Let $f$ be a function from $X$ to $Y$. If $\overline{f^{-1} ( B)} \subseteq f^{-1}( \overline B)$ for all subset $B$ of $Y$, then
  $f$ is sequentially continuous.

Note that $f$ is sequentially continuous if and only if for any sequence $(x_n)$, if $d(x_n,x)\to 0$, then $d′(f(x_n),f(x)) \to 0$.
 Please help me.

A: Suppose not, we have a subsequence of $f(x_n)$ s.t. $d'(f(x_{n_k}),f(x))\ge \epsilon$.WOLG, we assume the subsequence is $f(x_n)$ and $x_n\not =x\forall n$ (otherwise restrict our discussion to suitable subsequence).
Then set $B=\{f(x_n)\}$, hence $ \{(x_n)\}\subset f^{-1} ( B),\{(x_n)\}\cup \{x\}\subset \overline{f^{-1} ( B)}$ since $x_n\to x$
By assumption $\overline{f^{-1} ( B)} \subseteq f^{-1}( \overline B)$ , then $x\in
f^{-1}( \overline B)$, hence $f(x)\in \bar{B}$. which is impossible, by our selection of$f(x_n)$
Hence we get sequential continuity.


text:
Q: Exposing a port externally in Azure Compute Emulator I have made an Azure Cloud Service TCP listener in C#, and now I am trying to debug it locally. The service definition below exposes the port I am interested in, but when it is running locally, the address is bound to localhost, which is not visible to other devices on the same network.
<?xml version="1.0" encoding="utf-8"?>
<ServiceDefinition name="Foo.Listener.Azure" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition" schemaVersion="2015-04.2.6">
  <WorkerRole name="Foo.Listener" vmsize="Small">
    <ConfigurationSettings>
      <Setting name="Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString" />
    </ConfigurationSettings>
    <Endpoints>
      <InputEndpoint name="Foo Protocol" protocol="tcp" port="9100" localPort="9100" />
    </Endpoints>
  </WorkerRole>
</ServiceDefinition>

I have tried adding a port proxy with the following command:
netsh interface portproxy add v4tov4 listenport=9100 connectaddress=localhost connectport=9100 protocol=tcp

However, the compute emulator seems to think the port number 9100 is in use when I do this, and it chooses 9101 instead. How can I run my worker role locally, and allow it to accept external connections?

A: I managed to get this working by adding a check in the worker role. It's not pretty, and I'd much rather have this done through configuration than through code, but here's my solution:
IEnumerable<IPEndPoint> endpoints;

if (RoleEnvironment.IsEmulated)
{
    endpoints = Dns.GetHostEntry(Dns.GetHostName())
        .AddressList
        .Select(address => new IPEndPoint(address, 9100));
}
else
{
    endpoints = RoleEnvironment.CurrentRoleInstance
        .InstanceEndpoints
        .Select(endpoint => endpoint.Value.IPEndpoint);
}


text:
Q: how to print string from bytebuffer i have just started playing around with java nio packages an am at a bit of a loss
i have a client
Socket s=new Socket(ip,port);
OutputStream out=new OutputStream();
PrintStream ps=new PrintStream(s.getOutputStream());
String t=""hiya";
ps.print(t);
ps.flush();
InputSTreamReader in=new InputSTreamReader(s.getInputSTream);
BufferReader b=nwe BufferedReader(in);
System.out.println(b.readLine());//prints echo response from server

and on the server side
this.selkey = selkey;
this.chan = (SocketChannel) chan.configureBlocking(false); // asynchronous/non-blocking
buf = ByteBuffer.allocateDirect(64); // 64 byte capacity

void read() {
    try {
        int amount_read = -1;
        try {
           amount_read = chan.read((ByteBuffer) buf.clear());
        } catch (Throwable t) {
            }
        if (amount_read == -1)
            disconnect();//deelts client on exit
        if (amount_read < 1)
            return; // if zero
            System.out.println("sending back " + buf.position() + " bytes");
            // turn this bus right around and send it back!
            buf.flip();
            chan.write(buf);//sending data 2 client
    } catch (Throwable t) {
            disconnect();
            t.printStackTrace();
    }
}

what this does i send string t to the server into bytebuffer and echos it back which all works fine but hoiw would i print the string on the server side for example in read method
buf.flip()
System.out.write(buff);//which just prints what looks to be chinese

A: k this is typical have been working on this problem for like an hour but when i post the question the answer acours to me
CAST IT TO A CHAR!
this works
buf.flip();
while (buf.hasRemaining()) {
    System.out.print((char) buf.get();
}
System.out.println();

A: Since you are sending data as bytes, it wont work as Strings.
Even if you did, it would be referencing the byte array.
Try this:
String str = new String (buff);


text:
Q: how to get alignment or attention information for translations produced by a torch hub model? The torch hub provides pretrained models, such as: https://pytorch.org/hub/pytorch_fairseq_translation/
These models can be used in python, or interactively with a CLI.
With the CLI it is possible to get alignments, with the --print-alignment flag. The following code works in a terminal, after installing fairseq (and pytorch)
curl https://dl.fbaipublicfiles.com/fairseq/models/wmt14.v2.en-fr.fconv-py.tar.bz2 | tar xvjf -
MODEL_DIR=wmt14.en-fr.fconv-py
fairseq-interactive \
    --path $MODEL_DIR/model.pt $MODEL_DIR \
    --beam 5 --source-lang en --target-lang fr \
    --tokenizer moses \
    --bpe subword_nmt --bpe-codes $MODEL_DIR/bpecodes \
    --print-alignment

In python it is possible to specify the keyword args verbose and print_alignment:
import torch

en2fr = torch.hub.load('pytorch/fairseq', 'transformer.wmt14.en-fr', tokenizer='moses', bpe='subword_nmt')

fr = en2fr.translate('Hello world!', beam=5, verbose=True, print_alignment=True)

However, this will only output the alignment as a logging message. And for fairseq 0.9 it seems to be broken and results in an error message (issue).
Is there a way to access alignment information (or possibly even the full attention matrix) from python code?

A: I've browsed the fairseq codebase and found a hacky way to output alignment information.
Since this requires editing the fairseq sourcecode itself, I don't think it's an acceptable solution. But maybe it helps someone (I'm still very interested in an answer on how to do this properly).
Edit the sample() function and rewrite the return statement.
Here is the whole function (to help you find it better, in the code), but only the last line should be changed:
def sample(self, sentences: List[str], beam: int = 1, verbose: bool = False, **kwargs) -> List[str]:
    if isinstance(sentences, str):
        return self.sample([sentences], beam=beam, verbose=verbose, **kwargs)[0]
    tokenized_sentences = [self.encode(sentence) for sentence in sentences]
    batched_hypos = self.generate(tokenized_sentences, beam, verbose, **kwargs)
    return list(zip([self.decode(hypos[0]['tokens']) for hypos in batched_hypos], [hypos[0]['alignment'] for hypos in batched_hypos]))


text:
Q: Concatenate two wav files with different AudioFormat I have a method that should concatenate two .wav sound files. It works fine if I have two files with the same AudioFormat. But if I take files with two different formats, one of the files will sound really bad in result. So, I need to concatenate two .wav files with these formats:

*

*PCM_SIGNED 24000.0 Hz, 16 bit, mono, 2 bytes/frame, little-endian;

*PCM_SIGNED 44100.0 Hz, 16 bit, stereo, 4 bytes/frame, little-endian;
Code of the method:
private static void concatenateTwoWaves(String fileName1, String fileName2) {
        String wavFile1 = fileName1 + ".wav";
        String wavFile2 = fileName2 + ".wav";

        try {
            AudioInputStream clip1 = AudioSystem.getAudioInputStream(new File(wavFile1));
            AudioInputStream clip2 = AudioSystem.getAudioInputStream(new File(wavFile2));

            AudioInputStream appendedFiles =
                    new AudioInputStream(
                            new SequenceInputStream(clip1, clip2),
                            clip1.getFormat(),
                            clip1.getFrameLength() + clip2.getFrameLength());

            AudioSystem.write(appendedFiles,
                    AudioFileFormat.Type.WAVE,
                    new File("output.wav"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

A: One of the two formats will have to first be converted to the other. Oracle has provided the following tutorial dedicated to this topic, with examples: Using Files and Format Converters.


text:
Q: How to use one websocket connection from few controllers in Angularjs have angularjs app with few controllers.Every controller need to connect with server to receive some data. I use websocket connection.
First I did next:
  created websocket connection in every controller:
 ws = new WebSocket(wsUrl);

I used the same wsUrl for all.
But the problem is that when second connection opens, the first one doesn't response.
Than I've read that better way to make one connection and use it from diferent controllers.
the question is - how to make it? how to use websocket.onmessage from different controllers?
ws.onmessage = function (evt) {
            var data = angular.fromJson(evt.data);
            if (data.ok == false) {
                console.log('Error: {ok:false}') ;
            } else if (data.content.type != 4) {
                switch (data.state) {
                    case 'get_work_iterations':
                        listWorkIterations(data); // need to be started in controller_1

                        break;
                    case 'updateIterations':
                        updateIterations(data); //need to be started in controller_2

                }
            }
        };

A: I found the way:  http://clintberry.com/2013/angular-js-websocket-service/
with services and callbacks


text:
Q: jQuery - Get the class names of a div's children and add numerical value of them together I'm building a function based on Twitter Bootstrap's responsive grid. It uses .row-fluid as a container and spans as nodes that fit inside the rows. Each row can have a maximum of 12 'spans' in it.
I want my function to find any element with class .row-fluid, find its child nodes, take the class name, remove "span" from it (leaving only a number) and add those numbers together. If the result is bigger than 12, I'd like it to shrink the biggest number down until the number DOES equal 12.
Sounds complicated, hopefully I'm not TOO far off. Here's where I'm at so far:
$('.row-fluid').each(function() {
    var spanned = $(this).children('div[class*=span]').each(function() {
        var total = 0, nums = $(this).attr('class').match(/\d+/);
        nums.each(function() {
            total += this;
        }
        console.log(total);
    }
    );
    console.log("break");
}
);

At present this is logging the WHOLE element rather than just the numbers so I'm at a bit of a loss as to where I've gone wrong/what to do from here. Any advice?
EDIT: The structure is similar to this:

 //Function should check if the 3 above spans <= 12

 //Function should see this and...

Fluid 6

Fluid 6

Fluid 6
 //...this and see that they DON'T equal 12, then subtract 2 from the bigger span so that they DO equal 12

A: var total = 0, nums = $(this).attr('class').match(/\d+/);
Ugly line - define each var in separate line, because its easier to parse for human beeing ;]
nums = $(this).attr('class').match(/\d+/);
This is string, not a number, do such thing instead:
var numString = $(this).attr('class').match(/\d+/);
var num = parseInt(numString);

Im not sure what happens here:
nums.each(function() {
but nothing good i assume ... each function is for jQuery elements, so maybe jQuery treat your nums as jQuery object
total += this;
Generally inside each parameter function, 'this' keyword is kind of jquery selector, thats why u gets elements instead of numbers
I would say that you need to declare total variable outside spans.each(), because u will get it cleared after each iteration + do sth like that:
total += num;
assuming u will parse numString to number, as i mentioned above.

A: I'll take a wild guess, this is what you're trying to do :
$('.row-fluid').each(function(i,ele) {
    var total = 0;
    $(ele).children().each(function(i2, spans) {
        if (spans.className.indexOf('span') != -1) {
             total += parseInt(spans.className.replace(/[A-Za-z$-]/g, ""),10);
        }
    });
});