Q:

Ubuntu Server ethernet configuration naming error

I just installed the Ubuntu Server 16.04.1 LTS and wanted to configure my ethernet connection. My /etc/network/interfaces file looks like this:
source /etc/network/interfaces.d/*
auto lo
iface lo inet loopback

auth eth0
iface eth0 inet static
address 192.168.0.99 *whatever my ip is*
netmask 255.255.255.0
network 192.168.0.0
broadcast 192.168.0.255
gateway 192.168.0.999 *my router's ip*
post-up iptables-restore < /etc/iptables.up.rules
dns-nameservers *my router's ip* 8.8.8.8

This gave my ethernet connections weird names such as emp2s0, virbr0 etc.
Based on this post however biosdevname doesn't exist in my installation neither are any rules in /etc/udev/rules.d. What should I do to get an ethernet connection?

A:

The easiest way for you now is simply replacing eth0 with the actual name Ubuntu gave your device (both lines). You mention emp2s0, but I suspect it should be enp2s0.
Also, the auth should be auto
If you really dislike the new naming scheme, you can follow the many different howto's, but this will solve your immediate issue.
As clarification, this naming scheme is new in Ubuntu (since somewhere in 15) and doesn't occur on machines updated from 14, only on new installs


Q:

Jtable issue when adding columns

This is kinda a silly question,  but I'm beggining with java swing and have been doing kinda great, but I really can't make a JTable appear in my form, so far a blank square appears but no columns at all, here's a snippet:
DefaultTableModel modelo = new DefaultTableModel();
modelo.setColumnCount(1);
tblTrans = new JTable(modelo);
modelo.addColumn("Prueba");
tblTrans.revalidate();
tblTrans.setBounds(316, 47, 248, 243);
contentPane.add(tblTrans);

Here's the complete code in case you need it:
package mx.adk.grafos;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.DefaultListModel;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.ListSelectionModel;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JList;
import javax.swing.JTable;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Set;
import java.util.TreeSet;

public class GUI extends JFrame implements ActionListener {

    private JPanel contentPane;
    private JTextField txtEstados;
    private JTextField txtLenguaje;
    private JTextField txtFinal;
    private JTable tblTrans;
    private JList lstEstados;
    private JList lstLenguaje;

    DefaultListModel listaEstados;
    TreeSet<String> setEstados = new TreeSet<String>();

    DefaultListModel listaLenguaje;
    TreeSet<Character> setLenguaje = new TreeSet<Character>();

    /*
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    GUI frame = new GUI();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    */

    public void actionPerformed(ActionEvent e) {
        String comando = e.getActionCommand();
        if(comando.equalsIgnoreCase("btnAEstados")){
            String tmp = txtEstados.getText();
            if(setEstados.add(tmp)){
                listaEstados.addElement(tmp);
            }
            return;
        }
        if(comando.equalsIgnoreCase("btneestados")){
            String tmp = (String) lstEstados.getSelectedValue();
            setEstados.remove(tmp);
            listaEstados.removeElement(tmp);
        }
        if(comando.equalsIgnoreCase("btnALenguaje")){
            char tmp = txtLenguaje.getText().charAt(0);
            if(setLenguaje.add(tmp)){
                listaLenguaje.addElement(tmp);
            }
            return;
        }
        if(comando.equalsIgnoreCase("btnelenguaje")){
            char tmp = (char) lstLenguaje.getSelectedValue().toString().charAt(0);
            setLenguaje.remove(tmp);
            listaLenguaje.removeElement(tmp);
        }
    }

    public GUI() {
        setTitle("Automata finito no deterministico");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 599, 368);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        txtEstados = new JTextField();
        txtEstados.setBounds(26, 82, 72, 28);
        contentPane.add(txtEstados);
        txtEstados.setColumns(10);

        JButton btnAEstados = new JButton(">>");
        btnAEstados.setBounds(103, 69, 51, 29);
        contentPane.add(btnAEstados);
        btnAEstados.addActionListener(this);
        btnAEstados.setActionCommand("btnAEstados");

        listaEstados = new DefaultListModel();
        lstEstados = new JList(listaEstados);
        lstEstados.setBounds(154, 46, 105, 109);
        contentPane.add(lstEstados);
        lstEstados.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        JLabel lblEstados = new JLabel("Estados");
        lblEstados.setBounds(83, 19, 59, 16);
        contentPane.add(lblEstados);

        JButton btnEEstados = new JButton("<<");
        btnEEstados.setBounds(103, 96, 51, 29);
        contentPane.add(btnEEstados);
        btnEEstados.addActionListener(this);
        btnEEstados.setActionCommand("btnEEstados");

        JButton btnELenguaje = new JButton("<<");
        btnELenguaje.setBounds(103, 231, 51, 29);
        contentPane.add(btnELenguaje);
        btnELenguaje.addActionListener(this);
        btnELenguaje.setActionCommand("btnELenguaje");

        JButton btnALenguaje = new JButton(">>");
        btnALenguaje.setBounds(103, 204, 51, 29);
        contentPane.add(btnALenguaje);
        btnALenguaje.addActionListener(this);
        btnALenguaje.setActionCommand("btnALenguaje");

        txtLenguaje = new JTextField();
        txtLenguaje.setColumns(10);
        txtLenguaje.setBounds(26, 217, 72, 28);
        contentPane.add(txtLenguaje);

        listaLenguaje = new DefaultListModel();
        lstLenguaje = new JList(listaLenguaje);
        lstLenguaje.setBounds(154, 181, 105, 109);
        contentPane.add(lstLenguaje);
        lstLenguaje.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        JLabel lblLenguaje = new JLabel("Lenguaje");
        lblLenguaje.setBounds(95, 161, 59, 16);
        contentPane.add(lblLenguaje);

        txtFinal = new JTextField();
        txtFinal.setText("QFinal");
        txtFinal.setColumns(10);
        txtFinal.setBounds(26, 298, 72, 28);
        contentPane.add(txtFinal);

        DefaultTableModel modelo = new DefaultTableModel();
        modelo.setColumnCount(1);
        tblTrans = new JTable(modelo);
        modelo.addColumn("Prueba");
        tblTrans.revalidate();
        tblTrans.setBounds(316, 47, 248, 243);
        contentPane.add(tblTrans);

        JLabel lblTransiciones = new JLabel("Transiciones");
        lblTransiciones.setBounds(394, 19, 89, 16);
        contentPane.add(lblTransiciones);

        JButton btnAceptar = new JButton("Aceptar");
        btnAceptar.setBounds(476, 311, 117, 29);
        contentPane.add(btnAceptar);
        btnAceptar.addActionListener(this);
        btnAceptar.setActionCommand("btnAceptar");
    }
}

What I want to accomplish is to add a column for each "Estado" given, the program is about non deterministic automata, and a row for each "Lenguaje" given so I can make the transition matrix, I do know how to make this each time the buttons are pressed, but it appears like the column is being added but it's not visible at all, just a blank square.
Corrections suggested:
DefaultTableModel modelo = new DefaultTableModel();
        modelo.setColumnCount(1);
        tblTrans = new JTable(modelo);
        panel.add(tblTrans);
        panel.setBounds(316, 47, 248, 243);
        modelo.addColumn("Test");
        tblTrans.revalidate();
        contentPane.add(panel);

A:

I was right about the scroll pane. This is working for me:
    DefaultTableModel modelo = new DefaultTableModel();
    modelo.setColumnCount(1);
    modelo.addColumn("Prueba");
    tblTrans = new JTable(modelo);
    JScrollPane sPane = new JScrollPane(tblTrans);
    sPane.setBounds(316, 47, 248, 243);
    contentPane.add(sPane);


Q:

Encounter Error regarding javascript and JSON

i am learning JSON. i just write a simple code which is not working and also not giving any error when clicking on button. so please help me to catch the error. here is my html.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script type="text/javascript" language="javascript">
        function GetJSON()
        {
            alert("pp");

            var moviereviewtext = "{"title": "Friday the 13th", "year": 1980, "reviews":
            [{"reviewer": "Pam", "stars": 3, "text": "Pretty good, but could have used more Jason"},
            {"reviewer": "Alice", "stars": 4, "text": "The end was good, but a little unsettling"}]}";
            var jsonobj = eval("(" + moviereviewtext + ")");

            var reviewername = jsonobj.reviews[0].reviewer;
            var numberstars = jsonobj.reviews[0].stars;
            var reviewerthoughts = jsonobj.reviews[0].text;

            alert(reviewername);
            alert(numberstars);
            alert(reviewerthoughts);
        }
    </script>
</head>
<body >
    <form id="form1" runat="server">
        <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="GetJSON();return false;" />
    </form>
</body>
</html>

A:

This is browser dependent but with a few small changes:
// Use single quote to surround and line continuations to support new lines.
var movieReviewText =
    '{"title": "Friday the 13th", "year": 1980, "reviews":\
    [{"reviewer": "Pam", "stars": 3, "text": "Pretty good, but could have used more Jason"},\
    {"reviewer": "Alice", "stars": 4, "text": "The end was good, but a little unsettling"}]}';

var obj = JSON.parse(movieReviewText); // This should be available IE8+, FF3+

Also, take note that a function that starts with a capital letter is by convention considered a constructor. The name of your function also could be made better as the function does not actually get JSON. Maybe something like this?
function parseMovieReview() {

}


Q:

How to filter for last working day in Jira JQL

We use Jira Agile with a "Daily Scrum" board which filters for issues due in the last day. This will show us the issues we should have fixed yesterday and the issues we will fix today. This works great, except for Mondays.
On Monday we want to see the issues that had a due date of friday or duedate of today. How can I achieve this using JQL? It seems JQL doesn't support IF(), correct?
If it does, we might find a way using a compare like now() == startOfWeek().

A:

We have a similar issue on Monday morning where we need to review issues created over the last friday and the weekend rather than just the past 24 hours. You can't test whether today is Monday, but you can infer it:
AND (
(created >= startOfDay("-3d") AND created < startOfDay("-2d") AND created >= startOfWeek("-2d") AND created < startOfWeek("-1d"))
OR
(created >= startOfDay("-2d") AND created < startOfDay("-1d") AND created >= startOfWeek("-1d") AND created < startOfWeek())
OR
(created >= startOfDay("-1d") AND created < startOfDay() AND created >= startOfWeek() AND created < startOfWeek("+1d"))
OR
created >= -24.5h)

This basically includes things from Friday if Friday was 3 days ago, Saturday if Saturday was 2 days ago and Sunday was yesterday.
In your case you want to show where:

