text:
Q: View holder warning after creating list view After creating a list view and assigning the text of each item with a different colour, inflater.inflate(R.layout.list_item, parent, false) within View rowView = inflater.inflate(R.layout.list_item, parent, false); becomes highlighted in yellow and I get a warning associated with my view holder. What should the affected code be changed to in order to get rid of this warning?

Unconditional layout inflation from view adapter: Should use View Holder pattern for smoother scrolling

public class FragmentColourChooserList extends android.support.v4.app.Fragment {

    public FragmentColourChooserList() {
        // Required empty constructor
    }

    ListView list_colourchooser;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View v = inflater.inflate(R.layout.fragment_colour_chooser_list, container, false);

        String[] listContent = {
                getActivity().getResources().getString(R.string.item_0),
                getActivity().getResources().getString(R.string.item_1),
                getActivity().getResources().getString(R.string.item_2),
                getActivity().getResources().getString(R.string.item_3),
                getActivity().getResources().getString(R.string.item_4),
                getActivity().getResources().getString(R.string.item_5),
                getActivity().getResources().getString(R.string.item_6),
                getActivity().getResources().getString(R.string.item_7),
                getActivity().getResources().getString(R.string.item_8),
                getActivity().getResources().getString(R.string.item_9)
        };

        list_colourchooser = (ListView)v.findViewById(R.id.list_colourchooser);
        MyColoringAdapter adapter = new MyColoringAdapter(getActivity(),listContent);
        list_colourchooser.setAdapter(adapter);

        return v;
    }

    private class MyColoringAdapter extends ArrayAdapter<String> {
        private final Context context;
        private final String[] values;

        public MyColoringAdapter(Context context, String[] values) {
            super(context, R.layout.list_item, values);
            this.context = context;
            this.values = values;
        }

        class Holder
        {
            TextView txtView;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View rowView = inflater.inflate(R.layout.list_item, parent, false);
            Holder holder = new Holder();
            holder.txtView = (TextView) rowView.findViewById(R.id.list_item);
            txtView.setText(values[position]);
            int textColorId = R.color.white; // Default color
            switch (position) {
                case 0:
                    textColorId = R.color.brown; break;
                case 1:
                    textColorId = R.color.red; break;
                case 2:
                    textColorId = R.color.yellow; break;
                case 3:
                    textColorId = R.color.green; break;
                case 4:
                    textColorId = R.color.pink; break;
                case 5:
                    textColorId = R.color.grey; break;
                case 6:
                    textColorId = R.color.purple; break;
                case 7:
                    textColorId = R.color.white; break;
                case 8:
                    textColorId = R.color.darkblue; break;
                case 9:
                    textColorId = R.color.lightblue; break;
            }
            txtView.setTextColor(getResources().getColor(textColorId));
            return rowView;
        }
    }
}

A: Try using a viewHolder class rather than getting values from rowView directly into separate types.
create a holder class
class Holder
{
    private TextView txtView;
    public TextView getTxtView()
    {
        return txtView;
    }
}

try replacing
TextView textView = (TextView) rowView.findViewById(R.id.list_item);

with
    Holder holderObject = new Holder();
    holderObject.getTxtView() = (TextView) rowView.findViewById(R.id.list_item);


text:
Q: Kibana: store and load Kibana index from another Elasticsearch server? Hihi everyone
In the configuration file of Kibana,  "config.js" we can only configure elasticsearch address and the name of the kibana index, i would like to be able to configure another ES adress for the the kibana index.
So i could store and load kibana dashboard from/to another ES server that the one i'm requesting  data.
Could anyone please help ;) thanks
Hyacinthe

redpajama_set_name: RedPajamaStackExchange


text:
Q: Probability of Overlapping Interval Suppose I have two "lanes" where each lane is made of infinite number of segments of the same length.
Example 1:
|----  --||--  ----||----  --||--- ...
|----||--  --||----||----||--  --|| ...

1st lane: segments of length 6. 2nd lane: segments of length 4.
Example 2:
|----  ----||----  ----||---- ...
|----||----||----||----||----|| ...

1st lane: segments of length 8. 2nd lane: segments of length 4
For a segment in a particular lane, how can I calculate the expected number of segments that cover it on the other side? Along with the distribution?
In example 2, the 2nd lane is always covered by the segment of the 1st lane. Hence the expected number of segments that cover it should be one, along with the distribution. Meanwhile, the 1st lane is always covered by two segments of the 2nd lane. Hence, the expected value should be two, and the distribution is (1/2, 1/2).
In example 1, the coverage distribution for the 1st lane is always either (1/3, 2/3) or (2/3, 1/3). Meanwhile, for the 2nd lane, the coverage distribution is always either (1) or (1/2, 1/2).
Is there any particular probability formula that can be referred to for calculating the expected distribution of such a case?


text:
Q: Parse nested function call string in javascript I want to parse the following string (using Javascript):
color(alias(sumSeries(sys.mem.free.*),"memory (free)"),"#00AA88")

into an array of function names and arguments:
[["color", "#00AA88"],
 ["alias", "memory (free)"],
 ["sumSeries", ""]]

plus extract the innermost string
sys.mem.free.*

The string is actually the target parameter from graphite.
I don't want to write a parser myself (dealing with things like double quotes and brackets is hard to get right).
Is there a library which helps with basic parsing?
Since it's not JSON I cannot go for a JSON parser.


text:
Q: implementing GCM communication I want to implement GCM communication in order to create push notifications, from my application server to all the devices that my app is installed  via GOOGLE's servers.
I have found a library that helps me do this the Parse library and using the dashboard given I've sent a push notification from server to device and vice-versa.
The thing is that  I want to be able to use the push notification (server side) from my website and not having to log in in Parse's. I'm pretty clueless about this, So I'd appreciate any direction and suggestion given

A: You  may start with these tutorial
Using asp.net
Redth/PushSharp  - A server-side library for sending Push Notifications to iOS (iPhone/iPad APNS), Android (C2DM and GCM - Google Cloud Message), Windows Phone, Windows 8, Amazon, Blackberry, and (soon) FirefoxOS devices!
Push Messages to GCM server using visual c#.net application (server side).
And using  PHP and MySQL
Android Push Notifications using Google Cloud Messaging (GCM), PHP and MySQL
And using Parse API
if you want to send pushnotification from parse API (not dashboard) then see
Push Notification Guide

A: There are docs in Parse for sending push notification from Ios,Android,.net,Javascript,php and REST services, use one them which is appropriate for you.
https://parse.com/docs/push_guide#top/JavaScript


text:
Q: How can I list WooCommerce orders ( WC_Order ) of certain WC_Customer? With WooCommerce 2.4.13, I would like to obtain a list of orders ( WC_Order ) of certain customers ( WC_Customer , not only the current logged-in customer ). From the documentation, the class WC_Customer has no public property / function to access associated order records.
How can I achieve this? the only solution I can think of is to fetch the raw data from the database. Any better solution?
p.s. It seems it's difficult to obtain the list of WooCommerce customers as well.

A: You can get order for a specific customer as follows:
$customer_orders = get_posts( array(
    'numberposts' => -1,
    'meta_key'    => '_customer_user',
    'meta_value'  => $user->ID,
    'post_type'   => wc_get_order_types( 'view-orders' ),
    'post_status' => array_keys( wc_get_order_statuses() )
) );

Where $user->ID is the user id of the customer for whom you want to fetch order.
Hope this helps.


text:
Q: Transfering my Clash of Clans progress from Android to Windows I have logged in with Google play games, and want to know if I can get my progress saved on my new Windows phone.

A: Does your Windows COC have the 'Link a device' option in the settings menu?
If so, on your old device, go to Settings > Devices > Link a device > This is the old device. You will be issued a code.
On your new device, Settings > Devices > Link a device > This is the new device and input the code from your old device.
The rest is pretty much self-explanatory.

A: from this day clash of clans isn't available for windows phone please do a little search before posting any question.


text:
Q: symfony post deployment error i developed web site with symfony 3 and upload it on a server but when i try to access to config.php file i have this error

Fatal error: require(): Failed opening required '/homepages/26/d729697492/htdocs/Media/vendor/composer/../symfony/symfony/src/Symfony/Component/VarDumper/Resources/functions/dump.php' (include_path='.:/usr/lib/php7.0') in /homepages/26/d729697492/htdocs/Media/vendor/composer/autoload_real.php on line 66

and don't understand i search everywhere no good answer .

A: i just delete all my files on server and after re-upload all my files without vendor directory and after i install all my dependencies via composer install it works. thank


text:
Q: Android TCP socket connection with server whose IP is dynamically assigned Someone please help, I have two devices connected to a wifi router. One of the device is android mobile which works as a TCP client and the other device is a wifi module which works as the TCP server. I am able to open a TCP socket and send message but the problem is the IP address of the wifi module is getting changed by the WiFi router because of DHCP. How can i know the IP address of my WiFI module dynamically Please let me know if any of these methods work or which of these would be a better option or any other better option available that this

*

*Send a broadcast TCP message(i know broadcast are not allowed in TCP and is one to one protocol but in any way that i can do)

*Access wifi routers ARP cache table and get the ip address corresponding to that mac address

*Do an RARP for a particular mac address    -Ping every device on the subnet until i find my device(which im not comfortable doing
    it)

I want the solution in android.Somebody please help.
Thanks


text:
Q: Update panel and javascript I have a user control whose structure is -
<updatepanel UpdateMode="Always">
<ContentTemplate>
   <asp:FormView>
    <EditItemTemplate>

                 Textbox1
                 btn1

                  textbox2

   </EditItemTemplate>
  </asp:FormView>
</ContentTemplate>
</updatepanel>

