text:
Q: with css3, how to make table row expand/contract slowly? would like to gradually "open" and "close" row in a table, with the rows beneath being pushed down or pulled up as appropriate.
am able to get div to expand / contract by using transition for timing and transform for sizing (unable to use height)
sample.css
h1 { transition all 600s linear; }
h1.sqeeze {  transform scale( 1.0, 0.0 ); }

but this has no effect on the surrounding environment.  the h1.squeeze effectively goes to a 0px height, but the blocks following the h1 remain as they were.
what I'd like is a mechanism where something can be expanded / contracted, like a tr or div or li, and the surrounding blocks respond my making room or by taking the space newly available - like display: none; in slow motion.

A: I made a fiddle here.(Added the click operation.)
Css code looks like
transition:height 2s;

You can try it to see whether i understood what you wanted or not.

A: To do that u would need way more code because you can't set the size of all childs based on the parent size. Things like text and fixed size will not contract. I would suggest that you fade in/out with alpha instead.


text:
Q: Linq2Twitter Single User Authorisation Null Value Exception I've been developing an internal ASP.NET web forms application for our business and one of the requirements is to display our Twitter feed on our portal home page to all users.
For this I've decided that it is best to use LinqToTwitter Single User Authorisation to get the statuses for everyone without them having to authenticate their own accounts.
My main problem at the minute is that when we use the auth object to get the TwitterContext, it returns with an error on the TwitterContext saying
Value cannot be null

on every internal context object.
I've gone through our twitter application settings at http://dev.twitter.com and I have our correct consumer key/token and access key/token. The permission for the application is set to Read-Only. There is no callback URL specified on the http://dev.twitter.com website as it is currently on our internal system (so it wouldn't be able to get back anyway). Is this where it is going wrong? Do I need to forward some ports and allow the callback to get through to our development machines?
Here's the code for prudence. As far as I can see, there is nothing wrong with it. I know that it is set to .FirstOrDefault, this was just for seeing whether it is actually getting anything (which it isn't).
Thanks for any help you can give! :)
private async Task GetTweets()
{
    var auth = new SingleUserAuthorizer
    {
        CredentialStore = new SingleUserInMemoryCredentialStore
        {
            ConsumerKey = ConfigurationManager.AppSettings["consumerKey"],
            ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"],
            AccessToken = ConfigurationManager.AppSettings["accessToken"],
            AccessTokenSecret = ConfigurationManager.AppSettings["accessTokenSecret"],
        }
    };
    try
    {
        using (TwitterContext twitterContext = new TwitterContext(auth))
        {
            var searchResponse = await (from c in twitterContext.Status
                                        where c.Type == StatusType.User
                                        && c.ScreenName == "my_screenname"
                                        select c).ToListAsync();
            Tb_home_news.Text = searchResponse.FirstOrDefault().Text;
        }
    }
    catch (Exception ex)
    {
        Tb_home_news.Text = ex.Message;
    }
}

A: If you're creating a Web app, you do need to add a URL to your Twitter App page. It isn't used for the callback, but might help avoid 401's in the future if you're using AspNetAuthorizer.
It looks like you have a NullReferenceException somewhere. What does ex.ToString() say?
Double check CredentialStore after initialization to make sure that all 4 credentials are populated. AccessToken and AccessTokenSecret come from your Twitter app page.
Does searchResponse contain any values? Calling FirstOrDefault on an empty collection will return null.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Interpreting the logarithm as a sum of simple poles along the negative real axis I've heard it remarked that you can basically consider $\log z$ to be a function which has simple poles everywhere on the negative real axis (with a constant "residue density" at each pole).  This would be something like
$$ \log z = \int_0^\infty \frac{dx}{z + x} $$
But of course the integral on the right-hand side actually diverges.  We actually get
$$ \int_0^\infty \frac{dx}{z + x} = \lim_{b \to \infty} \int_0^b \frac{dx}{z + x} = \lim_{b \to \infty} \left( \log(z + b) - \log(z) \right) = \infty $$
In physics, there are a variety of methods for subtracting out the divergent part of such a limit to get a finite answer (various flavors of regularization and renormalization).  I'm wondering whether there is a standard approach here so that something similar can be done to "rescue" the first equation above from the divergent part of the integral.
Another way of phrasing the problem above is that I showed that the Stieltjes transform of a constant on the interval $(-\infty, 0]$ does not exist.  But perhaps there is another density function $\rho$ so that $\log z$ is the Stieltjes transform of $\rho$.
$$ \log z = \int_0^\infty \frac{\rho(x)}{z + x} dx $$
What is $\rho$?  Well, the Stieltjes inversion formula says that it should be given by
$$ \begin{align} \rho(x) &= \lim_{\epsilon \to 0} \frac{\log(x+i\epsilon) - \log(x-i\epsilon)}{2\pi i} \\ &= \frac{(\log |x| + \pi i) - (\log |x| - \pi i)}{2\pi i} \\ &= 1 \end{align} $$
But this gets me exactly back to the integral that I started with, which is divergent!  Hopefully I am just missing something obvious.
Edit: Alternate statement of question
There has been a lot of confusion in the comments below about what I am looking for, so let me restate it in a very narrow way.  I would be satisfied with either of the following:

*

*A sequence of meromorphic functions $f_n(z)$ with simple poles along the negative real axis with the following properties:
a. The poles become dense in the limit $n \to \infty$.
b. $\lim_{n \to \infty} f_n(z) = \log z$

*A proof that there is no such sequence.

A: The correct formula is
$$\log z = \lim_{T\to \infty} \log(z)-\log(1+\frac{z-1}{T+1})$$ $$=\lim_{T\to \infty} (\log(T+1)-\log(1))-(\log(T+z)-\log(z))$$ $$= \lim_{T\to \infty} \int_0^T (\frac1{1+x}-\frac{1}{z + x}) dx=\int_0^\infty (\frac1{1+x}-\frac{1}{z + x}) dx$$
There is no distribution such that $\log (x+iy) = \frac1{x+iy}\ast \rho$ because this distribution would have to be $C+1_{x>0}$ yielding a divergent integral.

A: By fiddling around with my original suggestion above, I have one solution that meets my criteria:
$$ f_n(z) = - \sum_{k=0}^{n} \frac{1}{n\frac{z}{1-z} + k} $$
This has poles at $z=-\frac{k}{n-k}$ for $0 \le k < n$ which becomes dense on the negative real axis as $n \to \infty$.
If we let $a=\frac{nz}{1-z}$, then
$$ f_n(z) = \psi(a) - \psi(a+n+1) $$
where $\psi$ is the digamma function.  As $n \to \infty$, $a \to \infty$, and the leading asymptotic behavior of $\psi(z)$ is $\log z$ as $z \to \infty$.  So we get
$$ f_n(z) \sim \log\left( \frac{a}{a+n+1} \right) \sim \log\left( \frac{1}{1 + \frac{1-z}{z} + 0} \right) = \log z $$
This works in a technical sense, but it seems more complex than it needs to be.  I would accept any answer which is more elegant, especially if it can be expressed in a Stieltjes-transform-like form.


text:
Q: Android :Tap on Push Notification does not open Application I have an android app which requires some notifications from my web-server to my android phone . Earlier I used to receive notifications and on tapping the notification , my application used to open . However without anything being changed now , I receive all notifications but I cannot tap on them to open my application anymore .
I have tried checking the code and the manifest for permissions , but dosen't seem to know the problem .
Here are some of the required code files :
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.rakibansary.roomautomator">

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

    <permission
        android:name="com.rakibansary.roomautomator.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.rakibansary.roomautomator.permission.C2D_MESSAGE" />

    <application

        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">

        <receiver
            android:name=".receivers.GcmBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <category android:name="com.rakibansary.roomautomator" />
            </intent-filter>
        </receiver>

        <service android:name=".services.GcmIntentService" />

        <activity
            android:name="com.rakibansary.roomautomator.Splash"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <activity android:name=".Welcome"
            android:configChanges="locale"/>
        <activity android:name=".CentralBox" />
        <activity android:name=".Register"
            android:configChanges="locale"/>

        <activity
            android:name="com.rakibansary.roomautomator.Home"
            android:label="@string/title_activity_home" />
    </application>

</manifest>

GcmBroadcastReceiver.java
package com.rakibansary.roomautomator.receivers;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

import com.rakibansary.roomautomator.CentralBox; // Added from New code

import com.rakibansary.roomautomator.Home;
import com.rakibansary.roomautomator.R;
import com.rakibansary.roomautomator.util.Tools;

import org.json.JSONObject;

/**
 * Created by rakib on 5/10/15.
 */
public class GcmBroadcastReceiver extends BroadcastReceiver {
    private static final String TAG = "GcmBroadcastReceiver";

// Added from new code

    public static final String TYPE_DEVICE_STATUS_MODIFIED = "1";
    public static final String TYPE_BATCH_OPERATION = "2";
    public static final String TYPE_DEVICE_DELETED = "3";
    public static final String BOX_ID = "boxid";

// Add Finish

    @Override
    public void onReceive(Context context, Intent intent) {
        if (Tools.needsLoginOrRegistration(context))
            return;

        context.sendBroadcast(new Intent(Home.FILTER_NOTIFICATION_RECEIVER));

        Bundle extras = intent.getExtras();
        try {
            String type = extras.getString("type");
            JSONObject data = new JSONObject(extras.getString("data"));

            Log.i(TAG, "Push notification received: " + data); // Added from new code

//            if (type.equals("1"))  Commented this and added new If clause below

            if (type.equals(TYPE_DEVICE_STATUS_MODIFIED))   {

                // Added from new code
                final String boxid = data.getString(BOX_ID);
                final String mac = data.getString("mac");
                final boolean powerState = data.getBoolean("ps");
                final boolean startState = data.getBoolean("ss");
                final String temperature = data.getString("temp");
                Intent resultIntent = new Intent(context, Home.class);
                resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                resultIntent.putExtra(Home.EXTRA_CENTRAL_BOX_ID, boxid);
                resultIntent.putExtra(Home.EXTRA_DEVICE_MAC, mac);
                resultIntent.putExtra(Home.EXTRA_POWER_STATE, powerState);
                resultIntent.putExtra(Home.EXTRA_START_STATE, startState);
                resultIntent.putExtra(Home.EXTRA_TEMPERATURE, temperature);
                PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);

                // Add finished

                NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)

                        .setContentIntent(resultPendingIntent)  // Added from new code
                        .setSmallIcon(R.drawable.ic_launcher)
                        .setContentTitle("Device status modified")
                        .setContentText("Device Mac: " + data.getString("mac"))
                        .setStyle(new NotificationCompat.BigTextStyle().bigText(
                                "Device MAC: " + data.getString("mac") +
                                        "\nPower State: " + (data.getBoolean("ps") ? "On" : "Off") + "\n" +
                                        "Start Sate: " + (data.getBoolean("ss") ? "Running" : "Stopped") + "\n" +
                                        "Temperature: " + data.getString("temp")
                        ));

                NotificationManager mNotifyMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                mNotifyMgr.notify(222, mBuilder.build());
            } else if (type.equals(TYPE_BATCH_OPERATION)) {               // Added from new code the if clause
                String boxid = data.getString("boxid");
                Tools.saveCentralBox(context, boxid);

                Intent resultIntent = new Intent(context, Home.class);
                resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
                        Intent.FLAG_ACTIVITY_CLEAR_TASK);