duedate is today
OR
duedate is yesterday (startOfDay("-1d")...startOfDay()) AND duedate is between Mon-Thurs (startOfWeek("+1d") .. startOfWeek("+4d"))
OR
duedate is last Friday (startOfWeek("-2d")) AND duedate is 3 days ago/today is Monday (startOfDay("-3d")...startOfDay("-2d"))

Note: This assumes the default US locale where startOfWeek() is Sunday
duedate >= startOfDay() OR
(duedate >= startOfDay("-1d") AND duedate < startOfDay() AND duedate >= startOfWeek("+1d") AND duedate < startOfWeek("+4d")) OR
(duedate >= startOfWeek("-2d") AND duedate < startOfWeek("-1d") AND duedate >= startOfDay("-3d") AND duedate < startOfDay("-2d"))


Q:

AVPlayer : How to handle network interruptions

When using AVPlayer to play audio from an url it will
discontinue to play when for example disconnecting from wifi.
[player play];

Does not resume the AVPlayer
player.rate // Value is 1.0

player.currentItem.isPlaybackLikelyToKeepUp // Value is YES

player.status // Value is AVPlayerStatusReadyToPlay

player.error // Value is nil

But the player is not playing any audio.
How do I handle a disconnect from AVPlayer, for reconnecting the AVPlayer
and start playing again?

A:

In order to handle network changes, you have to add an observer for AVPlayerItemFailedToPlayToEndTimeNotification.
- (void) playURL:(NSURL *)url
{
    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:url];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerItemFailedToPlayToEndTime:) name:AVPlayerItemFailedToPlayToEndTimeNotification object:playerItem];
    self.player = [AVPlayer playerWithPlayerItem:playerItem];
    [self.player play];
}

- (void) playerItemFailedToPlayToEndTime:(NSNotification *)notification
{
    NSError *error = notification.userInfo[AVPlayerItemFailedToPlayToEndTimeErrorKey];
    // Handle error ...
}

A:

You should add observer for AVPlayerItemPlaybackStalledNotification.
AVPlayerItemFailedToPlayToEndTimeNotification has no value for me on this problem.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackStalled:) name:AVPlayerItemPlaybackStalledNotification object:trackItem];

As the doc says, file-based playback does not continue if necessary streaming media wasn’t delivered in a timely fashion over a network.

The notification’s object is the AVPlayerItem instance whose playback
  was unable to continue because the necessary streaming media wasn’t
  delivered in a timely fashion over a network. Playback of streaming
  media continues once a sufficient amount of data is delivered.
  File-based playback does not continue.

This explained why AVPlayer can resume HLS streams after network switch, but cannot do the same if I use AVPlayer to play TuneIn resources which is file-based.
Then the answer becomes simple.
- (void)playbackStalled:(NSNotification *)notification {
    if ([self isFileBased:streamUri]) {
        // Restart playback
        NSURL *url = [NSURL URLWithString:streamUri];
        AVPlayerItem *trackItem = [AVPlayerItem playerItemWithURL:url];
        AVPlayer *mediaPlayer = [AVPlayer playerWithPlayerItem:trackItem];
        [self registerObservers:trackItem player:mediaPlayer];
        [mediaPlayer play];
    }
}

Further reading on discussion of automaticallyWaitsToMinimizeStalling.


Q:

A question about differentiability

Does there exist a continuous function $f:\mathbb{R}\to\mathbb{R}$ so that $f$ is differentiable exactly at one point?

A:

Yes. Idea: choose a function which is continuous but nowhere differentiable. Then multiply it with $x^2$, say.


Q:

background Images on pageViewController overlap in reverse

I have a pageViewController that shows a background image per the index.  It works fine swiping left to right (forward), but when you swipe in reverse the background images overlap each other.  Before I implemented the background image, the UI on each VC worked fine forward and reverse, so I know it's the background image.  Also if I change to page curl instead of scroll in my storyboard it works fine in reverse, just doesn't work for scroll.  This apparently is a known bug (Removing a view controller from UIPageViewController) however I need a solution in Swift.
pageviewController:
 func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {

        guard
            let currentPageViewController = viewController as? SinglePageViewController,
            let currentIndex = indexOfForecast(currentPageViewController.forecast!) as? Int where currentIndex != 0 else { return nil }  //fixed bug where index was -0 only on scroll

        return viewControllerAtIndex(currentIndex - 1)

    }

    func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
        guard
            let lastForecast = forecasts?.last,
            let currentPageViewController = viewController as? SinglePageViewController, currentForecast = currentPageViewController.forecast,
            let currentIndex = indexOfForecast(currentForecast) as? Int where currentIndex != forecasts?.indexOf(lastForecast) else {return nil}

            return viewControllerAtIndex(currentIndex + 1)

    }

 func viewControllerAtIndex(index: Int) -> UIViewController? {
        if let forecast = forecasts?[index] {
            let time = forecastTimes[index]
            let imageURL = conditionsIcons[index]
            let backgroundImageName = backgroundImageNames.names[index]
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let vc = storyboard.instantiateViewControllerWithIdentifier("SinglePageViewController") as! SinglePageViewController
            vc.forecast = forecast
            vc.time = time
            vc.imageURL = imageURL
            vc.backgroundImageName = backgroundImageName

            return vc
        }
        return nil
    }

    func showVC() {
        if let firstVC = viewControllerAtIndex(0) {
            busyAlertController.dismiss()
            let viewControllers = [firstVC]
            self.setViewControllers(viewControllers, direction: UIPageViewControllerNavigationDirection.Forward, animated: false, completion: nil)
        }
    }

singlePageViewController:
override func viewDidLoad() {
        super.viewDidLoad()

        backgroundImage = UIImageView(image: UIImage(named: backgroundImageName!))
        backgroundImage.contentMode = UIViewContentMode.ScaleAspectFill
        self.view.insertSubview(backgroundImage, atIndex: 0)
}

A:

The answer to this problem was so simple, just set clipsToBounds on the image to true


Q:

How do I find the set of regions that are fully enclosed by a color?

How do I get all areas surrounded by a certain color in a multidimensional array?
For example, this map has three regions that are fully enclosed by red tiles. They are highlighted enclosed in pink.

I'd want the algorithm to return three regions, with the positions of the tiles inside them.
How can I do this?

A:

I would use this algorithm (in pseudocode):
iterate your whole playing field to create a list of all non-red tiles called LIST
while LIST has entries
    flood-fill from the first entry of LIST
    remove the results of the flood-fill from LIST
    if no result of the flood-fill is at the edge of the map
        add floodfill result to surrounded areas


Q:

Can I simply 'read' a file that is in use?

I am trying to use a StreamReader to read a file, but it is always in use by another process so I get this error:

The process cannot access the file
  '\arfjwknasgmed17\C$\FLAG
  CONDITION\CP-ARFJN-FLAG.XLS' because
  it is being used by another process.

Is there a way I can read this without copying it?  Or is that my only option?

A:

You can read the file only if the program that opened the file first specified read sharing rights on that file.
If the file does indeed have no read sharing rights though, you wouldn't be able to copy it in the first place.
You may not be able to access a file if you are specifying a sharing right that conflicts with the sharing right of a program that already has the file opened.  For example you can't grant write access if the program that already has it opened isn't granting write access.
If the program that opened the file in the first place supports Volume Shadow Copy (VSS), you can also use VSS to gain access to the file.
There are commercial software drivers that allow you to access such files, even when they are in use.  You used to be able to get Open File Manager by St-Bernards, and you can also  use File Access Manager (FAM) by VisionWorks Solutions Inc.  These drivers are typically OEM'ed to backup software companies for inclusion in their products.
VSS works by telling the program that has the file opened already that another program would like to read from the file.  VSS then does a copy of the file and lets you read from this copy.   VSS does not work for legacy applications.
FAM transparently works for legacy and non-legacy programs alike by specifying an 'allowed list' of applications that can access exclusively opened and locked files.  Only programs in this list are allowed access to these files.  When a file is being opened, it goes into cache mode so that you will obtain a copy of the file as it was when the 'backup/open' of the file started.   At this point the program that originally opened the file sees the file as it actually is, and the second program in the allowed list, sees the file as it was when the 'open/backup' of the file happened.  This ensures consistency of the file.


Q:

connection to aspx page from android?

I have developed an application get location but i need to save it to server using aspx webpage.
I have created tables on the webpage and i need to save these lat,long to the webpagepage using the unique id as imei?
I have created a table with imei, latlong, datetime
aspx name /http://Log.aspx/
can anybody help me please I have searched many but I couldn't understand.
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        {
            // initialize location manager

            manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

            // check if GPS is enabled
            // else switch on gps

            if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                Intent intent = new Intent(
                        "android.location.GPS_ENABLED_CHANGE");
                intent.putExtra("enabled", true);
                this.sendBroadcast(intent);

                String provider = Settings.Secure.getString(
                        getContentResolver(),
                        Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
                if (!provider.contains("gps")) { // if gps is disabled
                    final Intent poke = new Intent();
                    poke.setClassName("com.android.settings",
                            "com.android.settings.widget.SettingsAppWidgetProvider");
                    poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
                    poke.setData(Uri.parse("3"));
                    this.sendBroadcast(poke);

                }
            }

            else {

                // get a location provider from location manager
                // empty criteria searches through all providers and returns the
                // best one

                String providerName = manager.getBestProvider(new Criteria(),
                        true);
                Location location = manager.getLastKnownLocation(providerName);

                TextView tv = (TextView) findViewById(R.id.locationResults);
                if (location != null) {
                    tv.setText(location.getLatitude() + " latitude, "
                            + location.getLongitude() + " longitude");

                    Intent intent = new Intent(
                            "android.location.GPS_ENABLED_CHANGE");
                    intent.putExtra("disabled", false);
                    this.sendBroadcast(intent);

                    String provider = Settings.Secure.getString(
                            getContentResolver(),
                            Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
                    if (provider.contains("gps")) { // if gps is enabled
                        final Intent poke = new Intent();
                        poke.setClassName("com.android.settings",
                                "com.android.settings.widget.SettingsAppWidgetProvider");
                        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
                        poke.setData(Uri.parse("3"));
                        this.sendBroadcast(poke);

                    }

                }

                else {

                    // get cell id
                    TelephonyManager mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
                    GsmCellLocation loc = (GsmCellLocation) mTelephonyManager
                            .getCellLocation();
                    String networkOperator = mTelephonyManager
                            .getNetworkOperator();

                    Log.d("CID", Integer.toString(loc.getCid()));
                    Log.d("LAC", Integer.toString(loc.getLac()));
                    int mcc = Integer.parseInt(networkOperator.substring(0, 3));
                    int mnc = Integer.parseInt(networkOperator.substring(3));

                    TextView tv1 = (TextView) findViewById(R.id.locationResults);
                    if (loc != null) {
                        tv.setText("Cell ID: " + loc.getCid() + " , " + "Lac: "
                                + loc.getLac() + "mcc : " + mcc + "mnc : "
                                + mnc);
                        // to write it to file
                        appendData("Cell ID: " + loc.getCid() + " , " + "Lac: "
                                + loc.getLac() + "mcc : " + mcc + "mnc : "
                                + mnc);
                    }

                }

                manager.requestLocationUpdates(providerName, 1000 * 60 * 15, 0,
                        this);
            }
        }
    }

    // Find the closest Bart Station
    public String findClosestBart(Location loc) {
        double lat = loc.getLatitude();
        double lon = loc.getLongitude();

        double curStatLat = 0;
        double curStatLon = 0;
        double shortestDistSoFar = Double.POSITIVE_INFINITY;
        double curDist;
        String curStat = null;
        String closestStat = null;

        // sort through all the stations
        // write some sort of for loop using the API.

        curDist = Math.sqrt(((lat - curStatLat) * (lat - curStatLat))
                + ((lon - curStatLon) * (lon - curStatLon)));
        if (curDist < shortestDistSoFar) {
            closestStat = curStat;
        }

        return closestStat;

    }

    @Override
    public void onLocationChanged(Location location) {
        TextView tv = (TextView) findViewById(R.id.locationResults);
        if (location != null) {
            tv.setText(location.getLatitude() + " latitude, "
                    + location.getLongitude() + " longitude");
            // to write the file..
            appendData(location.getLatitude() + " latitude, "
                    + location.getLongitude() + " longitude");
        } else {
            tv.setText("Problem getting gps NETWORK ID : ");

        }
    }