On page load I use following to hide tr2
ClientScriptManager cs = Page.ClientScript;
csText.AppendLine("");
csText.AppendLine("if(document.getElementById('tr2')!=null)
           document.getElementById('tr2').style.display = 'none';");
csText.AppendLine("");
cs.RegisterStartupScript(this, this.GetType(), csName, csText.ToString(), false);

This part is working fine. Now on click of the btn1 I am popping up the modal popup extendar control. This causes the tr2 to show again. I know that the script needs to be inline with the updatePanel. I tried using ScriptManager.RegisterStartupScript(....); but does not work. Also the updateMode needs to be always so that the data from pop extendar can be put inside the Textbox1
All the help is appreciated.
Thank you

A: Since you're using an UpdatePanel, you don't really need any javascript for this.
If you change your tr2 element to ...

this will allow you to control it in your server side code. To hide your tr2 row, simply do...
tr2.Style["display"] = "none";

this should keep things in sync nicely on callbacks.


text:
Q: Sencha Touch + PhoneGap not finding PhoneGap API I am new in Apps World, and I started developing with Sencha Touch + PhoneGap.
I think I installed everything right following these: http://docs.sencha.com/touch/2.3.1/#!/guide/cordova and http://vimeo.com/76568053.
My setup:

*

*Windows 7 x64

*GIT 1.9.4.msysgit.0

*NODEJS 1.4.9

*RUBY 2.0.0p481

*Sencha Touch 2.3.1

*Sencha Cmd 5.0.0.160

*Cordova 3.5.0-0.2.4

*PhoneGap 3.5.0-0.20.4

*ANT 1.9.4

*SASS

*COMPASS

*ANDROID ADK

Both are the last versions up-to-now. All paths set!
After that I created my new app following both links steps.

*

*sencha -sdk mypath/touch-2.3.1 generate app TestCordova TestCordova

*sencha cordova init com.sencha.TestCordova

*I opened the app.js and put inside launch: function() the line: alert(device.uuid); So I can access the device UUID that cordova API gives.

*Then I entered in the cordovas folder and write in cmd: cordova plugin add org.apache.cordova.device

*Finally I returned the folder and write: sencha app build -run native

That works perfectly, it opened the emulator and appears the UUID and then the Sencha default app.
The problem comes when I tried to work with PhoneGap, I did the same steps:

*

*sencha -sdk mypath/touch-2.3.1 generate app TestPhoneGap TestPhoneGap

*sencha phonegap init com.sencha.TestPhoneGap

*I opened the app.js and put inside launch: function() the line: alert(device.uuid); So I can access the device UUID that phonegap API gives.

*Then I entered in the phonegaps folder and write in cmd: phonegap plugin add org.apache.cordova.device

*Finally I returned the folder and write: sencha app build -run native

The device UUIDS doesn't appeared. When I use if(Ext.browser.is.PhoneGap) it returns false.
What is the problem? Why in cordova works and in phonegap it doesn't?

A: Check that cordova.js (probably best now with 3.5.0+) or phonegap.js are being loaded in your app.json file. Needs to load before sencha touch ...
"js": [
    {
        "path": "cordova.js",
        "remote": true
    },
    {
        "path": "touch/sencha-touch.js",
        "x-bootstrap": true
    },
    {
        "path": "bootstrap.js",
        "x-bootstrap": true
    },
    {
        "path": "app.js",
        "bundle": true,  /* Indicates that all class dependencies are concatenated into this file when build */
        "update": "delta"
    }
],

To get you started you might like to try the Sencha Touch Live app I wrote that will create, compile, deploy and run a Sencha Touch + PhoneGap app that you can then "live edit" changes into the device or emulator.
A simple way to get started debugging is to use GenyMotion Android simulator with Android 4.4+ so you can use Chrome's remote debugger from your desktop computer. Just open chrome://inspect and select the active instance of your app on the attached device or emulator.  Can do the same with recent Safari/iOS.  See installation details below.  This should help you to set breakpoints and diagnose the fault.
You might also fine the detailed installation check list helpful.


text:
Q: PHP doesn't see 2 equal strings So I'm busy on a verification system, when the player of the game puts a sentence in his/her status, in this case: HT-N5I4-S3ZI-GU6A and my script checks if it's the same one as the code in my db. If it is, its proven to be their account. Because I've experienced that people make accounts under fake names.
When I echo the code in my db, it echoes:
HT-N5I4-S3ZI-GU6A
And the one in my test players mission echoes:
HT-N5I4-S3ZI-GU6A
It is exactly the same code, but when I wanna compare them like this:
    if($_SESSION['user']['email_activation'] == $functions->getMotto($_SESSION['user']['username']))
    {
        echo "Works";
    }
    else
    {
        echo "Doesnt work";
    }

It aways echoes 'doesn\'t work'. Did I use the wrong equalization operator? Or any other mistakes?
Thanks

A: Try This Code
if($_SESSION['user']['email_activation'] === $functions->getMotto($_SESSION['user']['username']))
{
    echo "Works";
}
else
{
    echo "Doesnt work";
}

Thanks.


text:
Q: iOS 13 - FileManager url(forPublishingUbiquitousItemAt:expiration:) not working anymore I've developed an iOS app that uses the url(forPublishingUbiquitousItemAt:expiration:) method of Apple's FileManager class. Starting with the first Beta of iOS 13 this function stopped working and now it throws an error, stating "This code has been removed. You should switch off of this SPI". But I can't find anything related to this function neither in the release notes of iOS nor in the documentation for this function, and it even states there that it would be supported on Mac Catalyst 13.0+.
This also has nothing to do with Xcode 10 and 11, as it occurs when the app is built using either one of those versions.
Does anyone of you know more about that? It would be great to get new information on that.
Thanks,
Fabian.

A: This is fixed in iOS 13 beta 6. Updated today and this error magically disappeared!
Had my mind blown when I saw this error message.


text:
Q: Windows Azure Active Directory slow authentication on mobile devices I have a web site authenticating against Windows Azure Active Directory. It authenticates very quickly on desktop web browsers, but excruciatingly slowly on mobile devices (iOS, Android). Can anyone offer a possible explanation of why this is--and can anything be done about it? It takes minutes to authenticate on these devices which isn't a very good experience for users.

A: David,
Is it correct that your site is using wsfed and redirects to AAD where the client enters creds?
Do you notice where the slowdown occurs, is it before the user enters cred (if they do) or after?
Brent.


text:
Q: CSS: Wrap background-color on headlines I have a styled headline inside an CMS system with a background color. When the headline wraps on mobile devices (example width would be 500px), there is a large space on the right and the width of the div does not adjust.
How can I manage to do that?

.inside {
  position: relative;
  width: 1280px;
  max-width: 100%;
  margin: 0 auto;
  display: flex;
  flex-wrap: wrap;
}

.ce_headline {
  display: flex
}

.col-12 {
  flex: 0 0 100%;
  max-width: 100%;
  position: relative;
  width: 100%;
  min-height: 1px;
  padding-right: 15px;
  padding-left: 15px;
}

.ce_headline.angled h2 {
  clip-path: polygon(2vh 0, 100% 0, calc(100% - 2vh) 100%, 0 100%);
  padding: 10px 40px;
  -webkit-clip-path: polygon(2vh 0, 100% 0, calc(100% - 2vh) 100%, 0 100%);
}

.ce_headline h2 {
  font-family: Raleway, "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
  font-weight: 800;
  color: #fff;
  background: green;
}

 That is an example headline

A: G'day mate!
Just add this code into your  parameters!
body{margin:0;padding:0;}
*{box-sizing: border-box;}


text:
Q: SQL Server- How can I perform the same function as Excel index/match? So I have the following code which works fine:
SELECT
    CODE,
    TRADEDATE,
    SETTLE,
    SUBSTRING(EXPIRY, 1, 1) AS CONTRACT_CODE,
    SUBSTRING(EXPIRY, 2, 4) AS CONTRACT_YEAR
FROM
    QUANDL.DBO.AR_MWCS$
INNER JOIN
    QUANDL.DBO.AR_MWCF$ ON QUANDL.DBO.AR_MWCS$.FULL_code = QUANDL.DBO.AR_MWCF$.FULL_CODE
 WHERE
    CODE IN ('CI', 'TC', 'PG', 'PW', 'NG', 'NL', 'PD', '8X', 'PH', 'PM', 'NJ', 'NX', 'TZ6', 'TR', 'NW', 'CL', 'CY', 'WJ')
    AND EXPIRY IN ('H2020')
ORDER BY
    CODE ASC, TRADEDATE DESC, EXPIRY ASC

The output looks like this:

I have another table called "contract_key" which contains two columns. One is "contract_code" and the other is "contract_month". What I need is to join the tables so I can see the contract_month, March, instead of the contract_code, H.
In Excel it would be
=INDEX(A:A, MATCH(E2,B:B,0))

where column A is the month and column B is the code,cell E2 is the code H and the formula returns "3".
The desired output would look like this instead:

I'm using AR_MWCS$ to pull in the settle price. The table looks like this:

Table AR_MWCF$ looks like this:

I'm using substring to split EXPIRY into "H" and "2020"
Table CONTRACT_KEY looks like this:

So I need to join the CONTRACT_CODE from table CONTRACT_KEY and the substring CONTRACT_CODE created from table AR_MWCF$ to find the contract month then combine the contract month with the contract year as a date.
I was able to get my desired output by modifying the code to:
SELECT
     CODE
    ,TRADEDATE
    ,SETTLE
    ,CONCAT(CONTRACT_MONTH,'-','01','-',CONTRACT_YEAR) AS EXPIRATION

FROM
     QUANDL.DBO.AR_MWCS$

INNER JOIN
    QUANDL.DBO.AR_MWCF$
 ON QUANDL.DBO.AR_MWCS$.FULL_code = QUANDL.DBO.AR_MWCF$.FULL_CODE

INNER JOIN
    QUANDL.DBO.CONTRACT_KEY
ON QUANDL.DBO.AR_MWCF$.CONTRACT_CODE = QUANDL.DBO.CONTRACT_KEY.CONTRACT_CODE

WHERE
    CODE IN ('CI','TC','PG','PW','NG','NL','PD','8X','PH','PM','NJ','NX','TZ6','TR','NW','CL','CY','WJ')

ORDER BY
    CODE ASC, TRADEDATE DESC, EXPIRY ASC

Which returns the following:

A: SELECT
     CODE,
     TRADEDATE,
     SETTLE,
     contract_key.contract_month AS Expiration
FROM QUANDL.DBO.AR_MWCS$
INNER JOIN QUANDL.DBO.AR_MWCF$
           ON QUANDL.DBO.AR_MWCS$.FULL_code = QUANDL.DBO.AR_MWCF$.FULL_CODE
INNER JOIN contract_key ON contract_key.contract_code = QUANDL.DBO.AR_MWCS$.FULL_code

We do not know which, if any, of your original tables contains a joinable "CODE" field.  I used MWCS$.FULL_Code as the joinable table and field.  Use MWCS$ or MWCF$ and FULL_Code or PARTIAL_code or CD as the case may be for the Excel field you seek.
 WHERE
    CODE IN ('CI', 'TC', 'PG', 'PW', 'NG', 'NL', 'PD', '8X', 'PH', 'PM', 'NJ', 'NX', 'TZ6', 'TR', 'NW', 'CL', 'CY', 'WJ')
    AND EXPIRY IN ('H2020')
ORDER BY
    CODE ASC, TRADEDATE DESC, EXPIRY ASC

A: This code worked for what I needed:
SELECT
     CODE
    ,TRADEDATE
    ,SETTLE
    ,CONCAT(CONTRACT_MONTH,'-','01','-',CONTRACT_YEAR) AS EXPIRATION

FROM
     QUANDL.DBO.AR_MWCS$

INNER JOIN
    QUANDL.DBO.AR_MWCF$
 ON QUANDL.DBO.AR_MWCS$.FULL_code = QUANDL.DBO.AR_MWCF$.FULL_CODE

INNER JOIN
    QUANDL.DBO.CONTRACT_KEY
ON QUANDL.DBO.AR_MWCF$.CONTRACT_CODE = QUANDL.DBO.CONTRACT_KEY.CONTRACT_CODE

WHERE
    CODE IN ('CI','TC','PG','PW','NG','NL','PD','8X','PH','PM','NJ','NX','TZ6','TR','NW','CL','CY','WJ')

ORDER BY
    CODE ASC, TRADEDATE DESC, EXPIRY ASC


text:
Q: Função para ler arquivo em C Qual função usar em C para ler arquivo, linha por linha, e em cada linha contém tipos de dados diferentes?

A: Geralmente o que precisa é alguma variação do fscanf(). Eventualmente pode usar também vfscanf().

A: Para ler arquivo você pode utilizar o fgets :
#define N 10000
    [...]
      FILE *arquivo;
      arquivo=fopen("lugar.txt","r");
            if(arquivo == NULL)
            printf("Erro, nao foi possivel abrir o arquivo\n");
    else{
      while (fgets(linha, sizeof linha, arq3)) {
       //e se quiser escrever na tela na tela
       printf("%s",linha);
      }
     fclose(arquivo);
      }


text:
Q: Install .deb package on a Yocto system I have a Yocto system on which I need to install a .deb package. I do understand that some recipes need to be written, however, I am a newbie to this. Can some guide me on what the exact recipe is and/or how to write these recipes
root@cs15ka# uname -a Linux cs15ka 3.16.56-yocto-standard #1 SMP
PREEMPT Fri Oct 19 01:35:20 PDT 2018 x86_64 GNU/Linux

A: You can write a recipe modeled around something like below, fill in the details for the deb package you want to repackage using OE build system, this will take the .deb file and repackage into what you can then bundle into OE built image. Be aware that there might be binary dependencies that could be incompatible with versions of libraries etc. since the package is built using a different build system and meant for another debian-like OS. So you might have to provide correct versions etc again with additional recipes.
inherit bin_package

DESCRIPTION = "..."
LICENSE = "MIT"

PROVIDES = "..."
SRC_URI = " \
https://deb.nodesource.com/node_8.x/pool/main/n/nodejs/${DEB_FILENAME} \
"

LIC_FILES_CHKSUM = "..."

PROVIDES = "..."
RPROVIDES_${PN} = ".."

do_install_append () {
   ...
}

FILES_${PN} += "..."


text:
Q: Spring Integration Re-Processing Messages I am building an application for work using Spring Integration, and I am completely new to the framework.
I am using an idempotent receiver to check a database to see if I have seen the ID of a message before, and if I have, the message gets passed to an aggregator. Once the message has been aggregated a new message is sent to the following handler.
The issue I am seeing is when the message fails in the handler, it seems to get re-queued somehow. What I see in the logs is the idempotent receiver will drop messages it has seen, pass a message along it hasn't to the aggregator, and that message will fail. The next cycle the idempotent receiver will drop the message that had failed before. The cycle after that, the idempotent receiver will pass the message along, and it will fail again causing the cycle to start over.
What am I missing?

A: Not clear what you mean and what you expect. First of all a purpose of Idempotent Received do not process the same message again. According your description you expect something opposite:

The logic of the IdempotentReceiverInterceptor is based on the provided MessageSelector and, if the message isn't accepted by that selector, it will be enriched with the duplicateMessage header set to true. The target MessageHandler (or downstream flow) can consult this header to implement the correct idempotency logic. If the IdempotentReceiverInterceptor is configured with a discardChannel and/or throwExceptionOnRejection = true, the duplicate Message won't be sent to the target MessageHandler.handleMessage(), but discarded.

The very important word there is duplicate. So, please, reconsider your treatment for the Idempotent Receiver.
What you describer further with the failure, re-queuing and reprocessing sounds for me like transaction rollback. And that's also true if you use IdempotentReceiverInterceptor based on the JdbcMetadataStoreTests and all the data stored during roll backed TX will be dropped because no commit.
That might be easier for us to help you if you share a simple Spring Boot application on GitHub to let us to reproduce and understand better what's going on. Otherwise your question isn't clear and becomes a good candidate to be closed here by StackOverflow policies.


text:
Q: Like Button In Django Ajax my like button is working fine without ajax with page reloading but it is having problem when done by implementing ajax. the like and unlike is happening in the backend (like is created and deleted in database on ajax Post request), but the like count,like,unlike button does not change in response on ajax post request, until the page is reloaded. Need Help
here is the post model and like model for posting image and liking it in models.py
class PostModel(models.Model):
 user = models.ForeignKey(UserModel)
 image = models.FileField(upload_to='user_images')
 image_url = models.CharField(max_length=255)
 caption = models.CharField(max_length=240)
 created_on = models.DateTimeField(auto_now_add=True)
 updated_on = models.DateTimeField(auto_now=True)
 has_liked = False

 @property
 def like_count(self):
 return len(LikeModel.objects.filter(post=self))

 class LikeModel(models.Model):
  user = models.ForeignKey(UserModel)
  post = models.ForeignKey(PostModel)
  created_on = models.DateTimeField(auto_now_add=True)
  updated_on = models.DateTimeField(auto_now=True)

url for liking in urls.py
    url(r'^like/', like_view),

views.py
 def like_view(request):
    user = check_validation(request)
    if user and request.method == 'POST':
       form = LikeForm(request.POST)
       if form.is_valid():
           #post_id = form.cleaned_data.get('post').id
           post_id=request.POST['post']

           existing_like = LikeModel.objects.filter(post_id=post_id, user=user).first()

           if not existing_like:
                LikeModel.objects.create(post_id=post_id, user=user)
           else:
                existing_like.delete()

        return redirect('/feed/')

    else:
        return redirect('/login/')

template.html
    {% for post in posts %}
    <form id="like_form">
      {% csrf_token %}
      <input type="hidden" name="post" id="post_id"value="{{ post.id }}">
      {% if post.has_liked %}
      <button class="btn btn-link unlike"type="submit"></button>
      {% else %}
      <button class="btn btn-link like"type="submit"></button>
      {% endif %}

     </form>
    {% endfor %}

Javascript code


text:
Q: How does scaling friction in Langevin equation effect time delayed cross correlations? Assume we have a stochastic process
$$
dX_t = V_tdt
$$
$$
dV_t = -KX_tdt -MV_tdt +dB_t.
$$
with $X_t \in \mathbb{R}^n$ representing position and $V_t$ velocity. This is a linear elastic model described by the equation
$$
dZ_t = AZ_t dt + dB_t
$$
where $A$ is a $2n \times 2n$ matrix which has $0$ and $I$ on top $n\times 2n$ part of $A$ and $-K$, $-M$ on bottom $n \times 2n$ part. Here $M$ represents friction terms. I want to understand how scaling of $M$ by a uniform constant effects the normalized time delayed cross correlations:
$$
C(\epsilon) = \lim_{t\rightarrow \infty} \frac{\mathbb{E}(Z(t+\epsilon)Z^T(t))}{\sqrt{\mathbb{E}(Z(t+\epsilon)^2)\mathbb{E}(Z(t)^2)}}
$$
This matrix $A$ usually has some $0$ eigenvalues and in such cases calculating the correlation matrix above one needs to quotient them out otherwise the limit as $t$ goes to infinity does not converge.  But otherwise you more or less treat it like the regular case where you disregard the zero eigenvalue in any summation over eigenvalues that appear. Now I did some computational experiments and I see that if I scale $M$ by some large constant $\mu$ then the decay rate of $C(\epsilon)$ slows down considerably while if I decrease friction by scaling $M$ by a small constant the decay rate increases up to a point where if it is too small then you again get a slow decay rate. Of course the correlation matrix does not converge if the friction is $0$ so I can test very small values but beyond a certain value it might not be reasonable. So my question is:
1-Is this the kind of behavior one should expect,
2-And if so does any body have a better explanation for this physical intuition or mathematical that is better than some numerical simulations.
3-No matter what the values are $C(\epsilon)$ decays to $0$ as $\epsilon$ goes to $\infty$ which kind of makes sense from a physical point of view but is it somehow possible to devise systems where the time delayed cross correlations dont go to $0$?

A: We have
\begin{align}
\mathrm{d}\mathbf{x}_t &= \mathbf{v}_t \mathrm{d}t \\
\mathrm{d}\mathbf{v}_t &= -K \mathbf{x}_t \mathrm{d}t - M
\mathbf{v}_t\mathrm{d}t + \sigma_v\mathrm{d}\mathbf{B}_t
\end{align}
where I assume $M$, $\sigma$ are diagonal, $K$ not so, and the Brownian processes are uncorrelated.
Defining $\mathbf{z}_t = (\mathbf{x}_t, \mathbf{v}_t)$,
$$\mathrm{d}\mathbf{z}_t = \begin{pmatrix}0 & I \\ -K & -M \end{pmatrix} \mathbf{z}_t \mathrm{d}t + \sigma\mathrm{d}\mathbf{W}_t$$
Where the Brownian process bit changed notation as it now has length $2n$, and the first matrix we define as $A$.
The solution is now (Ornstein-Uhlenbeck), so you can just use this directly instead of running simulations:
$$\mathbf{z}_t = e^{tA}\mathbf{z}_0 + \int_0^t e^{-(s-t)A}\sigma\mathrm{d}\mathbf{W}_s$$
We want to compute the autocorrelation,
$$C(\varepsilon) = \frac{\operatorname{cov}(\mathbf{z}_t, \mathbf{z}_{t+\varepsilon})}{\sqrt{\operatorname{var}(\mathbf{z}_t)\operatorname{var}(\mathbf{z}_{t+\varepsilon})}}$$
Now (Ito isometry): $\operatorname{var}(\mathbf{z}_t) = \int_0^t \left(e^{-(s-t)A}\sigma\right)^2\mathrm{d}s$, and with some additional mathematical assuptions ($A$ invertible), $\operatorname{var}(\mathbf{z}_t) = \frac{1}{2}\sigma^2A^{-1}(e^{2tA}-I)$. Similarly $\operatorname{cov}(\mathbf{z}_t, \mathbf{z}_{t+\varepsilon}) = e^{\varepsilon A}\operatorname{var}(\mathbf{z}_t)$.
With some physics intuition from O-U processes, let's say that the variance is bounded (because some part of the network holds the entire thing close to a fixed coordinate, and the friction dissipates the rest; you could say that the system as a whole is free to move, but then you'd make a similar argument restricting all parts of the system to the center of mass; if the system is really two separate systems, we would just separate those into two and treat each in turn).
Put another way: $\lim_{t\to\infty} e^{2tA} = 0$ (i.e. $\lim_{t\to\infty} \operatorname{var}(\mathbf{z}_t) = - \frac{1}{2}\sigma^2A^{-1}$), so we see that $\lim_{\varepsilon\to\infty} C(\varepsilon) = 0.$