                resultIntent.putExtra(Home.EXTRA_CENTRAL_BOX_ID, boxid);

                PendingIntent resultPendingIntent = PendingIntent.getActivity(
                        context,
                        0,
                        resultIntent,
                        PendingIntent.FLAG_UPDATE_CURRENT
                );

                NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
                        .setSmallIcon(R.drawable.ic_launcher)
                        .setContentTitle("Batch operation performed!")
                        .setContentText("Tap to view details!")
                        .setAutoCancel(true)
                        .setContentIntent(resultPendingIntent);

                NotificationManager notifManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                notifManager.notify(223, mBuilder.build());
            }   else if (type.equals(TYPE_DEVICE_DELETED)) {                // Added the else if  from new code
                final String boxid = data.getString(BOX_ID);
                final String mac = data.getString("mac");
                Tools.deleteDevice(context, boxid, mac);
                Log.i(TAG, "Device deleted");
                Intent resultIntent = new Intent(context, Home.class);
                resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                resultIntent.putExtra(Home.EXTRA_CENTRAL_BOX_ID, boxid);
                resultIntent.putExtra(Home.EXTRA_DEVICE_MAC, mac);
                resultIntent.putExtra(Home.EXTRA_DEVICE_DELETED, true);
                PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
                        .setContentIntent(resultPendingIntent)
                        .setSmallIcon(R.drawable.ic_launcher)
                        .setContentTitle("Device Deleted")
                        .setContentText("Device Mac: " + data.getString("mac"))
                        .setStyle(new NotificationCompat.BigTextStyle().bigText(
                                "Device MAC: " + mac + " was just deleted!"
                        ));
                NotificationManager mNotifyMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                mNotifyMgr.notify(224, mBuilder.build());
            }
        } catch (Exception e) {

        }

    }
}

GcmIntentService.java
package com.rakibansary.roomautomator.services;

import android.app.IntentService;
import android.content.Intent;

/**
 * Created by rakib on 5/10/15.
 */
public class GcmIntentService extends IntentService {

    public GcmIntentService() {
        super("GcmIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {

    }
}

A: You may add a Intent to your notification to make it happen.
In your GcmBroadcastReceiver.java between NotificationManager mNotifyMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); and mNotifyMgr.notify(224, mBuilder.build());
You should add following code:
Notification notification = mBuilder.build();
Intent notificationIntent = new Intent(context, MainActivity.class);

notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                | Intent.FLAG_ACTIVITY_SINGLE_TOP);

PendingIntent intent = PendingIntent.getActivity(context, 0,
                notificationIntent, 0);

notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;


text:
Q: div changes its margins when select option is changed

$('#seltags').change(function() {
  var obj = $('#' + $(this).val());
  $('.txtags').hide();
  obj.show();
});
.seltags {
  display: block;
  padding: 1px 7px;
  width: 100%;
}

.txtags {
  display: block;
  width: 100%;
  padding: 5px 9px;
  outline: none;
  border: 1px solid #999;
  border-radius: 9px;
  resize: none;
  overflow-y: scroll;
  margin-top: 13px;
  text-transform: uppercase;
}

.tagsimg {
  display: none;
}

.divbottom {
  height: 14px;
  background: gold;
}

<select class='seltags' id='seltags'>
  <option value='tagsart'>TAGS ARTICLES</option>
  <option value='tagsimg'>TAGS IMAGES</option>
</select>

<textarea class='txtags' id='tagsart' rows="5"></textarea>
<textarea class='txtags tagsimg' id='tagsimg' rows="5"></textarea>

divbottom gets a top margin (about five pixels) when seltags is changed to second option, and lose that margin when it is returned to the first option.
Can anyone help me what's wrong here?
Thank you.

A: The margin appears because when the second option is chosen, the #tagsimg element gets display: inline-block inline style.
In order to remove this margin, you need to add vertical-align: middle to the styles of the #tagsimg element or find out why the display: inline-block is added and change that.
You can read why jQuery does it, and how to avoid it in this StackOverflow question: jQuery .show() adds style="display:inline-block" to elements

A: it's not a margin, it's the textarea ( .txtags ) that you show and hide that pushes it down a bit necause when shown it gets display:inline-block ,
add .obj.show().css({'display': 'block'}); so both textareas behave the same

$('#seltags').change(function(){
 var obj = $('#' + $(this).val());
 $('.txtags').hide();
 obj.show().css({'display': 'block'});
});
.seltags{
 display:block;
 padding:1px 7px;
 width:100%;
}

.txtags{
 display:block;
 width:100%;
 padding:5px 9px;
 outline:none;
 border:1px solid #999;
 border-radius:9px;
 resize:none;
 overflow-y:scroll;
 margin-top:13px;
 text-transform:uppercase;
}

.tagsimg{
 display:none;
}

.divbottom{
height:14px;
background:gold;
}

<select class='seltags' id='seltags'>
<option value='tagsart'>TAGS ARTICLES</option>
<option value='tagsimg'>TAGS IMAGES</option>
</select>

<textarea class='txtags' id='tagsart' rows="5"></textarea>
<textarea class='txtags tagsimg' id='tagsimg' rows="5"></textarea>

A: I'm not sure why, but the div.divbottom is not getting any margin or padding at all. The problem is that when you show the .tagsimg it is getting display: inline-block instead of just block which is the initial state of .txtags. Making .tagsimg be hidden by jQuery instead of starting with display:none makes jQuery change it to display:inline-block when shown which fix it.

$('#seltags').change(function(){
 var obj = $('#' + $(this).val());
 $('.txtags').hide();
 obj.show();
});

$('.tagsimg').hide();
.seltags{
 display:block;
 padding:1px 7px;
 width:100%;
}

.txtags{
 display:block;
 width:100%;
 padding:5px 9px;
 outline:none;
 border:1px solid #999;
 border-radius:9px;
 resize:none;
 overflow-y:scroll;
 margin-top:13px;
 text-transform:uppercase;
}

.tagsimg{
 display:block;
}

.divbottom{
height:14px;
background:gold;
}

<select class='seltags' id='seltags'>
<option value='tagsart'>TAGS ARTICLES</option>
<option value='tagsimg'>TAGS IMAGES</option>
</select>

<textarea class='txtags' id='tagsart' rows="5"></textarea>
<textarea class='txtags tagsimg' id='tagsimg' rows="5"></textarea>

A: both textareas should be either inline-block or block its the mixture of two which is causing the behavior

A: The margin appears because when the select box is changed and the second option is chosen, the text area that was hidden now gets display: inline-block; to show it, and the offset from being hidden causes the margin jump.
Try adding vertical-align: middle; to the styles of the .txtags class element.

$('#seltags').change(function() {
  var obj = $('#' + $(this).val());
  $('.txtags').hide();
  obj.show();
});
.seltags {
  display: inline-block;
  padding: 1px 7px;
  width: 100%;
}

.txtags {
  display: inline-block;
  width: 100%;
  padding: 5px 9px;
  outline: none;
  border: 1px solid #999;
  border-radius: 9px;
  resize: none;
  overflow-y: scroll;
  margin-top: 13px;
  text-transform: uppercase;
  vertical-align: middle;
}

.tagsimg {
  display: none;
}

.divbottom {
  height: 14px;
  background: gold;
}

<select class='seltags' id='seltags'>
  <option value='tagsart'>TAGS ARTICLES</option>
  <option value='tagsimg'>TAGS IMAGES</option>
</select>

<textarea class='txtags' id='tagsart' rows="5"></textarea>
<textarea class='txtags tagsimg' id='tagsimg' rows="5"></textarea>

A: Your 1st textarea is displayed as a block.
But the trick here is that when you make your 2nd textarea appear, it appears as an inline-block.
I suggest you to use inline-block or delete the property.
Here is a working snippet with some other comments:

// Optimized function
$('#seltags').change(function() {
  $('.txtags').hide();
  $('#' + $(this).val()).show();
});
.seltags {
  display: block;
  padding: 1px 7px;
  width: 100%;
}

.txtags {
  /* display: inline-block; /* Here is what I changed! */
  width: 100%;
  padding: 5px 9px;
  outline: none;
  border: 1px solid #999;
  border-radius: 9px;
  resize: none;
  overflow-y: scroll;
  margin-top: 13px;
  text-transform: uppercase;
}

.hidden { /* Changed name */
  display: none;
}

.divbottom {
  height: 14px;
  background: gold;
}

<select class='seltags' id='seltags'>
  <option value='tagsart'>TAGS ARTICLES</option>
  <option value='tagsimg'>TAGS IMAGES</option>
</select>
<textarea class='txtags' id='tagsart' rows="5"></textarea>
<textarea class='txtags hidden' id='tagsimg' rows="5"></textarea>

On a side note, I don't understand why your 2nd textarea appear as inline-block.
Here is an extract of show() documentation:
"The matched elements will be revealed immediately, with no animation. This is roughly equivalent to calling .css( "display", "block" ), except that the display property is restored to whatever it was initially. If an element has a display value of inline, then is hidden and shown, it will once again be displayed inline."
(link: http://api.jquery.com/show/)


text:
Q: Display correct fa fa icons inside phone and email input boxes Inside my form the email input box displays a green circle x when the email inside is correct.
I would like it to display a green check mark circle icon like the input boxes above (first name & last name).
In addition, the phone input box displays a red circle check mark icon when the number is invalid and I would like it to display a red circle x icon instead.
If anyone knows how to achieve this your help is appreciated!
Incorrect fa fa icon displaying on email and phone number:

JSFiddle
HTML:
<form class="container" action="https://webto.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8" method="POST">
  First Name
    <input id="first_name" maxlength="40" name="first_name" size="20" type="text" onkeyup="test()" required>

  Last Name
    <input id="last_name" maxlength="80" name="last_name" size="20" type="text" onkeyup="test()">

  Email
    Please enter a valid email address
    <input id="email" maxlength="80" name="email" size="20" type="text" onkeyup="test()">

  Phone
    Please enter a valid phone number
    <input id="phone" maxlength="80" name="phone" size="20" type="tel" onkeyup="test()">

  City
    <input id="city" name="city" maxlength="40" size="20" type="text" onkeyup="test()">

  State/Province
    <input id="state" maxlength="20" name="state" size="20" type="text" onkeyup="test()">

  Company
    <input id="company" name="company" type="text" onkeyup="test()">

  Comments
    <textarea id="comments" name="" id="" cols="30" rows="10" onkeyup="test()"></textarea>
    <input id="sub" type="submit" disabled="disabled" />

        <select  hidden="true" id="00N6A000008yXMN" name="00N6A000008yXMN" title="Product Interest">
        <option value="">--None--</option>
        <option selected="selected" value="Visiant">Visiant</option>
        <option  value="Tessellate">Tessellate</option>
    </select>

    <select  hidden="true" id="lead_source" name="lead_source">
        <option value="">--None--</option>
        <option value="Internal">Internal</option>
    <option value="Trade Show">Trade Show</option>
    <option selected="selected" value="Website">Website</option>
    <option value="Direct Marketing">Direct Marketing</option>
    <option value="Social Media">Social Media</option>
    <option value="Other">Other</option>
    </select>

</form>

CSS:
body {
  color: #fff;
  background-color: #f78e2a;
  text-align: center;
}
form {
  color: #fff;
  background-color: #f78e2a;
  text-align: center;
  font-family: Lato;
}

* {
  box-sizing: border-box;
}

.form-title {
  font-size: 38px;
  color: #fff;
  font-family: "Lato";
  letter-spacing: 70px;
}

input[type="tel"] {
  width: 100%;
  height: 85%;
  padding: 10px;
  background-color: #f9a558;
  border: 1px solid #fff;
}
input[type="text"] {
  width: 100%;
  padding: 10px;
  background-color: #f9a558;
  border: 1px solid #fff;
}

input[type="text"]:focus {
  background-color: #fff;
}

input[type="text"]:visited {
  background-color: #fff;
}

input[type="tel"]:focus {
  background-color: #fff;
}

input[type="tel"]:visited {
  background-color: #fff;
}

.container {
  display: flex;
  flex-direction: column;
  padding: 5px 0;
  margin-left: 10%;
  margin-right: 10%;
}

textarea {
  width: 100%;
  background-color: #f9a558;
  border: 1px solid #fff;
}

textarea:focus {
  background-color: #fff;
}

#co {
  flex-basis: 100%;
  max-width: 100%;
}