A:

I wrote a WS few months back like this:
    <%@ WebService   Language="VBScript" Class="DataIns" %>

Imports System
Imports System.Web.Services
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Data
Imports System.Globalization

<WebService(Namespace:="http://www.mysite.org/webservices/")> Public Class DataIns :Inherits WebService

<WebMethod()> Public Function devIns (ByVal dm As String) As String

    Dim strArr() As String
    Dim rtnVal As String
    strArr = dm.split("^")

    Dim connection As   SqlConnection
    Dim connection1 As  SqlConnection
    Dim connection2 As  SqlConnection
    Dim cmd As  SqlCommand
    Dim connectionString As String
    connectionString = ConfigurationManager.ConnectionStrings("sqlsds").ConnectionString
    connection = New SqlConnection(connectionString)

       Dim cmdtrans As SqlCommand
       Dim cmdCheck As SqlCommand

       Dim result as String
       Dim sqltrans as String
       Dim notes as String
       Dim notes1 As String

       sqltrans= "select dbo.fnCheckBlackList(@p_imei)"
       cmdtrans=new sqlcommand(sqltrans,connection)
       cmdtrans.Parameters.AddWithValue("@p_imei",strArr(0))
       Try
           connection.Open()
           notes=cmdtrans.ExecuteScalar()

       Catch ex As Exception
          notes = ex.Message
       Finally
          connection.Close()
       End Try

       notes = If(IsDBNull(notes),"","")

       if notes.Trim().Equals("TIMEUP") then

            Context.Response.Output.Write("Save Completed Wipeout")
            Context.Response.End()
             return string.Empty
        else
            connection1 = New SqlConnection(connectionString)
            result = "select dbo.fnCheckImeiDateWise(@p_imei)"
            cmdCheck=new sqlcommand(result,connection1)
            cmdCheck.Parameters.AddWithValue("@p_imei",strArr(0))

            Try
                       connection1.Open()
                       notes1=cmdCheck.ExecuteScalar()
            Catch ex As Exception
                      notes1 = ex.Message
            Finally
                connection1.close()
            End Try

            if notes1.Trim().Equals("FINE") then

                connection2 = New SqlConnection(connectionString)

                cmd = New SqlCommand("dbo.spInsertDeviceData", connection2)
                cmd.CommandType = CommandType.StoredProcedure

                cmd.Parameters.AddWithValue("@p_imei", strArr(0))
                cmd.Parameters.AddWithValue("@p_location", strArr(1))
                cmd.Parameters.AddWithValue("@p_aic", Integer.Parse(strArr(2)))
                cmd.Parameters.AddWithValue("@p_adc", Integer.Parse(strArr(3)))
                cmd.Parameters.AddWithValue("@p_ail", strArr(4))
                cmd.Parameters.AddWithValue("@p_adl", strArr(5))
                cmd.Parameters.AddWithValue("@p_tsss", Double.Parse(strArr(6)))
                cmd.Parameters.AddWithValue("@p_ts", Double.Parse(strArr(7)))
                cmd.Parameters.AddWithValue("@p_tsgp", Double.Parse(strArr(8)))
                cmd.Parameters.AddWithValue("@p_tvpc", Double.Parse(strArr(9)))

                Try

                  connection2.Open()
                  rtnVal = cmd.ExecuteNonQuery()

                Catch ex As Exception
                  rtnVal = ex.Message

                Finally
                    connection2.Close()
                End Try
                'Context.Response.Output.Write(rtnVal)

                Dim  parameterString As String

                  Dim dow2 As String

                parameterString = ConfigurationManager.AppSettings("FREQUENCY")
                parameterString = parameterString + "|"

                parameterString = parameterString + getNewTime(ConfigurationManager.AppSettings("UPDATEAT1"))
                parameterString = parameterString + "|"
                parameterString = parameterString + ConfigurationManager.AppSettings("DAYOFWEEK1")

                dow2 = ConfigurationManager.AppSettings("DAYOFWEEK2")

                if String.IsNullOrEmpty(dow2) then

                else

                    parameterString = parameterString +"*"
                    parameterString = parameterString + dow2

                end if
                parameterString = parameterString + "|"
                parameterString = parameterString  + ConfigurationManager.AppSettings("DAYOFMONTH")

                Context.Response.Output.Write("Save Completed" + "|"+  parameterString)
                Context.Response.End()
                return string.Empty
            else
                Context.Response.Output.Write("ERROR")
                Context.Response.End()
                return string.Empty
            End If
    End If

end function

end class

and this was called like
http://www.mysite.org/DataIns.asmx/dIns?dm=<data-separated=by-^>


Q:

how to filter out non-numeric values

I have a table (in a RethinkDB database) that has a bunch of documents with the field VIN0. This field almost always stores numbers, as intended.
I had some data corruption recently where there are some strings in place of numbers for the field VIN0. Queries I was using to manipulate this data now return the error: "e: Expected type NUMBER but found STRING in:"
I'd like to filter for the strings, but I can't seem to find them. Is there a way to use something like Number.isInteger() to filter out these items within RethinkDB?
Thanks!

A:

You can use typeOf to find type of a field, or a element. Let's say you want to filter document with VIN0 is a number
r.db('db').table('table').filter(r.row('VIN0').typeOf().eq('NUMBER'))

You can also try to correct problem by using coereTo to convert string to number.
r.db('db').table('table')
  .filter(r.row('VIN0').typeOf().eq('STRING'))
  .update({VIN0: r.row('VIN0').coerceTo('NUMBER')})

Hope this helps.


Q:

CSS Access ID through class

I saw a nice video on youtube about making transional gallery (http://www.youtube.com/watch?v=4sVTWY608go). I tried to do the slider right..
Now, I want to make a change. I want to give the first image a different width say(530px) and the other images(40px). Then when a user hover on any other images(not img no.1) the width of image no.1 change to be like(40px) and the hovering one (530px). how can I do that.
Here is my code:
HTML

=========
CSS
===SET THE WIDTH OF THE IMAGES IN a
.divSlider li a{
    width: 30px;
    height: 500px;
    text-decoration: none;
    color: black;
    display: block;
    border: 2px solid gray;
    border-radius: 5px;
}

=== image no.1 width
#slideImg1 a{
    width: 540px;
}

=== when hovering on all the images except image no.1
.divSlider li a:hover{
    width: 520px;
}

=== here is the problem I don't know how can I change it's width when user hover on other images
#slideImg1 li a:hover{
    width: 20px;
}

Any help
TIA

A:

If I understand your question correctly, here is one possible solution:
Demo Fiddle
The trick here is to set the CSS :hover to key off of the wrapping element, and then overwrite it with more specificity.
CSS:
/* initial setup */
li{ display: inline-block;}

a {
    display: block;
    width: 40px;
    height: 150px;
    background: url(http://www.placehold.it/150x150) no-repeat;
    -webkit-transition: .3s;
    transition: .3s;
}
#slideImg1 a { width: 150px;}

/* hover states */
.divSlider:hover #slideImg1 a {width: 50px;}

.divSlider ul #slideImg1 a:hover {width: 150px;}

a:hover { width: 150px;}


Q:

How can I put text within horizontal bar chart data points using Highcharts as well as adding text underneath each data point? Example below:

Here is what I am going for, disregard the pointer on top.

A:

You can use the annotations module:
annotations: [{
    labels: [{
        borderRadius: 0,
        padding: 20,
        backgroundColor: '#fff',
        style: {
            color: '#000'
        },
        point: {
            xAxis: 0,
            yAxis: 0,
            x: 0,
            y: 15
        },
        y: -130,
        text: 'Col de la Joux'
    }]
}]

Live demo: http://jsfiddle.net/BlackLabel/eb9k5o7m/
API Reference: https://api.highcharts.com/highcharts/annotations
Docs: https://www.highcharts.com/docs/advanced-chart-features/annotations-module


Q:

JTextField randomly not appearing in program even when code is not changed

I'm trying to write a small UI program with Swing. I need to have a few textfields, but defining a new textfield or textarea (I don't even have to add it to a Frame) will randomly prevent themselves and anything that is added after them in the code from appearing onscreen. I can recompile the same code without making any changes and maybe 1/3 of the time it will work properly. What's causing this problem and is there any way I can change it? I'll paste the code bellow:
import java.awt.*;
import javax.swing.*;

public class ThisApp
{
    public static void main(String [] Args)
    {
        new ThisUI();
    }
}