text:
Q: Mouse cursor does not 'stick' to silverlight scrollbar control I'm using the silverlight scrollbar and I'm finding that the mouse does not drag the scrollbar 1:1. When I drag downwards for instance I find the mouse cursor starts going down further than the scrollbar has..
edit: this issue occurs in IE8 but not Firefox 5.

A: Are you working with datasets or trying to display large, complex data within the object whatever the scrollbar is attached to?
If yes, try toggling UI virtualization and see if it changes anything.
If it doesn't work it may be something to do with GPU acceleration. Just toggle GPU acceleration in both SL project and IE. Sometimes when CPU loads a lot while scrolling, it just doesn't scroll correctly because of this, well, I call "lag".


text:
Q: Getting an error when trying to delete objects with Entity Framework 4 I'm getting the following error when trying to delete objects in my database while using Entity Framework 4.

"Unable to update the EntitySet 'SampleDetails' because it has a
  DefiningQuery and no  element exists in the
   element to support the current
  operation."

It seems to be a common problem with lots of solutions on Google but nothing seems to work for me. The affected table has a composite primary key made up of three fields.
I have tried deleting the <DefiningQuery> elements but then I can't read the data from the database in the first place.

A: You need to add primary key as a separate column like i.e. SampleDetailsID to SampleDetails.