label:nth-last-child(-n+2) {
  flex-basis: 100%;
  max-width: 100%;
}

select,
label {
  height: 50px;
  width: 48%;
  margin: 2% 1%;
  text-align: left;
  font-family: "Lato";
}

#sub {
  border-radius: 6px;
  width: 120px;
  height: 35px;
  text-transform: uppercase;
  display: block;
  margin-top: 10px;
}

button {
  margin-top: 10px;
  background-color: #B9B9B9;
  color: #959595;
  border-radius: 6px;
  width: 120px;
  height: 35px;
  margin-left: 1%;
  display: block;
}

button:focus {
  background-color: #fff;
  color: #f78e2a;
}

@media (max-width: 426px) {
  label {
    width: 98%;
  }
}

@media (min-width: 426px) {
  .container {
    flex-direction: row;
    flex-wrap: wrap;
    align-self: flex-start;
  }
}

label {
  position: relative;
}

.fa {
  position: absolute;
  bottom: 0;
  right: 0;
  transform: translate(-50%, -5%);
  opacity: 0;
  transition: opacity .5s, color .5s;
}

[data-valid] .fa {
  opacity: 1;
  color: green;
}

[data-valid="valid"] .fa {
  color: green;
}

[data-valid="error"] .fa {
  color: red;
}

.error {
  display: none;
  color: red;
  font-size: .7em;
  position: absolute;
  left: 10px;
  top: 0;
  transform: translateY(150%);
}

[data-valid="error"] .error {
  display: block;
}

jQuery:
function phoneNumber(phone)  {
  var phoneno = /^\d{9}|\d{10}|\d{11}$/;
  return phoneno.test(phone);
}

$('input[type="tel"]').on('keyup', function() {
  var $label = $(this).closest('label');
  if ($(this).val().trim() != '') {
    if ($(this).is('#phone')) {
      if (phoneNumber($(this).val())) {
        $label.attr('data-valid', 'valid');
      } else {
        $label.attr('data-valid', 'error');
        console.log("this works")
      }
    } else {
      $label.attr('data-valid', 'valid');
      console.log("this works")
    }
  } else {
    $label.removeAttr('data-valid');
    console.log("this works")

  }
});

function validateEmail(email) {
  var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  return re.test(email);
}

$('input[type="text"]').on('keyup', function() {
  var $label = $(this).closest('label');
  if ($(this).val().trim() != '') {
    if ($(this).is('#email')) {
      if (validateEmail($(this).val())) {
        $label.attr('data-valid', 'valid');
      } else {
        $label.attr('data-valid', 'error');
        console.log("this works")
      }
    } else {
      $label.attr('data-valid', 'valid');
      console.log("this works")
    }
  } else {
    $label.removeAttr('data-valid');
    console.log("this works")

  }
});

test = function() {
  if ($("#first_name").val() && $("#last_name").val() && $("#email").val() && $("#phone").val() && $("#city").val() && $("#state").val() && $("#company").val()) {
    $("#sub").removeAttr("disabled");
  }
}

A: Your script is working...
But you just dont change the FA icon depending on the validation result.
If valid, add:
 $(this).next("i").removeClass("fa-times-circle-o").addClass("fa-check-circle");

If error, add:
 $(this).next("i").removeClass("fa-check-circle").addClass("fa-times-circle-o");

CodePen


text:
Q: Typescript: Is there a way to get all the keys in a Javascript object with nested properties? For example, if i have
{
   "key1":{
      "key2":[
         {
            "key3":[
               {
                  "key4":{
                     "key5":0
                  }
               },
               {
                  "key6":{
                     "key7":""
                  }
               }
            ]
         },
         {
            "key8":{
               "key9":true
            }
         }
      ]
   }
}

is there a way to get all the keys like this?
["key1", "key2", "key3", "key4", "key5", "key6", "key7", "key8", "key9"]

edit: i tried the suggestion here, but it didn't work out Typescript: what could be causing this error? "Element implicitly has an 'any' type because type 'Object' has no index signature"

A: You need a recursive function in order to iterate.
Try like this

var obj = {
  "key1": {
    "key2": [{
      "key3": [{
        "key4": {
          "key5": 0
        }
      }, {
        "key6": {
          "key7": ""
        }
      }]
    }, {
      "key8": {
        "key9": true
      }
    }]
  }
};
var keys = [];

function collectKey(obj) {
  if (obj instanceof Array) {
    //console.log("array");
    for (var i = 0; i < obj.length; i++) {
      collectObj(obj[i]);
    }
  } else if (typeof obj == "object") {
    //console.log("object");
    collectObj(obj)
  } else {
    return;
  }
}

function collectObj(obj) {
  for (var i = 0; i < Object.keys(obj).length; i++) {
    keys.push(Object.keys(obj)[i]);
    collectKey(obj[Object.keys(obj)[i]]);
  }
}
collectKey(obj);
console.log(keys);


text:
Q: pg_dump and the superuser PostgreSQL lets me connect as superuser if I am system user postgres:
[T] jeff@nantes-5p:~ $ sudo -u postgres psql
psql (10.15 (Ubuntu 10.15-0ubuntu0.18.04.1))
Type "help" for help.

postgres=#

As a result, I've cleverly not created a superuser.  But it appears that pg_dump does not offer this shortcut:
130,[T] jeff@nantes-5p:~ $ sudo -u postgres pg_dump -h localhost -p 5432 -U postgres -w
pg_dump: [archiver (db)] connection to database "postgres" failed: fe_sendauth: no password supplied
1,[T] jeff@nantes-5p:~ $ sudo -u postgres pg_dump -h localhost -p 5432 -w
pg_dump: [archiver (db)] connection to database "postgres" failed: fe_sendauth: no password supplied
1,[T] jeff@nantes-5p:~ $ sudo -u postgres pg_dump -h localhost -w
pg_dump: [archiver (db)] connection to database "postgres" failed: fe_sendauth: no password supplied
1,[T] jeff@nantes-5p:~ $

Did I miss something?  It seems inconsistent, and a bit silly that creating a superuser just requires root but dumping tables requires something that root can just do.


text:
Q: kxml doens't parse wbxml to xml correctly I used to parse a wbxml traffic comes to my android device.
i use kxml parser to print out the contents, but parser says me there isn't any string or attributes to show.
where am i wrong ?
public static void main(String[] args) throws FileNotFoundException, XmlPullParserException, ParserConfigurationException, UnsupportedEncodingException, IOException, SAXException, TransformerConfigurationException, TransformerException {
    // TODO code application logic here
    File file = new File("path to wbxml file");
    //InputStream in = new FileInputStream("path to wbxml file");
    InputStream in = new DataInputStream(new FileInputStream(file));
    ByteArrayInputStream bin = new ByteArrayInputStream(in.toString().getBytes());
    WbxmlParser parser = new WbxmlParser();
    parser.setInput(bin, "UTF-8");

    int eventType = parser.getEventType();
    while (eventType != WbxmlParser.END_DOCUMENT) {
    if(eventType == WbxmlParser.START_DOCUMENT) {
        //Log.d(a, "Start document");
        System.out.printf("%s\n", "Start document");
    } else if(eventType == WbxmlParser.START_TAG) {
        //Log.d(a, "Start tag "+parser.getName());
        System.out.printf("%s\n", parser.getName());
    } else if(eventType == WbxmlParser.END_TAG) {
        //Log.d(TAG, "End tag " + parser.getName());
        System.out.printf("%s\n", parser.getName());
    } else if(eventType == WbxmlParser.TEXT) {
        //Log.d(TAG, "Text " +parser.getText());
        System.out.printf("%s\n", parser.getText());
    }
    eventType = parser.next();
}
System.out.println("End document");
    //try{

    Document doc = new Document();
    doc.parse(parser);

    //} catch (XmlPullParserException e){
   //     e.printStackTrace();
   // }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    KXmlSerializer ser = new KXmlSerializer();
    ser.setOutput(out, null);
    doc.write(ser);
    ser.flush();

    byte[] b = out.toByteArray();
    System.out.println(new String(b));
    /*TransformerFactory tfactory = TransformerFactory.newInstance();
    Transformer transformer = tfactory.newTransformer();

    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(System.out);
    transformer.transform(source, result); */

        }

I also checked Heiner's Blog for answer but nothing...
wbxml document i want to parse is sth like this.


text:
Q: Fetch all groups (Global, Universal, Domain-Local) for a given user I am struggling to fetch all groups for a given user (domain1/user1)...
The below C program (ran on a machine in domain1) works fine but it doesn't show the groups from other domain..
User1 is also part of domain2 but the below code doesn't show that information..
I breaking my head to figure out the other options but no luck..
Could you guys provide any suggestions...
void printGroups()
{
IADsUser *pUser;
IADsMembers *pGroups;
HRESULT hr = CoInitialize(NULL);
if (FAILED(hr)) return -1;
IID iid = IID_IADsUser;
hr = ADsGetObject(L"WinNT://domain1/user1", &iid, (void**)&pUser);

if (FAILED(hr)) {
printf("blad");
return -1;
}

pUser->lpVtbl->Groups(pUser, &pGroups);
//pUser->Groups(&pGroups);
pUser->lpVtbl->Release(pUser);
//pUser->Release();
if (FAILED(hr)) return -1;

IUnknown *pUnk;
hr = pGroups->lpVtbl->get__NewEnum(pGroups, &pUnk);
if (FAILED(hr)) return -1;
pGroups->lpVtbl->Release(pGroups);

IEnumVARIANT *pEnum;
iid = IID_IEnumVARIANT;
hr = pUnk->lpVtbl->QueryInterface(pUnk, &iid, (void**)&pEnum);
if (FAILED(hr)) return -1;

pUnk->lpVtbl->Release(pUnk);

// Enumerate.
BSTR bstr;
VARIANT var;
IADs *pADs;
ULONG lFetch;
IDispatch *pDisp;

VariantInit(&var);
hr = pEnum->lpVtbl->Next(pEnum, 1, &var, &lFetch);
while (hr == S_OK)
{
if (lFetch == 1)
{
pDisp = V_DISPATCH(&var);
iid = IID_IADs;
pDisp->lpVtbl->QueryInterface(pDisp, &iid, (void**)&pADs);
pADs->lpVtbl->get_Name(pADs, &bstr);
//printf("Group Name: %S\n", bstr);
pADs->lpVtbl->get_ADsPath(pADs, &bstr);
printf("Group ADPath: %S\n", bstr);
SysFreeString(bstr);
pADs->lpVtbl->Release(pADs);
}
VariantClear(&var);
pDisp = NULL;
hr = pEnum->lpVtbl->Next(pEnum, 1, &var, &lFetch);
};
hr = pEnum->lpVtbl->Release(pEnum);
return 0;

}

