text:
Q: Change Date to Future Date in Map Title Using Python or Dynamic Text I'm trying to create a dynamic map title in ArcMap that updates based on current day + 2 days. For example, if I run the code on the 20th of a given month, the title should update to show the 22nd.
I've arrived at two independent, but partial solutions: the first works in pure Python not integrated with ArcMap and the second works using Dynamic Text (but only for the current date). I'm not partial to one method over another, but am not familiar enough with either to arrive at a satisfactory solution. Is anyone aware of a way to use either of these methods to solve the issue?
Partial Solution #1 - Python code
from datetime import date, timedelta
import calendar
publication_date = date.today() + timedelta(days=2)
publication_day_of_week = calendar.day_name[publication_date.weekday()]

#Title format example:
#"Forecast for Thursday March 17"
print "Forecast for " + publication_day_of_week + " " + publication_date.strftime("%B %d")

Running this script as of today (March 17, 2016) correctly yields the text "Forecast for Saturday March 19"
Partial Solution #2 - ArcMap Dynamic Text tags
<dyn type="document" property="title"/> <dyn type="date" format="dddd MMMM d"/">

The title property above represents the text "Forecast for" which is followed by the formatted date.
However, the output is "Forecast for Thursday March 17"-- the current date. As far as I can tell, dynamic text can only use the current date, time, etc., and cannot be used to forecast 2 days out from the current date.
I've already reviewed the following but can't seem to see a complete solution:
1) http://pro.arcgis.com/en/pro-app/help/layouts/date-and-time-dynamic-text.htm
2) https://geonet.esri.com/thread/21281
3) Dynamic title in ArcMap

A: Displaying previous and current year with dynamic text? is a duplicate which was asked a couple of years ago and its finding was that text formatting does not support calculations.
To meet a requirement like yours I would use Python to calculate the future date, and then use Pseudo-dynamic Text instead of true Dynamic Text.
In other words, use a standard text element with a string in it that you replace using the contents of your Python variable.


text:
Q: If/Else in powershell to determine StrongAuthenticationStatus - powershell So I am trying to come up with a reliable method to determine if a user has o365 multi factor authentication configured on their account prior to a script running so They do not get re-enabled.
using:
$MFAUsers = Get-Msoluser -userprincipalname test.webjea@xxx.com  | select "StrongAuthenticationRequirements"

outputs if they are enabled
StrongAuthenticationRequirements
--------------------------------
{Microsoft.Online.Administration.StrongAuthenticationRequirement}

and the following if they are disabled
StrongAuthenticationRequirements
--------------------------------
{}

Ideally if the user is disabled then the script will run against their account enabling it.  If they are enabled then the script will skip them.
For testing I have this drawn up
if ($MFAUsers -eq "{Microsoft.Online.Administration.StrongAuthenticationRequirement}") {
"NO MFA"
}
Elseif ($MFAUsers -eq "{Microsoft.Online.Administration.StrongAuthenticationRequirement}"){
"MFA"
}

When running this against the test account that has been enabled I still get the "no MFA" response
Anyone have any idea?  I'm sure it is something stupid but I really cant put my finger on it?  Is it seeing the "StrongAuthenticationRequirments" header?

A: The test you are doing is the same for the if as for the elseif.
When {Microsoft.Online.Administration.StrongAuthenticationRequirement} is returned, it means that MFA is enabled for that user. When the function returns {} the user has no StrongAuthenticationRequirement set.
I cannot test this myself, but running the below code should show you which users have "MFA" enabled and which users do not.
# test for all users would be Get-MsolUser -All
Get-MsolUser -UserPrincipalName 'test.webjea@xxx.com' |
    Select-Object DisplayName, UserPrincipalName,
                  @{ Name = "MFA"
                     Expression = {
                        if($_.StrongAuthenticationRequirements.Count -ne 0) {
                            $_.StrongAuthenticationRequirements[0].State
                        }
                        else { 'Disabled' }
                     } }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Simple way to populate a collection with ViewModel objects with domain object properties to pass to index I'm new to MVC.NET (and development generally really) and I'm really starting to see the light of the benefit of ViewModels.
So, I'm currently refactoring one of my index methods to send a collection of ViewModel objects to the view. However, I'm not quite sure of the best way to achieve this.
Basically, my domain model is a UseCase and my ViewModel is UserGoalsStepViewModel. I know that in my UserGoalIndex action I'll need a collection to contain my ViewModel objects, each of these having had it's properties set by each UseCase that exists, but I'm not sure how to achieve it.
Help much appreciated.
Note: I know I could be using AutoMapper and probably a lot of other techniques to make life easier, but as I'm new to this (and time pressured!) I'm just looking for the simplest approach possible.
UseCase Model
public enum Level
{
    Summary, UserGoal, SubGoal,
}
public class UseCase
{
    public virtual int ID { get; set; }
    //[Required]
    public virtual int ProjectID { get; set; }
    public virtual Project project { get; set; }
    [Required]
    public virtual int ActorID { get; set; }
    [DisplayName("Actor")]
    public virtual Actor actor { get; set; }
    public virtual string Title { get; set; }
    public virtual Level? Level { get; set; }
    public virtual string Precondition { get; set; }
    [DisplayName("Minimal Guarantee")]
    public virtual string MinimalGuarantee { get; set; }
    [DisplayName("Success Guarantee")]
    public virtual string SuccessGuarantee { get; set; }
    public virtual ICollection<Step> Steps { get; set; }
    public virtual ICollection<Extension> Extensions { get; set; }
    public virtual ICollection<Query> Queries { get; set; }

}

UserGoalViewModel (subset of UseCase properties)
public class UserGoalsStepViewModel
    {
        public enum GoalLevel
        {
            Summary, UserGoal, SubGoal,
        }

            public int ProjectId { get; set; }
            //ActorId removed as SelectedActorId is what binds to model
            //public int ActorId { get; set; }
            [DisplayName("Actor Title")]
            public SelectList ActorList { get; set; }
            [DisplayName("Actor Title")]
            public string ActorTitle { get; set; }
            public int SelectedActorId { get; set; }
            [DisplayName("Goal Title")]
            public string GoalTitle { get; set; }
            public GoalLevel Level { get; set; }

            public UserGoalsStepViewModel ()
            {

            }

    }