text:
Q: Dynamic element not attaching to on() function? Im currently using the on() function to attach to dynamic elements in my application which are loaded initially but then reloaded via ajax. Due to the reloading this code
$('a.open-drawer').on('click', function(event){..});

Works well initially but on ajax reload it doesnt. I've resolved to use the data selector in the on() function instead
$('body').on('click', 'a.open-drawer', function(event){..});

But this one now doesnt work completely!!!! Ive used this second option repeatedly in my application and it works in the other cases. What Im I doing wrong?


text:
Q: How to implement Zebra Striping in handlebar.js tables? I found out that we can leverage an @index in an #each helper, but that doesn't seem to help much.
I am trying to implement optional zebra striping in some handlebar templates.
{#if ((@index % 2) == 0) }}

{{else}}

{{/if}}

But when I compile the template the error is
>> Error: Parse error on line 3:
        {{#if ((@index % 2) == 0)
>> ----------------------^
>> Expecting 'CLOSE', 'CLOSE_UNESCAPED', 'STRING', 'INTEGER', 'BOOLEAN', 'ID', 'DATA', 'SEP', got 'INVALID'

Is it possible to do something like this?

A: I've implemented my own solution by modifying the each helper.  Here's my new each code in the handlebars.js file
instance.registerHelper('each', function(context, options) {
  var fn = options.fn, inverse = options.inverse;
  var i = 0, ret = "", data;

  if (isFunction(context)) { context = context.call(this); }

  if (options.data) {
    data = createFrame(options.data);
  }

  if(context && typeof context === 'object') {
    if (isArray(context)) {
      for(var j = context.length; i<j; i++) {
        if (data) {
          // For zebra tables
          data.zebra = (((i+1)%2) == 0) ? "even" : "odd";
          // end mod
          data.index = i;
          data.first = (i === 0);
          data.last  = (i === (context.length-1));
        }
        ret = ret + fn(context[i], { data: data });
      }
    } else {
      for(var key in context) {
        if(context.hasOwnProperty(key)) {
          if(data) {
            data.key = key;
            data.index = i;
            data.first = (i === 0);
          }
          ret = ret + fn(context[key], {data: data});
          i++;
        }
      }
    }
  }

  if(i === 0){
    ret = inverse(this);
  }

  return ret;
});

And I use it in {{#each xx}} loops in my templates by putting the class="{{@zebra}}" on my divs or trs.
Hope this helps others!


text:
Q: Does the Microsoft Graph API provide access to the Change History (Cell level) of a Workbook or WorkSheet? Inside of OneDrive you can open an Excel Workbook/WorkSheet and see the history of all the version updates (exactly what you see in DriveItem Versions). However, you can drill down into the version entry and see that a web call is made to get a list of all the cell changes made.
I really need a way to programmatically connect to an Excel Sheet in OneDrive and see all the changes made since the last time I looked. Then look at those changes and decide what I want to do with them.
I have looked in the documentation for v1.0 and the Beta. I don't think this is provided, at least not in a way I can recognize.  Thoughts? Suggestions?


text:
Q: How to write to a JSON file in the correct format I am creating a hash in Ruby and want to write it to a JSON file, in the correct format.
Here is my code:
tempHash = {
    "key_a" => "val_a",
    "key_b" => "val_b"
}
fJson = File.open("public/temp.json","w")
fJson.write(tempHash)
fJson.close

And here is the contents of the resulting file:
key_aval_akey_bval_b

I'm using Sinatra (don't know what version) and Ruby v 1.8.7.
How can I write this to the file in the correct JSON format?

A: To make this work on Ubuntu Linux:

*

*I installed the Ubuntu package ruby-json:
apt-get install ruby-json

*I wrote the script in ${HOME}/rubybin/jsonDEMO

*$HOME/.bashrc included:
${HOME}/rubybin:${PATH}

(On this occasion I also typed the above on the bash command line.)
Then it worked when I entered on the command line:
jsonDemo

A: This question is for ruby 1.8 but it still comes on top when googling.
in ruby >= 1.9 you can use
File.write("public/temp.json",tempHash.to_json)

other than what mentioned in other answers, in ruby 1.8 you can also use one liner form
File.open("public/temp.json","w"){ |f| f.write tempHash.to_json }

A: Require the JSON library, and use to_json.
require 'json'
tempHash = {
    "key_a" => "val_a",
    "key_b" => "val_b"
}
File.open("public/temp.json","w") do |f|
  f.write(tempHash.to_json)
end

Your temp.json file now looks like:
{"key_a":"val_a","key_b":"val_b"}

A: With formatting
require 'json'
tempHash = {
    "key_a" => "val_a",
    "key_b" => "val_b"
}
File.open("public/temp.json","w") do |f|
  f.write(JSON.pretty_generate(tempHash))
end

Output
{
    "key_a":"val_a",
    "key_b":"val_b"
}


text:
Q: Getting specific child in xml file in Python How can I get the what is in the "Code", and "ModificationDate" attribute? The picture is showing what is in that tag "IntraModelReport". I know it prints out everything in the tag IntraModelReport. But I just want two attributes in that tag. I also want to note I get an error message at the end that says "find() missing 1 required positional argument: 'self'"
from bs4 import BeautifulSoup
with open(r'INTERACTION CDM.cdm') as f:
    data =f.read()
#passing the stored data inside the beautiful soup parser
soup = BeautifulSoup(data, 'xml')

unquieID = soup.find('ObjectID')
print(unquieID)

#Finding all instances of a tag.
intraModelReportTag = soup.find("IntraModelReport")
print(intraModelReportTag)

tag = soup.find(attrs={"IntraModelReport" : "Code"})
output = tag['Code']
print(tag)
print(output)

<Model xmlns:a="attribute" xmlns:c="collection" xmlns:o="object">

<o:RootObject Id="o1">
<a:SessionID>00000000-0000-0000-0000-000000000000</a:SessionID>
<c:Children>
<o:Model Id="o2">
<a:ObjectID>875D4C90-849D-43C2-827A-0BE7CA7265A4</a:ObjectID>
<a:Name>INTERACTION CDM</a:Name>
<a:Code>INTERACTION_CDM</a:Code>
<a:CreationDate>1578996736</a:CreationDate>
<a:Creator>b0000001</a:Creator>
<a:ModificationDate>1582198848</a:ModificationDate>
<a:Modifier>b0000001</a:Modifier>
<a:PackageOptionsText>[FolderOptions]

[FolderOptions\Conceptual Data Objects]
GenerationCheckModel=Yes
GenerationPath=
GenerationOptions=
GenerationTasks=
GenerationTargets=
GenerationSelections=</a:PackageOptionsText>
<a:ModelOptionsText>[ModelOptions]
.....

<c:Reports>
<o:IntraModelReport Id="o76">
<a:ObjectID>72517613-3F32-4E3D-8E4A-CDD186B0CBA3</a:ObjectID>
<a:Name>INTERACTION CDM</a:Name>
<a:Code>INTERACTION_CDM</a:Code>
<a:CreationDate>1578997381</a:CreationDate>

<a:ModificationDate>1578997500</a:ModificationDate>
<a:Modifier>b0000001</a:Modifier>
<a:ReportFirstPageTitle>INTERACTION CDM</a:ReportFirstPageTitle>
<a:ReportFirstPageAuthor>b0000001</a:ReportFirstPageAuthor>
<a:ReportFirstPageDate>%DATE%</a:ReportFirstPageDate>
<a:HtmlStylesheetFile>PWI_Theme.css</a:HtmlStylesheetFile>
<a:HtmlHeaderFile>Header_PWI.htm</a:HtmlHeaderFile>
<a:HtmlFooterFile>Footer_PWI.htm</a:HtmlFooterFile>
<a:HtmlHeaderSize>54</a:HtmlHeaderSize>
<a:HtmlFooterSize>18</a:HtmlFooterSize>
<a:HtmlTOCLevel>4</a:HtmlTOCLevel>
<a:HtmlHomePageFile>Home_PWI.html</a:HtmlHomePageFile>
<a:HtmlTemplate>PWI</a:HtmlTemplate>
<a:RtfTemplate>Professional</a:RtfTemplate>
<a:RtfUseSectionHeadFoot>1</a:RtfUseSectionHeadFoot>
<c:Paragraphs>

A: To get the "Code" and "ModificationDate", call the tag names as follows:
...
intra_model_report_tag = soup.find("o:IntraModelReport")

print(intra_model_report_tag.find("a:Code").text)
print(intra_model_report_tag.find("a:ModificationDate").text)

Output:
INTERACTION_CDM
1578997500


text:
Q: Div is not being placed next to each other Essentially I have some text message bubbles. I want to put in the date and time next to the bubbles (respectively) but they don't seem to be placed in the right place. As you can see the blue text bubble has the date displayed on the right hand side of the bubble and the grey bubble has text displayed on the left hand side of the bubble.
How I want it to look

How it actually looks

Could someone please help me with this. I am very confused

@import url('https://fonts.googleapis.com/css?family=Roboto&display=swap');
.chat {
  width: 320px;
  display: block;
  margin-left: auto;
  margin-right: auto;
  font-family: 'Roboto', sans-serif;
}

p {
  margin: 0.5em 0em;
}

.them-bubble {
  margin: 0 0 0.5em;
  border-radius: 1em;
  padding: 0px 16px;
  background: #e5e5ea;
  max-width: 75%;
  clear: both;
  position: relative;
  float: left;
}

.them-bubble::after  {
  content: "";
  position: absolute;
  left: -0.5em;
  bottom: 0;
  width: 0.5em;
  height: 1em;
  border-right: 0.5em solid #e5e5ea;
  border-bottom-right-radius: 1em 0.5em;
}

.me-bubble {
  margin: 0 0 0.5em;
  border-radius: 1em;
  padding: 0px 16px;
  max-width: 75%;
  clear: both;
  position: relative;
  float: right;
  float: right;
  background-color: #1289fe;
  color: white;
}

.me-bubble::after  {
  content: "";
  position: absolute;
  right: -0.5em;
  bottom: 0;
  width: 0.5em;
  height: 1em;
  border-left: 0.5em solid #1289fe;
  border-bottom-left-radius: 1em 0.5em;
}

.me-date {
    color: #98979c;
    font-size: 12px;
    font-weight: 700;
    width: 65px;
    float: right;
}

.them-date {
    color: #98979c;
    font-size: 12px;
    font-weight: 700;
    width: 65px;
    float: left;
}

22/11/19 11:42 PM

Hello how are you

22/11/19 11:43 PM

I am good, how are you?

22/11/19 11:44 PM

I am fantastic. This is a long message so the bubble goes down into another couple lines. Typing more text here

22/11/19 11:43 PM

This is a really long reply so the messahe makes multiple bubbles. More typing here

22/11/19 11:46 PM

Double sending them message

22/11/19 11:46 PM

Triple sending them message and this is a double long bubble

A: With flexbox and five style rules, you can create this effect:

/* New Code */

.message {
  display: flex;
  margin-bottom: 10px;
  align-items: center;
}

.message .me-date {
  order: 2;
}

.message .me-bubble {
  margin-left: auto;
}

.message .me-date {
  text-align: right;
}

.message .me-bubble,
.message .them-bubble {
  max-width: 200px;
}

@import url('https://fonts.googleapis.com/css?family=Roboto&display=swap');
.chat {
  width: 320px;
  display: block;
  margin-left: auto;
  margin-right: auto;
  font-family: 'Roboto', sans-serif;
}

p {
  margin: 0.5em 0em;
}

.them-bubble {
  margin: 0 0 0.5em;
  border-radius: 1em;
  padding: 0px 16px;
  background: #e5e5ea;
  max-width: 75%;
  clear: both;
  position: relative;
  float: left;
}

.them-bubble::after {
  content: "";
  position: absolute;
  left: -0.5em;
  bottom: 0;
  width: 0.5em;
  height: 1em;
  border-right: 0.5em solid #e5e5ea;
  border-bottom-right-radius: 1em 0.5em;
}

.me-bubble {
  margin: 0 0 0.5em;
  border-radius: 1em;
  padding: 0px 16px;
  max-width: 75%;
  clear: both;
  position: relative;
  float: right;
  float: right;
  background-color: #1289fe;
  color: white;
}

.me-bubble::after {
  content: "";
  position: absolute;
  right: -0.5em;
  bottom: 0;
  width: 0.5em;
  height: 1em;
  border-left: 0.5em solid #1289fe;
  border-bottom-left-radius: 1em 0.5em;
}

.me-date {
  color: #98979c;
  font-size: 12px;
  font-weight: 700;
  width: 65px;
}

.them-date {
  color: #98979c;
  font-size: 12px;
  font-weight: 700;
  width: 65px;
}

.chat {
  min-width: 400px;
  width: 100%;
}

22/11/19 11:42 PM

Hello how are you

22/11/19 11:43 PM

I am good, how are you?

22/11/19 11:44 PM

I am fantastic. This is a long message so the bubble goes down into another couple lines. Typing more text here

22/11/19 11:43 PM

This is a really long reply so the messahe makes multiple bubbles. More typing here

22/11/19 11:46 PM

Double sending them message

22/11/19 11:46 PM

Triple sending them message and this is a double long bubble


text:
Q: Cannot get Robot class to right click I am trying to get the Robot class to right click on a image on the screen so that I can save it. The problem is though that I cannot seem to get the Robot to successfully simulate a right click. Here is some sample code of what I am doing.
It seems that BUTTON2_DOWN_MASK is the mask for the scroll wheel. Whenever I execute this code it first just regularly clicks at the location but then the scroll wheel super fast move circle pops up and tells me I can now scroll at light speed, but I wanted a right click..
CODE:
// This is the function I use to simulate a full click at location x,y on the screen
// Rob is my Robot
public void click(int x, int y, int mask)
{
    rob.mouseMove(x, y);
    sleepy(1000);
    rob.mousePress(mask);
    rob.mouseRelease(mask);
}

// This is the few lines of code that call this function
// sleepy just calls the Thread.sleep function.

sleepy(1000); // Wait one second
click(705, 390, InputEvent.BUTTON1_DOWN_MASK);
sleepy(1000);
click(705, 390, InputEvent.BUTTON2_DOWN_MASK);
sleepy(1000);

A: use InputEvent.BUTTON3_DOWN_MASK for a right click. BUTTON2 is as you noticed correctly the mouse wheele and the left click is BUTTON1.
see this example.


text:
Q: Choosing a stand-alone search server with custom ranking function, spartial search I'm looking into the different options for choosing a search server for a project I'm involved in. The search server is used to power results on a dating website built in Rails, in which the search provides all the 'matchmaking'-magic.
Typical queries would involve ranking documents/results using an expression (in pseudo-code):

*

*Order by ranking:

*

*+50 if has_image attribute is true

*+10 if has_boost attribute is true

*+50 if latitude/longitude is within 40 miles from [point]

*+20 if latitude/longitude is within 80 miles [point]

*-(distance from attribute 'age' to 30)

*Filter by:

*

*Attribute 'age' between 25 and 35

*Attribute 'sex' equals 'male'

Per default I'm not needing the full-text features of most of the search servers out there, and I do not need the full documents to be retrieved - just a unique ID.
The nature of the project yields for a search-server with the following properties:

*

*Spartial ranking

*Ranking of results based on a custom function

*Attribute filters

*Scalable and fast

*Free

I've found Sphinx, Solr and ElasticSearch, but all of these are (as far as I see) built and optimized for full-text searching, with both ES and Solr built on Lucene, and I don't know what would perform best for filter/attribute heavy searching.
My questions:

*

*Which of these servers would you prefer and why?

*Have I missed any other obvious choices?

A: Don't know about the others, but Solr can do all of this:

Spatial ranking

You'll need a nightly build of Solr (the latest stable release as of this writing, Solr 1.4.1, doesn't include this feature), as far as I know this is a pretty stable feature in trunk.

Ranking of results based on a custom function

Solr has lots of function queries to do boosting.

Attribute filters

This is a common search feature.

Scalable and fast

Lots of big websites are using Solr, evidence of its scalability and speed.

Free

Solr is Apache licensed, a very permissive license.

A: ElasticSearch has all these feature, as well.
Geographic distance/bounding box/polygon and custom score scripts in various languages are supported:
http://www.elasticsearch.com/docs/elasticsearch/rest_api/query_dsl/
You will have no problem with performance of filters or other query types, we're doing heavy filtering on our queries with 100+ attributes in some cases and it is fast.
Another thing to take into account is integration with your data store. ES has a nice River feature for this, but it's not compatible with all data stores, but similar can be achieved via post commit hooks.
Also, social sites benefit from (near) realtime search and ElasticSearch has a 1 second default. It also is much more clean to configure and scale than Solr. This is my opinion after a month long eval of each app.  It also does a really good job of adapting to your data model.
Hope this helps.
Paul

A: You aren't talking about a search engine. You're talking about a database. in SQL, filtering is standard SELECT stuff; the ranking can be done by a somewhat crufty expression involving lots of CASE, and then ORDER BY.
To do the spatial parts of the query, you will need a database with geospatial features.
The only scalable, fast, free relational database with geospatial features is PostgreSQL.

A: I think that while you could use a search engine like Solr or ES to power this, I think that the "business rules" that you've defined mean that you are going to end up doing post processing.
I think that the filtering and basic search is pretty easily done in your search engine, but I am guessing that the ordering logic is going to end up pretty custom and complex, and trying to push that into your search queries may be like putting a round peg in a square hole...  You may be better off querying for results and then using your own post processor rules library to handle the ordering.


text:
Q: Unable to access a block which is passed as arguments in this method In the following example, I have no idea on how to access the block which I passed as parameter in the method. I should have used typedef, but only if I broke the code, I could get the below scenario. So didn't use typedef
@interface ViewController ()

- (void(^)(void))  anotherMethodWithReturnTypeAnd: ( void ( ^ )( int ))argumentsBlock;

@end

@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];

void (^twoBlock)(void) = [ self anotherMethodWithReturnTypeAnd:^(int n) {
    NSLog(@"%d, block without typedef",n);
}];
twoBlock();
}

- (void(^)(void))  anotherMethodWithReturnTypeAnd: ( void ( ^ )( int n) )argumentsBlock{
void (^blockToPassAsReturnType)(void) = ^{
    NSLog(@"Passing this block as return type");
};
return blockToPassAsReturnType;
}

OUTPUT:
2017-09-05 00:23:08.148 DeleteThisBlockProject[657:22195] Passing this block as return type

So how should I use and pass value for the block which I passed as parameter, [ self anotherMethodWithReturnTypeAnd:^(int n) {
        NSLog(@"%d, block without typedef",n);
    }];

A: You didn't call method
@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];

    void (^twoBlock)(void) = [ self anotherMethodWithReturnTypeAnd:^(int n) {
        // this will never execute because you didn't call it you just implemented it
        NSLog(@"%d, block without typedef",n);
    }];
    twoBlock();
}