class ThisUI extends JFrame //implements ActionListener
{
    public ThisUI()
    {
        setTitle("ThisApp - Best in the business");
        setResizable(false);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(300, 200);
        setLayout(new GridLayout(2,1));

        JButton cat = new JButton("Cat");

        this.add(new JButton("Button"));
        this.add(new JTextField("CAT CAT",10));
    }
}

Thanks in advanced for any help!

A:

The problem is you add components to the frame AFTER the frame is visible and don't invoke the layout manager so all the components have a size of 0 so there is nothing to paint.
The frame must be made visible AFTER all the components have been added to the frame.
So the structure of your code should be something like:
setTitle("ThisApp - Best in the business");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new GridLayout(2,1));

JButton cat = new JButton("Cat");
this.add(new JButton("Button"));
this.add(new JTextField("CAT CAT",10));

setSize(300, 200);
setLocationRelativeTo( null );
setVisible(true);


Q:

Is the address of local variable freed?

int *intAddr(){
  int i = 16;
  return &i;
}

char *charAddr(){
  char A = 'a';
  return &A;
}

Then I test these two function by
int *intaddr = intAddr();printf("%d\n", *intaddr);
char *charaddr = charAddr();printf(charaddr);

But the result is that only 16 not 'a'. When the funcion intAddr() is over, the variable i is destroyed. Why the *intaddr can get 16?

A:

You SHOULD NOT return a pointer to a variable that's function local.  That's UNDEFINED BEHAVIOUR. DO NOT DO IT. EVER!!
The reason is that your local variable, i in this case, is destroyed when your function exits, so you pointer after your function exit will point to memory that contains at most junk.


Q:

Error while trying Undo Redo

I am trying to do undo/redo on multidocument interface but facing following error:
 no matching function for call to 'qobject_cast(QMdiSubWindow*&)'
       return qobject_cast<CadGraphicsView *>(activeSubWindow);

My code to above function is as follows:
 MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
    {
        m_undoGroup = new QUndoGroup(this);
        QAction *undoAction = m_undoGroup->createUndoAction(this);
        undoAction->setShortcut(QKeySequence::Undo);
        QAction *redoAction = m_undoGroup->createRedoAction(this);
        redoAction->setShortcut(QKeySequence::Redo);
        menuEdit->insertAction(menuEdit->actions().at(0), undoAction);
        menuEdit->insertAction(undoAction, redoAction);
        menuEdit->addAction(undoAction);
        menuEdit->addAction(redoAction);
        updateActions();
    }
              void MainWindow::setCurrentDocument()
            {
               mdiArea->currentSubWindow();
            }

            void MainWindow::addnewFile()
            {
                m_undoGroup->addStack(view->scene->undoStack());
                connect(view->scene->undoStack(), SIGNAL(indexChanged(int)), this, SLOT(updateActions()));
                connect(view->scene->undoStack(), SIGNAL(cleanChanged(bool)), this, SLOT(updateActions()));
            }

            void MainWindow::updateActions()
            {
                CadGraphicsScene *scene = currentDocument();
                m_undoGroup->setActiveStack(scene == 0 ? 0 : scene->undoStack());
            }

         CadGraphicsView *MainWindow::currentDocument() const
         {
         if (QMdiSubWindow *activeSubWindow = mdiArea->currentSubWindow())
              return qobject_cast<CadGraphicsView *>(activeSubWindow);

            return 0;
        }

        void MainWindow::newFile()
        {
            // creates a new file
            createMdiView();

            view->newFile();
            addnewFile();
            curFileName = tr("Document %1").arg(++fileNumber);
            view->setWindowTitle(curFileName);
            view->scene->installEventFilter(this);
            view->show();

            isEntitySelected = false;
        }

        CadGraphicsView *MainWindow::createMdiView()
        {
            // creates a graphicsView and add it to the MDI window
            view = new CadGraphicsView;
            QMdiSubWindow *w = mdiArea->addSubWindow(view);
            mdiArea->setActiveSubWindow(w);
            windowViewList.append(qMakePair(w, view));

return view;
        }
Can you please help me to solve the error. I have added the basic idea how it is working.

A:

Got the solution to my problem. I need to change the currentDocument function as follows:
CadGraphicsView *MainWindow::currentDocument() const
{
    return qobject_cast<CadGraphicsView *>(mdiArea->parentWidget());
}


Q:

Using Python PyCrypto with Perl Crypt::CBC

On one side I have a texts encrypted/decrypted with Perl's Crypt::CBC
my $key = 'key to the gates';
my $cipher = Crypt::CBC->new(
    -key    => $key,
    -cipher => 'Blowfish',
    -salt   => '12341234'
);

On the other side I have Python's PyCrypto that I need to decode the data from Perl, but also send text that the Perl cipher can read given the encryption.
I have the key from the Perl program, and encrypt_hex:ed passphrases from Perl sent to the Python system.
But Python seems to absolutely want to have the IV to do its job
cipher = Blowfish.new( self.key, Blowfish.MODE_CBC, self.iv )
        return hexlify(cipher.encrypt(raw))

However, the Crypt::CBC documnetation seems to indicate that the IV is there already

"salt" -- Combine the passphrase with an 8-byte random value to
            generate both the block cipher key and the IV from the
            provided passphrase. The salt will be appended to the
            beginning of the data stream allowing decryption to
            regenerate both the key and IV given the correct
            passphrase.

Is there any way to extract the IV from the key/passphrase via PyCrypto? Or does IV have to be sent separately in some way?
This might be a naive question but I don't work with this every day.
I know I can get the IV from the Perl side, but I really want to extract it on Python side if possible.

A:

Crypt::CBC claims OpenSSL compatibility. This means that it performs an OpenSSL specific BytesToKey password-based key derivation function (PBKDF). During this derivation the IV is calculated as well. So the key you've provided for Crypt::CBC is actually treated as a password.
You have to lookup an implementation of EVP_BytesToKey and integrate that into your program. You can start with this code from GitHub:
def bytes_to_key(data, salt="12345678"):
    # Simplified version of M2Crypto.m2.bytes_to_key(). Based on:
    # https://github.com/ajmirsky/M2Crypto/blob/master/M2Crypto/EVP.py#L105
    # http://stackoverflow.com/questions/8008253/c-sharp-version-of-openssl-evp-bytestokey-method
    assert len(salt) == 8, len(salt)
    data += salt
    key = md5(data).digest()
    key += md5(key + data).digest()
    return key

Then take the first bytes for the key, and the next 8 bytes for the IV. But note the following statement for Crypt:CBC:

If -keysize is not specified, then Crypt::CBC will use the maximum length Blowfish key size of 56 bytes (448 bits).

So you may need a few more key += md5(key + data).digest() calls as the md5 output is only 128 bits.


Q:

finding value of dynamically created combobox

I'm using VS2010,C#, I have a table that its data should be created dynamically (from an SQL server table), I have to add a combobox (with 3 items) to one of the columns, this combo box is also created dynamically, then I give each combo a unique ID, it has autopost back set to off and also enableviewstate and viewstatemode to true and enabled, when users changes values for some combo boxes (each row has a combox), and then presses the submit button, I want to have current state of my comboboxes but their selectedindex is 0 so I cannot use them, what should I do? what are my options? (I find each combobox using FindControl and unique ID of the combobox)
thanks

A:

Please find below answer for your above questions

First of all you need to register onchange event of combobox in Javascript while create dynamic combobox.
Put one hidden field on page
And then put the code in onchange event, set the value in hidden field using Clientid from onchange event and then get the value of hidden field from server side.


Q:

Does real characteristic function imply even density

Does real characteristic function imply even density?

So, I was wondering over this. I know that when a characteristic function is real, it is even. Also, I know this result when the characteristic function is absolutely integrable, by the inversion formula. But can we generalize it?
1) Does real characteristic function imply that density exists and it is even?
2) How about the case when we know that density exists? Can we conclude about evenness?
Please prove or provide a counterexample.

A:

A characteristic function is real iff the distribution is symmetric. So a random variable taking values $\pm 1$ with probability $\frac  1 2$ each has real characteristic function but it does not have  density. If the characteristic function of a random variable $X$ is real and there is density $f$ then $f(-x)=f(x)$ almost everywhere  because $f(-x)$ is the density of $-X$ and $-X$ has same distribution as $X$.


Q:

Install new NANO (2.4) using BREW but still uses old versions (symbolic link not created?)

I installed NANO 2.4 but my OS X is still using 2.0. I beleive its something to do with the symbolic link that wasn't created.
I first tapped the homebrew/dupes so i could brew install nano
~  brew tap homebrew/dupes
==> Tapping homebrew/dupes

~  brew install nano
==> Installing nano from homebrew/homebrew-dupes

If I do a
which nano

I get
/usr/bin/nano

but the brew installed in the directory below and I have it confirmed as 2.4 by running the program directlt from here
/usr/local/Cellar/nano/2.4.2_1/bin

I think a symbolic link wasn't created becasue nano is already included with mac os x, is it safe to override it ?
I got the following warning on the brew install from
==> Downloading https://ftp.gnu.org/gnu/ncurses/ncurses-6.0.tar.gz
######################################################################## 100.0%
==> ./configure --prefix=/usr/local/Cellar/ncurses/6.0 --enable-pc-files --enable
==> make install
==> Caveats This formula is keg-only, which means it was not symlinked into /usr/local.

OS X already provides this software and installing another version in
parallel can cause all kinds of trouble.

Generally there are no consequences of this for you. If you build your
own software and it requires this formula, you'll need to add to your
build variables:

    LDFLAGS:  -L/usr/local/opt/ncurses/lib
    CPPFLAGS: -I/usr/local/opt/ncurses/include

==> Summary   /usr/local/Cellar/ncurses/6.0: 1970 files, 21M, built in 114 seconds

A:

You can always create a symlink in /usr/local/bin manually, which (depending on the order of path components in $PATH) will then shadow the standard binary in /usr/bin. As nano is used interactively only, the risk of breaking anything is probably rather small.


Q:

Set number of slides shown for mobile?

I'm using the Slick Carousel module in my D7 layout and it's awesome. My carousel view is currently set to Grid, and to display 9 slides at a time. That said, how can I set the view to display a different number of slides (at different sizes) when the site is being viewed from a mobile device? For example, if the browser is open on a phone and only 414px wide, I want to display 1 slide in the carousel instead of 9 slides with their current image style.

A:

You need to enable the Slick UI, then press on configure.

Click on the List tab, and edit the default.

You need to add some breakpoints, make sure you select the correct skin.