text:
Q: how to input value into field by using buttons? (html, js calculator) We've just started to learn Vanilla JS, we had exercise which is creating a calculator by using html, css and js.
I already created the calculator layout (I'll leave the CSS to the end), however I'm getting troubled of input the number that I want into field by using the buttons.
Basically this is my layout so far, but I have some questions about the calculator that I want.
Before I'll show you the layout, here is how I want the calculator looks like by looking at the fields:

So as you can see, in field 1 I want to input the first value,
now that we entered the first value, I want to show the math action that I want to do between the 2 values, in field 3 I want to input the second value,
after I inputted the value, I'll press on the equal button, the the last field will show me the result..
As I said before, I already created the layout for both fields and buttons, here is the layout:

    <input type="text" class="calculator-screen" value="1" disabled />
    <input type="text" class="calculator-screen" value="math action" disabled />
    <input type="text" class="calculator-screen" value="2" disabled />

    <button type="button" class="equal-sign" value="=" onclick="solve()">=</button>
    <input type="text" class="result" value="result" disabled />

      <button type="button" class="operator" value="+" onclick="dis('+')">+</button>
      <button type="button" class="operator" value="-" onclick="dis('-')">-</button>
      <button type="button" class="operator" value="*" onclick="dis('*')">*</button>
      <button type="button" class="operator" value="/" onclick="dis('/')">/</button>

      <button type="button" value="7" onclick="dis('7')">7</button>
      <button type="button" value="8" onclick="dis('8')">8</button>
      <button type="button" value="9" onclick="dis('8')">9</button>

      <button type="button" value="4" onclick="dis('4')">4</button>
      <button type="button" value="5" onclick="dis('5')">5</button>
      <button type="button" value="6" onclick="dis('6')">6</button>

      <button type="button" value="1" onclick="dis('1')">1</button>
      <button type="button" value="2" onclick="dis('2')">2</button>
      <button type="button" value="3" onclick="dis('3')">3</button>

      <button type="button" value="0" onclick="dis('0')">0</button>
      <button type="button" class="decimal" value="." onclick="dis('.')">.</button>
      <button type="button" class="all-clear" value="all-clear" onclick="clr()">AC</button>

and my js code so far:
function dis(val)
     {
         document.getElementById("result").value+=val
     }

     //function that clear the display
 function clr()
     {
         document.getElementById("result").value = ""
     }

So after I did the layout and the buttons how do I make it that I'll be able to input the values by using the buttons?
in addition to that, how to I show the math action (- * / +) between the values field?

A: The way I have solved this in the past is:

*

*Set a variable to keep track of which operand number we are working with, the
first or second operand. Let's call this variable thisOperand. Set
this variable to the first operand to begin with.

*When a number is input at any time, check the value of thisOperand. If first append the number (which you got from the value attribute) to the first operand field, if second to the second operand field.

*When the operator is chosen, if there is a first operand already
entered (i.e. the display element is not empty), set thisOperand
variable to value of second, so that the next numbers input are
placed after the operator. Otherwise if there is no first operand
entered don't do anything. If the second operand is already active,
this means we've already entered an operator earlier - otherwise the
second operand would not be active - so just update the operator with
the new value.

*When the '=' button is pressed, show the result and set thisOperand
to first again. If the result is shown and a new number is pressed,
run the clear function and place the number in the first operand
field (as a physical calculator would).
All this is easier if you set id attributes to refer to the display fields (the ones which have value attributes of '1', 'math action' and '2' in your example above).


text:
Q: How to call android function using javascript / jquery in android webview? I have tried pass the parameter from javascript to android but it return
01-08 20:32:17.214: D/WebConsole(27791): Uncaught Error: Error calling method on NPObject. -- From line 433 of file:///data/data/com.test/files/HK/news_list.html

My code is like the following
Js:
function changeSection(){
    //var pos = parseInt($(this).attr("data-index"),10);
    var pos = 2;
    if (pos == 3){
        window.location.href="video_list.html";
    } else {
        window.location.href="news_list.html?target="+$(this).attr("target")+"&type="+$(this).attr("type");
    }
    window.jsinterface.highLightLeftMenu(2);
}

The code that build up the button link:
    if(target+'_'+pageType == LMenu[k]['sid']){
        sectionMenu += "
"+LMenu[k]['name']+"
";
    }else{
        sectionMenu += "
"+LMenu[k]['name']+"
";
    }

Android:
 mWebView.addJavascriptInterface(this, "jsinterface");

public void highLightLeftMenu(int pos) {
        Log.d("test1","aa");
        Log.d("test1","bb" + pos);
        MainActivity.highLightLeftMenu(pos);
    }

It can log out the aa and bb with pos in android , but return the error message in the webview, also, how to pass the integer in js/jquery to android without hard coding ? thanks


text:
Q: What's the difference between code construction and architecture? When I read the book Code Complete, the word "construction" is referenced frequently.  What does that mean?

A: I would say that architecture is the design whereas construction is the implementation.

A: An analogy with a book could be:

*

*Architecture is the plot

*Construction is the text

A: The software architecture of a program or computing system is the structure or structures of the system, which comprise software components, the externally visible properties of those components, and the relationships between them.
Construction is the implementation of the design

A: Just like with houses, the construction (of the house) realizes the architecture (the plan).

A: Using a house as an analagy architecture is creating the drawings explaining what rooms the house will have, how they will be laid out, etc. Construction is the guys that show up with hammars and wood, take a look at the architecture and start building the house.


text:
Q: Interpreting the output of SciPy's hierarchical clustering dendrogram? (maybe found a bug...) I am trying to figure out how the output of scipy.cluster.hierarchy.dendrogram works... I thought I knew how it worked and I was able to use the output to reconstruct the dendrogram but it seems as if I am not understanding it anymore or there is a bug in Python 3's version of this module.
This answer, how do I get the subtrees of dendrogram made by scipy.cluster.hierarchy, implies that the dendrogram output dictionary gives dict_keys(['icoord', 'ivl', 'color_list', 'leaves', 'dcoord']) w/ all of the same size so you can zip them and plt.plot them to reconstruct the dendrogram.
Seems simple enough and I did get it work back when I used Python 2.7.11 but once I upgraded to Python 3.5.1 my old scripts weren't giving me the same results.
I started reworking my clusters for a very simple repeatable example and think I may have found a bug in Python 3.5.1's version of SciPy version 0.17.1-np110py35_1.  Going to use the Scikit-learn datasets b/c most people have that module from the conda distribution.
Why aren't these lining up and how come I am unable to reconstruct the dendrogram in this way?
# Init
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()

# Load data
from sklearn.datasets import load_diabetes

# Clustering
from scipy.cluster.hierarchy import dendrogram, fcluster, leaves_list
from scipy.spatial import distance
from fastcluster import linkage # You can use SciPy one too

%matplotlib inline

# Dataset
A_data = load_diabetes().data
DF_diabetes = pd.DataFrame(A_data, columns = ["attr_%d" % j for j in range(A_data.shape[1])])

# Absolute value of correlation matrix, then subtract from 1 for disimilarity
DF_dism = 1 - np.abs(DF_diabetes.corr())

# Compute average linkage
A_dist = distance.squareform(DF_dism.as_matrix())
Z = linkage(A_dist,method="average")

# I modded the SO code from the above answer for the plot function
def plot_tree( D_dendro, ax ):
    # Set up plotting data
    leaves = D_dendro["ivl"]
    icoord = np.array( D_dendro['icoord'] )
    dcoord = np.array( D_dendro['dcoord'] )
    color_list = D_dendro["color_list"]

    # Plot colors
    for leaf, xs, ys, color in zip(leaves, icoord, dcoord, color_list):
        print(leaf, xs, ys, color, sep="\t")
        plt.plot(xs, ys,  color)

    # Set min/max of plots
    xmin, xmax = icoord.min(), icoord.max()
    ymin, ymax = dcoord.min(), dcoord.max()

    plt.xlim( xmin-10, xmax + 0.1*abs(xmax) )
    plt.ylim( ymin, ymax + 0.1*abs(ymax) )

    # Set up ticks
    ax.set_xticks( np.arange(5, len(leaves) * 10 + 5, 10))
    ax.set_xticklabels(leaves, fontsize=10, rotation=45)

    plt.show()

fig, ax = plt.subplots()
D1 = dendrogram(Z=Z, labels=DF_dism.index, color_threshold=None, no_plot=True)
plot_tree(D_dendro=D1, ax=ax)

attr_1  [ 15.  15.  25.  25.]   [ 0.          0.10333704  0.10333704  0.        ]   g
attr_4  [ 55.  55.  65.  65.]   [ 0.          0.26150727  0.26150727  0.        ]   r
attr_5  [ 45.  45.  60.  60.]   [ 0.          0.4917828   0.4917828   0.26150727]   r
attr_2  [ 35.   35.   52.5  52.5]   [ 0.          0.59107459  0.59107459  0.4917828 ]   b
attr_8  [ 20.    20.    43.75  43.75]   [ 0.10333704  0.65064998  0.65064998  0.59107459]   b
attr_6  [ 85.  85.  95.  95.]   [ 0.          0.60957062  0.60957062  0.        ]   b
attr_7  [ 75.  75.  90.  90.]   [ 0.          0.68142114  0.68142114  0.60957062]   b
attr_0  [ 31.875  31.875  82.5    82.5  ]   [ 0.65064998  0.72066112  0.72066112  0.68142114]   b
attr_3  [  5.       5.      57.1875  57.1875]   [ 0.          0.80554653  0.80554653  0.72066112]   b

Here's one w/o the labels and just the icoord values for the x-axis

So check out the colors aren't mapping correctly. It says [ 15.  15.  25.  25.] for the icoord goes with attr_1 but based on the values it looks like it goes with attr_4. Also, it doesn't go to all the way to the last leaf (attr_9) and that's b/c the length of icoord and dcoord is 1 less than the amount of ivl labels.
print([len(x) for x in [leaves, icoord, dcoord, color_list]])
#[10, 9, 9, 9]

A: icoord, dcoord and color_list describe the links, not the leaves.  icoord and dcoord give the coordinates of the "arches" (i.e. upside-down U or J shapes) for each link in a plot, and color_list is the color of those arches.  In a full plot, the length of icoord, etc., will be one less than the length of ivl, as you have observed.
Don't try to line up the ivl list with the icoord, dcoord and color_list lists. They are associated with different things.


text:
Q: Funky results when using UI Automation to get items in a ComboBox We are using the code below to get a list of items out of a ComboBox inside another application's window. This code works (correctly retrieves the list of items) for ComboBoxes in any other application we've tested this code on, however for this particular application the Name property retrieved for each ListItem is garbled.
Here is the code:
using System.Windows.Automation;

var condition = new PropertyCondition(AutomationElement.NameProperty, "Change/Add/Delete Setting");
var condition2 = new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Window);
var condition3 = new AndCondition(new Condition[] {condition, condition2});
var window = AutomationElement.RootElement.FindFirst(TreeScope.Subtree, condition3);

condition = new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.ComboBox);
var combo = window.FindFirst(TreeScope.Subtree, condition);

condition = new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.ListItem);
AutomationElementCollection children = combo.FindAll(TreeScope.Subtree, condition);

var comboItems = new List<string>();
foreach (AutomationElement child in children)
{
    comboItems.Add(child.Current.Name);
}

And here is a screenshot of what we end up with for this one app.

*

*What could cause the Name property to be garbled like this? Could this be an encoding problem?

*How can we get the correct text for each item?

A: If this combobox has the CBS_OWNERDRAWFIXED or CBS_OWNERDRAWVARIABLE style, or the contained listbox has the LBS_OWNERDRAWFIXED or LBS_OWNERDRAWVARIABLE style. then the text isn't known by the control at all.  When an app uses one of these styles, it gets WM_DRAWITEM messages whenever the control needs to draw, then it pulls the text from it's pocket and draws it wherever it was asked to.
This is a trick that allows an application to quickly and easily change the contents of a listbox or combobox on the fly, it's mostly used when the contents are volatile or when there are LOTS of items.  It's one way to get around the limit on the number of items an listbox/combobox can hold.
Use Spy++ to check the styles on these windows.


text:
Q: Posting Non displayed checkbox values to next program in Perl CGI I am a newbie in Perl CGI . My code is shown below .
#!c:/xampp/perl/bin/perl.exe
use warnings;
use CGI;
my $q = CGI->new;
print $q->header;
print "<title>Test</title>\n";
print '';
@server = $q->param('sel');
if (!@server)
{
    print '
 please select a checkbox
';
    exit;
}
else
{
    print '<form action="next.pl" method="POST" id="sel" >';
    foreach my $i (@server) {
        print '<input type="checkbox" name="DEL"   value="';
        print $i;
        print ' checked ">';
        print $i;
        print '
';
    }
    print '<input type="submit" value="Kill">';
    print '<form>';
    print '';
}

In the first part of the code i am getting the list of checkboxes ticked from the previous program using the checkbox name "sel" and storing it in an array server. I am using the same array in foreach loop and making it a checkbox with a name.
Now in my above code I don't want the checkboxes to be displayed . I want only submit button to be displayed. When i click the submit button i want my checked checkboxes in the form to go to next page.
How can i achive this . Please help .

A: One way to hide the checkboxes is to use a  tag:
use strict;
use warnings;
use CGI;
my $q = CGI->new;
print $q->header;
print $q->start_html(-title => 'Test');
my @server = $q->param('sel');
if (!@server) {
    print $q->p('please select a checkbox');
    print $q->end_html();
    exit;
} else {
    print $q->start_form(-method => "POST",
                         -action => "next.pl",
                         -id => "sel");
    print $q->span({hidden=>1},
          $q->checkbox_group(-name => "DEL",
                             -values => \@server,
                             -default => \@server,
                             ));
    print $q->submit(-name => "submit",
                     -value => "Kill");
    print $q->end_form();
    print $q->end_html();
}

I do prefer using the HTML building methods that CGI.pm provides. Helps to keep HTML out of the Perl.


text:
Q: Why when i pass source manually it works but when i tried to pass source with vuex it doesn't - Vue3 / Vuex / Composition API I have a problem with passing source to audio. I want to do it dynamically so i created state in vuex with path to file and when I pass source manually it work's but when pass source using store.state.currAlarm it shows an error: Cannot find module '../assets/Alarm1.mp3'. Yes I imported store and returned in setup() function.
<audio ref="audio" controls>
      <source :src="store.state.currAlarm" type="audio/mpeg">
    </audio>

Vuex
 state: {
        currAlarm: '../assets/Alarm1.mp3'
    },

Anyone can help to solve this problem?


text:
Q: Creating Connect4 in Android I'm trying to create an Android app to play Connect 4 (Four In A Row, etc). As I'm new to Android dev I created a basic Java application to cope with the logic, which plays connect4 using a 2D array and just uses println to print the array to the console which shows the board.
My question is in my game activity what would be the best way to create a 'board' and have it so I can update it to show the position of counters throughout the game; should I create a canvas object, butcher a table layout, or do something else entirely.
Apologies if this is a silly question; I have very limited Android experience.
Many thanks.

A: As the board is always the same (4x4) you could use a GridLayout with 4 cols and 4 rows. Put an ImageView in every cell and modify it following the players touches.

