text:
Q: Printing an Image using a Bluetooth Thermal Printer From an Android App? I have been trying to get a print of an Image but I have not been successful so far.The printer is a locally manufactured 2" thermal printer having a printing resolution of 8dots/mm, 384dots/line, 203 dpi. The printer is based of a board having the "NXP 2388 ARM v7 Microproc." having a Memory FLASH size of 512 KB, RAM: 128 KB & a Receive Buffer Size of 16KB.
 I followed this question till now.
Problem: The image I tried printing is of 576x95 res.

The image got printed(with some error LED lighting up and debug buzzer noise :D) but the orientation of the image was vertical instead of getting horizontally printed; that too at the very left side of the page and the top part of the image was cut-off
Assuming here that I din't passed some of the flags(while making the "packet") compatible with the printer that I have.
I have not worked on bluetooth printing before so any help is appreciable :)
My Existing Main Activity:
public class MainActivity extends Activity
    {
    // will show the statuses
    TextView myLabel;
    // will enable user to enter any text to be printed
    EditText myTextbox;
    EditText devName;
    public TableLayout tl2;
    String devid;
    String[] pName;
    String[] LODQTY;
    String[] rte;
    String[] stk;
    String[] oQty;
    String[] oVal;
    String[] fQty;

    BitSet dots;
    int mWidth;
    int mHeight;
    String mStatus;
    String TAG = "TAG";

    public String msg;

    // android built in classes for bluetooth operations
    BluetoothAdapter mBluetoothAdapter;
    BluetoothSocket mmSocket;
    BluetoothDevice mmDevice;

    OutputStream mmOutputStream;
    InputStream mmInputStream;
    Thread workerThread;

    byte[] readBuffer;
    int readBufferPosition;
    int counter;
    volatile boolean stopWorker;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        devName = (EditText) findViewById(R.id.etdevice);

        devName.setText("BTprinter0377");

        String[] product_info = new String[6];
        product_info[0] = "CPL400^10^1^0^4^0.4^0";
        product_info[1] = "CPL400^10^1^0^4^0.4^0";
        product_info[2] = "CPL400^10^1^0^4^0.4^0";
        product_info[3] = "CPL400^10^1^0^4^0.4^0";
        product_info[4] = "CPL400^10^1^0^4^0.4^0";
        product_info[5] = "CPL400^10^1^0^4^0.4^0";

        tl2 = (TableLayout) findViewById(R.id.dynSummary);
        LayoutInflater inflater = getLayoutInflater();
    for (int current = 0; current <= (product_info.length - 1); current++) {

            final TableRow row = (TableRow)inflater.inflate(R.layout.table_summary_row, tl2 , false);

            TextView tv1 = (TextView)row.findViewById(R.id.tvSkuName);
            TextView tv2 = (TextView)row.findViewById(R.id.tvOrderQty);
            TextView tv3 = (TextView)row.findViewById(R.id.tvFreeQty);

            TextView tv4 = (TextView)row.findViewById(R.id.tvSampleQty);
            TextView tv5 = (TextView)row.findViewById(R.id.tvTotalOrderKg);
            TextView tv6 = (TextView)row.findViewById(R.id.tvTotalFreeKg);
           TextView tv7 = (TextView)row.findViewById(R.id.tvTotalSampleKg);

            StringTokenizer tokens = new StringTokenizer(String.valueOf(product_info[current]), "^");
            //System.out.println("tokens.nextToken().trim()"+tokens.nextToken().trim());
            tv1.setText(tokens.nextToken().trim());
            tv2.setText(tokens.nextToken().trim());
            tv3.setText(tokens.nextToken().trim());
            tv4.setText(tokens.nextToken().trim());
            tv5.setText(tokens.nextToken().trim());
            tv6.setText(tokens.nextToken().trim());
            tv7.setText(tokens.nextToken().trim());

            tl2.addView(row);

    }

        try {

            // we have three buttons for specific functions
            Button openButton = (Button) findViewById(R.id.open);
            Button sendButton = (Button) findViewById(R.id.send);
            Button closeButton = (Button) findViewById(R.id.close);

            myLabel = (TextView) findViewById(R.id.label);

            // open bluetooth connection
            openButton.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {

                    devid = devName.getText().toString().trim();

                    try {
                        findBT();
                        openBT();
                    } catch (IOException ex) {
                    }

                }
            });

            // send data typed by the user to be printed
            sendButton.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    try {
                        sendData();
                    } catch (IOException ex) {
                    }
                }
            });

            // close bluetooth connection
            closeButton.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    try {
                        closeBT();
                    } catch (IOException ex) {
                    }
                }
            });

        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
     * This will find a bluetooth printer device
     */
    void findBT() {

        try {
            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

            if (mBluetoothAdapter == null) {
                myLabel.setText("No bluetooth adapter available");
            }

            if (!mBluetoothAdapter.isEnabled()) {
                Intent enableBluetooth = new Intent(
                        BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBluetooth, 0);
            }

            Set<BluetoothDevice> pairedDevices = mBluetoothAdapter
                    .getBondedDevices();
            if (pairedDevices.size() > 0) {
                for (BluetoothDevice device : pairedDevices) {

                System.out.println("device.getName(): "+device.getName().toString());

                    if (device.getName().equals("BTprinter0377")) {
                        mmDevice = device;
                        break;
                    }
                }
            }
            myLabel.setText("Bluetooth Device Found");
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
     * Tries to open a connection to the bluetooth printer device
     */
    void openBT() throws IOException {
        try {
            // Standard SerialPortService ID
            UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");

            mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
            mmSocket.connect();
            mmOutputStream = mmSocket.getOutputStream();
            mmInputStream = mmSocket.getInputStream();

            beginListenForData();

            myLabel.setText("Bluetooth Opened");
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
     * After opening a connection to bluetooth printer device,
     * we have to listen and check if a data were sent to be printed.
     */
    void beginListenForData() {
        try {
            final Handler handler = new Handler();

            // This is the ASCII code for a newline character
            final byte delimiter = 10;

            stopWorker = false;
            readBufferPosition = 0;
            readBuffer = new byte[1024];

            workerThread = new Thread(new Runnable() {
                public void run() {
                    while (!Thread.currentThread().isInterrupted()
                            && !stopWorker) {

                        try {

                            int bytesAvailable = mmInputStream.available();
                            if (bytesAvailable > 0) {
                                byte[] packetBytes = new byte[bytesAvailable];
                                mmInputStream.read(packetBytes);
                                for (int i = 0; i < bytesAvailable; i++) {
                                    byte b = packetBytes[i];
                                    if (b == delimiter) {
                                        byte[] encodedBytes = new byte[readBufferPosition];
                                        System.arraycopy(readBuffer, 0,
                                                encodedBytes, 0,
                                                encodedBytes.length);
                                        final String data = new String(
                                                encodedBytes, "US-ASCII");
                                        readBufferPosition = 0;

                                        handler.post(new Runnable() {
                                            public void run() {
                                                myLabel.setText(data);
                                            }
                                        });
                                    } else {
                                        readBuffer[readBufferPosition++] = b;
                                    }
                                }
                            }

                        } catch (IOException ex) {
                            stopWorker = true;
                        }

                    }
                }
            });

            workerThread.start();
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
     * This will send data to be printed by the bluetooth printer
     */
    void sendData() throws IOException {
        System.out.println("tl2.getChildCount(): "+tl2.getChildCount());
        try {

            print_image("/sdcard/tryimg.png");

            String msg22;
            msg22 = "\n";
            msg22 += "PN     Or Fr Sa TOKg TFKg TSKg";
            msg22 += "\n";

            //mmOutputStream.write(msg22.getBytes());

            // tell the user data were sent
            myLabel.setText("Data Sent");

        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
     * Close the connection to bluetooth printer.
     */
    void closeBT() throws IOException {
        try {
            stopWorker = true;
            mmOutputStream.close();
            mmInputStream.close();
            mmSocket.close();
            myLabel.setText("Bluetooth Closed");
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String convertBitmap(Bitmap inputBitmap) {

        mWidth = inputBitmap.getWidth();
        mHeight = inputBitmap.getHeight();

        convertArgbToGrayscale(inputBitmap, mWidth, mHeight);
        mStatus = "ok";
        return mStatus;

    }

    private void convertArgbToGrayscale(Bitmap bmpOriginal, int width,
            int height) {
        int pixel;
        int k = 0;
        int B = 0, G = 0, R = 0;
         dots = new BitSet();
        try {

            for (int x = 0; x < height; x++) {
                for (int y = 0; y < width; y++) {
                    // get one pixel color
                    pixel = bmpOriginal.getPixel(y, x);

                    // retrieve color of all channels
                    R = Color.red(pixel);
                    G = Color.green(pixel);
                    B = Color.blue(pixel);
                    // take conversion up to one single value by calculating
                    // pixel intensity.
                    R = G = B = (int) (0.299 * R + 0.587 * G + 0.114 * B);
                    // set bit into bitset, by calculating the pixel's luma
                    if (R < 55) {
                        dots.set(k);//this is the bitset that i'm printing
                    }
                    k++;

                }

            }

        } catch (Exception e) {
            // TODO: handle exception
            Log.e(TAG, e.toString());
        }
    }

    private void print_image(String file) throws IOException {
        File fl = new File(file);
        if (fl.exists()) {
            Bitmap bmp = BitmapFactory.decodeFile(file);
            convertBitmap(bmp);
            mmOutputStream.write(PrinterCommands.SET_LINE_SPACING_24);

            int offset = 0;
            while (offset < bmp.getHeight()) {
                mmOutputStream.write(PrinterCommands.SELECT_BIT_IMAGE_MODE);
                for (int x = 0; x < bmp.getWidth(); ++x) {

                    for (int k = 0; k < 3; ++k) {

                        byte slice = 0;
                        for (int b = 0; b < 8; ++b) {
                            int y = (((offset / 8) + k) * 8) + b;
                            int i = (y * bmp.getWidth()) + x;
                            boolean v = false;
                            if (i < dots.length()) {
                                v = dots.get(i);
                            }
                            slice |= (byte) ((v ? 1 : 0) << (7 - b));
                        }
                        mmOutputStream.write(slice);
                    }
                }
                offset += 24;
                mmOutputStream.write(PrinterCommands.FEED_LINE);
                mmOutputStream.write(PrinterCommands.FEED_LINE);
                mmOutputStream.write(PrinterCommands.FEED_LINE);
                mmOutputStream.write(PrinterCommands.FEED_LINE);
                mmOutputStream.write(PrinterCommands.FEED_LINE);
                mmOutputStream.write(PrinterCommands.FEED_LINE);
            }
            mmOutputStream.write(PrinterCommands.SET_LINE_SPACING_30);

        } else {
            Toast.makeText(this, "file doesn't exists", Toast.LENGTH_SHORT).show();
        }
    }

}

The PrinterCommands Class:
public class PrinterCommands {
public static final byte[] INIT = {27, 64};
public static byte[] FEED_LINE = {10};

public static byte[] SELECT_FONT_A = {27, 33, 0};

public static byte[] SET_BAR_CODE_HEIGHT = {29, 104, 100};
public static byte[] PRINT_BAR_CODE_1 = {29, 107, 2};
public static byte[] SEND_NULL_BYTE = {0x00};

public static byte[] SELECT_PRINT_SHEET = {0x1B, 0x63, 0x30, 0x02};
public static byte[] FEED_PAPER_AND_CUT = {0x1D, 0x56, 66, 0x00};

public static byte[] SELECT_CYRILLIC_CHARACTER_CODE_TABLE = {0x1B, 0x74, 0x11};

public static byte[] SELECT_BIT_IMAGE_MODE = {0x1B, 0x2A, 33, (byte) 255, 3};
//public static byte[] SELECT_BIT_IMAGE_MODE = {0x1B, 0x2A, 0x64, 0x63, 48, (byte) 255};

public static byte[] SET_LINE_SPACING_24 = {0x1B, 0x33, 24};
public static byte[] SET_LINE_SPACING_30 = {0x1B, 0x33, 30};

public static byte[] TRANSMIT_DLE_PRINTER_STATUS = {0x10, 0x04, 0x01};
public static byte[] TRANSMIT_DLE_OFFLINE_PRINTER_STATUS = {0x10, 0x04, 0x02};
public static byte[] TRANSMIT_DLE_ERROR_STATUS = {0x10, 0x04, 0x03};
public static byte[] TRANSMIT_DLE_ROLL_PAPER_SENSOR_STATUS = {0x10, 0x04, 0x04};
}

As mentioned in the dev manual of the printer(pdf):
Bit Map Image Print
1. Select the image either from PC or from mobile's SD card.
2. Convert the image into monochrome bmp.
3. Resize the image to fit into the printer paper area if it is exceeding
4. Now read the processed image through fileinputstream and save it into byte array.
5. Make the packet of image and then send it to printer over outputstream.

The required packet structure:

 The packet fields chart:

Alignment table & other info:

A: private byte[] printbyte = {(byte)0x1B,(byte)0x2A,(byte)0x6F,(byte)0x63}

File file = new File(Environment.getExternalStorageDirectory + File.seprator()+"file_name");
FileInputStream fin = new FileInputStream(file);
byte imageContent[] = new byte[(int)file.length()];
fin.read(imageContent);

byte [] width  = hexToBuffer(Integer.toHexString(your_width));
byte [] height = hexToBuffer(Integer.toHexString(your_height));

byte[] imageToPrint = new byte[printbyte.lenght()+imageContent.lenght()+width.lenght()+height.lenght()];

  System.arraycopy(imagetoprint,0,printbyte,0,printbyte.lenght());
  System.arraycopy(imagetoprint,printbyte.lenght(),width ,0,width.lenght());
  System.arraycopy(imagetoprint,width.lenght(),height,0,height.lenght());
  System.arraycopy(imagetoprint,height.lenght(),imageContent,0,imageContent.lenght());

  mmOutputStream.write(imagetoprint);

Hex to Buffer method -
public static byte[] hexToBuffer(String hexString)
    throws NumberFormatException {
    int length = hexString.length();
    byte[] buffer = new byte[(length + 1) / 2];
    boolean evenByte = true;
    byte nextByte = 0;
    int bufferOffset = 0;

    if ((length % 2) == 1) {
        evenByte = false;
    }

    for (int i = 0; i < length; i++) {
        char c = hexString.charAt(i);
        int nibble; // A "nibble" is 4 bits: a decimal 0..15

        if ((c >= '0') && (c <= '9')) {
            nibble = c - '0';
        } else if ((c >= 'A') && (c <= 'F')) {
            nibble = c - 'A' + 0x0A;
        } else if ((c >= 'a') && (c <= 'f')) {
            nibble = c - 'a' + 0x0A;
        } else {
            throw new NumberFormatException("Invalid hex digit '" + c +
                "'.");
        }

        if (evenByte) {
            nextByte = (byte) (nibble << 4);
        } else {
            nextByte += (byte) nibble;
            buffer[bufferOffset++] = nextByte;
        }

        evenByte = !evenByte;
    }

    return buffer;
}

A: I have a thermal printer with bluetooth and Usb connection, if your printer support ESC/POS command search for its commands on internet,
for print raster image you should send this:
[Name] Print raster bit image
[Format] ASCII GS v 0 m xL xH yL yH d1...dk
         Hex 1D 76 30 m xL xH yL yH d1...dk
         Decimal 29 118 48 m xL xH yL yH d1...dk
[Range] 0£ m£ 3, 48£ m £ 51
0£ xL£ 255
0£ xH£ 255
0£ yL£ 255
0£ d£ 255
k=(xL+ xH*256)*(yL+yH*256)

Follow your printer guidelines, it is may be different from others.


text:
Q: php искажение кириллицы при добавлении в файл В php скрипт методом post передается подобный json объект: {"name":"Иван", "surname":"Иванов"}.
Далее необходимо данный объект записать в обычный текстовый файл. При попытке реализовать это так:
file_put_contents($file, json_encode($obj), FILE_APPEND);

В файл вместо кириллицы заносится подобный текст:

\u0418\u0432\u0430

Решить данную проблему получилось абсолютно неэлегантным способом:
    $file = "file.txt";
    $str = '{';
    foreach($obj as $key=>$val) {
        $str.='"'.$key.'":'.'"'.$val.'",';
    }
    $str = preg_replace("/.$/","",$str);
    $str .= "}\n";
    file_put_contents($file, $str, FILE_APPEND);

Объект должен быть записан в файл именно с фигурными скобками.
Все файлы имеют кодировку UTF8 без BOM. Подскажите пожалуйста, может быть есть какой-то более красивый и лаконичный способ справиться с данной задачей?

A: Используйте специальный флаг функции json_encode() (смори второй пример в документации)
file_put_contents($file, json_encode($obj, JSON_UNESCAPED_UNICODE), FILE_APPEND);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Css shadow entire screen length box shadows are basically your shape blurred.
that means that at the edges the shadow is curved up.
what if you don't want that? what if your shadow is for a top bar and you don't want it to seems like it ends?
issue:

desired effect :

how do I obtain this?
html :

css :
.TopBar {
    box-shadow: 0 4px 28px black;
}

Am I supposed to use an absolute positioned element that's bigger than screen width or something?

A: You can add a spread parameter to the shadow (not exactly the same appearance, but at least it does what you ask for):

html,
body {
  margin: 0;
}

.TopBar {
  height: 40px;
  background: #444;
  box-shadow: 0px 4px 24px 16px black;
}

A: Fake it! You can use linear gradient and a pseudo element to get the effect you want:

.TopBar {
  height: 50px;
  background: gray;
  position: relative;
}
.TopBar::after {
  content: "";
  background: linear-gradient(to bottom, rgba(0,0,0,.8) 0%,rgba(0,0,0,0) 100%);
  position: absolute;
  width: 100%;
  height: 20px;
  top: 100%;
}

A: You can add a pseudo-element (:before) to extend it beyond your original container and therefore, get a wider shadow :

html, body { margin:0; padding: 0 }

.TopBar {
  height: 50px;
  position: relative;
}
.TopBar:before {
  content: "";
  display: block;
  position: absolute;
  height: 100%;
  width: 100%;
  background: #454545;
  box-shadow: 0 4px 28px #000;
  transform: scaleX(1.1);
  z-index: -1;
}
.TopBar .content {
  color: #add8e6;
}

Here's some text inside my top bar


text:
Q: .htaccess url-rewriting help I'm a bit confused on url writing in .htaccess and have a question about rewriting urls.
My first question is I'm trying to do is have a one .htacces to make the urls go from http://www.website.com/index.php to http://www.website.com/Home/and another .htaccess to go from http://www.website.com/index.php to http://www.website.com/home.html. Here's a sample code I did to lose the ".php":
AddHandler application/x-httpd-php .php .html .htm
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

My second question I'm running into is I have my a tags are set up has  and it shows the the "index.php" not "/Home/" like I want to. Am I suppose to put "/Home/" into the href in order for it to work?
I only build websites has a hobby so I don't know much about htaccess.  Thanks a bunch.

A: I think you misunderstood how mod_rewrite works and how it is used: mod_rewrite is for rewriting or redirecting requested URIs. So if a URI path like /Home/ or /home.html is requested, mod_rewrite can be used to rewrite these requests internally to /home.php.
But to have mod_rewrite do this, you will actually need to request /Home/ or /home.html respectively and not /home.php. So /Home/ and /home.html have to be already used in the HTML documents instead of /home.php.


text:
Q: Convert Number to IP Address (v4) I'm trying to convert a four digit number into an IP Address. For example:
0001 ---> *.192.1.01
0011 ---> *.192.11.01
0111 ---> *.192.111.01
1111 ---> *.196.87.01
3458 ---> *.205.130.01
I believe the subnet mask is 255.255.192.0.
I would greatly appreciate any suggestions on the best way to do this in vb.net.
Other info:
This is for a simple pinger program where the user inputs a four digit number (the ID of the physical site that they wish to ping.) The IP Addressing scheme is simple, the 2nd & 3rd octet are used as the site number, and the fourth octet is used as the device at the site. I didn't design this scheme, hence why I'm unsure on how to get vb.net to understand it.
What I've Tried:
I thought about doing it the following way, which is extremely crude. However this would only work up to *.192.255.01 as I don't know how to split the number between the two octets once it goes over 255 in octet 3.
Private Sub btnStartPing(sender As Object, e As EventArgs) Handles btnStartPing.Click

    Dim Octet1 As Integer = *
    Dim Octet2 As Integer = 192
    Dim Octet3 As Integer = txtSiteID.text
    Dim Octet4 As Integer = 01
    Dim CompleteIP As String = ""

    CompletIP = Octet1 & "." & Octet2  & "." & Octet3 & "." & Octet4

    'PING CompleteIP

end sub

Solution:
        Dim var1 As Integer = Fix(192 + (NumericUpDown1.Value / 256))
        Dim var2 As Integer = Fix((NumericUpDown1.Value Mod 256))

        MsgBox("Your IP address is: " & "10." & var1 & "." & var2 & "." & "200")
    End Sub

A: You'll need to split the number in two. Get the first half of the bits and add them to 192 and the second half of the bits are directly used.
    Dim number As Integer

    number = 1
    Console.WriteLine("*.{0}.{1}.01", 192 + ((number And &HFF00) >> 8), number And &HFF) ' *.192.1.01

    number = 11
    Console.WriteLine("*.{0}.{1}.01", 192 + ((number And &HFF00) >> 8), number And &HFF) ' *.192.11.01

    number = 111
    Console.WriteLine("*.{0}.{1}.01", 192 + ((number And &HFF00) >> 8), number And &HFF) ' *.192.111.01

    number = 1111
    Console.WriteLine("*.{0}.{1}.01", 192 + ((number And &HFF00) >> 8), number And &HFF) ' *.196.87.01

    number = 3458
    Console.WriteLine("*.{0}.{1}.01", 192 + ((number And &HFF00) >> 8), number And &HFF) ' *.205.130.01

Take the number and split it in two

3458 = 0x0D82
0x0D
    0x82

Then add 192 to the first part

0x0D + 192 = 205
    0x82 = 130

A: This should make it
Public Function StartPing(txtSiteId As String) As String
    Dim SiteId As Integer = Integer.Parse(txtSiteId)

    'backslash performs integer division (no fractionary part)
    'will throw an error when SiteId results in values greater than 255
    'type Byte allows only values from 0 to 255
    Dim Octet2 As Byte = 192 + (SiteId \ 256)

    'Mod gets rest of division
    Dim Octet3 As Byte = SiteId Mod 256

    Return String.Format("*.{0}.{1}.01", Octet2, Octet3)
End Function


text:
Q: How to get a specific folder in develop branch git repository (VSTS) to my local directory I have a repository https://phm-dsc.visualstudio.com/PHM/_git/repo in VSTS git. How do I get a folder within this repository to my local using powershell/batch script commands? I tried the following but did not work (getting this error: Sparse checkout leaves no entry on the working directory). any suggestions will help
 mkdir sql
cd sql
git init
git remote add origin -f <<https URL of repository>>
git config core.sparsecheckout true
echo <<path of the folder>> >>.git/info/sparse-checkout
git pull origin master

A: That should work - or at least you are close. I have a script that does essentially the same thing and those steps look basically right.
However, try removing the -f option from git remote add origin.  You don't really want the fetch to happen until the sparse-checkout file is created.  That may be the issue.
If you still aren't able to get it to work, why don't you consider posting the steps you're trying along with a public repo (either on VSTS or github).  That way others can try the steps to see what exactly is wrong.

A: You can read some tips in "On Windows git: "error: Sparse checkout leaves no entry on the working directory""
In particular:

*

*The <path you want to checkout> might look like this: path/to/subfolder - note the lack of leading and trailing path separators.

*Important: Be sure to use a git bash prompt for the below, and use an editor supporting unix line-ending conventions and save as ANSI when editing the sparse-checkout file, or you may get "error: Sparse checkout leaves no entry on the working directory" errors.

So double-check the eol (end of line) used in your .git/info/sparse-checkout file.

A: To get a folder from VSTS git repo to your local directory, you can follow below commands (assume the folder name is myfolder, and it located in master branch):
mkdir sql
cd sql
git init
git remote add origin -f https://phm-dsc.visualstudio.com/PHM/_git/repo
cd repo
git checkout origin/master myfolder/

Now the contents in myfolder is get, you can commit to your local git repo if necessary.


text:
Q: What's the shortcut for showing a function parameters in NetBeans? Example:
void Sandwich(string ham, string bread, int cheese){
...do stuff...
};

When I type Sandwich(, I need to see what are the required parameters.
How can I do that?

A: For non-Mac, you can use Ctrl+P. For Mac, you can use Command + P

A: You need to enable the Auto Popup Code Completion option in Tools > Options > Editor > Code Completion.
Enable it for All Languages, the selection for individual languages does not seem to work, not for PHP at least. It seems there's a bug with the All Languages deactivation taking precedence over the rest of the languages.


text:
Q: Не видит файл с mixins_all.sass После запуска Gulp
вот такая ошибка
Я не знаю как пофиксить. Уже раза 3 файл переписывал и вс без толку.
вот пример что содержится в файле:

// функция для перевода в rem - пример перевода padding-top: rem(50px)
@import "functions/px-to-rem"

// Загружаем общие стили  и переменные для всех сайтов
@import "common/colors"   // Общие цвета для всех сайтов используя сайт http://chir.ag/projects/name-that-color/#6195ED
@import "common/vars"   // Общие переменные для всех сайтов

/** Bootstrap **/
// Core variables and mixins
@import "custom"
@import "bootstrap_c/custom"
@import "variables"
@import "bootstrap_c/variables"
@import "pages/mixins"

/** Bootstrap **/
// Reset and dependencies
@import "normalize"
@import "print"

вот сам файл gulpfile.js

const gulp = require('gulp');

const autoprefixer = require('gulp-autoprefixer');
const cleanCSS = require('gulp-clean-css');
const rename = require('gulp-rename');
const concat = require('gulp-concat');
const uglify = require('gulp-uglify');
const path = require('path');
const browserSync = require('browser-sync');
const sass = require('gulp-sass')(require('sass'));

var config = {
  bootstrapDir: './node_modules/bootstrap/scss/bootstrap.scss',
  tatherDir: './node_modules/tether',
  fontAwesomeDir: './node_modules/font-awesome/scss/font-awesome.scss',
  publicDir: 'app',
};

gulp.task('browser-sync', ['styles', 'scripts'], function () {
  browserSync({
    server: {
      baseDir: config.publicDir,
      baseDir: 'app',
    },
    notify: false,
  });
});

//Scripts

gulp.task('scripts', function () {
  return gulp
    .src([
      'app/libs/jquery/jquery-3.6.0.min.js',
      'app/libs/bootstrap/js/bootstrap.min.js',
      'app/js/material.min.js',
    ])
    .pipe(concat('libs.min.js'))
    .pipe(uglify())
    .pipe(gulp.dest('app/js'));
});
//Styles

gulp.task('styles', function () {
  return gulp
    .src('src/sass/mixins_all.sass')
    .pipe(
      sass({
        includePaths: [
          config.bootstrapDir,
          require('node-bourbon').includePaths,
          config.tatherDir,
          config.fontAwesomeDir,
        ],
      }).on('error', sass.logError)
    )
    .pipe(rename({basename: 'main2', prefix: ''}))
    .pipe(
      autoprefixer({
        browsers: ['all version'],
        cascade: false,
      })
    )
    .pipe(gulp.dest(config.publicDir + '/css'));
  // .pipe(browserSync.reload({stream: true}));
});

gulp.task('default', ['browser-sync', 'watch']);
gulp.task('watch', function () {
  gulp.watch(
    ['src/sass/*.sass', 'src/sass/**/*.sass', 'src/sass/**/*.scss'],
    ['styles'],
    browserSync.reload
  );
  gulp.watch(['app/*.html'], browserSync.reload);
  gulp.watch(['app/js/**/*.js'], browserSync.reload);
  gulp.task('default', ['browser-sync', 'watch']);
});

Структура проекта


text:
Q: mongodb index for $exists Given documents shaped like:
 { "some-blob-id": {
   { "error": "Some Error Message",
      "data": BinaryData(0, all-that-glop),
      "timestamp" : "time-for-completion-or-error"
   },
   ...
 }

and a desire to query for $exists of some-blob-id.data, what's the appropriate index spec? I don't want it building an index on that binary stuff.

A: I would set another field to be 1 when you set data (this is easy enough to backfill). Then add a sparse index on this new field.That is probably the most optimal way to do it.


text:
Q: What is the method on an onOptionsItemSelected menu in WebView for "forward" and "back" in Android? I am trying to get my webView to move back and forward by calling up the menu. Thus far I have the menu working fine and opening, and the refresh button will refresh the browser. However, I cannot find documentation anywhere about the methods for forward of back. If the default internet browser has them by just pressing the menu key there must be out there. I just can't find them/don't know how to implement them. Any help would be beneficial, thank you.
Here is what I am trying to do:
WebView.Java:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_navigation, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.back_button:

        "???"

    case R.id.forward_button:

        "???"

    case R.id.refresh_button:
            refreshBrowser();
            return true;
          }
    return false;
   }

The part that I'm missing is marked by the three question marks "???". Let me know if you need more information to get some help, and thanks again.

A: Use webView.canGoBack and webView.canGoForward to check if there is history data to go back / forward and then load that url.


text:
Q: Stop a 2nd Android Emulator opening up Hi I'm creating an Android app but am quite new to it so am having a few problems.  I'm using the emulator to run the app.  But the problem I'm having is that when I try to debug the app its starting up a 2nd emulator which doesn't have my SQLite database showing in the File Explorer.  Has anyone any idea how I can:

*

*Stop the 2nd Emulator from opening up or

*Get it to show the database in File Explorer when it does?

I can't debug the App until its sorted.

A: Just set the emulator you want to run for the project by right-clicking on your project --> Run As.. --> Run Configuration--> go to Target Tab, put a V next to your desired AVD, Apply your settings and Run the project.
Next time when you press the run button in your eclipse environment this will be the AVD that will be used for this project.
Update:
another option would be under the Target tab just set the Always prompt to pick device.
that way you will be prompted before running the application.
Update #2:
when the windows for choosing a devices opens but you can't see your current device what you should do is to open your command prompt(CMD) and type: adb kill-server and then adb logcat to start the server. you current device will be updated in the device chose window.

A: I get the same issue some time ago with the File Explorer, try with this plugin: sqlitemanager-plugin-for-eclipse.


text:
Q: Python Wand error when trying to display simple empty image: 'no encode delegate for this image format' I'm new to Wand, I tried the following very simple code, to display a red image:
from wand.color import Color
import wand.display

with Image(width=100, height=100, background=Color("red")) as img:
    wand.display.display(img)

But I'm getting this error:
MissingDelegateError                      Traceback (most recent call last)
<ipython-input-24-6badc0244551> in <module>
    1 with Image(width=100, height=100, background=Color("red")) as img:
----> 2     wand.display.display(img)
    3

~/dev/.venv/lib/python3.7/site-packages/wand/display.py in display(image, server_name)
    60         ext = '.' + image.format.lower()
    61         path = tempfile.mktemp(suffix=ext)
---> 62         image.save(filename=path)
    63         os.system(('start ' if system == 'Windows' else 'open ') + path)
    64     else:

~/dev/.venv/lib/python3.7/site-packages/wand/image.py in save(self, file, filename, adjoin)
8916                 r = library.MagickWriteImage(self.wand, filename)
8917             if not r:
-> 8918                 self.raise_exception()
8919
8920

~/dev/.venv/lib/python3.7/site-packages/wand/resource.py in raise_exception(self, stacklevel)
    228             warnings.warn(e, stacklevel=stacklevel + 1)
    229         elif isinstance(e, Exception):
--> 230             raise e
    231
    232     def make_blob(self, format=None):

MissingDelegateError: no encode delegate for this image format `' @ error/constitute.c/WriteImage/1240

Looking at the stack trace, I realize Wand temporarily stores the image in a file before displaying it, so I tried adding the following line before calling display():
img.format = 'png'

And it works. Am I missing something here? Is this the expected way of displaying a simple image?

A:
Am I missing something here? Is this the expected way of displaying a simple image?

The solution you came up with is correct. For Windows / macOS, wand assumes you are not running an X11 server. It's far easier to write the Image to disk, and ask the OS to display it in your default image viewer.
The problem
When creating a canvas, or a pseudo image format (PLASMA: for example), the internal "image info" & coder have yet to be defined. Is your simple image CMYK, or RGB? What about palettes, endianness, & etc etc. ImageMagick is right to throw an exception until the user specifies, at a minimum, a coder / delegate to write with.
The fix
Luckily, with most open-source projects, this was reported and patched in Wand a month ago(?). Wand's display() method will hand over a PNG file to the OS in the event that a Image's coder (format) is not defined.
Unluckily, with most open-source projects, it can take weeks for patch versions to be shipped & distributed. Best keep an eye on Wand's release notes


text:
Q: In community of 400 adults, 300 bike or swim or do both,. 160 swim and 120 swim and bike. ppose that in a community of 400 adults, 300 bike or swim or do both,. 160 swim and 120 swim and bike. What is the probability that an adult selected at random from this community bikes?
I got 140/400 because 160 +120+20=300
Therefore 20 must bike and not swim.
It is also given that 120 swim and bike.
Therefore 140/400 bike.

A: Hint: $$N(S\cup B)=N(S)+N(B)-N(S\cap B)\implies 300=160+N(B)-120\implies N(B)=260$$

A: Let
$$
A - \texttt{Bike}\\
B - \texttt{Swim}\\
C - \texttt{Do nothing}\\
$$
Then
$$
|\Omega| = |A \cup B \cup C| = 400\\
|A \cup B| = 300\\
|B| = 160\\
|A \cap B| = 120\\
$$
You are looking for $\frac{|A|}{|\Omega|}$.
Hint: Use inclusion–exclusion principle.


text:
Q: Charset conversion from XXX to utf-8, command line I have a bunch of text files that are encoded in ISO-8851-2 (have some polish characters). Is there a command line tool for linux/mac that I could run from a shell script to convert this to a saner utf-8?

A: GNU 'libiconv' should be able to do the job.

A: Use iconv, for example like this:
iconv -f LATIN1 -t UTF-8 input.txt > output.txt

Some more information:

*

*You may want to specify UTF-8//TRANSLIT instead of plain UTF-8. To quote the manpage:

If the string //TRANSLIT is appended to to-encoding, characters being converted are transliterated when needed and possible.  This means that when a character cannot be represented in the target character set, it can be approximated through one or several similar looking characters.  Characters that are outside of the target character set and cannot be transliterated are replaced with a question mark (?) in the output.

*For a full list of encoding codes accepted by iconv, execute iconv -l.

*The example above makes use of shell redirection. Make sure you are not using a shell that mangles encodings on redirection – that is, do not use PowerShell for this.

A: recode latin2..utf8 myfile.txt

This will overwrite myfile.txt with the new version.  You can also use recode without a filename as a pipe.


text:
Q: Is it possible to schedule table update/refresh in Oracle Application Express? I have SQL Server data dumped into a text or csv file available via HTTP. Is is possible to schedule Apex to create a table on that data and keep it updated? How?

A: You can do the following steps in a procedure:
1) User UTL_HTTP to read the csv file;
2) Save the file on a oracle directory;
3) Create an external table that will map this CSV file;
4) Schedule this procedure accordingly, using dbms_job_scheduler
This assumes your user has permissions to execute UTL_HTTP, UTL_FILE and DBMS_JOB_SCHEDULER, besides read/write permission in the given oracle directory.


text:
Q: How can I bind a DataSource to an InitialContext for JUnit testing? I'm trying to run JUnit tests on database "worker" classes that do a jndi lookup on an InitialContext to get a DataSource. The worker classes are usually running on a Glassfish v3 App Server which has the appropriate jdbc resources defined.
The code runs just fine when deployed on the App Server but doesn't run from the JUnit testing environment, because obviously it can't find the jndi resources.  So I tried to setup an InitialContext in the test class that binds a datasource to the appropriate context, but it doesn't work.
Here is the code I have in the test
@BeforeClass
public static void setUpClass() throws Exception {
    try {
        // Create initial context
        System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
            "org.apache.naming.java.javaURLContextFactory");
        System.setProperty(Context.URL_PKG_PREFIXES,
            "org.apache.naming");
        InitialContext ic = new InitialContext();

        ic.createSubcontext("java:");
        ic.createSubcontext("java:/comp");
        ic.createSubcontext("java:/comp/env");
        ic.createSubcontext("java:/comp/env/jdbc");

        // Construct DataSource
        SQLServerConnectionPoolDataSource testDS = new SQLServerConnectionPoolDataSource();
        testDS.setServerName("sqlserveraddress");
        testDS.setPortNumber(1433);
        testDS.setDatabaseName("dbname");
        testDS.setUser("username");
        testDS.setPassword("password");

        ic.bind("java:/comp/env/jdbc/TestDS", testDS);

        DataWorker dw = DataWorker.getInstance();
    } catch (NamingException ex) {
        Logger.getLogger(TitleTest.class.getName()).log(Level.SEVERE, null, ex);
    }
}

Then the DataWorker class has a method with the following code, more or less
InitialContext ic = null;
DataSource ds = null;
Connection c = null;
PreparedStatement ps = null;
ResultSet rs = null;
String sql = "SELECT column FROM table";
try{
    ic = new InitialContext();
    ds = (DataSource) ic.lookup("jdbc/TestDS");
    c = ds.getConnection();
    ps = c.prepareStatement(sql);
    // Setup the Prepared Statement
    rs = ps.executeQuery();
    if(rs.next){
        //Process Results
    }
}catch(NamingException e){
    throw new RuntimeException(e);
}finally{
    //Close the ResultSet, PreparedStatement, Connection, InitialContext
}

If I change the
ic.createSubContext("java:/comp/env/jdbc");
ic.bind("java:/comp/env/jdbc/TestDS",testDS);
lines to
ic.createSubContext("jdbc");
ic.bind("jdbc/TestDS",testDS);
The worker class is able to find the DataSource, but fails giving an error saying that "username failed to login to the server".
If I pass the DataSource that I create in the JUnit method directly into the worker, it can connect and run queries.
So, I would like to know how to bind a DataSource that can be looked up by the worker class without being in the Web Container.

A: When I last tried something like this a few years ago, I finally gave up and refactored: at that point, you could NOT create a DataSource outside of a container.   Maybe you can, now, maybe someone's mocked something up.
Still, that smells... You shouldn't have ANY "business logic" code directly dependent on DataSources or JNDI lookups or such.   That's all plumbing to be wired together outside your code.
How flexible is your design?   If your code under test is directly dependent on a DataSource (or even obtains its own Connection), refactor it.  Injecting a Connection will let you can test all you like with plain old JDBC, even using an in-memory implementation, and save you from having to prop up a lot of unnecessary (for the test, anyway) infrastructure to do it.

A: I found that example to be wrong as well.  This worked for me.
ic.createSubcontext("java:comp");
ic.createSubcontext("java:comp/env");
ic.createSubcontext("java:comp/env/jdbc");

final PGSimpleDataSource ds = new PGSimpleDataSource();
ds.setUrl("jdbc:postgresql://localhost:5432/mydb");
ds.setUser("postgres");
ds.setPassword("pg");

ic.bind("java:comp/env/jdbc/mydb", ds);

The difference you'll note is that the '/' after 'java:' in each of the contexts is wrong and shouldn't be there.


text:
Q: How to display hexadecimal bytes using NSLog How can I display the following bytes using NSLog?
const void *devTokenBytes = [devToken bytes];

A: If you want a hex sequence:
NSMutableString *hex = [NSMutableString stringWithCapacity:[devToken length]];
for (int i=0; i < [devToken length]; i++) {
  [hex appendFormat:@"%02x", [devToken bytes][i]];
}

A: Assuming that devToken is of type NSData * (from the bytes call), you can use the description method on NSData to get a string containing the hexadecimal representation of the data's bytes. See the NSData class reference.
NSLog(@"bytes in hex: %@", [devToken description]);


text:
Q: How do I get iScan to detect my Epson network Scanner? I would like to install my Epson Scanner ( model WP-4535 ) in Ubuntu 16.04 (had it installed in 15.10).
I installed this
sudo apt-get install sane libltdl7

then iScan from the epsonpage (1), which is supposed to be an all-in-one package. I installed it via ./install.sh which results in having the following iscan parts:
x@y:~$ dpkg -l iscan* | grep ii
ii  iscan                2.30.3-1     amd64        simple, easy to use scanner utility for EPSON scanners
ii  iscan-data           1.39.0-1     all          Image Scan! for Linux data files
ii  iscan-network-nt     1.1.1-1      amd64        Image Scan! Network Plugin

iScan still cannot communicate with the scanner, though it can be identified via the following command
scanimage -L
device `epson2:net:192.168.0.7' is a Epson PID 087D flatbed scanner

If I recall it from 15.10 (worked after hours of meh) , epkowa was the solution not epson2, but adding it manually via
    sudo nano /etc/sane.d/dll.conf
doesn't work.
The  ubuntuuser page (2), suggests installing ltdl7 packages, which seems to be important, but I have no clue, how to find it (same with the plugin):
iscan_2.X.X-1.ltdl7_i386.deb (32 bit) / iscan_2.X.X-1.ltdl7_amd64.deb (64 bit)

ggf. iscan-plugin-gt-1500_2.1.2-1_i386.deb (allgemein iscan-plugin-SCANNER_VERSION_ARCHITEKTUR.deb) oder z.B. etwas wie esci-interpreter-perfection-v330_0.1.1-2_i386.deb

Also installed  xsltproc (3), because of reasons, but didn't change it.
Any suggestions?; help appreciated!
(1): hxxp://support.epson.net/linux/en/iscan_c.php?version=1.0.4
(2): hxxps://wiki.ubuntuusers.de/Hardware/Epson/#Verwendung-von-iScan
(3): hxxps://wiki.ubuntuusers.de/Scanner/Epson/

A: Due to instant feedback, I post my comment as an answer - if you consider this a duplicate, feel free to delete - I still think, I shouldn't have to browse about 2 hours through different pages to install my *"$§%/( scanner in ubuntu, after this issue has been around for 2 1/2 years, though this probably isn't due to Ubuntu itself and surely not a problem of this community in particular...

Thanks to @belyid (1) I found the reason, in one of the dozen tabs I had opened during my research, while I was running with my head through a wall - edited epkowa.conf and added the ip of the scanner in the network, resulting in scanimage -L to mention epkowa, finding a scanner, and iscan to work with my printer. Thanks and out


text:
Q: Not able to update Entity Framework stored procedure I am using Entity Framework 6, I have a stored procedure (result set with 5 columns) in my DB, when I added it to Entity Framework it generating a class with 5 properties in .tt file.
Now I am changing the stored procedure in my DB (result set with 4 columns) and updating it in Entity Framework, but  I am still getting the 5th property which was not in the result set in my class
public string RoleName { get; set; }
public Nullable<int> RoleId { get; set; }
public Nullable<int> UserId { get; set; }
public string FullName { get; set; }
public Nullable<int> StepNo { get; set; }
public string ADCOId { get; set; }
public Nullable<int> UserId1 { get; set; }

I deleted the UserId1 in the stored procedure and updated Entity Framework, but I am still getting UserId1 property.
Can anyone please help me? Thank you

A: This is a functional limitation in the designer. Take a look at this work item on codeplex - it contains a work around for this.


text:
Q: Breakdown of Analytical Solution to 4th order ODE The Problem:
I have the 4th order Ordinary Differential Equation
$$
\frac{\text{d}^4\theta}{\text{d}\eta^4}
+R(\theta-\theta_*)=0
$$
in the interval $0\le\eta\le1$, subject to the boundary conditions
$$
\eta=0: \frac{\text{d}\theta}{\text{d}\eta}=-1 ;
        \frac{\text{d}^2\theta}{\text{d}\eta^2}=0
$$
$$
\eta=1: \frac{\text{d}\theta}{\text{d}\eta}=0 ;
        \frac{\text{d}^2\theta}{\text{d}\eta^2}=0
$$
and where $\theta_*$ is to be determined such that the clamping constraint
$$\theta(\eta=0)=0$$
is satisfied. Skipping details, it can be shown that the solution to the differential equation is
$$
\theta=\theta_* + e^{P(\eta-1)}(A\cos P\eta+B\sin P\eta)
+e^{-P\eta}(C\cos P\eta+D\sin P\eta)
$$
where $P=\frac{R^\frac{1}{4}}{\sqrt{2}}$ and (skipping details again) the constants $A,B,C,D$ and $\theta_*$ can be determined from the boundary conditions and constraint. So far, so good.
The issue:
The solution works beautifully, until $R$ approaches $10^7$ whereupon it breaks down due to what I believe is the stiffness of the differential equation - the difference between the largest and smallest roots of the characteristic equation is of the order of $2P$ ~$R^\frac{1}{4}$. This is also apparent from the original differential equation itself, where as $R$ becomes very large $\theta \rightarrow \theta_*$ which tends to violate the Neumann boundary condition $\frac{\text{d}\theta}{\text{d}\eta}(\eta=0)=-1$. What I find very odd however, is that the breakdown in the analytical solution is manifested not at $\eta=0$, where the Neumann BC is actually satisfied very well, but by blowing up in the vicinity of $\eta=1$. This is evident in the graphic below:

My Question
Given that the analytical solution tends to break down at large $R$, how much confidence can I place in the computed values in the vicinity of $\eta=0$. The Neumann condition at $\eta=0$ certainly seems to be honoured for $R=10^7$, but I'm a bit circumspect about the correctness of the peak value in the second derivative (right plot in the graphic above).
Any advice? Thanks in advance.
Note that in practice, I clamp the value of $\eta$ used to compute $\theta$ and its derivatives at $\eta=1.1-0.1\log_{10}R$, for $R\ge 10^6$

A: With a proper boundary value solver there is no such boundary layer problem. Using the one from python scipy.integrate the code is
import numpy as np
from scipy.integrate import solve_bvp, odeint
import matplotlib.pyplot as plt

def odesys(t,u,R):
    th = u[0]; th_ast = u[4];
    return [ u[1], u[2], u[3], -R*(th-th_ast), 0*th_ast]

def boundary(u0, u1):
    return [ u0[0], u0[1]+1, u0[2], u1[1], u1[2] ]

x = np.linspace(0, 1, 3)

for R in [ 1e3, 1e4, 1e5, 1e6, 1e7 ]:
    res = solve_bvp(lambda t,u: odesys(t,u,R), boundary, x, [-x, 0*x+1, 0*x, 0*x, 0*x-1])
    x_plot = np.linspace(0, 1, 500)
    u_plot = res.sol(x_plot)
    plt.subplot(1,2,1)
    plt.plot(x_plot, u_plot[0], label='R=%.2e'%R)
    plt.subplot(1,2,2)
    plt.plot(x_plot, u_plot[2], label='R=%.2e'%R)
vlabels = [" ", "$\\theta$", "$\\theta''$"]
for k in [1,2]:
    plt.subplot(1,2,k)
    plt.legend()
    plt.xlabel("$\eta$")
    plt.ylabel(vlabels[k])
    plt.grid();
plt.show()

Note that $\theta_*$ was included in the state as a constant function with derivative $0$ so that the bvp solver automatically also adapts this value. This system with now 5 state dimensions allows to give all 5 boundary conditions at once.
The resulting diagram is

A: I've figured out how to avoid the issue with the breakdown of the analytical solution as follows:
From the constraint $\theta(0)=0)$ we have
$$\theta_* = -(Ae^{-P} +C)$$
and from the no slip condition $\theta''(0)=0$, we have
$$D=Be^{-P}$$
whereupon the remaining boundary conditions yield the following 3 $\times$ 3 system for the constants $A,B$ and $C$
$$ \begin{bmatrix}
    e^{-P} &  2e^{-P} & -1 \\
  \cos P - \sin P\ &(1+e^{-P})\cos P +(1-e^{-P})\sin P  & -e^{-P}(\cos P + \sin P)\\
-\sin P & (1-e^{-P})\cos P &e^{-P}\sin P
  \end{bmatrix}
\begin{bmatrix} A \\ B \\ C\end{bmatrix}
=
\begin{bmatrix} -P^{-1} \\ 0 \\ 0\end{bmatrix}
$$
For very large values of $R$ (large $P$) , the associated very small values of $e^{-P}$ were causing roundoff errors with the default  double precision in the VBA implementation and yielding erroneous evaluations of $B$ and $C$. Assuming a machine roundoff threshold of $10^{-16}$ (typical for double precision), this occurs at a value of $R=7.4\times 10^6$ which is just about where I noticed the analytical solution breaking down! At such low values of  $e^{-P}$, the linear system above is functionally equivalent to
$$ \begin{bmatrix}
    0 &  0 & -1 \\
  \cos P - \sin P\ &\cos P +\sin P  & 0\\
-\sin P & \cos P &0
  \end{bmatrix}
\begin{bmatrix} A \\ B \\ C\end{bmatrix}
=
\begin{bmatrix} -P^{-1} \\ 0 \\ 0\end{bmatrix}
$$
which gives $C=P^{-1}$, $A=B=0$ which yields the correct solution without any restrictions on $R$ and without recourse to the $\eta$- cutoff hack that I was employing earlier.
So in essence, the solution to the problem that I observed is to just set $C=P^{-1}$, $A=B=0$ for $R>7.4\times 10^6$. As seen in the first graphic below, this does result in any perceptibly abrupt changes in $A$, $B$ or $C$ when this fix is implemented.

The temperature and velocity profiles now look like this

A: I found an even simpler solution - balancing the 3$\times$3 system prior to inversion for the coefficients $A,B$ and $C$.


text:
Q: how to extract multiple values from json object using jq command I am trying to get multiple values from a json object.
{
    "nextToken": "9i2x1mbCpfo5hQ",
    "jobSummaryList": [
        {
            "jobName": "012210",
            "jobId": "0196f81cae73"
        }
    ]
}

I want nextToken's value and jobName in one jq command.

A: https://stedolan.github.io/jq/manual/
jq '.nextToken, .jobSummaryList[].jobName' file


text:
Q: Как в Wordpress вывести список страниц с дополнительным полем вместо названия страницы? Надо вывести список страниц-городов. У каждой страницы есть поле Город, где есть нормальное название города. Но сами страницы называются типа "Сдать металлолом в Тагиле". Боги СЕО делали.
Есть страница "Московская область", в ней страницы с городами.
Если брать page-list, то он выводит заголовки вида "Сдать ...".
wp_list_page делает тоже самое.
Используя
[pagelist_ext child_of="699" depth="2" show_image="0" show_meta_key="town_name" show_title="0" show_content="0"]

получаю такое:

Это максимально приближено к требуемому, но там нет ссылок, просто тексты с названиями городов.
Нашёл такой код, но как его вставить на страницу?

    global $post;

    $args = array(
        'post_type' => 'page',
        'post_parent' => $post->ID,
    );

    $query = new WP_Query( $args );

    if ( $query->have_posts() ) {
        while ( $query->have_posts() ) {
            $query->the_post();
            // Здесь ваш код
            echo $post->post_title; // Например, вывод названия страницы
            // Вывод кастомных полей
        }
    } else {
        echo 'Нет записей';
    }

    wp_reset_postdata();


text:
Q: Coalesce array of integers in Hive foo_ids is an array of type bigint, but the entire array could be null.  If the array is null, I want an empty array instead.
If I do this: COALESCE(foo_ids, ARRAY())
I get:

FAILED: SemanticException [Error 10016]: Line 13:45 Argument type mismatch 'ARRAY': The expressions after COALESCE should all have the same type: "array<bigint>" is expected but "array<string>" is found

If I do this: COALESCE(foo_ids, ARRAY<BIGINT>())
I get a syntax error: FAILED: ParseException line 13:59 cannot recognize input near ')' ')' 'AS' in expression specification
What's the proper syntax here?

A: Use this one:
coalesce(foo_ids, array(cast(null as bigint)))
Before, hive is treating empty array [] as []. But in Hadoop2, hive is now showing empty array [] as null (see refence below).  Use array(cast(null as bigint)) for empty array of type bigint. Strangely, the size of empty array is -1 (instead of 0).  Hope this helps. Thanks.
Sample data:
foo_ids
[112345677899098765,1123456778990987633]
[null,null]
NULL

select foo_ids, size(foo_ids) as sz from tbl;
Result:
foo_ids                                        sz
[112345677899098765,1123456778990987633]        2
[null,null]                                     2
NULL                                           -1

select foo_ids, coalesce(foo_ids, array(cast(null as bigint))) as newfoo from tbl;
Result:
foo_ids                                         newfoo
[112345677899098765,1123456778990987633]        [112345677899098765,1123456778990987633]
[null,null]                                     [null,null]
NULL                                            NULL

Reference: https://docs.treasuredata.com/articles/hive-change-201602


text:
Q: HTML parsing in FLUTTER for android / iOS development We know there is a Jsoup library for android developers to parse html text, code etc. As I am new in flutter mobile app development  I want to know if there is any library like Jsoup to parse html text,code from a web site in flutter.

A: I solve the problem for me. Firstly, to user parser you should fetch data using http.get(url). After that you can parse what you want.
Fetch html page:
Future<String> fetchHTML(String url) async {
  final response = await http.get(url);

  if (response.statusCode == 200)
    return response.body;
  else throw Exception('Failed');
}

After that you must call FutureBuilder()
    FutureBuilder<String>(
      future: fetchHTML('http://your_page.ru/page.html'),
      builder: (context, snapshot){
        if (snapshot.hasData) {
          //Your downloaded page
          _temp = snapshot.data;
          print(snapshot.data);
          return Text('Finished');
        }
        else if (snapshot.hasError)
          return Text('ERROR');

        return Text('LOADING');
      },
    ),

And now you can parse it:
parse(_temp);

A: You can parse a HTML string this way
import 'package:html/parser.dart';
//here goes the function

String _parseHtmlString(String htmlString) {

var document = parse(htmlString);

String parsedString = parse(document.body.text).documentElement.text;

return parsedString;
}

Please let me know this doesn't solve your problem.


text:
Q: Casting from vector to array of object Actually am working on XML-RPC. Am trying to execute a method in client class which returns an array of objects. Here is the way am trying to execute it in client class.
Object[] result =  (Object[]) client.execute("getNames" , vector);

while vector represent an array of vector of types string & "getNames" represents the methods name in default handler class :
public Object[] getNames(String a, String b, String c) {
        Vector<String> strings = new Vector<String>();
        strings.add(a);
        strings.add(b);
        strings.add(c);
        String [] arrOfString = strings.toArray(new String[strings.size()]);
        return arrOfString ;
    }

when running, the following exception occured:
java.lang.ClassCastException: java.util.Vector cannot be cast to [Ljava.lang.Object;
    at org.apache.xmlrpc.demo.SimpleClient.<init>(SimpleClient.java:37)
    at org.apache.xmlrpc.demo.SimpleClient.main(SimpleClient.java:65)

what can I do to solve this casting problem ?

A: You can simply use the toArray method of the Vector class in your getNames method.
public Object[] getNames(String a, String b, String c) {
        Vector<String> strings = new Vector<String>();
        strings.add(a);
        strings.add(b);
        strings.add(c);
        return strings.toArray();
}

But, if i get what you really want to do I think you can simply do something like :
Object[] result =  vector.toArray();

if vector is indeed of type Vector.


text:
Q: How can I add 3 bullet points in Graphviz on top of the arrow between two nodes? I am trying to create a neural network diagram using Graphviz. So basically I want to leave more space between Dropout 1 and LSTM 4 and add on top of the arrow 3 bullet points to indicate that there are more layers repeating. Also since I have in total 50 nodes I would like to leave space between the first two red nodes and the third one and adding bullet points there as well. Hope I am making myself clear.
Diagram I am trying to create I used paint to draw the spacing and the bullets

digraph G {
    rankdir=LR
    splines=line
    node [fixedsize=false, label=""];

    subgraph cluster_0 {
        color=white;
        node [style=solid,color=red2, shape=circle];
        x1 x2 x3;
        label = "Input layer (60,1)";
    }
        subgraph cluster_1 {
        color=white;
        node [style=solid,color=blue4, shape=circle];
        a12 a22 a32;
        label = "LSTM 1 (60,1)";
    }

    subgraph cluster_2 {
        color=white;
        node [style=solid,color=blue4, shape=circle];
        b12 b22 b32;
        label="Dropout 1(0.2 probability)";
    }
subgraph cluster_7 {
    color=white;
    node [style=solid,color=blue4, shape=circle];
    c12 c22 c32;
    label="LSTM 4(60,50)";
}

subgraph cluster_8 {
    color=white;
    node [style=solid,color=blue4, shape=circle];
    d12 d22 d32;
    label="Dropout 4(0.2 probability)";
}

subgraph cluster_9 {
    color=white;
    node [style=solid,color=red2, shape=circle];
    O;
    label="Dense(1)";
}

        x1 -> a12;
        x1 -> a22;
        x1 -> a32;
        x2 -> a12;
        x2 -> a22;
        x2 -> a32;
        x3 -> a12;
        x3 -> a22;
        x3 -> a32;

        a12 -> b12;
        a12 -> b22;
        a12 -> b32;
        a22 -> b12;
        a22 -> b22;
        a22 -> b32;
        a32 -> b12;
        a32 -> b22;
        a32 -> b32;

        b12 -> c12;
        b12 -> c22;
        b12 -> c32;
        b22 -> c12;
        b22 -> c22;
        b22 -> c32;
        b32 -> c12;
        b32 -> c22;
        b32 -> c32;

        c12 -> d12;
        c12 -> d22;
        c12 -> d32;
        c22 -> d12;
        c22 -> d22;
        c22 -> d32;
        c32 -> d12;
        c32 -> d22;
        c32 -> d32;

        d12 -> O
        d22 -> O
        d32 -> O

}

A: Add some scafolding (invis nodes and edges)
also needed an xlabel not to bend one of the edges
and constraint on some edges to make drawing straight
e.g.:
digraph G {
    rankdir=LR
    splines=line
    node [fixedsize=false, label=""];

{node[shape=point color=invis] x0 a02 b02 c02 d02}

    subgraph cluster_0 {
        color=white;
        node [style=solid,color=red2, shape=circle];
        x0
        x1 x2 x3;
        label = "Input layer (60,1)";
    }
        subgraph cluster_1 {
        color=white;
        node [style=solid,color=blue4, shape=circle];
        a02
        a12 a22 a32;
        label = "LSTM 1 (60,1)";
    }

    subgraph cluster_2 {
        color=white;
        node [style=solid,color=blue4, shape=circle];
        b02
        b12 b22 b32;
        label="Dropout 1(0.2 probability)";
    }
subgraph cluster_7 {
    color=white;
    node [style=solid,color=blue4, shape=circle];
    c02
    c12 c22 c32;
    label="LSTM 4(60,50)";
}

subgraph cluster_8 {
    color=white;
    node [style=solid,color=blue4, shape=circle];
    d02
    d12 d22 d32;
    label="Dropout 4(0.2 probability)";
}

subgraph cluster_9 {
    color=white;
    node [style=solid,color=red2, shape=circle];
    O;
    label="Dense(1)";
}

edge[minlen=2]
    {node[shape=point color=invis]
     edge[dir=both arrowhead=tee arrowtail=tee]
    rank=same x03->x02[label=<⋮>] // is utf8 vertical ellipsis
    }
    {edge[style=invis minlen=1]
        x003[shape=none]
        x003->x03->x1
        x02->x2

    }
    {
     edge[dir=both arrowhead=tee arrowtail=tee]
        b02 -> c02[xlabel="..."]
    }
    //{rank=same b32 b02}

        x1 -> a12;
        x1 -> a22[constraint=0];
        x1 -> a32[constraint=0];
        x2 -> a12[constraint=0];
        x2 -> a22;
        x2 -> a32[constraint=0];
        x3 -> a12[constraint=0];
        x3 -> a22[constraint=0];
        x3 -> a32;

        a12 -> b12;
        a12 -> b22[constraint=0];
        a12 -> b32[constraint=0];
        a22 -> b12[constraint=0];
        a22 -> b22;
        a22 -> b32[constraint=0];
        a32 -> b12[constraint=0];
        a32 -> b22[constraint=0];
        a32 -> b32;

        b12 -> c12;
        b12 -> c22[constraint=0];
        b12 -> c32[constraint=0];
        b22 -> c12[constraint=0];
        b22 -> c22;
        b22 -> c32[constraint=0];
        b32 -> c12[constraint=0];
        b32 -> c22[constraint=0];
        b32 -> c32;

        c12 -> d12;
        c12 -> d22[constraint=0];
        c12 -> d32[constraint=0];
        c22 -> d12[constraint=0];
        c22 -> d22;
        c22 -> d32[constraint=0];
        c32 -> d12[constraint=0];
        c32 -> d22[constraint=0];
        c32 -> d32;

        d12 -> O
        d22 -> O
        d32 -> O

}

rendered on viz-js.com


text:
Q: DocumentDb transactions as a part of an external transaction scope Is there a way to make DocumentDb transactions part of an external transaction from C#?
This is a follow-up question from here and failure in transaction 3 below should rollback any documentDb updates.
using (var scope = new TransactionScope)
{
//first transaction

//write to document db

//third transaction
}

A: I solved this by implementing IEnlistmentNotification on DocumentDbRepository interacting with DocumentDb n the following way -

*

*Implement the interface

*Make the current instance part of the Transaction.Current in the constructor. (Or before any update if you are using dependency injection and object are created beforehand. Using Lazy<> can also be considered for constructor invocation during the transaction.

*During create/update - save the old document, or the fact that the new object was created and save the selfLink.

*If Rollback is called, take corrective action with the information saved in the step above.

PS - I can share the pseudo code if anyone is interested, please leave a comment.


text:
Q: Reformat List of Table Columns by Header I'm sure there's something obvious I'm missing, so any help is appreciated. I'm working with a Data Table in a Table Format. I have a few headers I'd like to reformat in a General number format. I'm unsure if the data when it's dropped in will remain the same so I figure I'd like to work off of names rather than the column numbers or letters. This is part of a bigger project, but this is the first steps so the rest is irrelevant for now.
When I run this I get the error

Run-Time error 438 Object doesn't support this property or method

on the .Union block.
Dim Table As Excel.ListObject
Dim SortColIndex As Long
Dim SortCol As Range

Private Sub DefineVars()

Set Table = ActiveWorkbook.Worksheets("Data").ListObjects("_Data")
SortColIndex = Table.ListColumns("Bill to Account Number").Index
Set SortCol = Table.ListColumns(SortColIndex).Range

End Sub

Sub Fedex()

Call DefineVars

With Table
    .Union(.ListColumns("Bill to Account Number").DataBodyRange, _
    .ListColumns("Net Charge Amount").DataBodyRange, _
    .ListColumns("Tracking ID Charge Amount").DataBodyRange, _
    .ListColumns("Tracking ID Charge Amount9").DataBodyRange, _
    .ListColumns("Tracking ID Charge Amount11").DataBodyRange).Select
End With
With Selection
    .NumberFormat = "General"
End With

With Table
    .Sort.SortFields.Clear
    .Sort.SortFields.Add _
        Key:=SortCol, _
        SortOn:=xlSortOnValues, _
        Order:=xlDescending
    With .Sort
    .Header = xlYes
    .Apply
    End With
End With

End Sub

A: Try the code below, I've added explanation inside the code's comments:
Option Explicit

Sub Fedex()

Dim Tbl As ListObject
Dim TblRng As Range

'Call DefineVars

' set the ListObject (assuming you have 1 table in your worksheet)
Set Tbl = Worksheets("Sheet1").ListObjects(1) ' rename according to your sheet's name

With Tbl
    ' set the Range inside the ListObject (don't use Select)
    Set TblRng = Application.Union(.ListColumns("Bill to Account Number").DataBodyRange, _
                .ListColumns("Net Charge Amount").DataBodyRange, _
                .ListColumns("Tracking ID Charge Amount").DataBodyRange, _
                .ListColumns("Tracking ID Charge Amount9").DataBodyRange, _
                .ListColumns("Tracking ID Charge Amount11").DataBodyRange)
End With
With TblRng
    .NumberFormat = "General"
End With

' rest of your code ...

End Sub


text:
Q: Cisco VPN connection using CertStore as in Windows In Windows I was using Cisco VPN client to connect with VPN. In connection properties I set only hostname and choose certificate which are stored in C:\Program Files\Cisco Systems\VPN Client\Certificates.
I moved yesterday to Ubuntu and I need to be able to connect with that host using those certificates too.
I know that there is vpnc and network-manager-vpnc but it not allows (or I do not know about it) to set cerificates dir.
Can someone tell me how to connect with VPN using certificates ?

A: I am not sure about the use of certificates but I use Cisco vpns for connecting to work and I just import the .pcf files into netowrk-manager and the connection works.
Perhaps you can try that.
Else you may try installing the Cisco VPN client from cisco for Linux. Here's the tutorial for that. http://blog.bitengine.ca/?p=107


text:
Q: How to convert all factor variables into numeric variables in a large data frame without loosing variables labels? I am trying to convert all factor variables to numeric variables in a large data frame. While converting, variable labels (elaborative name of variables) are lost in the new data frame. Is there any easy way to covert factor variables into numeric variables in a data frame without losing variable. The sample code is given below. Thank you.
v1 <- c('1','4','5')
v2 <- c('21000', '23400', '26800')
v3 <- c('2010','2008','2007')
data <- data.frame(v1, v2, v3)
library(Hmisc)
label(data$v1) <- "Number"
label (data$v2) <- "Value"
label (data$v3) <- "Year"

data[] <- as.numeric(factor(as.matrix(data)))
View(data)

A: You could save the attributes beforehand and restore them.
## save labels
attr.data <- lapply(dat, attr, "label")

## convert to numeric and restore labels
dat[] <- Map(function(x, y) `attr<-`(as.numeric(levels(x))[x], "label", y), dat, attr.data)

In one step:
dat[] <- Map(function(x, y)
  `attr<-`(as.numeric(levels(x))[x], "label", y), dat, Map(attr, dat, "label"))

Explanation
The labels are stored in attributes (try attributes(data)) and can be accessed with attr and their names. The name of label attributes is "label" and we can catch them during conversion. Map handles columns and attributes in a corresponding manner to ensure that the correct labels are assigned.
Result
dat
#   v1    v2   v3
# 1  1 21000 2010
# 2  4 23400 2008
# 3  5 26800 2007

str(dat)
# 'data.frame': 3 obs. of  3 variables:
#   $ v1: num  1 4 5
# ..- attr(*, "label")= chr "Number"
# $ v2: num  21000 23400 26800
# ..- attr(*, "label")= chr "Value"
# $ v3: num  2010 2008 2007
# ..- attr(*, "label")= chr "Year"

Data
dat <- structure(list(v1 = structure(1:3, .Label = c("1", "4", "5"), class = c("labelled",
"factor"), label = "Number"), v2 = structure(1:3, .Label = c("21000",
"23400", "26800"), class = c("labelled", "factor"), label = "Value"),
    v3 = structure(3:1, .Label = c("2007", "2008", "2010"), class = c("labelled",
    "factor"), label = "Year")), row.names = c(NA, -3L), class = "data.frame")

Sidenote: I use dat rather than data here, because data is already occupied from R to load specific datasets.


text:
Q: Good advices to use EF in a multithread program? Have you got some good advices to use EF in a multithread program ?
I have 2 layers :

*

*a EF layer to read/write into my database

*a multithread service which uses my entities (read/write) and makes some computations (I use Task Parallel Library in the framework)

How can I synchronize my object contexts in each thread ?
Do you know a good pattern to make it work ?

A: Good advice is - just don't :-) EF barely manages to survive one thread - the nature of the beast.
If you absolutely have to use it, make the lightest DTO-s, close OC as soon as you have the data, repack data, spawn your threads just to do calculations and nothing else, wait till they are done, then create another OC and dump data back into DB, reconcile it etc.
If another "main" thread (the one that spawns N calculation threads via TPL) needs to know when some ther thread is done fire event, just set a flag in the other thread and then let it's code check the flag in it's loop and react by creating new OC and then reconciling data if it has to.
If your situation is more simple you can adapt this - the key is that you can only set a flag and let another thread react when it's ready. That means that it's in a stable state, has finished a round of whatever it was doing and can do things without risking race conditions. Reset the flag (an int) with interchaged operations and keep some timing data to make sure that your threads don't react again within some time T - otherwire they can spend their lifetime just querying DB.

A: This is how I implemented it my scenario.
var processing= new ConcurrentQueue<int>();

//possible multi threaded enumeration only processed non-queued records
Parallel.ForEach(dataEnumeration, dataItem=>
{
     if(!processing.Contains(dataItem.Id))
     {
         processing.Enqueue(dataItem.Id);

          var myEntityResource = new EntityResource();

          myEntityResource.EntityRecords.Add(new EntityRecord
                                      {
                                        Field1="Value1",
                                        Field2="Value2"
                                      }
                               );

           SaveContext(myEntityResource);

       var itemIdProcessed = 0;
       processing.TryDequeue(out itemIdProcessed );

     }

}

public void RefreshContext(DbContext context)
    {
        var modifiedEntries = context.ChangeTracker.Entries()
            .Where(e => e.State == EntityState.Modified || e.State == EntityState.Deleted);
        foreach (var modifiedEntry in modifiedEntries)
        {
            modifiedEntry.Reload();
        }
    }

public bool SaveContext(DbContext context,out Exception error, bool reloadContextFirst = true)
    {
        error = null;
        var saved = false;
        try
        {
            if (reloadContextFirst)
                this.RefreshContext(context);
            context.SaveChanges();
            saved = true;
        }
        catch (OptimisticConcurrencyException)
        {
            //retry saving on concurrency error
            if (reloadContextFirst)
                this.RefreshContext(context);
            context.SaveChanges();
            saved = true;
        }
        catch (DbEntityValidationException dbValEx)
        {
            var outputLines = new StringBuilder();
            foreach (var eve in dbValEx.EntityValidationErrors)
            {
                outputLines.AppendFormat("{0}: Entity of type \"{1}\" in state \"{2}\" has the following validation errors:",
                    DateTime.Now, eve.Entry.Entity.GetType().Name, eve.Entry.State);
                foreach (var ve in eve.ValidationErrors)
                {
                    outputLines.AppendFormat("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage);
                }
            }

            throw new DbEntityValidationException(string.Format("Validation errors\r\n{0}", outputLines.ToString()), dbValEx);
        }
        catch (Exception ex)
        {
            error = new Exception("Error saving changes to the database.", ex);
        }
        return saved;
    }

A: I think Craig might be right about your application no needing to have threads.. but you might look for the uses of ConcurrencyCheck in your models to make sure you don't "override" your changes

A: I don't know how much of your application is actually number crunching. If speed is the motivation for using multi-threading then it might pay off to take a step back and gather data about where the bottle next is.
In a lot of cases I have found that the limiting factor in applications using a database server is the speed of the I/O system for your storage. For example the speed of the hard drive disk(s) and their configuration can have a huge impact. A single hard drive disk with 7,200 RPM can handle about 60 transactions per second (ball park figure depending on many factors).
So my suggestion would be to first measure and find out where the bottle next is. Chances are you don't even need threads. That would make the code substantially easier to maintain and the quality is much higher in all likelihood.

A: "How can I synchronize my object contexts in each thread ?"
This is going to be tough. First of all SP or the DB queries can have parallel execution plan. So if you also have parallelism on object context you have to manually make sure that you have sufficient isolation but just enough that you dont hold lock too long that you cause deadlocks.
So I would say dont need to do it .
But that might not be the answer you want. So Can you explain a bit more what you want to achieve using this mutithreading. Is it more compute bound or IO bound. If it is IO bound long running ops then look at APM by Jeff Richter.

A: I think your question is more about synchronization between threads and EF is irrelevvant here. If I understand correctly you want to notify threads from one group when the main thread performed some operation - in this case "SaveChanges()" operation. The threads here are like client-server applications, where one thread is a server and other threads are clients and you want client-threads to react on server activity.
As someone noticed you probably do not need threads, but let's leave it as it is.
There is no fear of dead locks as long as you are going to use separate OC per thread.
I also assume that your client threads are long-running thread in some kind of loop. If you want your code to be executed on client thread you can't use C# events.
class ClientThread {
public bool SomethingHasChanged;

  public MainLoop()
  {
    Loop {
      if (SomethingHasChanged)
      {
        refresh();
        SomethingHasChanged = false;
      }

      // your business logic here

    } // End Loop
  }
}

Now the question is how you will set the flag in all your client-threads? You could keep references to client threads in your main thread and loop through them and set all flags to true.

A: Back when I used EF, I simply had one ObjectContext, to which I synchronized all access.
This isn't ideal. Your database layer would effectively be singlethreaded. But, it did keep it thread-safe in a multithreaded environment. In my case, the heavy computation was not in the database code at all - this was a game server, so game logic was of course the primary resource hog. So, I didn't have any particular need for a multithreaded DB layer.


text:
Q: Update dropdownmenu with values from dataframe in pandas I'm busy with programming an interactive graph where the values in the graph are chosen based on columnvalues from a dataframe. So, I want to make a graph of values in column x where only the values are chosen which fullfil several conditions from another columns in the dataframe. I have the following dataframe (data): Dataframe
data = pd.DataFrame([[3,'VW-b','1 R- R',119.080,'TS',13.56],
                 [3,'VW-b','1 R- R',119.090,'RS',18.56],
                 [3,'VW-b','1 R- R',119.100,'TS',12.85],
                 [3,'VW-b','1 R- R',119.110,'TS',9.56],
                 [3,'VW-b','1 R- R',119.120,'RS',8.86],
                 [3,'VW-b','1 R- R',119.130,'TS',13.56],
                 [3,'VW-b','1 R- R',119.140,'TS',19.56],
                 [3,'VW-b','1 R- R',119.150,'TS',14.56],
                 [3,'HRL','1 R- R',159.080,'RS',13.56],
                 [3,'VW-c','1 R- R',19.080,'RS',13.56],
                 [3,'VW-s','1 R- R',254.080,'TS',13.56],
                 [3,'VW-b','1 R- R',25.020,'TS',13.56],
                 [3,'VW-b','1 R- R',25.030,'TS',16.56]],
                columns=['IGO', 'Baan','Strook','Km','Spoor','IDK1-2'])

My imports are:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import ipywidgets as widgets
from ipywidgets import interact
from ipywidgets import interactive
from IPython.display import display

%matplotlib inline

I wrote the following code:
def choice(igo, baan, strook, spoor, kmv, kmt):
    Igo = data['IGO'] == igo
    Baan = data['Baan'] == baan
    Strook = data['Strook'] == strook
    Spoor = data['Spoor'] == spoor
    Kmv = data['Km'] == kmv
    Kmt = data['Km'] == kmt

    plt.plot(data['IDK1-2'])
    plt.xlim(kmv,kmt)

w = interactive(choice,
     igo=widgets.Dropdown(options=data['IGO'].unique(),description='IGO'),
     baan=widgets.Dropdown(options=data['Baan'].loc[data['IGO'] == igo].unique(),description='Baan'),
     strook=widgets.Dropdown(options=data['Strook'].loc[data['Baan'] == baan].unique(),description='Strook'),
     spoor=widgets.RadioButtons(options=data['Spoor'].unique(),value='TS',description='Spoor'),
     kmv=widgets.Dropdown(options=data['Km'].unique(),description='Van km'),
     kmt=widgets.Dropdown(options=data['Km'].unique(),description='Tot km'))
display(w)

How can I make the code in such a way that I can choose first the IGO, than the baan (available choices based on IGO) etc?


text:
Q: Major HDD slowdown after hot swap of another drive Earlier I inserted a SATA drive into a simple one drive backplane I have.  After a "detect hardware changes" the drive appeared, and worked correctly.  Later, I removed it.
Since that time, my primary SATA drive, a Western Digital Caviar Black 640GB, which was never disconnected, is extremely slow, on the order of 4.0MB/second maximum transfer rate.
The first thing I considered is that the drive might be failing, but it passes the DataLifeguard Quick Test and Windows chkdsk.  While this cannot rule out a hardware problem, it indicates against it.
Can my insertion and removal of another SATA drive have reset the connection into some very slow compatibility mode?  How do I fix it?  If that is not the problem, what else could cause this?

A: Sure enough, the controller channel had fallen back to PIO from Ultra DMA 5.
The solution was:

*

*Find the sub-key for the controller channel within:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\{4D36E96A-E325-11CE-BFC1-08002BE10318}

*Delete MasterIdDataChecksum and SlaveIdDataChecksum

*Reboot


text:
Q: Error Handling on Controller In my MVC application, I use uploadify for file uploads. The controller action is:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase fileData, FormCollection forms)
{
  try
  {
    if (fileData.ContentLength > 0)
    {
      var statusCode = Helper.UploadList();
      if (statusCode.Equals(System.Net.HttpStatusCode.Created))
      return Json(new { success = true });
    }
  }
  return Json(new { success = false });
}
catch (Exception ex)
{
}

I set success= true/false based on the StatusCode and pass it to the onComplete event of uploadify (in a .js file) and show some meaningful alerts.
If Helper.UploadList() throws an exception like:
throw new ArgumentException("Doesn't exist");

How can I catch that exception in the controller action and eventually pass it to the .js file so that I can show an error to the user?
EDIT:
If I set  return Json(new { success = false });    in the catch block, the value doesn't reach the onComplete.
'onComplete': function (event, queueID, fileObj, response, data) {
                if (response == '{"success":true}') {
                    alert("file uploaded successfully.");
                }
                else if (response == '{"success":false}') {
                    alert('file failed to upload. Please try again!');
                }
                return false;
            },

    I see this on the UI:

A: you can do this a little smarter :
public class ErrorModel{
    public bool Success{get;set;}
    public string Reason{get;set;}
}

public JsonResult Upload(HttpPostedFileBase fileData, FormCollection forms)
 {
    var model = new ErrorModel { Success = false };
    try
 {
    if (fileData.ContentLength > 0)
  {
     var statusCode = Helper.UploadList();
    if (statusCode.Equals(System.Net.HttpStatusCode.Created))
    model.Reason = "File uploaded: " + filename;
    model.Success = true;
    return JSon(model);
   } else {
     model.REason = "ERROR: failed to upload file";
     return JSon(model);
   }
 }

   }
    catch (Exception ex)
  {
 model.reason = ex.Message;
 return JSon(model);
}

javascript:
dataTYpe: 'json',
success: function(data){
     if(data.Success){
       } else {
         alert(data.Reason);
      }
}

needs a little extra work and you need to do more checking on your file, but you will find it easier to return meaningful results this way.

A: you might consider returning a status code
catch(Exception ex)
{
    return new HttpStatusCodeResult(400, "Unexpected error uploading");
}

in your js
$.ajax({
    url: "http://blaa.com/Upload",
    type: "post",
    statusCode: {
        400: function(e) {
            // do whatever
        }
    }
});

the message can be found in e.statusText, but you must be using IIS or IIS Express to see it, the VS dev server does not send it when debugging - http://forums.asp.net/post/4180034.aspx


text:
Q: Try to answer some boolean queries using Term-Document-Incidence-Matrix I try answer some simple boolean query in these ways NOT x NOT y NOT z also x AND y AND z and also like this x OR y OR z x,y,z are some words and any of them belongs to a different file.txtor maybe all of them belongs to same file.txt, no matter .
I've written a class TermDocMatrix:
it must be able to answer a boolean query , I prepared some methods in class TermDocMatrix{ }for these purposes but it doesn't work. I even debug the code step by step, I realized loops have no turn. I don't know why, codes seems fine.
well you can see code in here :
class TermDocMatrix
{
    //stores distinct terms
    public HashSet<string> distinctTerm = new HashSet<string>();
    //stores document id and its contents without splitting
    public Dictionary<int, string> documentContentList = new Dictionary<int, string>();
    //stores document and its terms collection
    public Dictionary<string, List<string>> documentCollection = new Dictionary<string, List<string>>();
    public Dictionary<string, List<int>> termDocumentIncidenceMatrix = new Dictionary<string, List<int>>();

     //stop words collection
    public List<string> stopWords = new List<string> { "on", "of", "The", "an", "a", "in" };
    //boolean operators list
    public string[] booleanOperator = new string[] { "AND", "OR", "NOT" };

    private string _FileName = "words";
    public string _Path = "";
    int _lastDocNum = 0;

    public TermDocMatrix(string IndexPath,string FileName)
    {

        if (_Path.EndsWith("\\") == false) _Path += "\\";
        if (!Directory.Exists(IndexPath)) Directory.CreateDirectory(IndexPath);
        LogManager.Configure(_Path + _FileName + ".txt", false);
        // read all files
        LoadFiles();
    }

    private void LoadFiles()
    {
        int count = 0;

        if (File.Exists(_Path + _FileName + ".txt") == false)
            return;
        // load words
        string b = File.ReadAllText(_Path + _FileName + ".txt");
        String[] TermsCollection = RemoveStopsWords(b.ToUpper().Split(' '));
        foreach (string term in TermsCollection)
        {
            //prepeare distinct terms collection
            //remove stop words
            if (!stopWords.Contains(term))
            {
                distinctTerm.Add(term);
            }
        }
        //add document and their terms collection
        documentCollection.Add(_FileName, TermsCollection.ToList());
        //add document and its content for displaying the search result
        documentContentList.Add(count, b);
        count++;
    }
    public string ProcessFiles(string query)
    {
        termDocumentIncidenceMatrix = GetTermDocumentIncidenceMatrix(distinctTerm, documentCollection);
        do
        {
            List<int> lst = ProcessQuery(query);
            int count = 0;
            if (lst != null)
            {
                foreach (int a in lst)
                {
                    if (a == 1)
                    {
                         return documentContentList[count];
                    }
                    count++;
                }
            }
            else
            {
                return "No search result found";
            }

        } while (1 == 1);
    }
    public int WordCount()
    {
        return documentCollection.Count;
    }

    public int DocumentCount
    {
        get
        {
            return _lastDocNum;
        }
    }

    private void FilterQueryTerm(ref string[] str)
    {
        List<string> _queryTerm = new List<string>();

        foreach (string queryTerm in str)
        {
            if (queryTerm.ToUpper().Equals("BUT") || termDocumentIncidenceMatrix.ContainsKey(queryTerm.ToUpper()) || booleanOperator.Contains(queryTerm))
            {
                _queryTerm.Add(queryTerm);

            }
        }

        str = _queryTerm.ToArray();
    }

    //prepares Term Document Incidence Matrix
    public Dictionary<string, List<int>> GetTermDocumentIncidenceMatrix(HashSet<string> distinctTerms, Dictionary<string, List<string>> documentCollection)
    {
        Dictionary<string, List<int>> termDocumentIncidenceMatrix = new Dictionary<string, List<int>>();
        List<int> incidenceVector = new List<int>();
        foreach (string term in distinctTerms)
        {
            //incidence vector for each terms
            incidenceVector = new List<int>();
            foreach (KeyValuePair<string, List<string>> p in documentCollection)
            {

                if (p.Value.Contains(term))
                {
                    //document contains the term
                    incidenceVector.Add(1);

                }
                else
                {
                    //document do not contains the term
                    incidenceVector.Add(0);
                }
            }
            termDocumentIncidenceMatrix.Add(term, incidenceVector);

        }
        return termDocumentIncidenceMatrix;
    }
    //removes all stop words
    public string[] RemoveStopsWords(string[] str)
    {
        List<string> terms = new List<string>();
        foreach (string term in str)
        {
            if (!stopWords.Contains(term))
            {
                terms.Add(term);
            }
        }
        return terms.ToArray();
    }
    //process the boolean query
    public List<int> ProcessQuery(string query)
    {

        //query boolean operator
        string bitWiseOp = string.Empty;
        string[] queryTerm = RemoveStopsWords(query.ToUpper().Split(' '));

        //remove query term that doesnot appears on document collection
        FilterQueryTerm(ref queryTerm);
        List<int> previousTermIncidenceV = null;
        List<int> nextTermsIncidenceV = null;
        //holds the bitwise operation result
        List<int> resultSet = null;
        //suppose on query X AND Y, X is previousTerm term and Y is nextTerm
        Boolean hasPreviousTerm = false;
        Boolean hasNotOperation = false;
        foreach (string term in queryTerm)
        {
            //is a term
            if (!booleanOperator.Contains(term) && !term.Equals("BUT"))
            {
                //query case: structure AND NOT analysis
                if (hasNotOperation)
                {

                    if (hasPreviousTerm)
                    {
                        nextTermsIncidenceV = ProcessBooleanOperator("NOT", GetTermIncidenceVector(term), nextTermsIncidenceV);
                    }
                    //query case: eg.NOT analysis
                    else
                    {
                        previousTermIncidenceV = ProcessBooleanOperator("NOT", GetTermIncidenceVector(term), nextTermsIncidenceV);
                        resultSet = previousTermIncidenceV;
                    }
                    hasNotOperation = false;
                }
                else if (!hasPreviousTerm)
                {
                    previousTermIncidenceV = GetTermIncidenceVector(term);
                    resultSet = previousTermIncidenceV;
                    hasPreviousTerm = true;
                }
                else
                {

                    nextTermsIncidenceV = GetTermIncidenceVector(term);
                }
            }
            else if (term.Equals("NOT"))
            {
                //indicates that the  term in the next iteration should be complemented.
                hasNotOperation = true;
            }
            else
            {
                //'BUT' also should be evaluated as AND eg. structure BUT NOT semantic should be evaluated as structure AND NOT semantic
                if (term.Equals("BUT"))
                {
                    bitWiseOp = "AND";
                }
                else
                    bitWiseOp = term;
            }

            if (nextTermsIncidenceV != null && !hasNotOperation)
            {
                resultSet = ProcessBooleanOperator(bitWiseOp, previousTermIncidenceV, nextTermsIncidenceV);
                previousTermIncidenceV = resultSet;
                hasPreviousTerm = true;
                nextTermsIncidenceV = null;
            }
        }

        return resultSet;
    }

    //Process Boolean operators
    public List<int> ProcessBooleanOperator(string op, List<int> previousTermV, List<int> nextTermV)
    {
        List<int> resultSet = new List<int>();
        if (op.Equals("NOT"))
        {
            foreach (int a in previousTermV)
            {
                if (a == 1)
                {
                    resultSet.Add(0);
                }
                else
                {
                    resultSet.Add(1);
                }
            }
        }
        else if (op.ToUpper().Equals("AND")) //bitwise AND operation
        {
            for (int a = 0; a < previousTermV.Count; a++)
            {
                if (previousTermV[a] == 1 && nextTermV[a] == 1)
                {
                    resultSet.Add(1);
                }
                else
                {
                    resultSet.Add(0);
                }
            }
        }
        else if (op.ToUpper().Equals("OR")) //bitwise OR operation
        {
            for (int a = 0; a < previousTermV.Count; a++)
            {
                if (previousTermV[a] == 0 && nextTermV[a] == 0)
                {
                    resultSet.Add(0);
                }
                else
                {
                    resultSet.Add(1);
                }
            }
        }
        return resultSet;
    }

    //returns term incidence vector
    public List<int> GetTermIncidenceVector(string term)
    {
        return termDocumentIncidenceMatrix[term.ToUpper()];

    }
}

you need to now about another class named Class LogManager I used it on my Class TermDocMatrix.  Here :
namespace WindowsFormsApplication1
 {
   internal class FileLogger
   {
    public static readonly FileLogger Instance = new FileLogger();

    private string _filename;
    private bool _showMethodName = false;
    private string _FilePath = "";

    public bool ShowMethodNames
    {
        get { return _showMethodName; }
    }

    public void Init(string filename, bool showmethodnames)
    {
        _showMethodName = showmethodnames;
        _filename = filename;
        // handle folder names as well -> create dir etc.
        _FilePath = Path.GetDirectoryName(filename);
        if (_FilePath != "")
        {
            _FilePath = Directory.CreateDirectory(_FilePath).FullName;
            if (_FilePath.EndsWith("\\") == false)
                _FilePath += "\\";
        }
    }
}
internal static class LogManager
{

    public static void Configure(string filename, bool showmethodnames)
    {
        FileLogger.Instance.Init(filename, showmethodnames);
    }
}

}
it must work but it don't. tell me why don't it work, please. when I ask for answer I just see this "No search result found", no matter I'd typed what kind of boolean query.

A: Your problem is in this line: (ProcessFiles function)
String[] termsCollection = RemoveStopsWords(file.ToUpper().Split(' '));

you're splitting the name of the file and not its content
That's why you have no search results
you should do something like this instead:
String[] termsCollection = RemoveStopsWords(File.ReadAllText(file).ToUpper().Split(' '));

Now change your TermDocMatrix constructor:
public TermDocMatrix(string IndexPath,string FileName)
{
    if (!Directory.Exists(IndexPath)) Directory.CreateDirectory(IndexPath);
    LogManager.Configure(System.IO.Path.Combine(_Path, _FileName + ".txt"), false);
    // read all files
    LoadFiles();
}

And your LoadFiles function:
private void LoadFiles()
{
    int count = 0;

    if (File.Exists(System.IO.Path.Combine(_Path, _FileName + ".txt")) == false)
        return;
    // load words
    string b = File.ReadAllText(System.IO.Path.Combine(_Path, _FileName + ".txt"));

    .....
}


text:
Q: Jenkins - declarative pipeline for creating the ZIP package of the branch content I am just beginning with Jenkins but I could not find how I can zip the package of the master branch after the checkout and save it with the build number version. Could you please assist what should be added to make a ZIP? Job is executed on Docker agent
pipeline {
    agent any
    stages {
        stage ('ZIP stage') {
            steps {
                echo "Building the zip package"

            }
        }
    }
}
}

Thank you very much for kind assistance!


text:
Q: insert i would like to create a JavaScript string that holds a dynamic php page
for the
newwindow=window.open();
newdocument=newwindow.document;
newdocument.write(HTMLstring);
newdocument.close();

functions.
when i try to insert the first part of the page it starts a php block
    HTMLstring+='<?php';
    HTMLstring+='echo "this should print";';
    HTMLstring+='?>';

i have tried to start with
    HTMLstring+='<\?php';

but i get
    <!--?phpecho "this should print";?-->

is there a way to do this in JavaScript?
thank you

A: You are misunderstanding how JavaScript and PHP work. PHP runs on the server, JavaScript runs in the client. Using JavaScript to create PHP code is fundamentally impossible.
In your case, it should be possible to use PHP to output the string into JavaScript directly (like
<script> var myHTML = "<? echo $variable; ?>"; </script>

the other common workaround for when you need to access PHP from within JavaScript is Ajax.