Q:

Android Explicit Intent for Result

I have two standalone applications. Application A and Application B. I want to start activity in application B from Application A and get the results back. I can call activity in Application B from A using Action But Cannot get back to Application A after finishing the activity. OnActivityResult in A is never called. Following is the code.
public void onClickBtnToApplicationB(View v) {
        try {
            final Intent intent = new Intent(Intent.ACTION_MAIN, null);
            final ComponentName cn = new ComponentName("pakacagename","package.class");
            intent.setComponent(cn);
            intent.setAction(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);

            startActivityForResult(intent, REQUEST_CODE);
        } catch (ActivityNotFoundException e) {
        //handle Exception
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        switch (requestCode) {
            case REQUEST_CODE:
               handleResult(resultCode, intent);
               break;
        }
    }

    public void handleResult(int resultCode, Intent intentResult) {
        switch (resultCode) {
            case RESULT_OK:
                String Result = intentResult.getStringExtra("RESULT");
                // I need Results from Application B here..
                break;

             case RESULT_CANCELED:
                break;
        }
      }

Application B :
Intent s = new Intent(1.this,2.class);
startActivityForResult(s, REQUEST_CODE_B);
protected void onActivityResult(int requestCode, int resultCode, Intent intentResult) {
    switch(requestCode){
        case REQUEST_CODE_B:
            handleResult(resultCode, intentResult);
    }
}

public void handleResult(int resultCode, Intent intentResult) {
    switch (resultCode) {
    case RESULT_OK:
        String scanResult = intentResult.getStringExtra("RESULT");
        Intent newintent = new Intent();
        newintent.putExtra("RESULT", scanResult);
        setResult(Activity.RESULT_OK, newintent);
        finish();
        break;

    case RESULT_CANCELED:
        break;
}

A:

Perhaps I'm missing something. Application A seems to start an Activity in Application B for a result and implements onActivityResult. The way you've constructed the Intent to send has some issues, but let's skip that for a moment.
As far as I can tell, the form of the Intent you send is immaterial, because Application B is never looking at it. The receiving Activity should have a call to getIntent(). Based on the incoming ACTION, it set a result code and return Intent, call setResult(), and then call finish(). Your code isn't doing this; instead, it seems like you're trying to start Application A by calling startActivityForResult().
I understand why you might have tried this, but the sequence should be:

Activity A wants to start Activity B (regardless of Activity B's application).
Activity A constructs Intent X that matches Activity B.
Activity A calls startActivityForResult(X).
Activity B comes to the foreground.
The method onResume() in Activity B calls getIntent(). This ensures that Activity B can look at Intent X even if B was already running.
Activity B does the action that was requested by Activity A.
When done, Activity B puts its results in Intent Y.
Activity B calls setResult(result_code, Y);
Activity B calls finish(), which sends the result back to Activity A.
The method onActivityResult() in Activity is triggered.

The result Intent Y is not sent by startActivityForResult; instead, it's send by a combination of setResult() and finish().


Q:

How to create Sql Server login for a domain account?

All,
I have Sql Server 2008 installed on a server (let's say Server1) in a Domain (let's say AD). I also have a domain account called AD\Sql1. This is not an Admin account on the Domain (AD), but I want it to be an admin on the Server1. And then create a login on Sql Server for that Domain account (not local account).
How do I do that?
Questions:

The user AD\Sql1, I want him as Admin on Server1. For that, do I just create a local account with the same user name (let's say, Server1\Sql1) and make the local account an Admin on the machine. Will that local account be automatically mapped to the domain account with the same name?
May be I should add here that CREATE LOGIN [AD\Sql1] FROM WINDOWS did not work for me. I tried and got an error saying user does not exist in Windows (something like that)
Now, if the above technique works. Lets assume, AD\Sql1, becomes an Admin on Sever1. So, in theory I do not need to create a Sql Login for that Windows Domain account on the Sql Server, right? All the local admins that are part of BUILTIT\Admins automatically have sysadmin access to Sql Server, right?

Where did I go wrong? Please share any URLs that could explain this concept better.
Edit: I should also add that Question 1 and 2 are important independently. I know how to add a domain/windows account as sysadmin. But I am interested in how mapping works between Domain and local accounts. My goal here is not how to add a local account as sysadmin, I can do that pretty quickly. My intention is not to be rude, but be as clear as possible. If my question is still not clear, please let me know, so I could add more details.
Thanks,
_UB
Edit: Grammar

A:

Don't create a local account with the same name as the domain account. If you want to add a domain login as a sql admins do as follows:

create a login for the domain account: create login [AD\Sql1] from windows;
add the login to sysadmin group: exec sp_addsrvrolemember 'AD\Sql1', 'sysadmin';

Done. You would achieve the same result if you'd simply add the AD\Sql account to the local administrators via net localgroup Administrators /add AD\Sql1 (from a CMD shell) but that is not the correct solution as it grants AD\Sql1 all NT administrator privileges in addition to granting him SQL admin, which is not stated as a requirement therefore is unnecessary elevation. BTW the rule that members of the local Administrators group are SQL admins is not implicit, is an explicit privilege granted by default during SQL Setup and it can be revoked so you have to check for it.


Q:

SerialPort & CCS String Communication

I'm trying to send/receive a string through C#, in C# i just do:
SerialPort.WriteLine("A6");

but in CCS, if i try sending a string char after char it does not work at all, neither with ReadLine nor with ReadExisting! This is what i have tried creating an array, so that everytime we enter the RXBUFF pragma, we add the received char to the array, until the array is full (i randomly defined the array size to be 2, which means we deal with 2-char-length strings), and eventually send the string by sending char after char:
 #pragma vector = USCI_A1_VECTOR
__interrupt void USCI_A1_ISR(void)

if(__even_in_range(UCA1IV,18) == 0x02){          // Vector 2 - RXIFG
    if(counter==0)
    {
        Data[0]=UCA1RXBUF;
        counter++;
    }
    else
    {
        Data[1]=UCA1RXBUF;
        counter=0;
        UCA1TXBUF=Data[0];
        while(!(UCA1IFG & UCTXIFG)); // until UCTXBUF1 is empty
        UCA1TXBUF=Data[1];
    }
}

in C#:
 listBox2.Items.Add(SerialPort.ReadExisting());

i get non-sense text, like : ??A??? sometimes : ????A? etc.., but with:
listBox2.Items.Add(SerialPort.ReadLine());

in the first time i press the Send button which sends the "A6", i get nothing, the second time i get non-sense aswell , just like the ReadExisting behavior.
by the way, even if i try to send the string in the easiest way (without array and conditions), i mean like this:
#pragma vector = USCI_A1_VECTOR
__interrupt void USCI_A1_ISR(void)
        UCA1TXBUF='A';
        while(!(UCA1IFG & UCTXIFG));  // until UCTXBUF1 is empty
        UCA1TXBUF='6';

i also get inconsistent items in the listbox.
However, if i do this:
#pragma vector = USCI_A1_VECTOR
__interrupt void USCI_A1_ISR(void)
UCA1TXBUF=UCA1RXBUF;

i do get "A6" in the listbox and everything just work fine (with ReadLine and ReadExisting)!
could anyone just tell me why this is happening?

A:

I'v just neutralized the Parity bit, everything works now, Thank you all!


Q:

упорядочить значения в массиве

У меня есть массив, который содержит домены
array(
"yandex.ru",
"mail.ru",
"mail.ru",
"yandex.ru",
"gmail.com",
"rambler.ru",
"mail.ru",
)

Мне нужно, чтобы массив был перемешан таким образом, чтобы при переборе домены находились один за одним без повторов и, при этом, все были в равной степени максимально удалены друг от друга. Такое возможно ?
например:
array(
"yandex.ru",
"mail.ru",
"gmail.com",
"rambler.ru",
"yandex.ru",
"mail.ru",
"mail.ru", - тут допускается повтор, т.к больше доменов нет для формирования списка
)

мне это нужно, чтобы при рассылке на email, письмо отправлялось по очереди на разные домены, чтобы избежать возможных банов

A:

У вас есть массив:
$a = array(
  "yandex.ru",
  "mail.ru",
  "mail.ru",
  "yandex.ru",
  "gmail.com",
  "rambler.ru",
  "mail.ru",
);

Фильтруем его так:
$b = array_unique($a);

И получаем массив уникальных значений. Теперь в $b у нас:
$b = array(
  "yandex.ru",
  "mail.ru",
  "gmail.com",
  "rambler.ru",
);

Теперь запускаем цикл по $b. В каждой итерации цикла берем домен из $b и ищем его в $a. Если нашли в $a, посылаем письмо и вычеркиваем этот домен из $a. Если не нашли в $a, то вычеркиваем этот домен из $b. Если дошли до конца $b, а $a еще не пустое, то снова запускаем цикл по $b... и тд пока не опустеет $a.

Под вычеркиванием подразумевается unset.
Под поиском подразумевается array_search.


Q:

Automatically restart a python if it closes or crashes

I have 3 python files, 1.py, 2.py, 3.py and I'm trying to make a bat batch file that restarts my python files in case they break or close for some reason.
I'm trying with the following code, but it is not working very well:
@echo off
:Restart
start "1" /wait "C:\Users\PC\Desktop\test\1.py"
start "2" /wait "C:\Users\PC\Desktop\test\2.py"
start "3" /wait "C:\Users\PC\Desktop\test\3.py"
goto Restart

my goal is, with just a bat file, to automatically restart any of my 3 files in case any of them close or crash.
if only one of them has closed, restart only it, or if two of them close, restart both, so on

A:

I am just copying-pasting my answer from your another dublicate question (Batch that monitors and restarts a python):
A combination of an "infinite loop" which is needed in your case and python files will overload your CPU a lot I think. Have a revised piece of code (working only in single file extensions (*.bat, *.txt)). See below for something more general.
@echo off
setlocal EnableExtensions

:start_python_files
start "1st" "test1.py"
start "2nd" "test2.py"
start "3rd" "test3.py"

:check_python_files
call:infinite 1st test1.py
call:infinite 2nd test2.py
call:infinite 3rd test3.py
goto:check_python_files

:infinite
tasklist /FI "WINDOWTITLE eq %1 - %2" | findstr /c:PID > nul
rem findstr /c:PID command added above to confirm that tasklist has found the process (errorlevel = 0). If not (errorlevel = 1).
if %errorlevel% EQU 1 (start "%1" "%2")

Well, this way may last some time, so if a file is closed (~2-3 secs depending on your CPU overload).
Please notify me if it is not working for you. I haven't python installed and I don't know how they are named when they are opened :).
So, now as you have (kindly???) requested complete answers let me explain my code:

I enable extensions (setlocal EnableExtensions) to change call command as follows:

CALL command now accepts labels as the target of the CALL. The syntax
  is:
CALL :label arguments

From call /? command. You should type it in a fresh cmd for more information

I specify the window title with the start command, so my code will work. Type start /? in a fresh cmd window.
I call the infinite subroutine sending to it arguments (window title and filename). These can be accessed with %1 (first argument) and %2 (second argument).
In the infinite subroutine, I search for window title (WINDOWTITLE) EQUAL (eq) to format window title - filename. Even if it doesn't exist tasklist will return errorlevel value 0 with the message:

INFO: No tasks are running which match the specified criteria.

As here PID string doesn't exist (if it is found it will exist), we put findstr to search for it. If found, errorlevel will be 0. Else, it would be 1.

If the errorlevel is 1, that means that process not found, which means that the file is closed. So, we reopen it with the arguments sent (start "window title (%1)" "filename (%2)").
As we have called the infinite subroutine, after its end, we will return to check_python_files subroutine doing all of these above infinitely, until user termination or computer shutdown.

As later discussed in chat, when we run python files standardly (with start "window title") window title will be the full path to python.exe file. I found a way to fix it: start the cmd /c command. A revised piece of code:
@echo off
setlocal EnableExtensions

:start_python_files
start "1st" "cmd /c test1.py"
start "2nd" "cmd /c test2.py"
start "3rd" "cmd /c test3.py"

:check_python_files
call:infinite 1st test1.py
call:infinite 2nd test2.py
call:infinite 3rd test3.py
goto:check_python_files

:infinite
tasklist /FI "WINDOWTITLE eq %1" | findstr /c:PID > nul
rem findstr /c:PID command added above to confirm that tasklist has found the process (errorlevel = 0). If not (errorlevel = 1).
if %errorlevel% EQU 1 (start "%1" "cmd /c %2")

I have just added only a cmd /c extra (and remove %2) from window title as it was not needed.
cmd /c tells system to run a new cmd which will carry out the command specified by string and then it will terminate.
Synopsis:

Commands should be run to get more information about how they work:

call /?
start /?
goto /?
tasklist /?
findstr /?
cmd /?

I suggest to run the above in a fresh new cmd window.

Some interesting references:

https://ss64.com/nt/start.html
How do I pass command line parameters to a batch file?
Set Windows command-line terminal title in Python

I am really sorry for putting you into this mess. In anyway, thank you for providing such good information for me to understand where I was wrong.


Q:

How to trigger 'click' event of on a file input in Angular?

here is the view in jade:
button#save-csv-btn(ng-click="click()") Export CSV
input#save-csv(style="display:none", type="file", onchange="angular.element(this).scope().saveCSVFileChanged(this)")

js:
$scope.click = ->
    # $('#save-csv').trigger('click')

Error I get:
Error: $apply already in progress

A:

I changed $scope.click function to trigger the input click in a setTimeout. This lets the first $apply finish, and then will trigger another one.
$scope.click = function() {
    setTimeout(function() {
        inputEl.click();
    }, 0);
}

Note that I use setTimeout, not $timeout. $timeout would also be inside an $apply block.

A:

The idea was to use button to 'emulate' the file input; I achieved this using http://gregpike.net/demos/bootstrap-file-input/demo.html.
input#save-csv(type="file", title="Export to CSV", onchange="angular.element(this).scope().saveCSVFileChanged(this)")


Q:

How to preserve current font/style while making changes to RTF text in C# Windows Forms?

Using Visual Studio to create a Windows Forms application, using C#.
I have a RichTextBox. This box supports formatting like colours, bold, and underline.
I've added buttons such that people can format their text right in the box.
For example, the Bold button does this:
if (!message.SelectionFont.Bold)
    message.SelectionFont = new Font(message.Font, FontStyle.Bold);
else
    message.SelectionFont = new Font(message.Font, FontStyle.Regular);

This works fine for bolding and unbolding regular text. The issue is when it is combined with other formatting. The creation of a new Font wipes away the original formatting, and leaves me with pure bold or pure regular text.
How can I preserve original formatting, while changing text to bold?
It shouldn't be hard-coded. I shouldn't be checking if(bold), if(italics), if(underline) for every option, as ideally I'll be adding more options later (colour, font, font size, etc).

A:

Doesn't seem to be an easy way to do this.
This link might be of interest:
How do I maintain RichText formatting (bold/italic/etc) when changing any one element?


Q:

What virus is this?

Possible Duplicate:
virus-duplicated-user-account-on-xp?

I had an old netbook running windows xp.  I lent it to a friend and now it has a bizzare virus.
Here are the symptoms.  Everytime I boot up the computer, it says I have 0 harddrive space left, no matter how many files I delete.
When I go into Documents and Settings, then look at the list of users I see over 40 user accounts each with very bizzare names.
for instance, I saw Avi,  Avi.CRICKET.000, Avi.CRICKET.001 etc until Avi.CRICKET.020  and the same on another account.  I also saw a TEMP folder that looked like a user account.
When I log into the computer, I don't see my normal desktop image and icons.  When I tried to delete Avi.CRICKET.020 it said the file was in use.
This makes me believe that the virus is creating these extra accounts which doesn't allow me proper access to delete files or install an anti-virus but does allow it to use IE to do it's bot attacks or whatever.
I've tried deleting all those .CRICKET accounts and loggin in normally again, but when I do, I find another CRICKET folder created.
What files can I edit to get rid of this? Thanks.
edit----
I should add, That this computer does not have a CD drive, and I've searched all over google and couldn't find anything.
edit 2---
The answer I'm looking for, would be something which tells me which files I should look for, or a reg edit I should do, to remove these duplicate accounts so I can boot from my main account and run the proper tools.  Other possible answers would be the identity of this virus so I know what it is doing or can find details about what its doing so I can fix it.  Thanks.

A:

The only way to be safe is to do a format of your harddrive and reinstall Windows. Next time, don't let a user login as an administrator.


Q:

How to restore files from secondary model when using Reversion app (DJANGO)

I have 2 models:
Model1(models.Model):

and

Model2(models.Model):
fk = models.ForeignKey("Model1",  on_delete=models.CASCADE)
image  = models. ImageField(…..)

I use Reversion app to restore all deleted data and both models are registered in admin with Version admin. It works but when I restore any entry of model1 it would not restore actual files from Imagefield of the Model2. Thats reasonable because they are deleted by CASCADE. If I set on_delete = DO_NOTHING, it would rise integrity error as Postgree supports cross table integrity protection. Thats reasonable as well. If I use SET_NULL , then Reversion would not be able correctly restore images as it would loose foreignkey  ID obviously.
Question is how to restore associated images  of the Model2 within data of the Model1 by   Reversion or alternatively keep  foreignkey  ID of the Model2’s images intact if I use something outside CASCADE in order to not delete the images from the file system?
Thank you!

A:

I have made an additional field that would store foreighkey id and on_delete i set to "set_null"
And i have chancged delelete method in model, so that when reversion would try to restore model it would triger "save" method and fk id would be filled back from the memory field.

    def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
        if self.boat and not self.memory:
            self.memory = self.boat_id
        elif not self.boat and self.memory:
            self.boat_id = self.memory
        elif self.boat and self.memory and self.boat_id != self.memory:
            self.memory = self.boat_id
        models.Model.save(self, force_insert=False, force_update=False, using=None,
                          update_fields=None)


Q:

Opening fragment from another fragment

I have a fragment container in main activity. Inside this fragment container, three fragments are changing and are all connected to the navigation bar, like this:

I want to open another activity when pressing button in Fragment 3 (ProfileFragment). I put the button and wrote this code in ProfileFragment.java:
newButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            SettingsFragment nextFrag= new SettingsFragment();
            getActivity().getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fragment_profile, nextFrag)
                    .addToBackStack(null)
                    .commit();
        }
    });