A: Agreed, as 4x4 grid could work if that is what you want since you have limited android experience. You can really make a board/grid in multiple ways. I would suggest making sure you know a little about the UI and the android activity lifecycle before you start diving into something. Eventually you will like to add additional UI elements such as score, player's turn etc.
UI:
http://developer.android.com/guide/topics/ui/index.html
Lifecycle:
http://developer.android.com/training/basics/activity-lifecycle/index.html
Here is a grid tutorial instead of opening another view, just update the one with a piece/color or whatever
GridView tutorial:
http://www.androidhive.info/2012/02/android-gridview-layout-tutorial/


text:
Q: Scrolling to the Previously Selected ListBox item I am having trouble setting the Selected Item of a Listbox I am populating and adding to the LayoutRoot's children in code.
I am creating the ListBox over when going back to the page, so I am saving a variable which will tell me what the selected item was before the user clicked.
I tried setting SelectedIndex, but that did not seem to work. That selects the item and calls SelectionChanged, but the item does not come into focus.
I also tried the combination of  MyListBox.ScrollIntoView(MyListBox.Items[MyListBox.SelectedIndex]) and MyListBox.UpdateLayout(), but that did not seem to work either. The item does not seem to come into focus.

A: Try MyListBox.SelectedItem.EnsureVisible().
(If it doesn't have SelectedItem (ListBox on the desktop CLR doesn't), then use SelectedItems[0] instead)
E: Okay, looks like Windows Phone doesn't support that. However, it does support MyListBox.EnsureVisible(MyListBox.SelectedItems[0])

A: I ended up fixing this by Adding the UserControl that had the ListBox into the Page's XAML, and the ListBox into the UserControl's XAML.
Then, I was able to use the ScrollIntoView(MyListBox.Items[mySavedSelectedItem]);
I simply saved this value when the user made the selection.
mySavedSelectedItem = ((ListBox)sender).SelectedIndex;


text:
Q: Python Avro, how to write data to a modified schema? I'm new to Avro and I'm trying to perform basic tasks like read data from data.avro and now I want to write data to data.avro.
My problem is : ...is not an example of the schema...
I don't understand where is my mistake and I'd appreciate your help :
from avro import schema, datafile, io
from avro.datafile import DataFileWriter, DataFileReader
from avro.io import DatumWriter, DatumReader

OUTFILE_NAME = '4_2.avro'
SCHEMA_STR = """{
    "namespace": "advdaba",
    "type": "record",
    "name": "Conference",
    "fields": [
        { "name": "name",       "type": "string" },
        { "name": "time",       "type": "long" },
        { "name": "location",   "type": "string" },
        { "name": "speakers",   "type": {"type":"array","items":"string"} },
        { "name": "participants", "type": {"type": "array", "items": "string"} },
        { "name": "seating", "type": {"type": "map", "values": "int"} }
    ]
}"""

SCHEMA = schema.parse(SCHEMA_STR)

# read data writtent with the old schema
reader = DataFileReader(open("example.avro", "rb"), DatumReader())
#data = []
for example in reader:
    print(example)
    #data.append(example)
reader.close()

# generate data for new schema
data = {
    'name': 'Foo',
    'time': 25612345,
    'location': 'Berne',
    'speakers': ['Jean', 'Elton'],
    'participants': ['John', 'Michel', 'Jacques'],
    'seating': [{'John': 1}, {'Michel': 2}, {'Jacques': 3}]
}

rec_writer = io.DatumWriter(SCHEMA)
df_writer = datafile.DataFileWriter(
    open(OUTFILE_NAME, 'wb'),
    rec_writer,
    writers_schema=SCHEMA,
    codec='deflate'
)

df_writer.append(data)
df_writer.close()

I think for what I understand, it's even possible to write the old and new data in the same .avro file
[EDIT]
after debugging the problem comes from seating

A: The problem was in seating
The solution is
'seating': {"John": 1, "Michel": 2, "Jacques": 3}


text:
Q: Cast an object X to an object Y who inherits of X I have a class X who herits of TcpClient, and a TcpListener. I'd like that when I call the AcceptTcpClient(), which return a TcpClient, I'll get a X class, or be able to "cast" this TcpClient to my class X.
I can't do something like (X)TcpClient so i'm a little lost.

A: That's not possible. You can only downcast if the object has the correct runtime type.
Instead you could create an adapter with a constructor that accepts a TcpClient, but then adds its own functionality.
class MyTcpClientAdapter
{
    private TcpClient tcpClient;

    public MyTcpClientAdapter(TcpClient tcpClient) {
        this.tcpClient = tcpClient;
    }

    // etc...
}


text:
Q: React Redux update api with createAsyncThunk I'm trying to update api with React Redux using createAsyncThunk, Status Code is 200, but data is not updated.
Api are developed with Laravel Passport and working fine using Postman.
    export const fetchUpdateLead = createAsyncThunk(
        'leads/fetchUpdateLead',
        async (event) => {
            const data = new FormData(event.target);
            return await fetch("https://api.test/api/edit/173599", {
                method: 'PATCH',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    nome_cliente: data.get('name'),
                    telefono_cliente: data.get('phone')
                }),
            }).then(
                (res) => res.json()
            );
    });

const leadsSlice = createSlice({
    name: "leads",
    initialState: {
        leads: [],
        status: null
    },
    reducers: {},
    extraReducers: {
        [fetchUpdateLead.fulfilled]: (state, action) => {
            state.status = "updated";
        },
    }
});

export default leadsSlice.reducer;

A: Well, the code you are writing is only updating state.status, not state.data or anything else. If you want that to happen, you have to write it - it will not happen by itself.
Generally, please be aware that the object notation of extraReducers here is not the recommended way of using it, you should be using the builder callback notation. You are probably following outdated documentation.
I would highly recommend you read the chapter on using createAsyncThunk of the official Redux tutorial: https://redux.js.org/tutorials/essentials/part-5-async-logic
Chapters 7 and 8 might also be of interest to you as they go into using RTK Query, which automates most of that.


text:
Q: Cannot use having clause because it is not contained in either an aggregate function or the group by clause I am trying to complete this question, but I am having some trouble. I am receiving

'Column 'DOG.DOB' is invalid in the HAVING clause because it is not contained in either an aggregate function or the GROUP BY clause.'

error. There is no Age column. Below is a picture of the question and the desired output. I will also put my code down below
select
    Name AS 'Dog Name',
    DATEDIFF(year, getdate(), DOB) AS 'Age'
from DOG
Having
    DATEDIFF(year, getdate(), DOB) > avg(DATEDIFF(year, getdate(), DOB))
ORDER BY AGE DESC


text:
Q: Enable Adblocker Extension In Chrome Using RSelenium I am scraping data in R from this page, http://finviz.com/screener.ashx?v=111&f=earningsdate_nextdays5 which displays popup ads. Those ads interfere with script so I'd like to enable the adblocker extension: https://chrome.google.com/webstore/detail/adblock/gighmmpiobklfepjocnamgkkbiglidom
I'm working with code in the RSelenium package documentation here, https://cran.r-project.org/web/packages/RSelenium/RSelenium.pdf
I found the profile directory by opening a chrome browser and navigating to: chrome://version/. This is my usual profile which has the adblocker extension enabled.
However, when I open chrome, no adblocker is there. I looked at this page, http://scottcsims.com/wordpress/?p=450 and he suggests using the add_extension method which doesn't appear to be implemented in RSelenium.
Any idea on how I can get the adblocker enabled in the browser that R opens?
My code so far. Please note, this was done on a mac and of course your username will be different than mine, so be sure to change the first argument in getChromeProfile to what you find in Profile Path on this page, chrome://version/
require(RSelenium)
RSelenium::startServer()
cprof <- getChromeProfile("/Users/<username>/Library/Application Support/Google/Chrome/", "Profile 1")
remDr <<- remoteDriver(browserName = "chrome", extraCapabilities = cprof)
remDr$open()
appURL <- "http://finviz.com/screener.ashx?v=111&f=earningsdate_nextdays5"
remDr$navigate(appURL)

A: It isn't ablock extension specifically since I like adguard better, but I always use this:
Download adguard FROM A BROWSER OTHER THAN CHROME: https://www.crx4chrome.com/go.php?d=4687&i=158&p=31932&s=1&l=https%3A%2F%2Fclients2.googleusercontent.com%2Fcrx%2Fblobs%2FQwAAAHF3InbmK-wFIemaY3I3BCPa0e33dMYlYToYq-WCs1jSyPlSXnr3dNv-HTinVL8eTmtbBlPjwi-hJEL5_ZnPfXkYphLdiwB7LVwS3slKcj15AMZSmuWuPGYPZfS0woRX9brTIZ8faUYQCg%2Fextension_3_0_13_0.crx
Example download filepath: /Users/admin/Downloads/extension_3_0_13_0.crx
R Code:
library(RSelenium) #install_github("ropensci/RSelenium")
cprof <- list(chromeOptions =
                list(extensions =
                       list(base64enc::base64encode("/Users/admin/Downloads/extension_3_0_13_0.crx"))
                ))

rD <- rsDriver(port = 4444L,extraCapabilities=cprof, browser ="chrome",chromever = "latest"))

#if error port used or need to clear port
#rm(rD)
#rm(remDr)
#gc() #then try again

#set timeout preferences with chrome client
remDr <- rD$client
remDr$setTimeout(type = 'page load', milliseconds = 120000)
remDr$setTimeout(type = 'implicit', milliseconds = 120000)


text:
Q: output colored text in multiple output of function in R I am new to writing functions in R. When a function shall create multpile outputs, I aggregate these outputs to a list and make the function return this list. This method also allows for the output of simple text. However, I seem not to be able to print colored text.
An example:
library (crayon)

my_function <- function (a = 3, b = 6) {
    first_result <- a * 3
    second_result <- b / a
    print (list (first_result,
                 second_result,
                 "my_text"))
}

my_function()

which puts out (and is ok for me):
[[1]]
[1] 9

[[2]]
[1] 2

[[3]]
[1] "my_text"

Now I want to see "my_text" in color (which works):
cat (green ("my_text"))

However, when put in a list, the behaviour is not my desired one - the text is put out first, the first argument in the list follows up:
x <- 5
list (x, cat (green ("my_text")))

compare to:
list (x, "my_text")

This behaviour is a bit unlucky for me - I want the function to put out a colored line of text after the results. My attempt
my_function <- function (a = 3, b = 6) {
    first_result <- a * 3
    second_result <- b / a
    print (list (first_result,
                 second_result,
                 cat (green ("my_text"))))
}

my_function()

of course did not work out. Unfortunately, I have no alternative idea on printing colored text in R. Any help is appreciated.