A: I'd strongly urge you to consider something else besides that ancient COM/ActiveX API.  For example, here's a PowerShell script that queries for a list of users:
import-module activedirectory
echo ""
echo "User Memberships:"
try {
  $users = @(
    "John",
    "Paul",
    "George",
    "Ringo")
  foreach ($u in $users) {
    echo "USER: $u"
    Get-ADUser  -Identity $u -Properties MemberOf
  }
}
catch {
  $errmsg = "ERROR:Get-ADGroupMember(" + $g + "): " + $error
  $errmsg
  $error.Clear()
}

The other issue: I'm not sure how easy it is to do cross-domain queries - in any language, with any API.
For this example, I'd copy the script to a separate PC on the other domain, run it in both places, and just merge the results with notepad.
ADDENDUM:
You might also find this link helpful:
Search Active Directory for User and Office Locations


text:
Q: Why are writes to an html page buffered in Internet Explorer? Is there a way around it? I've written a very small html page for IE that uses client-side PerlScript. In the script, I launch a separate process which creates a TCP socket. After launching the process, I start a listener which appends HTML to the end of a div as lines are read, additionally for debugging, I added alerts as each line is read.
The problem is that the alerts hit spot on as lines are read, but the HTML doesn't update until the process has finished. Why is that? Is there a way to force the page to render so that I can get the same behavior?
Here's the page:

        <title>Message Test</title>

I have looked at on-line documentation for PerlScript which is incredibly sparse. I'm looking for hints at how to command IE to fire page renders, respond to these html insertions... etc.
In researching this, I have found that I can get it to render as the lines are read if instead of onload, I use an onclick on the div. Perhaps I'm not using the right event and the page isn't fully rendered before the subroutine is fired? I'm very frustrated with IE here (v. 9).
And yes, when I use this in a command line situation, everything fires as expected. The CreateServer/CreateClient are just wrappers around IO::Socket::INET for client and server.
UPDATE (based @Oleg V. Volkov's answer):
I modified go and added a _read() function that reads a line, then passes control back to the browser to render. Seems to do an ok job.
sub _read() {
  my $port = shift;
  $INPUT = util::CreateClient($port) if ! $INPUT;
  if (defined (my $line = <$INPUT>)) {
    _write($line);
    $window->setTimeout("_read($port)", 0);
  }
  else {
    _write("Fin!");
  }
}
sub go() {
  _write("starting!
");
  my $port = 12345;
  Win32::Process::Create(my $Proc, "C:/perl/bin/perl.exe", "perl clitest2.pl $port", 1, CREATE_NO_WINDOW | NORMAL_PRIORITY_CLASS | DETACHED_PROCESS, "C:/development/plslog");
  $window->alert("Hi! started!");
  $window->setTimeout("_read($port)", 0);
}

That seems to get near real-time updates.

A: Most (if not all) browsers do not redraw page until you return from hosted script process. They can reflow internal representation of data on some operations, but still won't spend time redrawing it until you've returned control. To allow browser to redraw, you should break your task into steps and yield once in a while by scheduling next step with setTimeout and returning from your script.
In your particular case, replacing sleep(3), where you do nothing anyway, with scheduling of next loop iteration to happen 3 seconds later, seems like the best way.


text:
Q: Add existing folders with identical content on multiple PCs to OneDrive I have two PCs in two different locations, each with a folder named "Foo". The folders have identical content of around 50GB, and will be kept in sync via OneDrive in the future.
Can I add the folders to OneDrive on both PCs without OneDrive re-downloading all the files on one of the PCs (or on both, for that matter)?
I'm trying it out right now, but OneDrive seems to be stuck, reporting something like "32,768 changes are being processed".


text:
Q: Two normal humans interact with a team of clones I'm looking for a story I read in the 90s - I'd guess it's 20-30 pages long.
Two men are posted as scientific observers on an isolated planet for many years.  Despite their differences, they learn to get along and survive the solitude.  One day, a team of 12 identical clones arrives.  There are 6 males and 6 females who were cloned from a brilliant male biologist (by adding X chromosomes, etc.).  They are super close to each other; each one specializes in a different field of science, they all sleep together, and they don't really communicate well with outsiders.
The point of the story is the contrast between the original pair's way of dealing with differences and the clone's identical, in-built similarity which makes those skills unnecessary.
A disaster on the planet results in the death of some of the clones & explores the psychological aftermath of the breakup of their unit.

A: This is Nine Lives by Ursula K. LeGuin.  Posted in its entirety here.  And ISFDB info here.   First published in Playboy magazine! (I only looked at it for the sf stories).

"It's a clone," Kaph said. "The other Exploit Team they're bringing with them."
"Is it then?"
"A twelveclone. They came out with us on the Passerine."


text:
Q: I need gender ratio of user friends from Facebook Graph Api I know Facebook does not give list of friends list who have not accepted permission our app ask, I don't need actual names of friends. I just need gender ratios of my friend list. Is there any way for that?
I've tried some solution like:-
https://developers.facebook.com/docs/graph-api/reference/user/taggable_friends/
https://developers.facebook.com/docs/graph-api/reference/user/invitable_friends/
But these services were deprecated on April 4th, 2018.
So, any another solution ?

A: You can try this approach

*

*Get the actual names of friends( You are going to need them)

*Find a way to retrieve gender of the [retrieved names] using https://genderize.io/ API or https://gender-api.com/. Note though that it's algorithms are not perfectly true.

*Then once you have genders of the list of your users you can then compute the gender ratio.


text:
Q: IReliableDictionary 2 vs IReliableDictionary Can anyone explain why service fabric has both IReliableDictionary and IReliableDictionary2 where IReliableDictionary DERIVES from IReliableDictionary2?  It makes no sense and the documentation doesn't appear to explain it.  Which one are you supposed to use?
https://learn.microsoft.com/en-us/dotnet/api/microsoft.servicefabric.data.collections.ireliabledictionary-2?view=azure-dotnet
Proof:

A: You are reading the documentation incorrectly. "Derived", means that IReliableDictionary2 is derived from IReliableDictionary. For proof look at ICollection interface in .Net, https://learn.microsoft.com/en-us/dotnet/api/system.collections.icollection?view=netframework-4.7.
You want use IReliableDictionary2 if you need to use Count that doesn't enumerate all items in the dictionary or key enumeration.

A: IReliableDictionary2 has an additional property Count which is persisted alongside the collection's entries. This allows quick access to the number of entries in the collection, as usually you'd have to enumerate over its entries and calculate the count.
This is not very clear from the API documentation, merely seeing "Oh this has an extra count property" does not, to me, alert that "You should use this if you need to readily access the count". Perhaps you could open an issue here explaining how it's not clear, or edit it and create a PR!


text:
Q: How to create query to match child collection attributes using NEST .net client library for ElasticSearch? I have following 4 documents located at http://xyzserver:9200/mydocs/brands in ElasticSearch 7.3
Each document represents some details of a Brand. A brand can be associated with multiple Groups and can be active for 0 or more groups.
UPDATE 1: Here is document mapping
{
    "mydocs": {
        "mappings": {
            "properties": {
                "Groups": {
                    "properties": {
                        "GroupId": {
                            "type": "long"
                        },
                        "GroupName": {
                            "type": "text"
                        },
                        "IsActive": {
                            "type": "boolean"
                        }
                    }
                },
                "Id": {
                    "type": "long"
                },
                "Name": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type": "keyword",
                            "ignore_above": 256
                        }
                    }
                }
            }
        }
    }
}

I have 4 documents loaded.
{
    Id: 100,
    Name: 'Diet Coke',
    Groups:
    [{
        GroupId: 200,
        GroupName: 'US East',
        IsActive: true
     },
     {
        GroupId: 201,
        GroupName: 'US West',
        IsActive: true
     },
     {
        GroupId: 202,
        GroupName: 'US South',
        IsActive: false
     }
    ]
}
{
    Id: 110,
    Name: 'Coke',
    Groups:
    [{
        GroupId: 200,
        GroupName: 'US East',
        IsActive: false
     },
     {
        GroupId: 201,
        GroupName: 'US West',
        IsActive: true
     },
     {
        GroupId: 202,
        GroupName: 'US South',
        IsActive: true
     }
    ]
}
{
    Id: 120,
    Name: 'Coke with Lime',
    Groups:
    [{
        GroupId: 200,
        GroupName: 'US East',
        IsActive: true
     },
     {
        GroupId: 201,
        GroupName: 'US West',
        IsActive: true
     },
     {
        GroupId: 202,
        GroupName: 'US South',
        IsActive: true
     }
    ]
}
{
    Id: 130,
    Name: 'Cola',
    Groups:
    [{
        GroupId: 300,
        GroupName: 'Europe East',
        IsActive: true
     },
     {
        GroupId: 400,
        GroupName: 'Mexico',
        IsActive: true
     },
     {
        GroupId: 410,
        GroupName: 'Brazile',
        IsActive: true
     }
    ]
}

I am searching for "Coke" and which is "Active" for both "200 - US East Group" && "201 - US West Group" groups. Assume that I have a search criteria type
public class BrandSearchCriteria {
    public string Keyword {get; set;}
    public IEnumerable<int> GroupIds {get; set;} = new List<int>();
    public bool? IsActive {get; set;} //true if looking for only active items, false if looking for inactive items, null if looking for both
}

searchCriteria = new BrandSearchCriteria
{
    Keyword = "Coke",
    GroupIds = new List<int> { 200, 201 },
    IsActive = true
}