- (void(^)(void))  anotherMethodWithReturnTypeAnd: ( void ( ^ )( int n) )argumentsBlock{
    void (^blockToPassAsReturnType)(void) = ^{
        NSLog(@"Passing this block as return type");
    };
    // you should call method which you did provide to this function
    argumentsBlock(yourInt)
    return blockToPassAsReturnType;
}


text:
Q: Rails generating a new directory multiple levels deep i have built this little app that generates a excel document. i am trying to make a directory to stick it in. these documents are built differently depending on the @agency that people select. so i made this method to return the path since the path is used in a few places.
def reportsheet_dir
  file_path = "#{Rails.root}/public/reportsheets/#{@agency.downcase.gsub("_","")}"
end

At the beginning of the method that creates the document i have this method that supposedly builds directories but it doest seem to be working
Dir.mkdir(reportsheet_dir) unless File.exists?(reportsheet_dir)

I keep getting. this
and i get
Errno::ENOENT at /addons/agency_report_builders
No such file or directory -/Users/fortknokx/Work/toolkit/public/reportsheets/empowerlogicbuilder

I think its because its multiple levels deep?? since public/reportsheets/agency_name/file_name has to be made. i could just go and make the folders but i would like to just make the dir each time because new agencies could be made at any time. is this possible?