A: Cat does not return a variable, and instead returns NULL.
Does the green output need to be in the list? If not then this can work:
my_function <- function (a = 3, b = 6) {
first_result <- a * 3
second_result <- b / a
print (list (first_result,
           second_result
           ))
cat(green ("my_text"))
}

my_function()

I tried using capture.output(), but it only captures the text and not the colour.
print(capture.output(cat(green ("my_text"))))

I also tried using R markdown (https://rmarkdown.rstudio.com/index.html) and also then you lose the coloration. So I don't believe it is currently possible


text:
Q: How to Automate Plugins adding in eclipse IDE I am trying to automate code for adding plugins in eclipse IDE. Are there any ways to do it?
normally we use eclipse marketplace/install software to add our plugins. How to write automate code to do this for eclipse ide the same way?
Any script /java code to automate?
i need example code for automate plugin install for testng in eclipse ide


text:
Q: CKeditor language direction How Could I set ckeditor language direction to nothing like this:
<html dir="">

by default it is:
<html dir="rtl">

Where could I modify its code?

A: I think u can use this :
config.contentsLangDirection = 'rtl';

A: the best solution for my problem is:
config.contentsLangDirection = 'ui';

A: abdolsamadseif
code down success
RtlCkeditor();
function RtlCkeditor() {
    CKEDITOR.on('dialogDefinition', function (ev) {
        // Take the dialog name and its definition from the event data.
        var dialogName = ev.data.name;
        var dialogDefinition = ev.data.definition;
        // Check if the definition is from the dialog we're
        // interested in (the 'image' dialog).
        if (dialogName == 'image') {
            // Get a reference to the 'Image Info' tab.
            var infoTab = dialogDefinition.getContents('info');
            // Remove unnecessary widgets/elements from the 'Image Info' tab.
            infoTab.remove('browse');
            infoTab.remove('txtHSpace');
            infoTab.remove('txtVSpace');
            infoTab.remove('txtBorder');
            infoTab.remove('txtAlt');
            infoTab.remove('txtWidth');
            infoTab.remove('txtHeight');
            infoTab.remove('htmlPreview');
            infoTab.remove('cmbAlign');
            infoTab.remove('ratioLock');
        }
    });
    CKEDITOR.config.contentsLangDirection = 'rtl';

    CKEDITOR.replace('#IDElementCkeditore');
}


text:
Q: Implementing Equals based on Hash Code According to equals and hashCode contract rules, is there anything wrong in the code below?
class Test {
    @Override
    public int hashCode() {
        int hash = 0;
        //Calculate hash
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null)
            return false;
        if (this == obj)
            return true;
        if (getClass() != obj.getClass())
            return false;
        Test other = (Test) obj;
        if(this.hashCode() == other.hashCode()) {
            return true;
        } else {
            return false;
        }
    }
}

A: According to the hashcode / equals contract, there is nothing wrong.
But that doesn't necessarily make the code correct.  It all depends on the required equality semantics of the class.
For instance, if there are required to be more than 2^32 distinct states that a Test object could have, then this approach cannot possibly work ... because there are only 2^32 distinct values that can be returned by a hashCode() method.  And even in the sub 2^32 case, you are depending on the existence of a perfect hashing function for the class.  Finding / writing a function won't always be practical.

The other thing to note is that your approach is often going to be less efficient than implementing equals in the normal way.  Why?  Compare this example:
class Test {
    private boolean field1;
    private boolean field2;

    @Override
    public int hashCode() {
        return (field1 ? 0 : 1) * 2 + (field2 ? 0 : 1);
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null)
            return false;
        if (this == obj)
            return true;
        if (getClass() != obj.getClass())
            return false;
        Test other = (Test) obj;
        // version 1
        if(this.hashCode() == other.hashCode()) {
            return true;
        } else {
            return false;
        }
        // version 2
        if (this.field1 == other.field1 && this.field2 == other.field2) {
            return true;
        } else {
            return false;
        }
    }
}

Now compare the "version 1" and "version 2" fragments:

*

*version 1 - 2 method calls, 5 compare-and-branches and 1 multiply.

*version 2 - 0 method calls, 2 compare-and-branch and 0 multiplies.

Now the JIT compiler may optimize significantly, but in this case, the calculation of the hashcodes will probably out-weigh any saving.  Even if you cached the hashcodes (like String does for example) you need the conditions to be "just right" for the hashcode-based approach to be better.

A: Assuming you have concrete implementation of hashCode instead of "calculate hash" line, your code is correct and even will make sense for some cases.
For example, if Test is essentially Boolean, i.e. it can have only two values. Then if you define hashCode as:
 public int hashCode() {
    return value ? 1 : 0;
 }

Your equals method will be fully functional.
Another similar example if your Test class is Integer value object. If you return value as hash, equals will work and will be logically correct.
Base rule is that as long as you can define hashCode so that it covers all possible values of your class, you are good. Otherwise your equals implementations just does not make sense, as it can returns true for some logically distinct objects.
P.S. For those who say that this implementation violates equals-hashcode contract. You are totally wrong. As equals for this implementation works equally to hashCode, contract can't be violated by definition.

A: It is incorrect because the hashCode method is not required to return distinct ints for all possible states of the object.

It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.

It is theoretically possible for two objects not to be equal to each other, but they return the same hash code.
The testing for null, same reference, and different class appears correct.
But instead of relying on the hash code to determine equality, you must make your own comparisons based on the object's own fields and own standards for equality.

A: Two points.  First, don't start with int hash = 0;  Better to start with a positive value, say: int hash = 17;  That avoids the danger of multiplying your initial 0 by some input and hence losing the effect of that input on the final hash value.
Second, your explicit test for null is unnecessary.  Try using:
if (!(obj instanceOf MyType)) {
  return false;
} else {
  MyType myty = (MyType)obj;
  ...
}

The instanceOf operator will return false if either obj is null or it is not of MyType.


text:
Q: why i can not get nodeType of node attributes as DOM standard says attribute is also a attribute node? I can get nodeType from nodes like  or
 in Chrome devtools, but I can't get the nodeType of an attribute. I've tried like this:
document.getElementByTagName('a')[0].href.nodeType

The DOM Standard says attributes are also a type of node. Why can't get its nodeType?
Links : https://dom.spec.whatwg.org/#attr

A:
...but I can't get the nodeType of an attribute. I've tried like this:
document.getElementByTagName('a')[0].href.nodeType

When you access .href on an Element, you're not using the attribute node (not directly), you're using the reflected property for the attribute (which accesses the attribute node under the covers). That property is an accessor property that returns a string. Strings don't have a nodeType property. (You can find this in the HTML spec, starting at the a element which tells you it's an HTMLAnchorElement, which includes HTMLHyperlinkElementUtils, which has href which defines the behavior of the href accessor property.)
To access the attribute node directly, you'd use the attributes collection or getAttributeNode:

const example = document.getElementsByTagName("a")[0];
const node = example.attributes[0];
console.log(`node.nodeType = ${node.nodeType}`);
console.log(`node.nodeName = ${node.nodeName}`);
console.log(`node.nodeValue = ${node.nodeValue}`);
example

In a comment you've asked:

But how do you know that?Does the Dom standard says that in any line?

Truthfully I've learned this stuff over a period of ~24 years and don't remember when I first learned that while attributes are part of the DOM, they aren't part of the node tree, they're held separately as the attributes NamedNodeMap. That information is in the DOM spec where it defines the node tree (note that it doesn't mention attribute nodes), but...you'd have to be looking for it to catch that I think. :-) If you kick around the DOM and HTML specs long enough, though, you'll pick these things up.


text:
Q: Play: How to render before and after a job I have a Play app that compiles some code behind the scenes and I was wondering what the best strategy was to first render a "please wait..." message before the job starts and then a "job complete" message once it is finished.
It's not something that can be chunked, it's either done or not, so I'm guessing without using websockets the only way is to poll with ajax?
thanks!

A: When executing a Job (using .now()), it returns a Promise object. Using this, you can use the play await function and ajax (long polling) or web sockets.
So, you would do the following

*

*display the please wait page

*make your ajax call that executes the job, and awaits for the job to complete

*when your ajax returns you simply update the page, whether that is a javascript update to a div, or a redirect to a new page.

A: It sounds like Ajax is a good technique for this, but you don't need to poll.
Send an Ajax request and at the same time display "please wait...", then when the response arrives, display "job complete". And yes, you should do long-running tasks in a "play job", so you don't block the thread too long.


text:
Q: FlashBuilder loosly coupled and reusable component architecture I want my mxml or actionscript components to be reusable and loosly coupled.  I am wondering if it is good practice to use the FlexGlobals.topApplication to dispatch and listen for events.  For instance I want my login component to dispatch events to the topApplication so when i reuse that component in a different project I won't have to change anything being all applications have a topApplication.
My other option is to have a separate static class to handle event dispatching but then I am creating a dependency on that static class.
Any suggestions would be appreciated.
Thanks.

A: I would recommend that you read about event propagation and have your login component dispatch the event to "whoever" catches it as it bubbles up through the hierarchy.
http://livedocs.adobe.com/flex/3/html/help.html?content=events_08.html

A: I have to agree with the answer by Stian here for the most part.  With regard to weltraumpirat's comment I feel dependency injection can be great but also adds a lot of complication with regard to debugging/testing IMO and if you're not actually going to have different implementations of an interface just adds a lot of garbage code to look through without any real benefit.  I feel like Spring on the service layer side works out well because you can change out implementations for the data access layer (DAO) if you switch DBs or something of that nature but it's hard for me to see the benefit on the front-end.
I would not recommend using the topLevelApplication as you'll end up with something like cairngorm where you have this humongous set of events/event handlers happening at the top level.  Not to mention if you follow their suggested model you end up with a bunch of pointless event classes that simply define a string (there's better and worse ways to go about it using Cairngorm but I'm not a fan of what I've seen in the wild).
A developer at my company wrote a custom MVC "micro-framework" that works great for us where we can attach a controller to any display object to handle events for it, this works wonderfully but does require the initial overhead of developing/testing it.  It's built on top of the existing Event scheme in Flex so our MVCEvent class extends Event (ours just bubble by default as we tend to want this for the types of events we're creating where the controller could be at any level above the UIComponent dispatching the event, and can always opt to turn off bubbling, however starting with the Event base class means we can utilitze the built in EventDispatcher dispatchEvent() method).  He wrote just about everything using an interface to define the methods for each part and only assuming objects implement a given interface to be used in a particular context (as in IMVCEvent, IMVCCommand) this way if the built in framework implementation doesn't work for your particular scenario you just need to create a new class that implements the same interface (if extension also doesn't work for your case).  This gives a huge amount of flexibility yet at the same time we're generally able to just re-use existing implementations of events, commands, or controllers.  In each app we're just defining new views and commands for things that are specific to the business rules of the application.
So what's that all boil down to, I suggest you roll your own as a library then re-use that library for your many projects.  You will know your own library in and out and can tweak it as you see fit quickly without trying to understand the many use cases someone designed their MVC framework to handle.
I realize this isn't an ideal solution in terms of speed to get something done now, but I think it really is the best solution for the long haul (it's been great for us that's really all I can say).
Amendment here to acknowledge the existing Flex MVC frameworks available and appease the crowd.
Robot Legs
By the way see what the creator of robot legs has to say about using his code: His words not mine
Swiz
Mate
Stackoverflow question about flex frameworks