How do I create a query using NEST library? This is what I have so far
QueryContainerDescriptor<Brand> queryDescriptor = new QueryContainerDescriptor<Brand>();
queryDescriptor.Bool(b =>
    b.Must(q =>
        q.Match(m => m.Field(f => f.Name).Fuzziness(Fuzziness.Auto).Query(searchCriteria.KeyWord) &&
        q.Terms(t => t.Field("Groups.GroupId").Terms<int>(searchCriteria.GroupIds)) &&
        q.Term(t => t.Field("Groups.IsActive").Value(searchCriteria.IsActive.ToString()))
      )
    );

I am suppose to get only two documents back with Id 100 (Diet Coke) and 120 (Coke with Lime) as these two documents are the only two active for both Groups "200 - US East Group" && "201 - US West Group".
But above query is bring me 3 documents back 100 (Diet Coke), 110 (Coke), 120 (Coke with Lime). Even thou document 110 (Coke) is inactive for Group "201 - US West Group", it is still getting included in the results.
I just started learning NEST library usage and could not figure out how to formulate the query to retrieve the results. Any help will be greatly appreciated.

A: First of all I believe you need to change the mappings. specifically Groups should be nested
{
    "mappings": {
        "properties": {
            "Groups": {
              "type": "nested",
                "properties": {
                    "GroupId": {
                        "type": "long"
                    },
                    "GroupName": {
                        "type": "text"
                    },
                    "IsActive": {
                        "type": "boolean"
                    }
                }
            },
            "Id": {
                "type": "long"
            },
            "Name": {
                "type": "text",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            }
        }
    }
}

Then the nest code based on yours would look like:
// preparing the query
var groupIds = new[] { 200, 201 };
Func<QueryContainerDescriptor<Brand>, int, QueryContainer> nestedQuery = (q, groupId) => q.Nested(n => n.Path("Groups").Query(nq => nq.Bool(nb => nb.Filter(
        fq => fq.Term(t => t.Field("Groups.GroupId").Value(groupId)),
        fq => fq.Term(t => t.Field("Groups.IsActive").Value(true))))
    )
);
var query = groupIds.Select(groupId => nestedQuery(new QueryContainerDescriptor<Brand>(), groupId)).ToList();
query.Add(new QueryContainerDescriptor<Brand>().Match(m => m.Field("Name").Fuzziness(Fuzziness.Auto).Query("coke")));

var queryDescriptor = new QueryContainerDescriptor<Brand>();
queryDescriptor.Bool(b => b.Must(query.ToArray()));

Few suggestions:

*

*Use Expression instead of strings in methods like Field

*boolean type on ES side is bool on C#. not sure why you are converting it to string.

*Use filters whenever you don't need scoring, basically yes/no answer.

*I would've used painless script here. Would have looked cleaner


text:
Q: How to calculate age in years in SQL Need to create a basic Age Calculator function which calculates the age in years on the age field of the peoples table.

The function should be called agecalculator, it needs to take 1 date and calculate the age in years according to the date NOW and must return an integer.
You may query the people table while testing but the query must only contain the function on your final submit.

people table schema
id
name
age

This is my code:
select convert(int,DATEDIFF(d, '1933-10-31', getdate())/365.25)

A: Try this:
 DECLARE @DOB DATETIME ='12/29/1980'

 SELECT @DOB 'Date of Birth', GETDATE() 'Current Date',

 DATEDIFF(YEAR,@DOB,GETDATE()) -
 (CASE WHEN DATEADD(YY,DATEDIFF(YEAR,@DOB,GETDATE()),@DOB) > GETDATE()
    THEN 1
    ELSE 0
      END) 'Age in Years'

A: You need to create a function,so use the CREATE FUNCTION statement .
Try this:
CREATE FUNCTION ageCalculator (a timestamp) RETURNS integer AS $$
BEGIN
  RETURN (SELECT date_part('year',age(a)))::int;
END;
 $$ LANGUAGE plpgsql;

Or:
CREATE FUNCTION ageCalculator (a timestamp)
RETURNS integer AS $$
BEGIN
  RETURN (SELECT EXTRACT(year FROM age(a)))::int;
END;
 $$ LANGUAGE plpgsql;

A: DECLARE @DOB DATETIME ='08/14/1980'

 SELECT @DOB 'Date of Birth', GETDATE() 'Current Date',

 DATEDIFF(YEAR,@DOB,GETDATE()) -
 (CASE WHEN DATEADD(YY,DATEDIFF(YEAR,@DOB,GETDATE()),@DOB) > GETDATE()
    THEN 1
    ELSE 0
      END) 'Age in Years'


text:
Q: How to use different version of Elixir runtime for Visual Studio Code extension(ElixirLS) from locally set one(.tool_versions) elixir(1.8.1) and erlang(21.3.5) are set locally via .tool-versions(ASDF) file.
ElixirLS launched using above version of elixir but it requires higher version.
** (UndefinedFunctionError) function ElixirLS.Utils.OutputDevice.get_opts/0 is undefined (module ElixirLS.Utils.OutputDevice is not available)
    ElixirLS.Utils.OutputDevice.get_opts()
    lib/wire_protocol.ex:33: ElixirLS.Utils.WireProtocol.intercept_output/2
    lib/language_server/cli.ex:6: ElixirLS.LanguageServer.CLI.main/0
    (stdlib) erl_eval.erl:680: :erl_eval.do_apply/6
    (elixir) lib/code.ex:232: Code.eval_string/3
[Info  - 1:09:58 PM] Connection to server got closed. Server will restart.
** (UndefinedFunctionError) function ElixirLS.Utils.OutputDevice.get_opts/0 is undefined (module ElixirLS.Utils.OutputDevice is not available)
    ElixirLS.Utils.OutputDevice.get_opts()
    lib/wire_protocol.ex:33: ElixirLS.Utils.WireProtocol.intercept_output/2
    lib/language_server/cli.ex:6: ElixirLS.LanguageServer.CLI.main/0
    (stdlib) erl_eval.erl:680: :erl_eval.do_apply/6
    (elixir) lib/code.ex:232: Code.eval_string/3
[Info  - 1:09:59 PM] Connection to server got closed. Server will restart.
** (UndefinedFunctionError) function ElixirLS.Utils.OutputDevice.get_opts/0 is undefined (module ElixirLS.Utils.OutputDevice is not available)
    ElixirLS.Utils.OutputDevice.get_opts()
    lib/wire_protocol.ex:33: ElixirLS.Utils.WireProtocol.intercept_output/2
    lib/language_server/cli.ex:6: ElixirLS.LanguageServer.CLI.main/0
    (stdlib) erl_eval.erl:680: :erl_eval.do_apply/6
    (elixir) lib/code.ex:232: Code.eval_string/3
[Info  - 1:10:00 PM] Connection to server got closed. Server will restart.
** (UndefinedFunctionError) function ElixirLS.Utils.OutputDevice.get_opts/0 is undefined (module ElixirLS.Utils.OutputDevice is not available)
    ElixirLS.Utils.OutputDevice.get_opts()
    lib/wire_protocol.ex:33: ElixirLS.Utils.WireProtocol.intercept_output/2
    lib/language_server/cli.ex:6: ElixirLS.LanguageServer.CLI.main/0
    (stdlib) erl_eval.erl:680: :erl_eval.do_apply/6
    (elixir) lib/code.ex:232: Code.eval_string/3
[Info  - 1:10:02 PM] Connection to server got closed. Server will restart.
** (UndefinedFunctionError) function ElixirLS.Utils.OutputDevice.get_opts/0 is undefined (module ElixirLS.Utils.OutputDevice is not available)
    ElixirLS.Utils.OutputDevice.get_opts()
    lib/wire_protocol.ex:33: ElixirLS.Utils.WireProtocol.intercept_output/2
    lib/language_server/cli.ex:6: ElixirLS.LanguageServer.CLI.main/0
    (stdlib) erl_eval.erl:680: :erl_eval.do_apply/6
    (elixir) lib/code.ex:232: Code.eval_string/3
[Error - 1:10:02 PM] Connection to server got closed. Server will not be restarted.

Can I make the extension to use global version(set by ASDF) of elixir?

A: Before running anything that requires Elixir (e.g. in your case VScode and ElixirLS), you can override the elixir version by setting a temporary shell version - asdf shell elixir <elixir version you want>. This sets a shell environment variable that the asdf shim will read when running that will override the version set in .tool-versions. Of course you'll need to have the version of Elixir you want to use already installed on your system and launch everything from the shell that has the environment variable set.
Alternatively you can try something like this to disable reading of .tool-versions files entirely - https://github.com/asdf-vm/asdf/issues/870#issuecomment-780862765


text:
Q: NFS Server has low performance First of all, here are the specs of the server we are talking about (only the relevant stuff):

*

*AMD-6400K with AES-NI

*6x3TB WD Red HDDs in Software Raid5 (AES encrypted)

*16GB of DDR3 RAM

The overall performance of the HDDs is about 300 - 400MB/s in sequential write/read. The problem is now that it is severly slower when using NFS. It it connected to my PC with a Gigabit network, which should give me a maximum of 120MB/s. But I only come to 17MB/s per second. I once had this server running with Gentoo Linux, Raid5 and NFS and had about 110MB/s. Now it is running with Debian. Unfortunately, I cannot remember my old NFS settings (via Samba the server reaches about 90MB/s btw). This is my current setup:
/nfs/data   bueckstueck01(rw,sync,nohide,no_subtree_check,anonuid=1000,anongid=1000) 192.168.2.0/255.255.255.0(ro,sync,nohide,no_subtree_check,anonuid=1000,anongid=1000)

and I mount it via:
mount.nfs -o users,exec,rw,wsize=8192,rsize=8192 databueck01:/nfs/data /mnt/data

Can you tell me what I am doing wrong or what you think would be more optimized settings? I am mainly backupping Systems via TAR (single file, sequential write) on this server, so I do not copy multiple small data files on it which would generate a massive overhead. I pipe the systems backup files to tar and direct that directly on the server.
Any help is appreciated!

A: The sync (synchronous) setting is probably your bottleneck. You may consider trying to export with the async (asynchronous) flag, depending on your workload.
Try benchmarking with it.


text:
Q: Full text search & fuzzy search with PostgreSQL Forgive me if this is a silly question.
I have the following code in one of my migrations:
    DB::statement("
    CREATE MATERIALIZED VIEW searchable_stores AS
    SELECT
    chain_stores.id as chain_store_id,
    local_chain_stores.id as local_chain_store_id,
    chain_stores.website as website,
    chain_stores.name as name,
    chain_stores.cname as cname,
    chain_stores.flyer_url as flyer_url,
    local_chain_stores.city as city,
    local_chain_stores.shopping_mall as shopping_mall,
    local_chain_stores.postal_code as postal_code,
    local_chain_stores.street_address as street_address,
    to_tsvector('sv', chain_stores.name) ||
    to_tsvector('sv', replace(chain_stores.name, ' ', '')) ||
    to_tsvector('sv', local_chain_stores.city) ||
    to_tsvector('simple', to_char(local_chain_stores.postal_code, '99999')) ||
    to_tsvector('sv', coalesce(local_chain_stores.shopping_mall)) ||
    to_tsvector('sv', local_chain_stores.street_address) ||
    to_tsvector('sv', chain_stores.bio)
    as document
    FROM
        local_chain_stores, chain_stores
    WHERE
        local_chain_stores.chain_store_id = chain_stores.id
    ");

And this is how I query the table:
    $results = SearchableStore::
        whereRaw("document @@ plainto_tsquery('simple', ?)", array($searchQuery->getQuery()))
        ->orWhereRaw("document @@ plainto_tsquery('sv', ?)", array($searchQuery->getQuery()))
        ->orderBy('name', 'asc')
        ->get();
    return $results;

This works perfectly fine, unless someone spells some word(s) wrong. And that's what I'm trying to solve. You will also notice these 2 lines:
    to_tsvector('sv', chain_stores.name) ||
    to_tsvector('sv', replace(chain_stores.name, ' ', '')) ||

I know this is ugly, but what I am essentially doing is making sure that if someone does a search for e.g "BurgerKing" I want to return results for "Burger King". I know this looks like a silly example, but these mistakes happen a lot in the swedish language (not necessarily for Burger King, but other terms). Aside from that, I also want to make sure that when someone does a typo I still want to return relevant results.
So, my question is. How do I implement this? I tried playing around with fuzzy search, but I'm kind of stuck because I don't know how to query a column (document) consisting of tsvector values.

A: Full Text Search works with dictionaries and stemming and is not fit for fuzzy search and general pattern matching.
Consider the additional module pg_trgm for that. Its operator classes allow GIN or GiST indexes that support LIKE and related pattern-matching operators.
Details in this related answer:
PostgreSQL LIKE query performance variations
Overview over pattern-matching techniques in Postgres:
Pattern matching with LIKE, SIMILAR TO or regular expressions in PostgreSQL

A: What you looking for are Synonyms and Thesaurus dictionaries, it is a lot of work to compile them, yet is will make your searches way more cost effective in terms of CPU and disk usage.
For some languages you can find Thesaurus dictionaries that can be easily converted in the OpenOffice for others you are on your own. I am still searching for good sources and posted a question about this topic here: https://dba.stackexchange.com/questions/80632/where-to-download-dutch-postgresql-fulltext-search-dictionaries , no answers so far.
If you are running Linux it can also prove worth your will to install the myspell or hunspell packages of your language. For installation of these packages see: https://askubuntu.com/questions/72099/how-to-install-a-libreoffice-dictionary-spelling-check-thesaurus
If you want to know how to use them in PostgreSQL you should read up on configuring full text search, I really like this guy since here writes about it in a light and understandable manner: a full text search engine


text:
Q: Magento - Issue with php code not running PHP code not running in /header.phtml
I have the following code in /app/design/frontend/default/gumball/template/page/html/header.phtml

<a href="<?php echo $this->getUrl('checkout/cart/')?>" class="cartcount cartlink">

<? if(Mage::getSingleton('checkout/session')->getQuote()->getItemsSummaryQty() > 0) { ?>
<?=__(Mage::getSingleton('checkout/session')->getQuote()->getItemsSummaryQty())?>
    <? } else { ?>
    0
 <? } ?> Item(s)

On the current server the Correct html being produced is

   0 Item(s)

but on the other server that I am trying to move the current site to I get the following html

<? if(Mage::getSingleton('checkout/session')->getQuote()->getItemsSummaryQty() > 0) { ?>
<?=__(Mage::getSingleton('checkout/session')->getQuote()->getItemsSummaryQty())?>
<? } else { ?>
0
<? } ?> Item(s)

It seems that the php code is not running. What can I do to resolve this issue?
Thanks.

A: This is not a magento issue. It's a server configuration "issue".
Most likely short tags are not enabled on you server. Change your code into this and it should work regardless of the short tags settings.

<a href="<?php echo $this->getUrl('checkout/cart/')?>" class="cartcount cartlink">

<?php if(Mage::getSingleton('checkout/session')->getQuote()->getItemsSummaryQty() > 0) { ?>
<?php echo __(Mage::getSingleton('checkout/session')->getQuote()->getItemsSummaryQty())?>
    <?php } else { ?>
    0
 <?php } ?> Item(s)

A bit off topic:
read more guidelines on how to write magento code. Your issue is listed in there also.


text:
Q: Modifying global variable from within function that have the same parameter name in python I have this function:
def applychange(L):
    result=3+2
    L=[4,5,6]
    return result
L = [1,2,3]
print(applychange(L))
print(L)

and the result is :
5
[1, 2, 3]

how to change the L variable to new value to have this result:
5
[4, 5, 6]

A: If your goal is to modify L as global variable you need to declare it as such.
For your code to run as intended, insert global L after the result assignment in your function.
Additionally, there is no need to pass L to the function in order to modify L.
def applychange():
    result = 3 + 2
    global L
    L = [4, 5, 6]
    return result

L = [1, 2, 3]
print(applychange())
print(L)

Your code written this way will result in the intended output:
5
[4, 5, 6]

A: The problem is that you overwrite the variable L, instead of modifying it. You can use
L[:] = [4,5,6]

instead of
L = [4,5,6]


text:
Q: How to count values matches in another column I am making a query system where a person post a query, db allocated an id (query_id) to that query. I am using that query_id in another column query_reply_id in same table to store the data of send emails. Now I am trying to count the number of emails sent on that id, following code giving me the number of emails sent per id in MySQL but when I call it, the preview shows it combine.
$new_sql = "SELECT t.query_id, count(o.query_reply_id) mycount
            from query t
               left join query o on t.query_id = o.query_reply_id
            Where t.query_form = 'contactus'
              AND t.query_status= 'replied'
            group by o.query_reply_id
            order by t.query_reply_date DESC";

$new_run = mysqli_query($conn, $new_sql);
while($new_rows = mysqli_fetch_assoc($new_run)){

echo $new_rows['mycount'];}

query_id  mycount
70          1
23          8
43          11
49          1

In preview, its showing 18111 against each of the query.

A: The reason you are getting a long line with just the mycount values is that all you are echoing out are mycount values.
You need to add a line break at the end and output the query_id values too. Perhaps something a bit like this:
while($new_rows = mysqli_fetch_assoc($new_run)){
    echo $new_rows['query_id'], ':', $new_rows['mycount'],"
";
}

Personally, as this is tabular data I'd be tempted to use a table.
This sort of thing:
echo "

query_id	mycount
";
while($new_rows = mysqli_fetch_assoc($new_run)){
    echo '
' ,$new_rows['query_id'], '	', $new_rows['mycount'],"
";
}
echo "</table";


text:
Q: Domain class not accessible in my controller I'm new to Grails and groovy..
I created a domain class
\grails-app\domain\Abc

Now i created a controller in
\grails-app\controllers\myapp\myController

In that, when i created an object it shows error.
def Abc obj = new Abc

The error i got is
unable to resolve class Abc

I tried to import, but didn't shown there also. Me working in grails 1.3.7 and IntelliJ IDEA 10.0.2
Thank you

A: I think you created your domain class & controller class manually. First, your controller should be in the folder controllers, not myapp. Second, you should define a package for both your domain class & controller class, for example:
Domain class:
package myapp

class Book {
...
}

Controller class
package myapp

class BookController {
....
}

A: Make sure that the location of each class is consistent with the class and package declaration.

I created a domain class
\grails-app\domain\Abc

This class should look like this
class Abc {
    // implementation omitted
}

make sure you have no package declaration, because based on the location, this class should be in the default package (which is actually a bad practice). Ideally you should put this class into a package, then move the source file into a subdirectory of \grails-app\domain that corresponds to the package name.

Now i created a controller in
\grails-app\controllers\myapp\myController

This class should look like this
package myapp

class myController {
    // implementation omitted
}

Notice that this class should be named with a lower-case 'm' because that's how the file is named. The standard Java/Groovy naming conventions dictate that classes should begin with a capital letter.

In that, when i created an object it shows error.

def Abc obj = new Abc

There are a couple of problems with this code:

*

*define the type as either def or
Abc but not both

*you're missing some parentheses

Try this instead:
Abc obj = new Abc()


text:
Q: ordfilt2: Find requires variable sizing I want to generate c++ code from the following Matlab function (Harris corner detection) that detects corners from an image.My constraint is that I have to generate a static library in C++ without variable-sizing support.
So, I have disabled variable size support from settings and also selected target platform as unspecified 32 bit processor.
In this way I'll be able to use it in Vivado HLS for an FPGA project.
However, when I generate the code, the line containing ordfilt2 function throws an error that FIND requires variable sizing.
Please, help me if there is a workaround to this problem.I have seen a similar question posted here Matlab error "Find requires variable sizing" . But I am not sure how this applies to my case.Thanks.
Here's the code:
function [cim] = harris(im , thresh)

dx = [-1 0 1; -1 0 1; -1 0 1]; % Derivative masks
dy = dx';

Ix = conv2(im, dx, 'same');    % Image derivatives
Iy = conv2(im, dy, 'same');

% Generate Gaussian filter of size 6*sigma (+/- 3sigma) and of
% minimum size 1x1.
sigma = 1.5;
g = fspecial('gaussian',max(1,fix(6*sigma)), sigma);

Ix2 = conv2(Ix.^2, g, 'same'); % Smoothed squared image derivatives
Iy2 = conv2(Iy.^2, g, 'same');
Ixy = conv2(Ix.*Iy, g, 'same');

cim = (Ix2.*Iy2 - Ixy.^2)./(Ix2 + Iy2 + eps); % Harris corner measure

% Extract local maxima by performing a grey scale morphological
% dilation and then finding points in the corner strength image that
% match the dilated image and are also greater than the threshold.

radius = 1.5;
sze = 2*radius+1;                   % Size of mask.

mx = ordfilt2(cim,sze^2,ones(sze)); % Grey-scale dilate.

cim = (cim==mx)&(cim>thresh);       % Find maxima.

end


text:
Q: SSRS/ SQL security over client's site I was wondering if anyone can help. I have started a new job for a firm where they are looking to create BI reports for clients. The clients have the server on their site. We have access to only query the data, but not allowed to create tables, stored procedure etc.However we are allowed to create temporary tables.
I am looking to create an SSRS report for the client but at the same time want hide the SQL from them to prevent them knowing how the reports are built.
Is there a way to create a self service bespoken report which I can deploy for them but keep the SQL hidden from them, despite them having the server on their site and them having admin access to the sql server box and SSRS reporting server?
Any advice on best handling this tough situation will be greatly appreciated!

A: For the purposes of this answer I am ignoring any ethical issue with this question.
Short Answer:
There is no way of doing this with SSRS and your restrictions on the client database.
Long Answer:
SSRS reports are stored as a .rdl file on your clients reporting server. This is basically easily readable XML which will allow anyone with an interest to view the report definition.
If the report definition also contains the dataset SQL (SELECT secret_sql FROM table) then the client would have:

*

*The definition of the report, in order to be able to modify it.

*The definition of the dataset, in order to modify it or apply it to another report they design.

Your only chance would have been to obfuscate your SQL on the actual SQL Server  (WITH ENCRYPTION) however

*

*You state you're not allowed to do it

*The client may be able to either decrypt or using SQL Profiler detect the SQL you are running and therefore capture it for reuse.


text:
Q: Inconsistency in row returns My question: I'm wondering why the results from a query from a prepared statement should be inconsistent per run.
Warning weird stuff ahead.
I'm on an Oracle database. I'm using the ojdbc6.jar driver. I have a query which returns about 1300 rows (it changes over time because there's a where clause which depends on sysdate). When I run it in Toad (SQL Developer tool) and Netbeans Services tool (Another interface with the database) it works great. My results are consistant. But when I run the query in java code my results are highly inconsistent. In an effort to try and see how frequent each result count returned I put it into a for loop and iterated 10 times. There is a relatively consistent row count within each run, but not across runs. My output and code are below. Let me know whether any more information is helpful.
When an attempt works (sorta...):
Got real queries (1308)
Got real queries (1308)
Got real queries (1308)
Got real queries (1307)
Got real queries (1307)
Got real queries (1317)
Got real queries (1317)
Got real queries (1317)
Got real queries (1317)
Got real queries (1315)

When an attempt does not work:
Got real queries (212)
Got real queries (212)
Got real queries (212)
Got real queries (212)
Got real queries (212)
Got real queries (212)
Got real queries (212)
Got real queries (212)
Got real queries (212)
Got real queries (212)

My code:
public static void main(String[] args) throws Exception {
  for (int i = 0; i < 10; i++) {
    List<String> realQueries = new ArrayList<>();
    String sqlAllRealQueries = "select V.SQL_FULLTEXT" + StringHelper.newline
            + "from v$sql v" + StringHelper.newline
            + "where V.PARSING_SCHEMA_NAME = 'DSS1_PTC'" + StringHelper.newline
            + "and to_number(replace(replace(replace(v.last_load_time,'-',''), '/',''), ':','')) > to_number(to_char(sysdate - (24/24),'yyyymmddHH24mmss'))" + StringHelper.newline
            + "order by V.LAST_LOAD_TIME desc";
    try (ResultSet rs = getInstance().executeQuery(sqlAllRealQueries)) {
      while (rs.next()) {
        realQueries.add(rs.getString(1));
      }
    }

    System.out.println("Got real queries (" + realQueries.size() + ")");
  }
  System.exit(0);
}

public ResultSet executeQuery(String connection, String query, QueryParameter... params) throws DataException, SQLException {
  Connection conn = ConnectionPool.getInstance().get(connection);
  PreparedStatement pstmt = conn.prepareStatement(query);
  for (int i = 1; i <= params.length; i++) {
    //... stuff to fill in the '?'s of the query (in this case, there are none).
    }
  }

  ResultSet rs = pstmt.executeQuery();
  ConnectionPool.getInstance().release(conn);
  return rs;
}

A: You have small bug in date format 'yyyymmddHH24mmss', should be 'yyyymmddHH24miss'  ("mi" instead of "mm")
mm means month, minutes are "mi".


text:
Q: iterate a directory and find only file whose names start with the certain string I have a directory path and in this path there are several folders. So i am  am trying to build a script which would find all the xml files and the file name must start with report. I have been so far able to iterate over all the directories but further i do not know how to proceed. Here is my code:
def search_xml_report(rootdir):
     for subdir, dirs, files in os.walk(rootdir):
        for file in files:
            print os.path.join(subdir,file) # print statement just for testing

A: You can use str.startswith:
def search_xml_report(rootdir):
    for subdir, dirs, files in os.walk(rootdir):
        for file in files:
            if file.startswith('report'):
                yield subdir, file

A: use str.startswith with os.path.splitext
os.path.splitext:  Split the extension from a pathname. Extension is everything from the last dot to the end, ignoring leading dots. Returns "(root, ext)"; ext may be empty.
 if file.startswith('report') and os.path.splitext(filepath+filename)[-1] == '.xml':
     return file


text:
Q: Retrive all rows from last month (Laravel + Eloquent) I'm trying to get all records that belongs to last month, so far I managed to get all from last month but to date today, I'm not sure how I can get only for last month
$revenueMonth = Callback::where('created_at', '>=', Carbon::today()->startOfMonth()->subMonth())->sum('payment');

A: UPDATED
eloquent version of the your answer
$fromDate = Carbon::now()->subMonth()->startOfMonth()->toDateString();
$tillDate = Carbon::now()->subMonth()->endOfMonth()->toDateString();

$revenueLastMonth = Callback::whereBetween('created_at',[$fromDate,$tillDate])->get();

A: None of the answers get's me to where I'm looking to go :(.
I have a solution but I think it's ugly and hoped it could be made more clean
$fromDate = Carbon::now()->subMonth()->startOfMonth()->toDateString();
$tillDate = Carbon::now()->subMonth()->endOfMonth()->toDateString();

$revenueLastMonth = Callback::whereBetween(DB::raw('date(created_at)'), [$fromDate, $tillDate])->get();

This will give my the result I'm looking for, here is my records:
2017-09-07 09:46:43
2017-09-07 09:46:43
2017-09-07 09:46:43
2017-09-02 09:46:43
2017-08-07 09:46:43

And I want it to return ONLY what records is made in August 2017 (2017-08-07 09:46:43)

A: More clear solution for your problem:
$revenueMonth = Callback::whereMonth(
    'created_at', '=', Carbon::now()->subMonth()->month
);

A: Try this solutions:
$revenueMonth = Callback::where(
    'created_at', '>=', Carbon::now()->subDays(30)->toDateTimeString()
);

You get all Callback for last 30 days.
$revenueMonth = Callback::where(
    'created_at', '>=', Carbon::now()->firstOfMonth()->toDateTimeString()
);

Get  for current month.
$revenueMonth = Callback::where(
    'created_at', '>=', Carbon::now()->startOfMonth()->subMonth()->toDateString()
);

Get for start last month.
UPDATED
$revenueMonth = Callback::where(
    'created_at', '>=', Carbon::now()->subMonth()->toDateTimeString()
);

This is what are you looking for :)
Hope it will help you:)


text:
Q: Two seperate Flask apps communicating in docker containers EDIT:
I managed to get it working using network_mode: "host" for both containers as suggested below. This is fine for now. However, I feel like it's a bad hack and I would like to learn more about what I'm doing wrong with my containers instead of hacking it.

I'm having a problem getting my two Flask apps to communicate in two separate Docker containers. I have ran app.py from m1 outside of a docker container and it works, but clearly something different needs to be done to communicate outside of a docker container.
I get this traceback:
Traceback (most recent call last):
m1_1  |   File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 2309, in __call__
m1_1  |     return self.wsgi_app(environ, start_response)
m1_1  |   File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 2295, in wsgi_app
m1_1  |     response = self.handle_exception(e)
m1_1  |   File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1741, in handle_exception
m1_1  |     reraise(exc_type, exc_value, tb)
m1_1  |   File "/usr/local/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise
m1_1  |     raise value
m1_1  |   File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 2292, in wsgi_app
m1_1  |     response = self.full_dispatch_request()
m1_1  |   File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1815, in full_dispatch_request
m1_1  |     rv = self.handle_user_exception(e)
m1_1  |   File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1718, in handle_user_exception
m1_1  |     reraise(exc_type, exc_value, tb)
m1_1  |   File "/usr/local/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise
m1_1  |     raise value
m1_1  |   File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1813, in full_dispatch_request
m1_1  |     rv = self.dispatch_request()
m1_1  |   File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1799, in dispatch_request
m1_1  |     return self.view_functions[rule.endpoint](**req.view_args)
m1_1  |   File "/app/app.py", line 11, in home
m1_1  |     res = requests.get(url)
m1_1  |   File "/usr/local/lib/python3.6/site-packages/requests/api.py", line 75, in get
m1_1  |     return request('get', url, params=params, **kwargs)
m1_1  |   File "/usr/local/lib/python3.6/site-packages/requests/api.py", line 60, in request
m1_1  |     return session.request(method=method, url=url, **kwargs)
m1_1  |   File "/usr/local/lib/python3.6/site-packages/requests/sessions.py", line 533, in request
m1_1  |     resp = self.send(prep, **send_kwargs)
m1_1  |   File "/usr/local/lib/python3.6/site-packages/requests/sessions.py", line 646, in send
m1_1  |     r = adapter.send(request, **kwargs)
m1_1  |   File "/usr/local/lib/python3.6/site-packages/requests/adapters.py", line 516, in send
m1_1  |     raise ConnectionError(e, request=request)
m1_1  | requests.exceptions.ConnectionError: HTTPConnectionPool(host='127.0.0.1', port=8002): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7ff58dd1bd30>: Failed to establish a new connection: [Errno 111] Connection refused',))

app.py from m1
from flask import Flask, jsonify
import requests
import json

app = Flask(__name__)

@app.route("/")
def home():
    url = "http://127.0.0.1:8002/"
    res = requests.get(url)
    dictFromServer = res.json()
    return dictFromServer['message']

if __name__=='__main__':
    app.run(debug=True, host='0.0.0.0')

app.py from m2
from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/')
def hello_world():
    return jsonify({ 'message': 'Hello From M2'})

if __name__=='__main__':
    app.run(debug=True, host='0.0.0.0')

dockerfile(s)
FROM python:3.6-alpine
WORKDIR /app
COPY requirements.txt /app
COPY app.py /app
RUN pip install -r requirements.txt
EXPOSE 5000
ENTRYPOINT ["python"]
CMD ["app.py"]

docker-compose
version: '3'

services:
      m1:
        build: m1
        ports:
          - "8001:5000"
      m2:
        build: m2
        ports:
          - "8002:5000"

A: Docker containers don't run with the same IP address, so 127.0.0.1 within m1 only resolves to the m1 container.
Two fixes:

*

*"network: host" for both containers will use the host network stack, so both m1 and m2 will have the same IP address. "127.0.0.1" will work then.

*Replace "127.0.0.1" with "m2". This will use the built-in DNS server and resolve the correct IP address for the m2 container. This approach has the added benefit that both containers can use the same port, because they have different addresses.


text:
Q: Role of Coax Cable in bringing TV signal to our TV sets We know that we receive the programs/shows of TV Channels from the producers of programs through

*

*CATV Service providers (almost obsolete, just wanted to  get clarified on its working process)

*DTH Service.

Consider that a TV Channel produces programs and wants its programs to be telecasted to a wide audience. It will request a CATV Service provider to telecast its programs. After an agreement, the producer/channel will send his programs to the service provider. The service provider will then allocate a unique number to that channel. Transmission of the programs produced by the channel will be enabled through a Coaxial Cable.
Now, a single RG-6 coax cable can carry multiple channel programs with the concept of Frequency Division Multiplexing whereby, each channel will be allocated a bandwidth of 6-7 MHz. Typically 166-200 channels will be transmitted through the same single RG-6 cable.
My queries are

*

*Will the Service provider transmit an AC of radio frequency for all the channel programs into the cable, which gets converted to EM waves and reaches the 3-way splitter?

*Is it just an assumption that the two currents in the coax conductors need to be equal and opposite in order to not radiate outward?

*Provided that each channel can occupy only 6-7 MHz band, is it obvious that each program produced by the channel will be transmitted at frequencies within this band? And, if 0-6 MHz is allocated for channel A, 7-12 MHz will be allocated for channel B? To avoid overlapping of frequencies?

A:
"Will the Service provider transmit an AC of radio frequency for all the channel programs into the cable"

Yes, the classic CTV distribution provides all channels simultaneously.

"which gets converted to EM waves"

No.

"and reaches the 3-way splitter?"

Which splitter?

"Is it just an assumption that the two currents in the coax conductors need to be equal and opposite in order to not radiate outward?"

Yes, that is a weird assumption. There could very well be a DC imbalance between the two currents. The point is that the outer conductor is at ground potential, and encloses the inner conductor.

"Provided that each channel can occupy only 6-7 MHz band"

which is roughly correct

"is it obvious that each program produced by the channel will be transmitted at frequencies within this band?"

yes

"And, if 0-6 MHz is allocated for channel A, 7-12 MHz will be allocated for channel B? To avoid overlapping of frequencies?"

The frequency bands will be non-overlapping, but to match the TV receiver HF part, the frequencies will be choosen to fall into the old over-the-air transmission bands. And there will be some considerable margin between the bands.

A: One way of distributing TV over Coax is DVB-C, see: en.wikipedia.org/wiki/DVB-C
This describes the signals that are used. A DVB-T signal can be distributed through a coax cable but it does not have to. In my country only the last meters to the houses are coax, optical fibres are used for long distance distribution.

*

*There is no explicit "conversion to EM waves", all the bitstreams containing TV programmes are converted (modulated onto a carrier frequency) and combined into one signal which needs to be distributed. It can be directly fed into a Coax cable or modulated on a light beam and distributed using an optical fibre.

Before it reaches all the TVs the signal will be amplified and splitted many times.

*Coax is shielded, it does not radiate. Study how transmission lines work, Coax is just a T-line in shape of a cable

*Roughly yes but actually more complex, study DVB-C and OFDM etc.

A:
Will the Service provider transmit an AC of radio frequency for all the channel programs into the cable, which gets converted to EM waves and reaches the 3-way splitter?

Yes, but there's no "conversion" per se, only manipulation. Any change in voltage or current in any circuit necessarily begins an electromagnetic wave. If you trace the received signal back to the source, it's probably electromagnetic waves all the way back to a hard drive which generated waves from rapidly spinning, magnetized cobalt, and an electric power plant burning hydrocarbons to turn electromagnetic generators.

Is it just an assumption that the two currents in the coax conductors need to be equal and opposite in order to not radiate outward?

That's mostly true. The current and voltage on each of the shield and center conductor are associated with a magnetic and electric field around them. When the conductors are arranged concentrically, and the fields are equal and opposite, the fields cancel outside the cable. If there are no electromagnetic fields outside the cable, it can't be radiating.
If the fields are not equal but opposite, the fields don't cancel. A field outside the cable means it can radiate.
Note there still may be a DC bias to the cable. DC does not radiate, so it does not cause an issue.

Provided that each channel can occupy only 6-7 MHz band, is it obvious that each program produced by the channel will be transmitted at frequencies within this band? And, if 0-6 MHz is allocated for channel A, 7-12 MHz will be allocated for channel B? To avoid overlapping of frequencies?

The frequencies are allocated in non-overlapping bands, but there's a "guard band" between them. There are also backwards compatibility concerns that dictate where each channel is placed.


text:
Q: Spark SQL .distinct() performance I want to source few hundreds of gigabytes from a database via JDBC and then process it using Spark SQL. Currently I am doing some partitioning at that data and process is by batches of milion records. The thing is that I would like also to apply some deduplication to my dataframes and I was going to leave that idea of separated batches processing and try to process those hundreds of gigabytes using a one dataframe partitioned accordingly.
The main concern is: how will .distinct() work in such case? Will Spark SQL firstly try to load ALL the data into the RAM and then apply deduplication involving many shuffles and repartitioning? Do I have to ensure that a cluster has enough of RAM to contain that raw data or maybe it will be able to help itself with HDD storage (thus killing the performance)?
Or maybe I should do it without Spark - move the data to the target storage and there apply distinct counts and detect duplicates and get rid off them?

A: Spark SQL does NOT use predicate pushdown for distinct queries; meaning that the processing to filter out duplicate records happens at the executors, rather than at the database. So, your assumption regarding shuffles happening over at the executors to process distinct is correct.
Inspite of this, I would still advise you to go ahead and perform the de-duplication on Spark, rather than build a separate arrangement for it. My personal experience with distinct has been more than satisfactory. It has always been the joins which push my buttons.


text:
Q: iteration of for loop in shell script I have a simple script that uses a for loop where I want to take the value of a variable and assign it to another command and kill the screen.
 The script goes as
#!/usr/bin/sh/
echo 'I am going to kill the screens now';
for j in $(seq 1 1 10)
do
    i=$(grep -oP '.*?(?=\.)');
    echo $i
    screen -S $i -p 0 -X quit
done <file1.txt
echo 'exiting...'

file1.txt
There are screens on:

    4974.eth2   (Detached)
    5105.eth11  (Detached)
    4990.eth3   (Detached)
    5006.eth5   (Detached)
    5054.eth8   (Detached)
    5070.eth9   (Detached)
    5038.eth7   (Detached)
    5022.eth6   (Detached)
8 Sockets in /var/run/screen/S-root.

So here, I am iterating through 10 lines and assigning the value of i=whatever before a period(.). eg. 4974. Then placing 4974 in screen command and killing it. The problem here is, it is reading and grepping all the lines at a time and in the value of i it places as  4974 5105 4990 5006 5054 5070 5038 5022 in the screen command and it obviously it cannot find a screen id like that and doesn't kill any screen.
How do i iterate the loop such that at a time it takes one id ie.value of i=4974 and place only that in the screen command so that it will kill it..
Let me know if you understand my question correctly.

A: Try this:
awk -F'[. ]+' '/Detached/ {print $2}' file.txt | while read i
do
    echo "$i"
    screen -S "$i" -p 0 -X quit
done

A: Instead of iterating over a counter, iterate over your results directly:
set -f # disable globbing, so globs in grep's output aren't expanded
echo 'I am going to kill the screens now' >&2
for i in $(grep -oP '.*?(?=\.)'); do
    echo "$i"
    screen -S "$i" -p 0 -X quit
done <file1.txt
echo 'exiting...' >&2


text:
Q: How do I use popover from Twitter Bootstrap to display an image? The canonical example for Twitter Bootstrap's popover feature is sort of a tooltip on steroids with a title.
HTML:
hover for popover

JS:

I'd like to use popover to display an image.  Is this possible?

A: Very simple :)
hover for popover