A: Have a look at FileUtils.mkdir_p()
http://ruby-doc.org/stdlib-1.9.3/libdoc/fileutils/rdoc/FileUtils.html#method-c-mkdir_p
It will recursively create non-existent directories.  Dir.mkdir will not.


text:
Q: Chain promises and decorate an object I'm trying to understand promises, I need to chain them and decorate an object width data from different endpoints.
For example:
I have this in my node-express app
//controller.js
export const getItem = (req, res) => {
    ItemService.getItem(req.params.id).then(function(item) {
        return res.json({ 'success': true, 'message': 'Item found successfully', 'item': item});
    }).catch(function(result) {
        return res.json({ 'success': false, 'errorMessage': 'Ups!' });
    });
};

//itemService.js
export const getItem = function(id){
    return new Promise(function(resolve, reject) {
        fetch(apiUrls.getItem(id))
            .then(response => {
                if(response.ok){
                    response.json().then(data => {
                        resolve(data);
                    })
                } else {
                    reject(response.err);
                }
            });
    });
};

So what I want to accomplish is to decorate the data before the resolve statement. Indeed, I want to make other fetch to a different API and use the data from that response to decorate the data I'm talking about in the first place. I'll write some pseudocode:
fetch (api1)
   responseApi1 //{id: 123, name: 'Mike'}
   fetch (api2)
      responseApi2
      responseApi1.description = responseApi2.description
      responseApi1.address = responseApi2.address

  return responseApi1 //responseApi1 decorated width responseApi2

//Controller
return res.json({ 'success': true, 'message': 'Item found successfully', 'item': responseApi1});

I don't understand the promises at all, can't make this chain of promises and decorate just one object throught this promises and return it.

A: To answer your "pseudo code" example (assuming both api's return JSON)
return fetch (api1)
    .then(res => res.json())
    .then(responseApi1 => fetch(api2)
        .then(res => res.json())
        .then(({descritpion, address}) => ({...responseApi1, description, address}))
    )
    .then(result => {
        //result is responseApi1 decorated width responseApi2
    });

or, if api2 does not rely on the result of api1 (which is not clear from your pseudo code)
return Promise.all(fetch(api1).then(res => res.json()), fetch(api2).then(res => res.json()))
    .then((responseApi1, {descritpion, address}) => ({...responseApi1, description, address}));

Though, I'm unsure what the controller section in the pseudo code is meant to be - makes no sense like you have it at all


text: Q: как сделать возврат в owl карусели на первую позицию? как сделать возврат в owl карусели на первую позицию ,когда при клике на меню нет следующего слайда на которое ссылается меню,а он предыдущий,но листать надо только дальше


text:
Q: open(file) from anywhere Working on OS X Lion, I'm trying to open a file in my python-program from anywhere in the terminal. I have set the following function in my .bash_profile:
function testprogram() {python ~/.folder/.testprogram.py}

This way I can(in the terminal) run my testprogram from a different directory than my ~/.
Now, if I'm in my home directory, and run the program, the following would work
infile = open("folder2/test.txt", "r+")

However, if I'm in a different directory from my home-folder and write "testprogram" in the terminal, the program starts but is unable to find the file test.txt.
Is there any way to always have python open the file from the same location unaffected of where i run the program from?

A: Use the tilde to represent the home folder, just as you would in the .bash_profile, and use os.path.expanduser.
import os
infile = open(os.path.expanduser("~/folder2/test.txt"), "r+")

A: If you want to make it multiplatform I would recommend
import os
open(os.path.join(os.path.expanduser('~'),'rest/of/path/to.file'))

A: This is no different than referring to a file via anything else besides Python, you need to use an absolute path rather than a relative one.
If you'd like to refer to files relative to the location of the script, you can also use the __file__ attribute in your module to get the location of the currently running module.
Also, rather than using a shell function, just give your script a shebang line (#!/usr/bin/env python), chmod +x it, and put it someplace on your PATH.

A: You could simply run the function in a subshell so you can cd home before running it:
function testprogram() { (
    cd && python .folder/.testprogram.py
) }

A: In python sys.argv[0] will be set to the path of the script (if known). You can use this plus the functions in os.path to access files relative to the directory containing the script. For example
import sys, os.path

script_path = sys.argv[0]
script_dir = os.path.dirname(script_path)

def script_relative(filename):
  return os.path.join(script_dir, filename)

infile = open(script_relative("folder2/test.txt"), "r+")

David Robinson points out that sys.argv[0] may not be a full pathname. Instead of using sys.argv[0] you can use __file__ if this is the case.

A: Use either full path like
/path/to/my/folder2/test.txt

or abbreviated one
~/folder2/test.txt


text:
Q: Appium desktop with webhook log How can I  use webhook log option in appium-desktop?
In appium server I can add an arg "--webhook localhost:9876" but I cant find this option in appium-desktop app.

A: The solution found in appium-desktop is to create a new session and point your session to the local Appium under the Custom Server tab.
https://github.com/appium/appium-desktop/issues/398#issuecomment-361782318


text:
Q: How to capture jenkins build cause? triggered by GitLab In Jenkins file(groovy syntax), manual build action(if any) cause is grabbed using hudson.model.Cause$UserIdCause in  currentBuild.getBuildCauses('hudson.model.Cause$UserIdCause')

hudson.triggers.SCMTrigger.SCMTriggerCause looks deprecated in Jenkins CI code.
    @Deprecated
    public SCMTrigger(String scmpoll_spec, boolean ignorePostCommitHooks) throws ANTLRException {
        super(scmpoll_spec);
        this.ignorePostCommitHooks = ignorePostCommitHooks;
    }

On push event or merge event from GitLab, How do Jenkinsfile read the build cause?

A: If you're looking to execute a stage on a Gitlab trigger:
stage('stage) {
    when {
        triggeredBy "GitLabWebHookCause"
    }
}

To get the data of the Gitlab cause you have the following syntax:
currentBuild.rawBuild.getCause(com.dabsquared.gitlabjenkins.cause.GitLabWebHookCause).getData()

Example: get last commit
commit = currentBuild.rawBuild.getCause(com.dabsquared.gitlabjenkins.cause.GitLabWebHookCause).getData().getLastCommit()

Documentation of the GitlabWebHookCause:
https://javadoc.jenkins.io/plugin/gitlab-plugin/com/dabsquared/gitlabjenkins/cause/GitLabWebHookCause.html


text:
Q: Firebase Push Notification not working when app is closed I am new to android and I'm having this problem
if the app is in the foreground the notification shows normally
if I put the app in the background the notification will show and it works normally also
BUT the problem is ->  when I close the application(the app is killed) the notification does not show <-
solutions I tried

*

*only send notification

*only send data

*not putting a custom view for the notification

what I understand is if I send only notification  without data it will show when the app is in the foreground AKA when it's open and you can see it and
if I only send data without notification it will show in the background and when the app is killed and the data will be found in the main activity intent (but clearly this is NOT the case for me)
I am using an android 10 Infinix Note 5 stylus just in case there is something with this model
but I still can see notifications from any other app normally
edit
so I tried to run the app on other phones and it works as it supposed to but on my phone all the notifications that is sent when the app is closed will only show when I open the app
I close the app -> send some notifications -> no thing on the phone ->
open the app again -> all the notifications I sent are are now there

it still works fine when i send the notifications when the app is on foreground and when i put it in the backgorund
code:

    public class FirebasePushNotificationConfig extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        sendNotification(remoteMessage);
    }

    private void sendNotification(RemoteMessage remoteMessage) {

         NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(AppStrings.MSG.name(), "Testing", NotificationManager.IMPORTANCE_DEFAULT);
            channel.enableVibration(false);
            channel.enableLights(true);
            manager.createNotificationChannel(channel);
        }
        PendingIntent pendingIntent = getPendingIntent(remoteMessage);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, AppStrings.MSG.name())
                .setSmallIcon(R.drawable.ic_notifications_black_24dp)
                .setVibrate(null)
                .setContentTitle(remoteMessage.getData().get(AppStrings.MSG.name()))
                .setContentText(remoteMessage.getData().get(AppStrings.MSG.name()))
                .setAutoCancel(true)
                .setWhen(System.currentTimeMillis())
                .setContentIntent(pendingIntent);
        Notification n = mBuilder.build();
        manager.notify(1, n);}

    private PendingIntent getPendingIntent(RemoteMessage remoteMessage) {
        Intent intent = new Intent(this, LoginActivity.class);
        intent.putExtra(AppStrings.Notifications_Data.name(), remoteMessage.getData().get(AppStrings.Notifications_Data.name()));
        intent.putExtra(AppStrings.Is_There_Notification.name(), AppStrings.YES.name());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra(AppStrings.Notifications_Destination.name(), remoteMessage.getData().get(AppStrings.Notifications_Destination.name()));
        return PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
    }

    @Override
    public void onNewToken(String token) {
        super.onNewToken(token);
        System.out.println("log Token is " + token);
        Log.d("Test", "token: " + token);
    }}

manifest
    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.test">

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.READ_PHONE_NUMBERS" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.SET_ALARM " />
    <uses-permission android:name="android.permission.READ_PHONE_STATE " />
    <uses-permission android:name="android.permission.READ_PHONE_NUMBERS " />
    <uses-permission android:name="android.permission.READ_SMS " />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <application
        android:name=".Config.App"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:usesCleartextTraffic="true"
        tools:ignore="GoogleAppIndexingWarning">
        <activity android:name=".LocationActivity"></activity>
        <activity android:name=".MapsActivity" />
        <!--        <activity android:name=".ProfileActivity" />-->
        <activity android:name=".ChatManagerActivity" />
        <activity android:name=".RegisterActivity" />
        <activity android:name=".MainActivity" />
        <activity android:name=".AuthActivity" />
        <activity android:name=".ChatActivity" />
        <activity android:name=".LoginActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <action android:name=".LoginActivity" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

        <receiver
            android:name=".broadcastRecivers.AlertReciver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.SEND" />
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
        <receiver
            android:name=".broadcastRecivers.LoginReciver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.SEND" />
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

        <service
            android:name=".Config.FirebasePushNotificationConfig"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="key" />

        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="com.example.test.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        </provider>
    </application>