text:
Q: Need my code to count each words position number and store to file I need to develop a program on python that identifies individual words in a sentence and stores them in a list but stores a word's position number in the sentence not the actual word. I have developed this code yet cannot get it to save the words position.
 sentence= input("Enter a sentence")
 keyword= input("Input a keyword from the sentence")
 words = sentence.split(' ')

 for i, word in enumerate(words):
    if keyword == word:
        print(i+1)

 file = open("newfile.txt","a")
 file.write(input("text to write in the file")+"/n")
 file.close()

Anyone got any advice, pointers or help?

A: Based on you question and the code snippet, I have come to a conclusion that your program,

*

*Accept sentence from user

*Get a keyword from user

*If the word in sentence matches the keyword, save the word number in file.

So, for that, Here's the code.
sentence= input("Enter a sentence")
keyword= input("Input a keyword from the sentence")
words = sentence.split(' ')

file=open("newfile.txt","a") #open the file in append mode

for i, word in enumerate(words):
  if keyword == word:
    file.write(str(i+1)+" ") #append the text. I've added space to distiguish digit.
file.close() #Close the file after loop.


text:
Q: New SQLContext: Spark 1.6 backward-compatibility with Spark 2.1 On IBM DSX I have the following problem.
For the Spark 1.6 kernels on DSX it was/is necessary to create new SQLContext objects in order to avoid issues with the metastore_db and HiveContext : http://stackoverflow.com/questions/38117849/you-must-build-spark-with-hive-export-spark-hive-true/38118112#38118112
The following code snippets were implemented using Spark 1.6 and both run for Spark 2.0.2, but not for Spark 2.1:
from pyspark.sql import SQLContext
sqlContext = SQLContext(sc)

df = sqlContext.createDataFrame([(1, "a"), (2, "b"), (3, "c"), (4, "d")], ("k", "v"))
df.count()

and
from pyspark.sql import SQLContext
sqlContext = SQLContext(sc)

properties= {
    'jdbcurl': 'JDBCURL',
    'user': 'USER',
    'password': 'PASSWORD!'
}

data_df_1 = sqlContext.read.jdbc(properties['jdbcurl'], table='GOSALES.BRANCH', properties=properties)
data_df_1.head()

I get this error:
IllegalArgumentException: u"Error while instantiating 'org.apache.spark.sql.hive.HiveSessionState':"

However, when I execute the same code a second time it works again.

A: IIRC, creating a new SQLContext was only necessary for the legacy Spark services (bluemix_ipythonspark_16) in Bluemix. DSX supports only the newer services (bluemix_jupyter_bundle), where creating a new SQLContext is more likely to create problems with Hive than to solve them. Please try without.

A: Instead of creating a new SQLContext using SQLContext(sc) you can use SQLContext.getOrCreate(sc). This will return an existing SQLContext if it exists.


text:
Q: Could not initiate tui-image-editor on Localhost I am trying to initialize, tui-image-editor on my local host. I have downloaded this famous image editor from https://github.com/nhn/tui.image-editor
Here is my code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>TUI Image Editor</title>

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.7.0/fabric.js"></script>
<script type="text/javascript" src="https://uicdn.toast.com/tui.code-snippet/v1.5.0/tui-code-snippet.min.js"></script>

<link rel="stylesheet" href="http://localhost/imageEditor/dist/tui-image-editor.css">
<script src="http://localhost/imageEditor/dist/tui-image-editor.js"></script>
<script>

var ImageEditor = require('tui-image-editor');

var instance = new ImageEditor(document.querySelector('#tui-image-editor'), {
     includeUI: {
         loadImage: {
             path: 'jp.jpg',
             name: 'SampleImage'
         },

         theme: blackTheme, // or whiteTheme
         initMenu: 'filter',
         menuBarPosition: 'bottom'
     },
    cssMaxWidth: 700,
    cssMaxHeight: 500,
    selectionStyle: {
        cornerSize: 20,
        rotatingPointOffset: 70
    }
});
</script>
</head>

<body>

<div id="tui-image-editor" style="height: 200px">
    <canvas></canvas>
</div>

</body>
</html>

In result, I am getting blank page, No error no warning
I am not getting way out of this situation, could you please identify where I am doing bad ?


text:
Q: Scala instantiate common val on two classes with same parent I have two classes that extend the same trait :
trait Event {
  val propertyCommon : String = ""
}

case class EventA(propertyA : String) extends Event
case class EventB(propertyB : String) extends Event

Now I instantiate my classes in a List :
myList : List[Event] = List(EventA("a"),EventB("b"))

What I want to do is to instantiate after the common property, as if there was a copy method in my trait :
myList.map(_.copy(propertyCommon = "Something"))

How could I do that ?

A: What you say you want to do is called a prototype pattern in OOP, and as far as I can tell it isn't supported out of the box in Scala (and I think anywhere else).
There are also a few problems:

*

*propertyCommon is not set up using constructor, so each implementation that would have to set it, would most likely have to override it using anonymous class (but then, this property will not be a part of equals, hashcode, toString, derivation, etc)

*Event doesn't define any interface that would allow updating it

The easiest (and safest) way I see to implement functionality you want, would be something like this:
trait Event {
  val propertyCommon: String // will be set by implementing class

  def clone(propertyCommon: String = this.propertyCommon): Event
}

// children define propertyCommon to match the interface
case class EventA(propertyA: String, propertyCommon: String = "") extends Event {
  def clone(propertyCommon: String = this.propertyCommon): EventA = copy(propertyCommon)
}
case class EventB(propertyB: String, propertyCommon: String = "") extends Event {
  def clone(propertyCommon: String = this.propertyCommon): EventB = copy(propertyCommon)
}

However, probably if we knew more about your problem we could provide some other, simpler solution.


text:
Q: What is the difference between Facebook start_time in Events table and on FB event page? I'm using explorer to test this event
FQL to Event table : fql?q={'events': 'select eid, name, start_time from event where eid = 359724487410779'} - returns start_time = 1337410800
Converting 1337410800 gives Saturday, May 19th 2012, 07:00:00 (GMT)
Event object in FB api explorer: https://graph.facebook.com/359724487410779 - returns start_time = 2012-05-19T00:00:00
Event object in browser: https://graph.facebook.com/359724487410779 - returns start_time = 2012-05-18T14:00:00
FB page https://www.facebook.com/events/359724487410779 - Friday, May 18, 2012
11:00pm until 4:00am in UTC+02
How can I get the right local time, like on FB Event page (Friday, May 18, 2012
11:00pm) based on Facebook API ?

A: *

*Event table - it contains time of the event (in GMT) if it would be in Pacific zone (see here) - so 1337410800 will give you May 19th 7am in GMT -> which is May 18th 11pm in PST - which is the time of the event if you remove timezone.

*Event object in FB api explorer - it returns time converted to YOUR Facebook profile time zone - which gives me 2012-05-18T17:00:00 for example (EST). Again, this converts to May 18th 11pm in CET

*Event object in browser - i.e. direct call to FB API - gives you start time in PST time zone (2pm PST -> 11pm in Europe/Amsterdam timezone)

*FB page obviously have LOCAL time
Answering your question - personally I would go with Graph API call and will convert start_time from Pacific into UTC. Then use "timezone: Europe/Amsterdam" to convert UTC time into local time.


text:
Q: momentJs year stopped at 2006 the year stopped at 2006 in the daterangepicker i don't know why ?
my code is :
<script type="text/javascript">
    moment.locale('fr');
    $(document).ready(function () {

      $('#sdate').daterangepicker({
        singleDatePicker: true,
        timePicker: true,
        timePicker24Hour: true,
        locale: {
          format: "LLLL",
          applyLabel: 'Appliquer',
          cancelLabel: 'Annuler'
        },
        firstDay: 1
      });
    });
</script>

the time in my PC is correct

A: We must normalize our source code to be able running in all browsers .
1 - Use format+string
2 - don't use points "." or "-" in the date we must use just "/"
3 - You can see this document
So the code in the part of "format" will be like this :
<script type="text/javascript">
    moment.locale('fr');
    $(document).ready(function () {

      $('#sdate').daterangepicker({
        singleDatePicker: true,
        timePicker: true,
        timePicker24Hour: true,
        locale: {
          format: ("Jeudi 14/Janvier/2016 10:30", "dddd DD/MMMM/YYYY HH:mm"),
          applyLabel: 'Appliquer',
          cancelLabel: 'Annuler'
        },
        firstDay: 1
      });
    });
</script>


text:
Q: Retrieve a window handle whitin outlook I'm working on a custom outlook addin where I need to subclass the appointment window. This works basically pretty well following the principles mentioned in the following ariticle:
http://www.codeproject.com/Articles/27262/Additional-custom-panel-in-Microsoft-Outlook
I'm struggeling by getting the handle to the social connector within the new appointment window.

I've tryied out a few approaches (FindWindow, FindWindowEx, EnumChildWindow) but none of them gave me the correct handle.
Here you can find a small addin project to have a quick look at it.
Download
Or have a quick look at this abstract
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Outlook;
using Office = Microsoft.Office.Core;

namespace FindSocialConnector._2013
{
    public partial class ThisAddIn
    {
        /// <summary>
        /// Delegate for the EnumChildWindows method
        /// </summary>
        /// <param name="hWnd">Window handle</param>
        /// <param name="parameter">Caller-defined variable; we use it for a pointer to our list</param>
        /// <returns>True to continue enumerating, false to bail.</returns>
        public delegate bool EnumWindowProc(IntPtr hWnd, IntPtr parameter);

        /// <summary>
        /// Hält den Klassennamen des NewAppointment Windows.
        /// </summary>
        public const string NewAppointmentWindowClass = "rctrl_renwnd32";

        private Inspectors _inspectors;

        /// <summary>
        /// The EnumChildWindows function enumerates the child windows that belong to the specified parent window by passing the handle to each child window,
        /// in turn, to an application-defined callback function. EnumChildWindows continues until the last child window is enumerated or the callback function returns FALSE.
        /// </summary>
        /// <param name="parentHandle">
        /// Handle to the parent window whose child windows are to be enumerated.
        /// If this parameter is NULL, this function is equivalent to EnumWindows.
        /// Windows 95/98/Me: parentHandle cannot be NULL.
        /// </param>
        /// <param name="callbackFunction">
        /// Pointer to an application-defined callback function. For more information, see EnumChildProc.
        /// </param>
        /// <param name="param">
        /// Specifies an application-defined value to be passed to the callback function.
        /// </param>
        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        public static extern int EnumChildWindows(IntPtr parentHandle, Delegate callbackFunction, IntPtr param);