var img = '';

$("#blob").popover({ title: 'Look! A bird!', content: img, html:true });

http://jsfiddle.net/weuWk/

A: simple with generated links  :)
html:
preview

js:
$('.preview').popover({
    'trigger':'hover',
    'html':true,
    'content':function(){
        return "";
    }
});

http://jsfiddle.net/A4zHC/

A: This is what I used.
$('#foo').popover({
    placement : 'bottom',
    title : 'Title',
    content : '

'
});

and for the HTML
text goes here

A: Sort of similar to what mattbtay said, but a few changes. needed html:true. Put this script on bottom of the page towards close body tag.

Then HTML is:
mischief

A: Here I have an example of Bootstrap 3 popover showing an image with the tittle above it when the mouse hovers over some text. I've put in some inline styling that you may want to take out or change.....
This also works pretty well on mobile devices because the image will popup on the first tap and the link will open on the second.
html:

Template Preview 1

Template Preview 2

Template Preview 3

js:
$('.preview').popover({
    'trigger':'hover',
    'html':true,
    'content':function(){
        return "";
    }
});

https://jsfiddle.net/pepsimax_uk/myk38781/3/


text:
Q: Problema com formatação de formulário Bom dia pessoal, estou com um certo problema no formulário de newsletter de meu site.
Já fiz várias pesquisas tentando solucionar o problema, porém a falta de conhecimento da área acho que está me impossibilitando. rsrs
O formulário basicamente leva Nome, Email e o botão de envio.
Por padrão vem um embaixo do outro e gostaria de converte-lo para um do lado do outro.
Consegui chegar a esse ponto usando float, porém os campos estão "colados" um no outro e eu precisaria colocar uma margem.
O código está da seguinte forma:

    Nome
    <input type="text" name="FNAME" placeholder="Digite seu nome."
    required="">

   E-mail
    <input type="email" name="EMAIL" placeholder="Digite seu e-mail"
    required="">

    <input type="submit" value="Inscrever">