</manifest>`

the data I send looks like this
{"to":"key"
,"notification":{
"title":"hello it's test"
,"body":"still a test"

},
"data": {
"Notifications_Destination" : "direction"
,"MSG":"this is a test notifiation",
"Notifications_Data":5
}}

A: create FcmHelper class with extends FirebaseMessagingService.
<!--Fcm Starts-->

        <service
            android:name="google_classes.FcmHelper"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

        <meta-data
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@drawable/ic_noti" />

        <meta-data
            android:name="com.google.firebase.messaging.default_notification_color"
            android:resource="@color/black" />

        <meta-data android:name="com.google.firebase.messaging.default_notification_channel_id"
            android:value="@string/default_notification_channel_id" />

        <meta-data
           android:name="firebase_messaging_auto_init_enabled"
           android:value="true" />

        <!--Fcm End-->

A: Try this:
    <uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/>

and under application tag add:
<service android:name=".FirebaseService"
    android:permission="com.google.android.c2dm.permission.SEND">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT"/>
        <action android:name="com.google.android.c2dm.intent.RECEIVE"/>

    </intent-filter>

</service>
<activity android:name=".MainActivity">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

Change class names as per requirements.


text:
Q: Trying to find the right event for when to dismiss a spinner in Swift I am using PKHUD to generate a spinner for loading so that the user knows the app is working correctly rather than just frozen.
I have to load other web pages as part of the app's functionality.
Preferably I'd have the spinner the entire time while the webpage loaded.
Currently I have the spinner working correctly, but it dismisses when the actual webview loads (so when the website starts loading) - I want that to happen when the website finishes loading.
Here's my code:
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    HUD.show(.labeledProgress(title: "Loading Webview", subtitle: nil))
    self.navigationController?.setToolbarHidden(true, animated: true)
    userInfoUpdater.startPolling(closure: self.userUpdated(user:))
}

func webViewDidFinishLoad(webView : UIWebView) {
    HUD.hide()
}

So what event do I need to put HUD.hide() in? I'm relatively new to native iOS development so I'm not sure of what every potential event is.

A:  func webViewDidFinishLoad(webView : UIWebView) {
     //Check here if still webview is loding the content
     if webView.isLoading {
        return
      }
     //executes after page finished loading
     NSLog(@"WebView loading finished");
     HUD.hide()
}

webViewDidFinishLoad fires multiple times, first when it renders the first frame and so on. webView.isLoading will become false when page is finished loading.


text:
Q: How to use site template in sharepoint 2007 I have a site template called test1.stp. I have create a new web application and when creating a site collection, it is not showing the option for 'Custom tab' to select the template in web application in sharepoint 2007.
But it is available in sharepoint 2010. How to do it?

A: Is it the template for 2007 or 2010? It seems it is the template created from SharePoint 2010 site, so it will work only on 2010 site.


text: Q: Is there a way to change the severity of the message sent to the syslog daemon when a unit goes into a failed state? Is there a way to change the severity of the message sent to the syslog daemon when a unit goes into a failed state? Currently it's "warning" and I'd to change it to "error".


text:
Q: How to render multiple components with different component name? I have a few components, they have the same parameter with iterative values, like this:
import React from "react";
import Panel from "./Panel";
import Navbar from "./Navbar";

export default function App() {
  return (

      <Panel id={1} />
      <Navbar id={2} />

  );
}

const Panel = ({ id }) => {
  return (

The id is {id}

  );
};

const Navbar = ({ id }) => {
  return (

The id is {id}

  );
};

Working example here: https://codesandbox.io/s/staging-pond-mpnnp
Now I'd like to use map to render those components at once in App.js, something like this:
export default function App() {
  const compnentArray = ['Panel', 'Navbar'];
  const RenderComponents = () => {
    let _o = [];
    return (
      componentArray.map((item, index) => _o.push(<{item} id={index} />))
    )
  }
  return (

      {RenderComponents()}

  );
}

So that item renders component names. Is this possible?

A: Sure, you could make use of Array.map()'s second parameter which gives you the index in the array:
import React from "react";
import Panel from "./Panel";
import Navbar from "./Navbar";

const components = [Panel, Navbar];

export default function App() {
  return (

      {components.map((Component, i) => (
        <Component key={i} id={i + 1} />
      ))}

  );
}

As mentioned in React's documentation, to render a component dynamically, just make sure you assign it to a variable with a capital first letter and use it like you'd use any other component.

A: import React from "react";
import Panel from "./Panel";
import Navbar from "./Navbar";

const components = [Panel, Navbar]; // notice you are using the components as items, not strings;

/*
if the components need props from the parent,
the `renderComponents()` function should be declared
inside the parent component (and possibly with a `useCallback()`
hook, to avoid unnecessary re-declarations on re-renders)
*/
function renderComponents() {
  return components.map((comp, index) => <comp key={index} id={index} />) || null;
}

export default function App() {
  return (

      {renderComponents()}

  );
}

A: You could swap strings with your actual component references and itererate over them directly in your JSX part, like this :
 export default function App() {
  const componentsArray = [Panel, Navbar];

  return (

      {componentsArray.map((Component, index) => <Component key={index} id={index + 1} />)}

  );
}

Though I would suggest to memoize them to improve performance once you're confortable enough with React to start using memoization.


text:
Q: How can I use a Hibernate validator without an annotation on a field? Is it possible to use the Hibernate validator API storing the validated object in a field with an annotation? For example, I would like to validate Email address by calling a Java method instead of putting an @Email annotation on a Java bean property.

A: zinan.yumaks solution where they are creating a dummy Car object that you don't need is not the right way to do this. There is a better solution, the validateValue method:
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

String emailAddress = "...";

Set<ConstraintViolation<User>> constraintViolations =
    validator.validateValue(User.class, "email", emailAddress);

From the documentation:

Validates all constraints placed on the property named propertyName of the class beanType would the property value be value.

A: Yes, it is possible. Try Something like,
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

Car car = new Car(null);

Set<ConstraintViolation<Car>> constraintViolations =
    validator.validateProperty(car, "manufacturer");

Take a look at here.


text:
Q: TensorFlow: I defined only 4 Variables but trainable_variables() shows way more I'm trying to use TensorFlow. I define in my code only four tf.Variable() instances, and then I'm continuing to define the output (root.out) via some tf.placeholders (tfgraphinputs) that use these four Variables.
I then run:
    sess = tf.InteractiveSession()
    sess.run(tf.initialize_all_variables())
    print len(tfgraphinputs)
    y = tf.placeholder(tf.float32, name='y')
    cost = tf.reduce_mean(tf.square(tf.cast(root.out, tf.float32) - y))
    optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1)
    print 'no trainable:',len(tf.trainable_variables())
    train_op = optimizer.minimize(cost)

On printing len(tfgraphinputs) I get the correct number of inputs. However, on printing no trainable I get 312 (!) even though there are just 4 Variables. Then, the last command (minimize(cost)) fails, due to No gradients provided for any variable, showing a very long ValueError list of variables.
How can this be possible? In my code I'm reusing the variables (that is, I'm multiplying some data by my Variables more than once), is it possible this process somehow duplicates them?
EDIT: I think I got it, I cannot use tf.argmax when calculating graidents. Is that so?


text:
Q: Initialize parameter of method with default value I would like to initialize a method's parameter with some default value if an explicit value was not passed into the method - something like this:
class Example
   def __init__(self, data = self.default_data()):
      self.data = data

   def default_data():
      # ....
      return something

I got the error:
NameError: name 'self' is not defined

How do I fix this?

A: The common idiom here is to set the default to some sentinel value (None is typical, although some have suggested Ellipsis for this purpose) which you can then check.
class Example(object): #inherit from object.  It's just a good idea.
   def __init__(self, data = None):
      self.data = self.default_data() if data is None else data

   def default_data(self):  #probably need `self` here, unless this is a @staticmethod ...
      # ....
      return something

You might also see an instance of object() used for the sentinel.
SENTINEL = object()
class Example(object):
   def __init__(self, data = SENTINEL):
      self.data = self.default_data() if data is SENTINEL else data

This latter version has the benefit that you can pass None to your function but has a few downsides (see comments by @larsmans below).  If you don't forsee the need to pass None as a meaningful argument to your methods, I would advocate using that.


text:
Q: number theory polynomial congruences Let $n \in \mathbb{N}$ and $f(x)$, $g(x)$ be polynomials with integer coefficients. If $f(x)\equiv g(x)\pmod{n}$ then what condition must $f(x)$ and $g(x)$ have to satisfy in order for this statement to be true?
If possible please give an example


text:
Q: Python Decrypting with Crypto: first 16 characters are gibberish I am trying to decrypt a file that was encrypted in Java using AES/CBC/PKCS5Padding. However, I'm having some trouble completely decrypting the file. I think I'm missing something simple. I am pretty new to encryption, so this is highly probable:
import base64
import re

from Crypto import Random
from Crypto.Cipher import AES

# generate the key
passphrase = "my_secret_passphrase"
key = passphrase[0:16].encode()

# load in the encrypted file as bytes
file_name = "tbd/enc.csv"
with open(file_name, "rb") as in_file:
    encrypted_bytes = in_file.read()

# initialize the cipher
iv = Random.new().read(AES.block_size)
cipher = AES.new(key, AES.MODE_CBC, iv)

# use the cipher to decrypt the bytes
decrypted_bytes = cipher.decrypt(encrypted_bytes)

# write to an out_file
file = re.sub("\.csv", "_decoded.csv", file)
with open(file, "wb") as binary_file:
    binary_file.write(decrypted_bytes)

Here's a the first line of text from what I get:
M¢p†'GW§'tÄ%èéired Date,Employees - Id,First,Employees - Middle,Last,Employees - Preferred Name,Job Title,Employees - Marital Status,Employees - Trade Code,...

I noticed that the first 16 chars are complete gibberish, so I know I'm close. What could I be missing that is causing the first 16 chars to not be decoded properly? The weird thing is that we are able to decrypt the entire file in java, so we know its something wrong with the python implementation.
Bonus Round: the java code used to encrypt the file (I did not code it nor do I know java):
package rpa.ipaengine.bots.cmic.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.Security;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TestFile {
  private static Logger LOGGER = LoggerFactory.getLogger(TestFile.class);
  public static void main(String[] args) {
    LOGGER.info("running");
    try {
      Security.setProperty("crypto.policy", "unlimited");
      encryptedFile("my_secret_passphrase", "/tbd/enc.csv", "tbd/dec.csv");
      decryptedFile("my_secret_passphrase", "/tbd/enc.csv", "tbd/dec.csv");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static void encryptedFile(String secretKey, String fileInputPath, String fileOutPath)
    throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException, IllegalBlockSizeException,
    BadPaddingException {
    try {
      byte[] raw1 = "my_secret_passphrase"
        .getBytes();
      byte[] raw = new String(raw1, 0, 16).getBytes();
      Key skeySpec = new SecretKeySpec(raw, "AES");
      Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
      byte[] iv = new byte[cipher.getBlockSize()];
      IvParameterSpec ivParams = new IvParameterSpec(iv);
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivParams);
      var fileInput = new File(fileInputPath);
      var inputStream = new FileInputStream(fileInput);
      var inputBytes = new byte[(int) fileInput.length()];
      inputStream.read(inputBytes);
      var outputBytes = cipher.doFinal(inputBytes);
      var fileEncryptOut = new File(fileOutPath);
      var outputStream = new FileOutputStream(fileEncryptOut);
      outputStream.write(outputBytes);
      inputStream.close();
      outputStream.close();
      System.out.println("File successfully encrypted!");
      System.out.println("New File: " + fileOutPath);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public static void decryptedFile(String secretKey, String fileInputPath, String fileOutPath)
    throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException, IllegalBlockSizeException,
    BadPaddingException, InvalidAlgorithmParameterException {
    try {
      byte[] raw1 = "my_secret_passphrase"
        .getBytes();
      byte[] raw = new String(raw1, 0, 16).getBytes();
      Key skeySpec = new SecretKeySpec(raw, "AES");
      Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
      byte[] iv = new byte[cipher.getBlockSize()];
      IvParameterSpec ivParams = new IvParameterSpec(iv);
      cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivParams);
      var fileInput = new File(fileInputPath);
      var inputStream = new FileInputStream(fileInput);
      var inputBytes = new byte[(int) fileInput.length()];
      inputStream.read(inputBytes);
      byte[] outputBytes = cipher.doFinal(inputBytes);
      var fileEncryptOut = new File(fileOutPath);
      var outputStream = new FileOutputStream(fileEncryptOut);
      outputStream.write(outputBytes);
      inputStream.close();
      outputStream.close();
      System.out.println("File successfully decrypted!");
      System.out.println("New File: " + fileOutPath);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

A: Using bytes(16) as matt suggested, I was able to decipher the text completely:
import base64
import re

from Crypto import Random
from Crypto.Cipher import AES

# generate the key
passphrase = "my_secret_passphrase"
key = passphrase[0:16].encode()

# load in the encrypted file as bytes
file_name = "tbd/enc.csv"
with open(file_name, "rb") as in_file:
    encrypted_bytes = in_file.read()

# initialize the cipher
iv = bytes(16)
cipher = AES.new(key, AES.MODE_CBC, iv)

# use the cipher to decrypt the bytes
decrypted_bytes = cipher.decrypt(encrypted_bytes)

# write to an out_file
file = re.sub("\.csv", "_decoded.csv", file)
with open(file, "wb") as binary_file:
    binary_file.write(decrypted_bytes)

First line of file:
Employees - Hired Date,Employees - Id,First,Employees - Middle...

However Michael provides some valid comments about the Java code used to encrypt the file. I will work with my team to make sure its more secure.


text:
Q: When do static declarations get run? Here's a piece of my code:
public class MyClass {
  public object Value { get; set; }

  public MyClass(object value) {
    this.Value = value;
  }
}

public class AnotherClass {
  private static MyClass _MyObj = new MyClass(new object());

  public static void Main(string[] args) {
    var x = _MyObj; // no problem
    var y = x.Value; // no problem
    var z = y.ToString(); // Null ref exception
  }
}

I don't understand how this can be. _MyObj is not null, which means that the inline assignment did work, yet _MyObj.Value comes out null, meaning that the constructor code wasn't invoked!  There's some dark magic at work here, and I'd greatly appreciate an explanation.
Thanks!
EDIT - sorry about the no repro.  My actual code is (obviously) more complex than this, so I tried to dumb it down, and obviously in the process I must have removed some other obstruction to the code's proper function.  But Kobi's answer is really what I was trying to get out of this question, anyway - so answer credit to him.  :)

A: The proper way to initialize static members is by using a static constructor:
static AnotherClass(){
  _MyObj = new MyClass(new object());
}

A: Status: No repro.
The code sample as provided does not compile, public object Value { get; } is not a valid auto-property.
After fixing it with a private set; it compiles and runs w/o error.

A: Put a setter and it will work as expected:
public object Value { get; set; }


text:
Q: How to transfer imageview into a ListView on a different layout? I have a layout with a heart imageview to "favorite" the image. When the heart is clicked I want the image to go into another layout. I am trying to accomplish something like a music application. When user favorites a song it goes into another layout under Favorites. I am trying to accomplish the same something but with an image and some text. Whats the best way to accomplish this? Thank You!
ClassOne.java
private ImageView favHeartImage;

LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.ClassTwo, null);
favListView = (ListView) view.findViewById(R.id.list_view);

favHeartImage.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
           //add the image into ClassTwo listview
        }
    });

ClassTwo.xml
<ListView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/list_view" />


text:
Q: Custom TeamCity plugin is uploaded but doesn't seem to get executed I'm developing a TeamCity plugin and I fail to even get it executed by TeamCity.
I upload the zip file with the plugin and restart TeamCity, then I can see the plugin on the list of external plugins, it also gets unpacked into .BuildServer/plugins/.unpacked but other than that nothing happens.
It doesn't seem that the plugin is running. (I don't even see the plugin name in any logfile)
My simplest attempt was to just create a plugin from maven archetype:
mvn archetype:generate -DarchetypeRepository=http://download.jetbrains.com/teamcity-repository -DarchetypeArtifactId=teamcity-server-plugin -DarchetypeGroupId=org.jetbrains.teamcity.archetypes -DarchetypeVersion=RELEASE

and then only add some logging:
package com.example.plugin;

import jetbrains.buildServer.log.Loggers;

public class AppServer {

    public void run() {
        Loggers.SERVER.info("I'm running");
    }
}

and create the necessary bean with init method:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
   default-autowire="constructor">

     <bean id="appServer" class="com.example.plugin.AppServer" init-method="run"/>
</beans>

I upload the plugin, restart TeamCity but the log message from AppServer does not appear in any logfile.
What am I missing? How to log this message?

A: I would expect to see an exception (plus a stacktrace) in the teamcity-server.log file. Are you sure you checked that file?
The behaviour you're describing can be symptomatic of you having built the plugin with a JDK version incompatible with TeamCity's JRE. For example, you build your plugin with Java 8 but your TeamCity is running under Java 7. In that case, the plugin will be detected (as it is in your case) but will crash when TC tries to invoke it.


text:
Q: Action vs Reply action WCF What's the use of action/reply action for service operation in WCF. So far, what I've understood is; action is used by WSDL to identify the service operation to which the message from the client belongs and in return reply action is used by service operation to identify the caller to which reply message belong --> Please correct me if I am wrong with this!
Now, I want to understand; what's the real use (apart from handling anonymous messages by using aster ix [*]), I mean this could well be handled internally by WCF instead of exposing it to the developer.
Also, why is action and replyaction required at all? I mean, we already have a name property for the service operation to identify the method and when I call Proxy.SomeMethod() then somemethod is already mapped to the Name property and it should be enough to identify the destination method for the message and similarly the replyaction. Please clarify.
Can I please get a simple real world scenario/or link to that to understand Action/ReplyAction in real life.
Many Thanks.

A: Actions are part of the various SOAP and WS-* specifcations.
So the first point is that this is not something unique to WCF it is a standard part of the specification you need to support if you want to have interoperable web services. They are used for message routing and other message handling functions.
Second, WCF DOES manage these by default. You only need to specify them yourself if you wish to customise or manage them in some other way. E.g. WCF will automatically generate them into the WSDL for you. WCF will also use them by default when it is selecting which operation to invoke for an incoming message. Again, WCF provides extension points to customise this behavior if you require.


text:
Q: If $T_1, \dots, T_r$ are commutative, dim($V$) = $n,$ and nullity($T_i$) = $n_i,$ then rank($T_1 \cdots T_r$) $\geq n - \sum_{i = 1}^{r} n_i.$ Let $T_1, T_2, \dots, T_r$ be commutative operators on an $n$-dimensional vector space $V.$ For each $i = 1, 2, \dots, r,$ let $n_i$ = nullity($T_i$). Prove that rank($T_1 T_2 \cdots T_r$) $\geq n - \sum_{i = 1}^{r} n_i.$
$Proof.$ We proceed by induction on $r.$ Clearly, when $r = 1,$ the result holds by the rank-nullity theorem. We suppose that the inequality holds for some integer $k \geq 2.$ We claim that the result holds for $k + 1.$ We define the restriction of $T_{k+1}$ to the range of $T_k \cdots T_1$ to be the map $$ \overline{T}_{k+1} = T\, \big|\,_{R_{T_k \cdots T_1}}:\, {R_{T_k \cdots T_1}} \to {R_{T_{k+1} \cdots T_1}}.$$ Observe that by our inductive hypothesis, we have
\begin{align*}
\mbox{rank}(T_1 \cdots T_{k+1}) &= \mbox{rank}(T_1 \cdots T_k) - \mbox{nullity}(T_{k+1}) \\ \\
&\geq n - \sum_{i=1}^{k} n_i - n_{k+1} = n - \sum_{i = 1}^{k+1} n_i, \\
\end{align*}
as desired. By the Principle of Mathematical Induction, therefore, the inequality holds. $\quad \square$
I am curious as to whether this argument holds. It seems a bit convenient. I happen to know, furthermore, that nullity($T_1 \cdots T_r$) $\leq n_1 + \dots + n_r.$ But why does this latter inequality hold? If anyone could shed some light or intuition on this, it would be greatly appreciated.

A: This is pretty good modulo some small errors.
Rank-Nullity says that $$\text{rank}(\overline{T}_{k+1}) = \text{rank}(T_k\dots T_1) - \text{nullity}(\overline{T}_{k+1})$$
Next we note that $$\text{nullity}(\overline{T}_{k+1}) \leq \text{nullity}(T_{k+1})$$
and
$$\text{rank}(T_{k+1} T_k \dots T_1) = \text{rank}(\overline{T}_{k+1}).$$
Combining these together then allows you to apply the hypothesis of induction to get the desired result.
I rescind my statement that the commuting of the operators is important. Truth be told, it doesn't matter that the codomain you chose for the restriction is too large. There was another fact I was worried about, but I can't see any flaws with the argument here, and it doesn't refer to the commuting. Therefore unless someone else can spot a flaw here, I must believe that the commuting is extraneous.