        /// <summary>
        /// Retrieves a handle to the top-level window whose class name and window name match the specified strings. This function does not search child windows.
        /// This function does not perform a case-sensitive search. To search child windows, beginning with a specified child window, use the FindWindowEx function.
        /// <returns>
        /// <param name="className">
        /// The class name or a class atom created by a previous call to the RegisterClass or RegisterClassEx function.
        /// The atom must be in the low-order word of lpClassName; the high-order word must be zero.
        /// If lpClassName points to a string, it specifies the window class name.
        /// The class name can be any name registered with RegisterClass or RegisterClassEx, or any of the predefined control-class names.
        /// If lpClassName is NULL, it finds any window whose title matches the lpWindowName parameter.
        /// </param>
        /// <param name="windowName">The window name (the window's title). If this parameter is NULL, all window names match.</param>
        /// If the function succeeds, the return value is a handle to the window that has the specified class name and window name.
        /// If the function fails, the return value is NULL. To get extended error information, call GetLastError.
        /// </returns>
        /// </summary>
        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        public static extern IntPtr FindWindow(string className, string windowName);

        /// <summary>
        /// The FindWindowEx function retrieves a handle to a window whose class name and window name match the specified strings.
        /// The function searches child windows, beginning with the one following the specified child window.
        /// This function does not perform a case-sensitive search.
        /// </summary>
        /// <param name="parentHandle">
        /// Handle to the parent window whose child windows are to be searched.
        /// If hwndParent is NULL, the function uses the desktop window as the parent window.
        /// The function searches among windows that are child windows of the desktop.
        /// </param>
        /// <param name="childAfter">
        /// Handle to a child window. The search begins with the next child window in the Z order.
        /// The child window must be a direct child window of hwndParent, not just a descendant window.
        /// If hwndChildAfter is NULL, the search begins with the first child window of hwndParent.
        /// </param>
        /// <param name="className">
        /// Pointer to a null-terminated string that specifies the class name or a class atom created by a previous call to the RegisterClass or RegisterClassEx function.
        /// The atom must be placed in the low-order word of lpszClass; the high-order word must be zero.
        /// </param>
        /// <param name="windowTitle">
        /// Pointer to a null-terminated string that specifies the window name (the window's title).
        /// If this parameter is NULL, all window names match.
        /// </param>
        /// <returns>
        /// If the function succeeds, the return value is a handle to the window that has the specified class and window names.
        /// If the function fails, the return value is NULL. To get extended error information, call GetLastError.
        /// </returns>
        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        public static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string className, string windowTitle);

        /// <summary>
        /// Liefert das Handle des NewAppointmentWindow's.
        /// </summary>
        private static IntPtr FindNewAppointmentWindowByCaption(string caption)
        {
            IntPtr newAppointmentWindowHandle = FindWindow(NewAppointmentWindowClass, caption);
            if (newAppointmentWindowHandle == IntPtr.Zero)
            {
                throw new ArgumentException("NewAppointment Window wasn't found.");
            }
            return newAppointmentWindowHandle;
        }

        private void ThisAddIn_Startup(object sender, EventArgs e)
        {
            _inspectors = Application.Inspectors;
            _inspectors.NewInspector += Inspectors_NewInspector;
        }

        private void Inspectors_NewInspector(Inspector inspector)
        {
            AppointmentItem appointmentItem = inspector.CurrentItem as AppointmentItem;
            if (appointmentItem != null)
            {
                IntPtr appointmentWindow = FindNewAppointmentWindowByCaption(inspector.Caption);

                // Get all child windows based on the new appointment window
                // Unfortunately the social connector handle isn't returned
                GetChildWindows(appointmentWindow);

                // Directly get the social connector based on the class name
                // Unfortunately this returns 0
                IntPtr socialConnectorWindow = FindWindowEx(appointmentWindow, IntPtr.Zero, "MerenguePane", null);
            }
        }

        /// <summary>
        /// Callback method to be used when enumerating windows.
        /// </summary>
        /// <param name="handle">Handle of the next window</param>
        /// <param name="pointer">Pointer to a GCHandle that holds a reference to the list to fill</param>
        /// <returns>True to continue the enumeration, false to bail</returns>
        private static bool EnumWindow(IntPtr handle, IntPtr pointer)
        {
            GCHandle gch = GCHandle.FromIntPtr(pointer);
            List<IntPtr> list = gch.Target as List<IntPtr>;
            if (list == null)
            {
                throw new InvalidCastException("GCHandle Target could not be cast as List<IntPtr>");
            }
            Debug.WriteLine("Current Window Handle: {0}, Hex: {1}", handle, handle.ToString("X"));
            list.Add(handle);

            // You can modify this to check to see if you want to cancel the operation, then return a null here
            return true;
        }

        /// <summary>
        /// Returns a list of child windows
        /// </summary>
        /// <param name="parent">Parent of the windows to return</param>
        /// <returns>List of child windows</returns>
        public static List<IntPtr> GetChildWindows(IntPtr parent)
        {
            List<IntPtr> result = new List<IntPtr>();
            GCHandle listHandle = GCHandle.Alloc(result);
            try
            {
                EnumWindowProc childProc = EnumWindow;
                EnumChildWindows(parent, childProc, GCHandle.ToIntPtr(listHandle));
            }
            finally
            {
                if (listHandle.IsAllocated)
                {
                    listHandle.Free();
                }
            }
            return result;
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InternalStartup()
        {
            Startup += ThisAddIn_Startup;
        }
    }
}

Btw. the social connector is only displayed if you directly create a meeting request e.g. go to the calendar, right click --> New meeting request
Any thoughts on this?
Regards,
Lukas


text:
Q: Approve Jenkins Pipeline input step with Bitbucket webhook I have a pipeline that waits for a merge of a branch to master. It contains an input step:
input message: 'Merge complete?', id: 'merge', ok: 'Done'

Instead of approving it manually I'd like it to be automatically approved by Bitbucket using post-merge webhook. I know that it's possible to approve it using the Jenkins REST API with the following url:
https://JENKINS_HOST/JOB_NAME/BUILD_NUMBER/input/Merge/proceedEmpty
Build number changes on every subsequent build. Is it possible to somehow pass the $BUILD_NUMBER variable to Bitbucket, so it could dynamically update its endpoint URL field in post-merge hook configuration?


text:
Q: Knockout JS Count only numbers in maxLength attribute Is there a way to manipulate maxLength attribute to count only numbers?
I have seen this code MyObservable.replace(/[^0-9]/g, '').length that can only count numbers but I don't know where to put it. Or any better Idea. Thanks

A: You'll need to use a custom binding if you want to limit to a certain amount instead of the length of a string. There's 2 options, with one you remain with an input="text" and the second being an input="number"
The difference that with the first you'll need to include a regex somewhat like your example into the following piece of code, where with the second option the browser has already taken care of that, I'll leave it up to you where you want to go with this.

ko.bindingHandlers.maxValue = {
    init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        var valueObservable = valueAccessor();

        ko.utils.registerEventHandler(element, "change", function () {
            var value = Number(element.value);
          if (value >= 0) {
            if (value > allBindings().maxAmount) {
                value = allBindings().maxAmount;
            }
            element.value = value;
            valueObservable(value);
          }
        });
    },
};

var ViewModel = function ()
{
    var self = this;
  self.value = ko.observable();
};

ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<input type="number" data-bind="maxValue: $root.value, maxAmount: 100" />


text:
Q: How do I use a DialogFragment if my app doesn't use Fragments? I'm updating an older app that still supports Android 2.0.
There is a new chunk of code that I would really like to put up a custom dialog - but all the docs talk about using DialogFragments.
I'm not using Fragments anywhere in my app, so how do I get a FragmentManager to let me show the dialog?
Or can someone point me to the docs for the pre-Fragment dialog support?

A: you still create dialogs the same way just without using a fragment.
for example:
AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setMessage(R.string.dialog_fire_missiles)
           .setPositiveButton(R.string.fire, new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                   // FIRE ZE MISSILES!
               }
           })
           .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                   // User cancelled the dialog
               }
           });
    // Create the AlertDialog object and return it
    return builder.create();

I would highly recommend you stop supporting 2.0 and start supporting 2.2 and your minimum sdk target so you can switch to using fragments as this is the preferred way to do things now

A: You should use the Android Support Library v4 and also convert all the activities where you need to display the dialog from Activity to FragmentActivity. In this way you don't have to modify your activities but you can use the DialogFragment.


text:
Q: Static method call from AsyncTask is async? I'm trying to use a AsyncTask to check if internet connection is available and then doing some stuff.
My problem is while the comprobation is being executed I can´t interacting with the UI. The "progressbar" is on front and if I try to click on a button the UI doesn't respond
This is the call to AsyncTask
@Override
    public void onStart(){
        super.onStart();
            AsyncHttpHandler check = new AsyncHttpHandler(**paramaters**);
            check.execute("checkshared");

    }

This is the code of AsyncTask
public class AsyncHttpHandler extends AsyncTask<String, Integer, String>{

    public AsyncHttpHandler(Context c, Intent i, Bundle _data, String _language){
        ctx = c;
        intent = i;
        data = _data;
        language = _language;

        startClock();

    }

    public void startClock(){
        mDialog = new ProgressDialog(ctx,R.style.MyTheme);
        mDialog.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
        mDialog.setCancelable(false);
        mDialog.show();
    }

    @SuppressWarnings("unchecked")
    @Override
    protected String doInBackground(String... peticion) {
        String response = "null";
        //call to check if internet connection is available
        if(Utils.isInternetConn(ctx)){

        try {

            // do stuff
            response = "...";

        }
        else response = "offline";

        return response;
        }
    }

    protected void onPostExecute(String response) {
        if(mDialog != null) mDialog.dismiss();

        if(!response.equals("offline")){
        // do stuff
        }
        else Toast.makeText(ctx, ctx.getResources().getString(ctx.getResources().getIdentifier(language+"_toast_nointernet", "string", ctx.getPackageName())), Toast.LENGTH_LONG).show();

    }

}