I don't get an error while opening the application, but after clicking the button, the application closesa dn I get this error:
ScrollView can host only one direct child.
But in the XML file, ScrollView already has one child.
The XML file of the Fragment I want to open:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="@color/whiteColor"
tools:context=".FragmentClasses.SettingsFragment">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:background="@drawable/bottomsheet_settings"
        android:fontFamily="@font/inter_bold"
        android:gravity="center"
        android:letterSpacing="-0.03"
        android:text="Settings"
        android:textColor="@color/whiteColor"
        android:textSize="15sp" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="25dp"
        >

        <TextView
            android:id="@+id/textview1_settings"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Name"
            android:fontFamily="@font/inter_semibold"
            android:textColor="#686868"
            android:textSize="17sp"
            android:letterSpacing="-0.03"
            />

        <TextView
            android:id="@+id/textview2_settings"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="John"
            android:fontFamily="@font/inter_semibold"
            android:textColor="#454545"
            android:textSize="17sp"
            android:letterSpacing="-0.03"
            android:layout_alignParentRight="true"/>

    </RelativeLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/profileLine"/>

</LinearLayout>

</ScrollView>

ProfileActivity XML file:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/whiteColor"
android:id="@+id/fragment_profile"
tools:context=".FragmentClasses.ProfileFragment">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:src="@drawable/profile__image_example"
        android:scaleType="centerCrop"/>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipToPadding="false"
        android:paddingLeft="25dp"
        android:paddingRight="25dp"
        android:paddingTop="15dp">

        <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="John"
                android:id="@+id/nameProfile"
                android:fontFamily="@font/inter_bold"
                android:letterSpacing="-0.03"
                android:textSize="22sp"
                android:textColor="#313131"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="USA"
            android:layout_below="@id/nameProfile"
            android:textSize="16sp"
            android:textColor="#A7A7A7"
            android:letterSpacing="-0.03"
            android:fontFamily="@font/inter_semibold"/>

        <Button
            android:id="@+id/newButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/settings_icon"
            android:layout_alignParentRight="true"
            android:layout_marginTop="15dp"/>

    </RelativeLayout>

    </LinearLayout>

    </ScrollView>

Main Activity XML file:
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".D.Main_Activity">

<com.google.android.material.tabs.TabLayout
    android:layout_width="match_parent"
    android:layout_height="55dp"
    app:layout_constraintBottom_toBottomOf="parent"
    android:id="@+id/navigationBar"
    app:tabRippleColor="@null"
    app:tabIndicator="@null"
    android:background="@drawable/dialog_holo_tablayout"
    android:elevation="5dp"
    app:tabMinWidth="75dp"/>