O endereço do site é: http://159.203.130.115/wesley/wordpress/
Poderiam me ajudar a dar uma "arrumada"?

A: Você pode adicionar uma margin-right (margem direita) para os inputs (campos) do formulário, conforme exemplo abaixo:

#inscricao input {
    margin-right: 15px;
}

      Nome
      <input type="text" name="FNAME" placeholder="Digite seu nome."
      required="">

     E-mail
      <input type="email" name="EMAIL" placeholder="Digite seu e-mail"
      required="">

      <input type="submit" value="Inscrever">

Coloquei todos dentro de uma div para não aplicar a margin aos demais inputs da página, mas somente aos inputs que estão dentro da div 'inscricao'.

A: Adicione no css este código:
.campos {
    margin: 5px;
}

que resolverá seu problema, tente inserir na div  onde tem o botão de submit uma

isso resolverá o problema de alinhamento do botão.


text:
Q: VSTO Outlook Addin Dialog Boxes I've been trying to figure out the correct way to pop up a dialog box in a way similar to MessageBox.Show in my VSTO addin.  I read this could be achieved using WPF, but is there a better way?  I've found many different examples most of which are in VBA, but I'm using C# so I'm having trouble translating them over.  If someone could provide me with an example of popping up a dialog box in the addin in order to collect some information from the user, and point me towards the correct docs to tweak the settings of the dialog box it would help a lot.  I can't seem to get it to work in C# using the VBA examples and as for the docs I can't find ones pertaining to dialog boxes in VSTO, just outside of it in WPF which I am not sure is possible to use in this situation.
Any assistance would be most appreicated.  I just want to display a dialog box, and collect some info and that's it.  I know of dialog launcher for VSTO ribbon groups, but that is not what I need.
Thanks in advance.