And this is the method to check if the internet connection is available:
public static Boolean isInternetConn(Context ctx){

    ConnectivityManager connec = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

    boolean conectado = false;
    if((wifi != null && wifi.isConnectedOrConnecting()) || (mobile != null && mobile.isConnectedOrConnecting())){

        try {

            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
            URL myurl = new URL("http://www.google.com");
            URLConnection connection;
            connection = myurl.openConnection();
            connection.setConnectTimeout(2000);
            connection.setReadTimeout(2000);
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            int responseCode = -1;
            responseCode = httpConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                  conectado = true;
                  httpConnection.disconnect();
            }
            else {
                httpConnection.disconnect();
            }

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

  return conectado;
}

What am I doing wrong?

A: The problem is not in your AsyncTask calling static method. That will also execute async. Problem is that you are showing progress dialog until your task finishes. And, of course, while your progress dialog is visible you will not be able to interact with the UI. If you want to interact with the UI, show your progress in another way, not with dialog.

A: You display a progressDialog on top of the screen. The progress dialog takes the UI interaction, so the buttons underneath don't respond. If you use a progress bar in your UI instead of a progress dialog, your buttons will work.

A: If you want to show the progress of your task to the user, use the method onProgressUpdate, as it has been implemented to run on the UI thread.
Now, each time you want to show the progress from doInBackground, call it by passing an argument. To be clear, AsyncTask (String, Integer, String) uses argument types:

*

*First is the type of argument you pass when you call execute

*Second is the type of the argument you pass to onProgressUpdate

*Third is the type of argument you pass to onPostExecute

A: I'm not sure if I understood what is your problem, but it seems to me, that you cannot interact with UI because the ProgressDialog is not cancelable, and it's in front of everything else.
You will only have feedback when dialog is dismissed.


text:
Q: Pontuar no output em JavaScript Estou tentando resolver um problema, onde o usuário inseri apenas os números do cpf em um input e, ao lado, ele vai sendo exibido no formato correto do CPF (xxx.xxx.xxx-xx).
Porém, alguém sabe porque a pontuação aparece, mas depois que continuo digitando a pontuação some?
var inCPF = document.getElementById("inCPF");
var outCPF = document.getElementById("outCPF");

function formatar() {
    var cpf = inCPF.value;

    if (cpf.length == 3 || cpf.length == 7) {
        cpf += ".";
    } else if (cpf.length == 11) {
        cpf += "-";
    }

    outCPF.textContent = cpf;
}

inCPF.addEventListener("keyup", formatar);

A: Está acontecendo esse problema pois no seu código é adicionado o . somente quando o tamanho é 3 ou 7: if (cpf.length == 3 || cpf.length == 7). E o - somente quando o tamanho é 11: else if (cpf.length == 11). Em outros casos não irá adicionar nada, ou seja, no final não adicionará os elementos.
O que recomendo fazer é pegar o inCPF, retirar os valores símbolos indesejáveis e colocar os caracteres, . e -, entre eles.
Ficaria desse jeito:

var inCPF = document.getElementById("inCPF");
var outCPF = document.getElementById("outCPF");

function formatar() {
    var cpf = inCPF.value;
    //retira os caracteres indesejados e adiciona os novos
    cpf = cpf.replace(/\D/g, "").replace(/^(\d{3})(\d{3})?(\d{3})?(\d{2})?/, "$1.$2.$3-$4");
    //Aqui limita os caracteres exibidos no outCPF
    if(cpf.length <= 14){
        outCPF.textContent = cpf;
    }
}

inCPF.addEventListener("keyup", formatar);
<input id="inCPF" maxlength="14">

EDIT
Fiz as alterações que me foram sugeridas nos comentários. Inclusive limitei o código para no máximo 14 caracteres.


text:
Q: Update an object that is indirectly related to another object in a list I have a list of custom object (Meeting Note) and I want to be able to edit a custom field (Firm Type) from another object (Net Prospect Score) that is indirectly related to the Meeting Note object. They both have a lookup field to Contact object. Below is my attempt at an Apex class that does not work. I was able to only display (in a VF page) the custom field but it does not update.
public class MeetingNoteCtrlr{

public List<MeetingNote__c> meetingNotesOutstanding {get; set;}
public MeetingNoteMDHomePageCtrlr() {

    meetingNotesOutstanding = [
        SELECT FIELDS(STANDARD), Name__r.Net_Prospect_Score__r.Firm_Type__c
        FROM MeetingNote__c
        LIMIT 100];
}

public PageReference saveMeetingNotes() {

    try{
       update meetingNotesOutstanding;
    }
    catch(DmlException ex){
        ApexPages.addMessages(ex);
    }
    return null;
}

}

A: DML operations will not update Child records in the records whihc you pass to it,
So you need to create another list for Net_Prospect_Score__c object and update this list.
Also you need to add another parameter to your query to get Net_Prospect_Score__c Id.
The updated code will look like this :
public class MeetingNoteCtrlr {
    public List<MeetingNote__c> meetingNotesOutstanding {get; set;}

    public MeetingNoteMDHomePageCtrlr() {
        meetingNotesOutstanding = [
              SELECT FIELDS(STANDARD),
              Name__r.Net_Prospect_Score__c
              Name__r.Net_Prospect_Score__r.Firm_Type__c
              FROM MeetingNote__c
              LIMIT 100];
    }

    public PageReference saveMeetingNotes() {
        try{
            List<Net_Prospect_Score__c> netProspectScores = new List<Net_Prospect_Score__c>();
            for(MeetingNote__c meetingNote: meetingNotesOutstanding) {
                if(
                    meetingNote.Name__c != null
                    && meetingNote.Name__r.Net_Prospect_Score__c != null
                ){
                    netProspectScores.add(
                        new Net_Prospect_Score__c(
                            Id = meetingNote.Name__r.Net_Prospect_Score__c,
                            Firm_Type__c = meetingNote.Name__r.Net_Prospect_Score__r.Firm_Type__c
                        )
                    );
                }
            }
            update netProspectScores;
        } catch(DmlException ex){
            ApexPages.addMessages(ex);
        }
        return null;
    }
}

Some of Object or fields API Names may be different,
So if you copy-paste the code than you should check it.
--- Update ----
If multiple Contacts can be related to the same net prospect score,
You need to make sure that there are no duplicates in netProspectScores list.
You can use a Map instead of a list or make sure there are no
Net_Prospect_Score__c duplicates returned in the query.
The variant with Map will look like this :
****
    Map<Id,Net_Prospect_Score__c> netProspectScoresMap = new Map<Id,Net_Prospect_Score__c>();
    for(MeetingNote__c meetingNote: meetingNotesOutstanding) {
        if(
           meetingNote.Name__c != null
           && meetingNote.Name__r.Net_Prospect_Score__c != null
        ){
            netProspectScoresMap.put(
                meetingNote.Name__r.Net_Prospect_Score__c,
                new Net_Prospect_Score__c(
                    Id = meetingNote.Name__r.Net_Prospect_Score__c,
                    Firm_Type__c = meetingNote.Name__r.Net_Prospect_Score__r.Firm_Type__c
                )
            );
        }
    }
    update netProspectScoresMap.values();
***

Ensure you do not lose any data with the Map approach, as if there are multiple Contacts with the same net prospect score you can lose some data.


text:
Q: I can't move items in viewDidAppear in Swift I'm having the issue where I have a UIView that displays no internet connection. I want it to dive out of the way when the view is loaded so as not to be seen. It should pop back up and go away when connections are either on and off..The notifier is working and if the connection goes on and off it will move or remove the banner. However when the view first loads it doesn't move the UIView out of the way.
 override func viewWillAppear(animated: Bool) {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.actOnSpecialNotification(_:)), name: "ReachabilityChangedNotification", object: nil)
       print("viewappeard")
        self.unableBox.center.y  -= view.bounds.height

    }

    func actOnSpecialNotification(note:NSNotification){
        let reachability = note.object as! Reachability

        if reachability.isReachable() {
            self.unableBox.center.y  -= view.bounds.height
            print(self.unableBox.center.y)
            print(view.bounds.height)
            if reachability.isReachableViaWiFi() {
                print("Reachable via WiFi")
            } else {
                print("Reachable via Cellular")
            }
        } else {
            self.unableBox.center.y  = view.bounds.height/2
            print(self.unableBox.center.y)
            print(view.bounds.height)
            print("Network not reachable")
        }

        }


text:
Q: Integral involving Hermite polynomials Is there any way to calculate the following integral ?
$\int_{-\infty}^{+\infty} H_n(x)H_m(x)e^{-\alpha x^2} d x$ with $\alpha > 0$ and $(H_n,H_m)_{w = e^{-x^2}} = 2^n n! \sqrt{\pi}\delta_{nm}$
(without using Gauss-Hermite quadrature)

A: We want to evaluate
\begin{eqnarray*}
J_{n,m}=\int_{-\infty}^{\infty} e^{-\alpha x^2} H_n(x) H_m(x) dx.
\end{eqnarray*}
The Hermite polynomials are defined by the generating function
\begin{eqnarray*}
\sum_{n=0}^{\infty} H_n(z) \frac{t^n}{n!} =\exp( 2tz-t^2).
\end{eqnarray*}
Now we define
\begin{eqnarray*}
I(t_1,t_2)&=&\sum_{n=0}^{\infty} \frac{t_1^n}{n!} \sum_{m=0}^{\infty}  \frac{t_2^m}{m!} \int_{-\infty}^{\infty} e^{-\alpha x^2} H_n(x) H_m(x) dx \\
&=& \int_{-\infty}^{\infty} \exp( -\alpha x^2+2t_1x-t_1^2+2t_2x-t_2^2) dx \\
&=& \int_{-\infty}^{\infty} \exp \left( -\alpha \left(x-\frac{t_1+t_2}{\alpha} \right)^2 -t_1^2-t_2^2 +\frac{(t_1+t_2)^2}{\alpha}\right) dx \\
&=& \sqrt{\frac{\pi}{\alpha}}  \exp \left(  -t_1^2-t_2^2 +\frac{(t_1+t_2)^2}{\alpha}\right).
\end{eqnarray*}
It now becomes clear why $\alpha=1$ gives the orthogonality relation ($I = 2^n n! \delta_{n,m} \sqrt{\pi}$). In our case we require the coefficient of $t_1^n t_2^m$ in $I(t_1,t_2)$, in the case where $n,m$ are even ($(n,m) \rightarrow (2n,2m)$) we get
\begin{eqnarray*}
I(t_1,t_2)&=& \sqrt{\frac{\pi}{\alpha}}  \sum_{j_1=0}^{\infty} \frac{(1/\alpha -1)^{j_1} t_1^{2j_1}}{j_1 !}   \sum_{j=0}^{\infty} \frac{(2 t_1 t_2 )^{j}}{j !}   \sum_{j_2=0}^{\infty} \frac{(1/\alpha -1)^{j_2} t_2^{2j_2}}{j_2 !}
\end{eqnarray*}
So $2j_1+j=2n$ and $2j_2+j=2m$ giving
\begin{eqnarray*}
J_{2n,2m} &=&(2n)!(2m)! \sqrt{\frac{\pi}{\alpha}}   \sum_{j=0}^{\min(n,m)} \frac{2 ^{j}(1/\alpha -1)^{n+m-2j}}{(2j) ! (n-j)!(m-j)!} .
\end{eqnarray*}
$J$ will be zero in the case where one of $n,m$ is even and one is odd, I leave you to evaluate the case where they are both odd.