<RelativeLayout
    android:id="@+id/toolbarFriendpie"
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:gravity="center"
    app:layout_constraintTop_toTopOf="parent"
    android:background="@drawable/dialog_holo_light_frame"
    android:elevation="3dp"
    >

    <ImageView
        android:id="@+id/mainLogo_Friendpie"
        android:layout_width="80dp"
        android:layout_height="wrap_content"
        android:src="@drawable/friendpie_text_logo"/>

</RelativeLayout>

<androidx.viewpager.widget.ViewPager
    android:id="@+id/fragmentContainer"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    app:layout_constraintBottom_toTopOf="@id/navigationBar"
    app:layout_constraintTop_toBottomOf="@+id/toolbarFriendpie" />

</androidx.constraintlayout.widget.ConstraintLayout>

And lastly, this is the logcat error:
Process: com.example.test_friendpie, PID: 16929
java.lang.IllegalStateException: ScrollView can host only one direct child
    at android.widget.ScrollView.addView(ScrollView.java:446)
    at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:887)
    at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
    at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
    at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439)
    at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079)

What is the problem? Thank you for all.
UPDATE: SOLUTION
I changed ScrollView with RelativeLayout in my ProfileActivity and wrote ScrollView under RelativeLayout. I don't know why the previous one failed but this works.

A:

The FragmentTransaction.replace() method you're calling inside your listener removes all fragments, from a given container, before replacing them with the provided fragment, adding the new fragment's root View to the layout. In this particular case, the Activity's root view is a ScrollView which already has a LinearLayout child. This LinearLayout is, however, not a different fragment's layout, and as such is not removed when calling FragmentTransaction.replace(). As a result, when adding the new fragment's layout to the container view, you're effectively calling ScrollView.addView() on a ScrollView which already has a direct child. I can see two ways of solving your exception (which one fits better with your design/layout is for you to decide):

Have the ProfileActivity layout be just the ScrollView (essentially delete the LinearLayout under it). This is not really ideal, since it adds a ScrollView (your fragment's root View) child to another ScrollView, making either one redundant. You should either change the fragment's root View not to be a Scrollview, or
Change the ProfileActivity's root View not to be a ScrollView.


Q:

iPhone iOS 4 Core Data - Program received signal: “EXC_BAD_ACCESS”

I'm trying to create an app based on Apple's example project TheElements, but using Core Data for the model.  In Core Data I have 4 related DB tables.  In the UI I have several tableViews, each showing rows from a different Db table.  Clicking a row in a tableView drills down to items in a related table, shown in another TableView.
Everything is working but the app crashes unexpectedly at random times with the error: Program received signal:  “EXC_BAD_ACCESS”.  BTW this error only shows in the console when debugging on the device.  No error shows when debugging on the simulator.  This screen grab shows the contents of the debugger after a crash.
I have no idea how to decipher the debugger. All I can see is the crash seems to stem from the main() function and _PFManagedObjectReferenceQueue is also listed, which leads to guess that I'm doing something wrong with Core Data.
To implement Core Data I'm adding the following to my App Delegate header:
@private
    NSManagedObjectContext *managedObjectContext_;
    NSManagedObjectModel *managedObjectModel_;
    NSPersistentStoreCoordinator *persistentStoreCoordinator_;

@property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;
@property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;
@property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator

and adding Apple's default methods for these to App Delegate implementation file.
Then to my Data Source Protocol header I've added:
@property (nonatomic, retain) NSFetchedResultsController *fetchedResultsController;
@property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;`

and my Data Source header files are as follows:
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>
#import "TableViewDataSourceProtocol.h"

@interface MatchesAllDataSource : NSObject <UITableViewDataSource,TableViewDataSource, NSFetchedResultsControllerDelegate>
{
 NSFetchedResultsController *fetchedResultsController;
 NSManagedObjectContext *managedObjectContext;
}

@end

When a table cell is clicked I pass the selectedObject as follows:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)newIndexPath
{
 // deselect the new row using animation
    [tableView deselectRowAtIndexPath:newIndexPath animated:YES];

 // get the element that is represented by the selected row.
 Match *selectedMatch = [dataSource objectForIndexPath:newIndexPath];

 // create an AtomicElementViewController. This controller will display the full size tile for the element
 MatchViewController *matchController = [[MatchViewController alloc] init];

 // set the element for the controller
 matchController.selectedMatch = selectedMatch;

 // push the element view controller onto the navigation stack to display it
 [[self navigationController] pushViewController:matchController animated:YES];
 [matchController release];
}`

Does anyone have any idea what might be causing my crash?
Will someone please point me in the right direction to look for an answer?
Is there a better way to implement Core Data with multiple tableViews?
Will someone point me to a good example of Core Data with multiple tableViews?

A:

I had this problem too with Marcus' code because I changed the UITableViewController to a regular UIViewController and forgot to put in the title.  Here is his original code:
- (id)initWithStyle:(UITableViewStyle)style {
if (self = [super initWithStyle:style]) {
    self.title = @"Australia";
}
return self;

}
So if you happened to have changed things make sure that you are setting the self.title somewhere so the custom NSArray+PerformSelector can see it when the app is initializing... like in init.


Q:

MKS how to display all Revisions of a member

I want to have a list of all revisions of a member.
Also for branches.
I know how to do for subprojects, but didn't find a solution for Members

A:

I would go with the si rlog command, as you can change the layout quite easy.
The following example shows just the revision numbers
si rlog --format="{revision}\n" --noHeaderFormat --noTrailerFormat member

The same result gives
si viewhistory --fields=revision member

Review also the usage page for both commands.
And of course the above commands imply that you are working in the correct sandbox. Otherwise you'd need to specify the project.


Q:

MS Access Designview ODBC call flow

Can any one give some idea, when we open a Designview in Ms-Access using ODBC driver, what functions are called from ODBC.
I am trying to figure out, why my designview throws an warning and the datatypes for each column prefilled with Text type.
Thx in advance to get any response

A:

You can turn on ODBC tracing and examine the resulting ODBC trace file...
NOTE: you NEED to restart ALL ODBC applications (including the ODBC Administrator) in order for tracing to commence...
(The driver ODBC Driver Manager needs to get reloaded...)


Q:

docker-compose up failes: The current .NET SDK does not support targeting .NET Core 2.2

I have .net core app which is dockerized
Inside docker compose file bellow there are details of this container
docker-compose up from windows cli produces following error
Step 11/20 : RUN dotnet restore My.Api/My.Api.csproj
 ---> Running in bc9d0ee76a7e
/usr/share/dotnet/sdk/2.1.202/Sdks/Microsoft.NET.Sdk/build/Microsoft.NET.TargetFrameworkInference.targets(135,5): error : The current .NET SDK does not support targeting .NET Core 2.2.  Either target .NET Core 2.0 or lower, or use a version of the .NET SDK that supports .NET Core 2.2. [/src/My.Api/My.Api.csproj]
ERROR: Service 'my.api' failed to build: The command '/bin/sh -c dotnet restore My.Api/My.Api.csproj' returned a non-zero code: 1

docker-compose.yml
version: '3.4'

networks:
    frontend:
    backend:

services:
    my.api:
        image: ${DOCKER_REGISTRY}myapi
        build:
            context: .
            dockerfile: My.Api/Dockerfile
        ports:
            - "5000:80"
        networks:
            - backend
            - frontend
        depends_on:
            - mssqlserver

    mssqlserver:
        image: "microsoft/mssql-server-linux:latest"
        .....

Dockerfile
FROM microsoft/aspnetcore:2.0 AS base
WORKDIR /app
EXPOSE 80

FROM microsoft/aspnetcore-build:2.0 AS build
WORKDIR /src

COPY My.Api/
RUN dotnet restore My.Api.csproj
COPY . .
WORKDIR /src/My.Api
RUN dotnet build My.Api.csproj -c Release -o /app

FROM build AS publish
RUN dotnet publish My.Api.csproj -c Release -o /app

FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "My.Api.dll"]

dotnet --version
2.2.105
Update:

When I change Dockerfile to use microsoft/aspnetcore:2.2 instead of
  microsoft/aspnetcore:2.0 I'm getting

Step 1/20 : FROM microsoft/aspnetcore:2.2 AS base
ERROR: Service 'my.api' failed to build: manifest for microsoft/aspnetcore:2.2 not found

A:

First, an important point:
The versions of .NET Core installed in Windows don't matter when it comes to a docker container. Whatever dotnet --version says in Windows doesn't matter. A docker container is a separate environment from your Windows environment. It actually runs a different userspace (Linux, not Windows). It can have a completely different set of programs and versions installed.
Now, going back, the error says:
error : The current .NET SDK does not support targeting .NET Core 2.2.  Either target .NET Core 2.0 or lower, or use a version of the .NET SDK that supports .NET Core 2.2