A: You can use a regular System.Windows.Forms.Form instance to display a dialog window for collecting the required information. Use ShowDialog method which shows the form as a modal dialog box with the specified owner. Don't forget to psecify the parent window handle to prevent any changes in Outlook. The IWin32Window interface provides an interface to expose Win32 HWND handles to the ShowDialog method.
If you need to diaplay a WPF contant you may use the ElementHost class. This is a Windows Forms control that can be used to host a Windows Presentation Foundation (WPF) element.


text:
Q: Google charts change haxis font size Does anyone know a way to change the font size of these dates? I want to make them a little smaller so they will all fit instead of skipping one each time..

A: I fixed this issue using below code:
titleTextStyle -- An object that specifies the title text style. The object has this format:
    var options = {
    title: 'Chart Name ',
    width: '100%',
    height: '100%',
    legend: {
        position: "none"
    },
    hAxis: {
        title: 'Request Status',
        titleTextStyle: {
            color: "#000",
            fontName: "sans-serif",
            fontSize: 11,
            bold: true,
            italic: false
        }
    },
    vAxis: {
        title: 'Amount requested ($)',
        titleTextStyle: {
            color: "#000",
            fontName: "sans-serif",
            fontSize: 11,
            bold: true,
            italic: false
        }
    },
    annotations: {
        alwaysOutside: true,
        textStyle: {
            fontSize: 14,
            auraColor: 'none'
        }
    }
};

More details from Google Chart
Happy coding...

A: Try with:
options:{
    hAxis : {
        textStyle : {
            fontSize: 7 // or the number you want
        }

    }

}