text:
Q: How do I configure one SQL Server to connect to another, so it appears query data is coming from only one connection? Somewhere recently I read of a method to connect one SQL Server to another, so clients could connect and run queries that appeared to come only from the first server. I cannot remember the proper terminology for this technique, and Google searches have not helped. I thought it was called "external connection", or "external source", but I cannot find this again.
Have I remembered correctly, and can someone give me an overview how to do this..?
To explain further, my preferred SQL client DBeaver only allows one connection in each query. As such, if I wish to join tables from two different servers, there's no direct way to do it...except perhaps this method which I can't remember how to do.

A: Take a look at the linked server in MsSQL.
https://www.sqlshack.com/how-to-create-and-configure-a-linked-server-in-sql-server-management-studio/
https://learn.microsoft.com/en-us/sql/relational-databases/linked-servers/create-linked-servers-sql-server-database-engine?view=sql-server-ver15

A: Use DBVisualizer instead of Dbeaver, if you are on Linux.


text:
Q: C - alternative to #ifdef I'm trying to streamline large chunk of legacy C code in which, even today, before doing the build guy who maintains it takes a source file(s) and manually modifies the following section before the compilation based on the various types of environment.
The example follows but here's the question. I'm rusty on my C but I do recall that using #ifdef is discouraged. Can you guys offer better alternative? Also - I think some of it (if not all of it) can be set as environment variable or passed in as a parameter and if so - what would be a good way of defining these and then accessing from the source code?
Here's snippet of the code I'm dealing with
#define DAN          NO
#define UNIX         NO
#define LINUX        YES
#define WINDOWS_ES   NO
#define WINDOWS_RB   NO

/* Later in the code */
#if ((DAN==1) || (UNIX==YES))
#include <sys/param.h>
#endif

#if ((WINDOWS_ES==YES) || (WINDOWS_RB==YES) || (WINDOWS_TIES==YES))
#include <param.h>
#include <io.h>
#include <ctype.h>
#endif

/* And totally insane harcoded paths */
#if (DAN==YES)
char MasterSkipFile[MAXSTR] = "/home/dp120728/tools/testarea/test/MasterSkipFile";
#endif

#if (UNIX==YES)
char MasterSkipFile[MAXSTR] = "/home/tregrp/tre1/tretools/MasterSkipFile";
#endif

#if (LINUX==YES)
char MasterSkipFile[MAXSTR] = "/ptehome/tregrp/tre1/tretools/MasterSkipFile";
#endif

/* So on for every platform and combination */

A: One thing we used to do is have a generated .h file with these definitions, and generate it with a script. That helped us get rid of a lot of brittle #ifs and #ifdefs
You need to be careful about what you put there, but machine-specific parameters are good candidates - this is how autoconf/automake work.
EDIT: in your case, an example would be to use the generated .h file to define INCLUDE_SYS_PARAM and INCLUDE_PARAM, and in the code itself use:
#ifdef INCLUDE_SYS_PARAM
#include <sys/param.h>
#endif

#ifdef INCLUDE_PARAM
#include <param.h>
#endif

Makes it much easier to port to new platforms - the existence of a new platform doesn't trickle into the code, only to the generated .h file.

A: Platform specific configuration headers
I'd have a system to generate the platform-specific configuration into a header that is used in all builds.  The AutoConf name is 'config.h'; you can see 'platform.h' or 'porting.h' or 'port.h' or other variations on the theme.  This file contains the information needed for the platform being built.  You can generate the file by copying a version-controlled platform-specific variant to the standard name.  You can use a link instead of copying.  Or you can run configuration scripts to determine its contents based on what the script finds on the machine.
Default values for configuration parameters
The code:
#if (DAN==YES)
char MasterSkipFile[MAXSTR] = "/home/dp120728/tools/testarea/MasterSkipFile";
#endif

#if (UNIX==YES)
char MasterSkipFile[MAXSTR] = "/home/tregrp/tre1/tretools/MasterSkipFile";
#endif

#if (LINUX==YES)
char MasterSkipFile[MAXSTR] = "/ptehome/tregrp/tre1/tretools/MasterSkipFile";
#endif

Would be better replaced by:
#ifndef MASTER_SKIP_FILE_PATH
#define MASTER_SKIP_FILE_PATH "/opt/tretools/MasterSkipFile"
#endif

const char MasterSkipFile[] = MASTER_SKIP_FILE_PATH;

Those who want the build in a different location can set the location via:
-DMASTER_SKIP_FILE_PATH='"/ptehome/tregtp/tre1/tretools/PinkElephant"'

Note the use of single and double quotes; try to avoid doing this on the command line with backslashes in the path.  You can use a similar default mechanism for all sorts of things:
#ifndef DEFAULTABLE_PARAMETER
#define DEFAULTABLE_PARAMETER default_value
#endif

If you choose your defaults well, this can save a lot of energy.
Relocatable software
I'm not sure about the design of the software that can only be installed in one location.  In my book, you need to be able to have the old version 1.12 of the product installed on the machine at the same time as the new 2.1 version, and they should be able to operate independently.  A hard-coded path name defeats that.
Parameterize by feature not platform
The key difference between the AutoConf tools and the average alternative system is that the configuration is done based on features, not on platforms.  You parameterize your code to identify a feature that you want to use.  This is crucial because features tend to appear on platforms other than the original.  I look after code where there are lines like:
#if defined(SUN4) || defined(SOLARIS_2) || defined(HP_UX) || \
    defined(LINUX) || defined(PYRAMID) || defined(SEQUENT) || \
    defined(SEQUENT40) || defined(NCR) ...
#include <sys/types.h>
#endif

It would be much, much better to have:
#ifdef INCLUDE_SYS_TYPES_H
#include <sys/types.h>
#endif

And then on the platforms where it is needed, generate:
#define INCLUDE_SYS_TYPES_H

(Don't take this example header too literally; it is the concept I am trying to get over.)
Treat platform as a bundle of features
As a corollary to the previous point, you do need to detect platform and define the features that are applicable to that platform.  This is where you have the platform-specific configuration header which defines the configuration features.
Product features should be enabled in a header
(Elaborating on a comment I made to another answer.)
Suppose you have a bunch of features in the product that need to be included or excluded conditionally.  For example:
KVLOCKING
B1SECURITY
C2SECURITY
DYNAMICLOCKS

The relevant code is included when the appropriate define is set:
#ifdef KVLOCKING
...KVLOCKING stuff...
#else
...non-KVLOCKING stuff...
#endif

If you use a source code analysis tool like cscope, then it is helpful if it can show you when KVLOCKING is defined.  If the only place where it is defined is in some random Makefiles scattered around the build system (let's assume there are a hundred sub-directories that are used in this), it is hard to tell whether the code is still in use on any of your platforms.  If the defines are in a header somewhere - the platform specific header, or maybe a product release header (so version 1.x can have KVLOCKING and version 2.x can include C2SECURITY but 2.5 includes B1SECURITY, etc), then you can see that KVLOCKING code is still in use.
Believe me, after twenty years of development and staff turnover, people don't know whether features are still in use or not (because it is stable and never causes problems - possibly because it is never used).  And if the only place to find whether KVLOCKING is still defined is in the Makefiles, then tools like cscope are less helpful - which makes modifying the code more error prone when trying to clean up later.

A: Its much saner to use :
#if SOMETHING

.. from platform to platform, to avoid confusing broken preprocessors. However any modern compiler should effectively argue your case in the end. If you give more details on your platform, compiler and preprocessor you might receive a more concise answer.
Conditional compilation, given the plethora of operating systems and variants therein is a necessary evil. if, ifdef, etc are most decidedly not an abuse of the preprocessor, just exercising it as intended.

A: My preferred way would be to have the build system do the OS detection. Complex cases you'd want to isolate the machine-specific stuff into a single source file, and have completely different source files for the different OSes.
So in this case, you'd have a #include "OS_Specific.h" in that file. You put the different includes, and the definition of MasterSkipFile for this platform. You can select between them by specifying different -I (include path directories) on your compiler command line.
The nice thing about doing it this way is that somebody trying to figure out the code (perhaps debugging) doesn't have to wade through (and possibly be misled by) phantom code for a platform they aren't even running on.

A: I've seen build systems in which most of the source files started something off like this:
#include PLATFORM_CONFIG
#include BUILD_CONFIG

and the compiler was kicked off with:
cc -DPLATFORM_CONFIG="linuxconfig.h" -DBUILD_CONFIG="importonlyconfig.h"

(this may need backslash escapes)
this had the effect of letting you separate out the platform settings in one set of files and the configuration settings in another.  Platform settings manages handling library calls that may not exist on one platform or not in the right format as well as defining important size dependent types--things that are platform specific.  Build settings handles what features are being enabled in the output.

A: Sure, you can pass -DWHATEVER on the command line.  Or -DWHATEVER_ELSE=NO, etc.  Maybe for the paths you could do something like
char MasterSkipFile[MAXSTR] = SOME_COMMAND_LINE_DEFINITION;

and then pass
-DSOME_COMMAND_LINE_DEFINITION="/home/whatever/directory/filename"

on the command line.

A: Generalities
I'm a heretic who has been cast out from the Church of the GNU Autotools. Why?  Because I like to understand what the hell my tools are doing.  And because I've had the experience of trying to combine two components, each of which insisted on a different, incompatible version of autotools being the default version installed on my computer.
I work by creating one .h file or .c filed for every combination of platform and significant abstraction.  I work hard to define a central .h file that says what the interface is.  Often this means I wind up creating a "compatibility layer" that insulates me from differences between platforms.  Often I wind up using ANSI Standard C whenever possible, instead of platform-specific functionality.
I sometimes write scripts to generate platform-dependent files.  But the scripts are always written by hand and documented, so I know what they do.
I admire Glenn Fowler's nmake and Phong Vo's iffe (if feature exists), which I think are better engineered than the GNU tools.  But these tools are part of the AT&T Software Technology suite, and I haven't been able to figure out how to use them without buying into the whole AST way of doing things, which I don't always understand.
Your example
There clearly needs to be
extern char MasterSkipFile[];

in a .h file somewhere, and you can then link against a suitable .o.
The conditional inclusion of the "right set of .h files for the platform" is something I would handle by trying to stick to ANSI C when possible, and when not possible, defining a compatibility layer in a platform-specific .h file.  As it is, I can't tell what names the #includes are trying to import, so I can't give more specific advice.