The last part of this error message is really important. It tells you the problem: you are using a .NET Core SDK (inside the docker container) that can not target 2.2.
(Remember that the version of .NET Core SDK that's normally installed in Windows is irrelevant for docker?)
So that version of the SDK are you using inside the docker container? Look at the Dockerfile again:
FROM microsoft/aspnetcore-build:2.0 AS build

You are using a .NET Core SDK that supports ASP.NET Core 2.0. In other words, you are using .NET Core SDK 2.0 and it only supports targetting .NET Core 2.0. You need to switch to an SDK that supports .NET Core 2.2.
Change FROM microsoft/aspnetcore:2.0 AS base to FROM microsoft/aspnetcore:2.2 AS base and FROM microsoft/aspnetcore-build:2.0 AS build to FROM microsoft/aspnetcore-build:2.2 AS build.
That will get you an SDK that lets you target .NET Core 2.2.
Edit: Ah, right. I missed something.
The Microsoft container images are described here. You need to use microsoft/dotnet:2.2-sdk for building (FROM microsoft/dotnet:2.2-sdk AS build) and microsoft/dotnet:2.2-aspnetcore-runtime for running (FROM microsoft/dotnet:2.2-aspnetcore-runtime as base).


Q:

Do SMO assemblies have to be explicitely referenced when compiling a C# program?

I am developing a c# program that uses Microsoft.SqlServer.Management.Smo. In order to compile it, I need to explicitely reference the corresponding assemblies:
csc -reference:"c:\Program Files\Microsoft SQL Server\140\SDK\Assemblies\Microsoft.SqlServer.Smo.dll" ...

I am wondering if this is expected. I have assumed that these assemblies were somehow "registered" (if this is the correct terminology) when SQL Server was installed so that they are found by the compiler and runtime environment when needed.
If they were not registered, is it possible to register them?

A:

In an IDE like Visual Studio, references would normally be added from the Solution Explorer->References->Add reference and these are automatically passed down to the compiler at compile time. Without an IDE that supports this, you have to manually pass them down to the csc as a command line argument (like you're doing). If you can't afford VS, you can go for the Community Edition of VS, or try another free IDE like MonoDevelop, or use a build script/system like CMake to handle it.


Q:

Find matching rows associated with the ref passed in SQL stored procedure

I want to pass a reference number in a stored procedure which will give me all the other reference number which has matching name and address in the passed in reference number.
Eg.  If I pass in 27 in the table below
RefNo         Name                Address
47            ABC                 CBA
27            ZYX                 XYZ
46            LKJ                 JKL
745           ZYX                 XYZ
3456          LKJ                 JKL
364           ZYX                 XYZ

I want the stored procedure to return 27, 745 and 364.

A:

http://www.sqlfiddle.com/#!3/c39a4/5
create procedure proc1
 @ref int
as

select a.refno from table1 a
inner join table1 b
  on a.name=b.name and a.address = b.address
where b.refno=@ref


Q:

Where does documentation like business and software requirement spec docs fit in an agile project?

We are implementing scrum in our company. The problem we faced is our traditional thinking, which always requires physical document.
Management is constantly asking for documents like Business Requirements Specification (BRS) and Software Requirements Specification(SRS).
When moving towards agile, is it ok writing user stories and their acceptance criteria as an alternative of (BRS and SRS) in a single document?
If that's the case, can you supply me with templates or examples? Is there something like an ISO standard related to Agile documentation?
We use TFS for project management.

A:

In the manifesto for Agile software development one can read:

Working software over comprehensive documentation

This doesn't mean documentation is a bad thing. Instead, working code is better so you can document what you are going to code.
That being said, user stories and acceptance criteria might be all you need to understand the requirements, considering you're not responsible for the Vision and Scope Document.

A:

I encourage people not to think of user stories (or backlog items of any kind) as another form of requirements. There is a critical difference in thinking between the use of requirements documents and backlogs that teams and organizations need to understand in order to effectively use the latter. Backlogs are emergent. This means that they not only change over time (there's nothing stopping a BRS from changing) but that later backlog items build on and modify earlier items such that it is possible that the earlier items no longer describe the application's behavior.
This means that the documentation you require will largely be separate from your requirements (think of it as what you walked into development knowing vs what you did in development). Note that things like ISO 9001 is mostly about validating that you follow your processes (whatever those happen to be) and that you record information you will need to audit or maintain the software later. The days where documentation and audit standards were about making sure the result matched the original idea perfectly are largely gone. The only place I see that anymore is places where they have it written into their processes and don't want to change the documented processes, in which case it's a conscious choice, not a constraint.
Adding this section to respond to the comment:
Agile and Scrum can be confusing to adopt because there are a lot of good practices that people have come up with that have been lumped into Agile and Scrum, while at the same time, many of the core practices and principles get left out.
Agile: Agile is just values statements and principles. You can find them at https://agilemanifesto.org/. You can't really practice Agile - rather, your practices can be more or less Agile (as an adjective) depending on how well aligned they are with these values and principles.
Scrum: You can follow Scrum practices. Scrum is a lightweight framework, meaning it gives a number of events, artifacts, roles, and practices, but there's a lot of space to fill in how you do the work and what that work looks like. You can find the latest version of the Scrum Guides at https://www.scrumguides.org/scrum-guide.html. It is probably worth noting that if many teams pick and choose what to follow out of Scrum. While that isn't inherently wrong, it is designed to work as a whole and many benefits are lost when you start dropping practices.
XP: You didn't mention this, but a lot of practices common in Scrum that aren't specifically listed in the Scrum Guide (like User Stories) are actually from XP. XP is a lot more prescriptive on how to do the work. There's a pretty big change curve with adopting XP and I don't see many teams do it, but when Scrum started, they were often assuming that XP was going to fill some of the how-to space in their framework, so it's always worth looking at. http://www.extremeprogramming.org/ is a good place to start, if a bit clunky.

A:

Customer-side BA here, currently in the middle of a large-scale enterprise data warehousing and infrastructure modernization initiative.  The project teams use Jira instead of TFS, and though the concepts are the same, our use of the platform is mainly as a tracking and reporting tool to interface with the core (enterprise) Agile development team.  The focus of our user stories are mainly to discuss and track testing, enhancement requirements, defect reporting - all of the type of feedback that comes "after the fact" of each sprint's work-product, so to speak, and well after the initial requirements have been published.
Key commentary on the BRS/SRS specifications - these should be solicited from end-users in the planning/prototyping phase in order to prioritize architecture development and to develop the overall project plan; this can be accomplished with a survey or other requisition assessment tool, drafted by technical leads and the E/PMO and sent out to consumer leads in the initial stages of planning.  This allows the E/PMO to gauge the baseline scope and feasibility of the draft requirements, make necessary resource allocations, and prioritize work to waves, sprints, along a kanban board, etc. for the methodologies in play.
User stories, on the other hand, tend to be more focused on responding to feedback over particular channels, services, domains, or templates that arise after consumers have conducted feasibility and gaps analysis against the prototyped release.
In short - while the exact purpose of each document will vary across different organizations and projects, the requirements documentation and user stores are ultimately apples-to-oranges, however all three could feasibly be combined in the same basket of fruit. Emphasis on the role of each should be tailored to the interests of the group(s) driving the initiative.
End-users will set their requirements ahead of time and independently of the work being done in each sprint; they will likewise continuously adjust their plan in alignment with BA/DevOps feedback along the way - this communication gets relayed through the user stories during development as a tracking bulletin of sorts.  The three are complimentary, but oftentimes they'll serve to document the interests and needs or distinctly different shareholder groups.


Q:

HttpUtility.UrlEncode in C# Translates to What on the server?

I have a string that I am trying to pass from my C# app to my ASP.NET MVC 3 endpoint. This string looks like the following
(2+3=5)/20

I am using the HttpUtility.UrlEncode method to prepare the data. I've noticed that the resulting string looks like the following:
(2%2b3%3d5)%2f20

This value is getting passed back to an ASP.NET MVC 3 endpoint. I know that the endpoint looks like the following:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UploadData(string data)
{
  // What does "data" look like here? Does it look like (2+3=5)/20 or, (2%2b3%3d5)%2f20
}

I'm trying to understand what data will look like on the server when its passed back. If the variable on the server is used WITHOUT any manipulation, will it be (2+3=5)/20 or (2%2b3%3d5)%2f20?
Thank you!

A:

What does "data" look like here? Does it look like (2+3=5)/20 or, (2%2b3%3d5)%2f20

It looks like this: (2+3=5)/20. ASP.NET takes care of url decoding properly url encoded query string parameters.


Q:

fly back diode for use with DC motors

I asked a question the other day but am still unsure, I just bought a 0-30v 0-5A dc regulated power supply today and want to use it to play around with various DC motors, I was told I didn't need to worry about a fly back diode with a straight motor one the other question but the store I bought it from still recommended and sold me a 10A07 diode, the data sheet is in this link http://pdf.datasheetcatalog.com/datasheet/mcc/10A07.pdf
My question is, is it really needed?, the guy at the store said its just safer to use one so i figured why not. After looking at the data sheet it seems it can handle up to 1000V reverse voltage so im assuming its good.
The power supply is only a cheap $150 AUD one so im not to sure if it would have the proper protection but I have read that fly back diodes are mainly used with transistors, Is that true and did I get sold something I don't really need or would it still pay to use it anyway? Im completely new to electronics so any help would be appreciated.
Thanks in advance

A:

but the store I bought it from still recommended and sold me a 10A07
  diode, the data sheet is in this link

The motor can be supplied up to 5 amps so all you need is a diode that can handle a peak of 5 amps (not continuous) and has a reverse working voltage that is at least 40 volts (a bit more than 30 volts).
A 10 A continuous diode capable of a reverse voltage of 1000 volts is of course perfectly usable but i question why a 1N400x wasn't recommended: -

It can stand-off 50 volts and handle a peak of 30 amps and probably cost a fraction of what you paid for the heavy duty diode (that can handle up to 600 amps of peak current).
Yes, I would still fit a reverse diode.


Q:

How can I best log a failed cast in Swift?

How do I log that casting failed in an elegant way? Ideally I'd love to do something like what follows but since extending Any isn't possible I'm at a loss. I'm also not aware of a way to cast using an assigned type (ex. String.self) so that's two problems.
let actuallyADouble: Any = 3.0
let stringType = String.self
guard let anyToString = actuallyADouble as? stringType else {
    actuallyADouble.logFailedCast(to: stringType)
    return
}
setString(anyToString) // will never reach

For bonus points, what would be even more magical would be a way to extend all casting, so I could just do the following and a log occurs outside this scope on failure:
guard let anyToString = actuallyADouble as? stringType else { return }

Background:
We have a Swift project that didn't enforce the practice of avoiding force-casts, so there are lots of things like this:
let anyToString = actuallyADouble as! String

We are refactoring to this safer code:
guard let anyToString = actuallyADouble as? String else { return }

Now our app won't crash, but instead we'll just continue operation like nothing is wrong, potentially making troubleshooting more difficult.

A:

As you said, extending Any isn't possible. But optionals hold whatever, and if you rely on them, you can get your logging and have very similar code to what you're already using.
extension Optional {
  struct UnwrapError: Error { }

  static func unwrap(_ any: Any) throws -> Wrapped {
    guard let wrapped = any as? Wrapped else {
      print("\(any) cannot be cast to \(Wrapped.self)")
      throw UnwrapError()
    }

    return wrapped
  }
}

try Double?.unwrap(actuallyADouble) // 3
let double: Double = try Optional.unwrap(actuallyADouble) // 3
try? String?.unwrap(actuallyADouble) // nil. "3.0 cannot be cast to String"

…or even just
extension Optional {
  init(_ any: Any) {
    self = any as? Wrapped
    if self == nil {
      print("\(any) cannot be cast to \(Wrapped.self)")
    }
  }
}

Double?(actuallyADouble) // 3
String?(actuallyADouble) // nil. "3.0 cannot be cast to String"