text:
Q: How can I optimize this MySql table for search speed using indexes? As a MySql amateur I would like to ask for some advice regarding table optimization and the use of indexes.
Consider a table containing advertisements posted by users. The table has the following structure (this is a Laravel implementation but I think the code is quite self-explanatory):
Schema::create('advertisements', function (Blueprint $table) {
        $table->increments('id');     //PRIMARY KEY AUTOINCREMENTS
        $table->text('images');       //TEXT
        $table->string('name', 150);  //VARCHAR(150)
        $table->string('slug');       //VARCHAR(255)
        $table->text('description');
        $table->string('offer_type',7)->nullable()->index();
        $table->float('price')->nullable();
        $table->string('deal_type')->nullable()->index();
        $table->char('price_period',1)->nullable()->index();
        $table->float('price_per_day')->nullable();
        $table->float('deposit')->nullable();

        $table->integer('category_id')->unsigned()->index();
        $table->foreign('category_id')->references('id')->on('categories');

        $table->integer('author_id')->unsigned()->nullable();
        $table->foreign('author_id')->references('id')->on('users');

        $table->timestamps();
    });

Users on a website can search for advertisements in the table above using several criteria, such as: price range, offer_type, price_period or deal_type.
As you can see I have indexed the offer_type, price_period and deal_type columns. From what I understand this causes the DB to create a BTREE index of the values within these columns.
However these values are always going to be from a pre-defined set:
For example - price_period is always one of: NULL, h, d, w, m, y (hour, day, week, month, year.)
The deal_type column would always be either offer or demand.
Question: If I have a set of columns that will only contain values from a pre-defined, small range of values, is it better (performance-wise) to create a separate table for them and use foreign keys rather than indexing the columns? EDIT: After further research I realize now, that foreign keys are just a referrence tool and not a performance one and they can (and should) be indexed as well. But does having an indexed foreign key, which is a number, perform better than having a short string indexed?

A: Indexing flags and other low-cardinality columns is usually useless.  For example, if half the table has a certain value for a flag, it is faster to ignore the index on that flag and simply scan the entire table.
We really need to see the queries in order to judge what indexes are needed.  Based on your hints, I will make a stab anyway...
"such as: price range, offer_type, price_period or deal_type" -- I assume the user will give a min and max price?  Then let's build a "composite" index ending with price_per_day.  Will they always be specifying all of the other three columns?  And a single value for each column?  If yes to all of the above, then this composite index is optimal:
INDEX(over_types, price_period, deal_type, price_per_day)

(The first 3 columns can be in any order, but the thing applied to the range needs to be last.)
If the user may include only some of those flags, and/or may include multiple values for them, then it becomes messier.  Watch what users ask for and tailor extra indexes based on common queries.  Use this index cookbook to help build them.


text:
Q: MBCS to UTF-8: How to encode in Python I am trying to create a duplicate file finder for Windows. My program works well in Linux. But it writes NUL characters to the log file in Windows. This is due to the MBCS default file system encoding of Windows, while the file system encoding in Linux is UTF-8. How can I convert MBCS to UTF-8 to avoid this error?

A: Tell Python to use UTF-8 on the log file. In Python 3 you do this by:
open(..., encoding='utf-8')

If you want to convert an MBCS string to UTF-8 you can switch string encodings:
filename.encode('mbcs').decode('utf-8')

Use filename.encode(sys.getdefaultencoding())... to make the code work on Linux, as well.

A: Just change the encode to 'latin-1' (encoding='latin-1')
Using pure Python:
open(..., encoding = 'latin-1')
Using Pandas:
pd.read_csv(..., encoding='latin-1')

redpajama_set_name: RedPajamaStackExchange


text:
Q: placeholders in HTML I have a Thymeleaf template that uses placeholders, where the placeholder attribute specifies a short hint that describes the expected value or format of an input field.
The placeholders work when the input text is empty. But if a field containing previously entered data needs to be edited, the previously entered text disappears  and is replaced with placeholder text when the input receives focus.
Is there a way to avoid this ?
the  Thymeleaf template
<form class="form-style-9" action="#" th:action="@{/guardian/save}" th:object="${guardian}" method="post">

        <input type="text"  th:field="*{name}"      id="nameInputTextId"    name="field1" class="field-style field-split align-left"    placeholder="NOMBRE" />
        <input type="text"  th:field="*{surName}"   name="field2" class="field-style field-split align-right"   placeholder="APELLIDOS" />

        <input type="text"  th:field="*{description}"   name="field1" class="field-style field-split align-left"    placeholder="DESCRIPTION" />
        <input type="text"  th:field="*{mobile}"        name="field2" class="field-style field-split align-right"   placeholder="TELEFONO" />

        <input type="text"  th:field="*{email}"     name="field1" class="field-style field-split align-left"    placeholder="EMAIL" />

            <input type="button" value="CANCELAR" />

        <input type="submit" value="GRABAR" />

</form>

and the HTML generated
<!DOCTYPE HTML>

    <meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="tdk" />

<link rel="apple-touch-icon" sizes="57x57" href="../../../images_sebloc/favicon/apple-icon-57x57.png" />
<link rel="apple-touch-icon" sizes="60x60" href="../../../images_sebloc/favicon/apple-icon-60x60.png" />
<link rel="apple-touch-icon" sizes="72x72" href="../../../images_sebloc/favicon/apple-icon-72x72.png" />
<link rel="apple-touch-icon" sizes="76x76" href="../../../images_sebloc/favicon/apple-icon-76x76.png" />
<link rel="apple-touch-icon" sizes="114x114" href="../../../images_sebloc/favicon/apple-icon-114x114.png" />
<link rel="apple-touch-icon" sizes="120x120" href="../../../images_sebloc/favicon/apple-icon-120x120.png" />
<link rel="apple-touch-icon" sizes="144x144" href="../../../images_sebloc/favicon/apple-icon-144x144.png" />
<link rel="apple-touch-icon" sizes="152x152" href="../../../images_sebloc/favicon/apple-icon-152x152.png" />
<link rel="apple-touch-icon" sizes="180x180" href="../../../images_sebloc/favicon/apple-icon-180x180.png" />
<link rel="icon" type="image/png" sizes="192x192" href="../../../images_sebloc/favicon/android-icon-192x192.png" />
<link rel="icon" type="image/png" sizes="32x32" href="../../../images_sebloc/favicon/favicon-32x32.png" />
<link rel="icon" type="image/png" sizes="96x96" href="../../../images_sebloc/favicon/favicon-96x96.png" />
<link rel="icon" type="image/png" sizes="16x16" href="../../../images_sebloc/favicon/favicon-16x16.png" />

<meta name="msapplication-TileColor" content="#ffffff" />
<meta name="msapplication-TileImage" content="_sebloc/favicon/ms-icon-144x144.png" />
<meta name="theme-color" content="#ffffff" />

<title>tdk</title>

<link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.6.0/pure-min.css" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,700" type="text/css" />
<link rel="stylesheet" href="/fonts/font-awesome/css/font-awesome.min.css" />
<link rel="stylesheet" href="/css_sebloc/styles.css" />
<link rel="stylesheet" href="/css/jquery.mCustomScrollbar.css" />

<link rel="stylesheet" type="text/css" href="/css/jquery.mCustomScrollbar.css" />
<link rel="stylesheet" type="text/css" href="/css/bootstrap-datepicker.css" />

<link type="text/css" href="/css/jquery.simple-dtpicker.css" rel="stylesheet" />

        <link rel="stylesheet" href="/css_sebloc/side-menu.css" />

            <link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.6.0/grids-responsive-min.css" />

Notifications

0

0

1

Start

                      Home

                          Horarios Alarma

                          Guardianes

  Account

  SetUp

                      Ideefe Web

                      Help

Device manager V 0.1.2
© Ideefe and Wits 2016

                    Sebloc demo

NUEVO GUARDIAN

<form class="form-style-9" action="/guardian/save" method="post">

      <input type="text" id="nameInputTextId" name="name" class="field-style field-split align-left" placeholder="NOMBRE" value="" />
      <input type="text" name="surName" class="field-style field-split align-right" placeholder="APELLIDOS" id="surName" value="" />

      <input type="text" name="description" class="field-style field-split align-left" placeholder="DESCRIPTION" id="description" value="" />
      <input type="text" name="mobile" class="field-style field-split align-right" placeholder="TELEFONO" id="mobile" value="" />

      <input type="text" name="email" class="field-style field-split align-left" placeholder="EMAIL" id="email" value="" />

            <input type="button" value="CANCELAR" />

    <input type="submit" value="GRABAR" />

<input type="hidden" name="_csrf" value="a5ecc9df-964e-4824-8402-926db7f377f6" /></form>

LOCATION INFO

                                API GOOGLE MAPS (iframe configuration must be width 100% height 100%)

ADDRESS: Rue du Marteau Nº25 BTE65

WORKER: Name Surname

A: I figure out the problem. Removing this file it solved the problem

A: I think this issue has nothing to do with the placeholder being set. It may be due to the reason that you specified the value attribute to be "" ie
in the textfields you specified value = "" .this makes the value of the text field empty and when the text field is empty the placeholder is shown.
try removing value = "".


text:
Q: ASP.NET MVC 5 windows authentication with custom properties I have an ASP.NET MVC web application which is using Windows authentication. I can use HttpContext.User.Identity.Name to get the users username.
I need to be able to store and access additional fields for example full name, telephone etc. I don't have access to Active Directory. I was planning on creating a simple table in the database with with the Windows username and the additional fields as columns.
What is the correct/recommended way to implement this? I'd like to be able to do something like:
HttpContext.User.Identity.Telephone


text:
Q: One function is in scope and one out of scope even though both are defined in the same location Both functions are called from document.ready:
$(document).ready(function () {
    pnp.sp.web.lists.getByTitle("inReviewContracts").items.getAll().then (function(items) {
        spContractList = items;
        constructTable('#in-review-requests-table');
        colorTable();
        getNumVisibleContracts();
        calculateTotalCost();
        populateDashboardNumbers();
    }).catch(function(items) {
        console.log("Catch: ", items);
    });

    const dirMenuElement = document.querySelector('.dir-menu');
    dirMenuElement.addEventListener('change', (event) => {
        constructTable('#in-review-requests-table');
        filterTable("");
    });
});

Both calls for constructTable() work fine. The filterTable() call throws "not a function" error. Both functions are defined outside of document.ready. Neither is using a specified namespace.
This is the actual error:
Uncaught TypeError: filterTable is not a function
at HTMLSelectElement.<anonymous> (scripts.js:49)

(anonymous) @ scripts.js:49
Screenshot of function definitions:

Why can I call constructTable(), but cannot call filterTable()?
Function Definitions:
function constructTable(selector) {
var list = getContractsFromLocalStorage();
if (!list) {
    $(selector).addClass('no-data-text').html("No Data Available");
    return;
}

// Get column names
var cols = getHeaderValues(list, selector);

// Traverse JSON data
for (var i = 0; i < list.length; i++) {
    var row = $('
');
    for (var colIndex = 0; colIndex < cols.length-1; colIndex++)
    {
        var val = list[i][cols[colIndex]];
        if (val) {
            if (colIndex !== cols.length-2) {
                switch (colIndex) {
                    case 0:
                        row.append($('<input type="checkbox" class="checkbox-col">	'))
                        row.append($('').html(val + '
'));
                        break;
                    case 1:
                        row.append($('').html(val + '
'));
                        break;
                    case 2:
                        row.append($('').html(val + '
'));
                        break;
                    case 3:
                        row.append($('').html(val + '
'));
                        break;
                    case 4:
                        row.append($('').html(val + '
'));
                        break;
                    case 5:
                        row.append($('').html(val + '
'));
                        break;
                    case 6:
                        row.append($('').html(val + '
'));
                        break;
                    case 7:
                        row.append($('').html(val + '
'));
                        break;
                }
            }  else {
                $(selector).append(row);
                $(selector).append($('
' + '' + (val) + '	' + '
'));
            }
        }
    }
}
// use this to set the colspan attr with jquery b/c it cannot be done when building the table
$('td.cont-desc-row').attr('colspan', 9);

}
function filterTable(segName) {
var filter, activeTable, tr;
var dirFilter = document.getElementById("dir-menu").value.toUpperCase();
var officeFilter = document.getElementById("sca-menu-1").value.toUpperCase();
var activeTabID = $('.tab-link:not(.non-active-tab)').attr('id');
var activeTableID = activeTabID.replace('btn', 'table');
activeTable = document.getElementById(activeTableID);
tr = activeTable.getElementsByTagName("tr");

var yearFilter = document.getElementById("sca-menu-2").value.toUpperCase();

var filter3 = document.getElementById("sca-menu-3").value.toUpperCase();

var addFilter = document.getElementById("sca-menu-4").value.toUpperCase();

var scarbRevFilter = document.getElementById('scarb-review-menu-1').value.toUpperCase();

var contractFilter = document.getElementById('contract-term-menu-1').value.toUpperCase();

filterAll(activeTable, dirFilter, officeFilter, yearFilter, filter3, addFilter, scarbRevFilter, contractFilter, tr, segName);

colorTable(activeTable);
calculateTotalCost();
if (!segName) {
    populateDashboardNumbers();
}
getNumVisibleContracts();

}

A: The issue is unrelated to JS. SharePoint has a native function named "filterTable" that I was overwriting. Renamed the function, and the code is now working.


text:
Q: pcshow figure quality with subsequent fill3 I have noticed a weird behavior that I can't explain neither overcome.
Suppose I want to plot a point cloud:
figure;pcshow(myPtCloud)

The resulting figure looks like this:

Now, I want to add a filled polygon to my point cloud:
x = [-2; -2; -2; -2];
y = [4; 5; 5; 4];
z = [-0.5; -0.5; 0.5; 0.5];
hold on; h = fill3(x, y, z, 'b');hold off

This results in:

So far so good. But if I instead do:
x = [-2; -2; -2; -2];
y = [4; 5; 5; 4];
z = [-0.5; -0.5; 0.5; 0.5];
hold on; h = fill3(x, y, z, 'b''FaceAlpha', 0.8);hold off

the result looks like this:

The figure does not look as nice anymore! Why? And what can I do about it if I want to plot a semitransparent polygon in my pointcloud?!
P.S. The point cloud can be downloaded here

A: This is due to the fact that in order to render transparency, MATLAB forces the renderer to be opengl  which can affect how things appear when renderered. You can check this by getting the Renderer of the current figure before and after plot setting the FaceAlpha.
get(gcf, 'Renderer')

As far as why your plot looks "not as nice". I'm guessing that you are referring to the jagged axes lines. This is controlled by the GraphicsSmoothing property of the figure. Check that it is enabled and ensure that you are using a graphics card that supports OpenGL.

Axes graphics smoothing, specified as 'on' or 'off'. Smoothing reduces the appearance of jagged lines in an axes graphic. MATLAB applies a smoothing technique to an axes graphic (and the axes rulers) if GraphicsSmoothing is set to 'on', and either of these conditions is true:

*

*The Renderer property is set to 'painters'.

*The Renderer property is set to 'opengl' and your hardware card supports OpenGL®.

Update
If you're talking about the points being too small on the second one, you can increase the MarkerSize when createing the pcshow object.
pcshow(myPtCloud, 'MarkerSize', 10)

Or after createing the plot
set(findall(gca, '-property', 'MarkerSize'), 'MarkerSize', 10);


text:
Q: How can I get the vice C64 (commodore 64) emulator to work I want to play games on the vice emulator on Ubuntu 14.04. I have never managed to get vice working in Ubuntu. What are the steps needed to achieve this?

A: To install vice with the default roms, you can

*

*Install vice from the system repos
sudo apt-get install vice

*Install the roms,

*

*Download the source tarball http://vice-emu.sourceforge.net/index.html#download and extract it to /tmp

*Run the following commands to copy over the data files,
find /tmp/vice-*/data \
  -mindepth 1 \
  -type d \
  -exec sudo cp -rnv {} /usr/lib/vice/ \;

now you can use x64 and x64sc to run the bin files.

A: update --- there is a new release now, 3.3, and as 3.2, works great.
I managed to compile it with trial-and-errors adding the following libraries:
sudo apt install xa65 libreadline-dev libxaw7-dev libgtkmm-3.0-dev libpulse-dev

and compiled with
./configure
make
sudo make install

...and it seems to work (the lib hack is not needed anymore). Seems a quite live project!
Original content:
You can compile the native version pretty easily (well...). Tested with version 2.4.
(compact instructions --- tell me if you need more details).
1) download the last version from http://vice-emu.sourceforge.net/
2) unpack it where you want
tar xvzf vice-3.1.tar.gz
cd vice-3.1

3) install required dev libraries:
sudo apt install build-essential  libvte-dev libasound2-dev libgtk2.0-dev libgnome2-dev byacc flex

4) configure, compile and install (it will go in /usr/local/). On my netbook, I have a coffee after the "make"...
./configure --enable-gnomeui
make
sudo make install

5) if you machine is 64 bit, do the following (as root)
cd /usr/local/lib
sudo ln -s ../lib64/vice .

(this is probably a bug; the emulator will search the ROMS in /usr/local/lib even if the installation is a 64 bit one and the install program will put the libraries under /usr/local/lib64/)
6) type x64 and Enjoy! (this thing evokes a tear... my first computer ever was a C64. If only I did not lose my discs...)

A: Compile and install went well 1st time on my
fresh install of Ubuntu 18.04 LTS, however
i found that the C64 had no keyboard response.
This was fixed by copying the x11_sym.vkm and
sdl_sym.vkm files from the source codes data/C64
folder into the installed C64 folder.


text:
Q: How to call DblClick sub from code VBA Excel I have an Excel worksheet with two forms: Form1 and Form2.
Form1 has TextBox1 with double-click events:
Public Sub TextBox1_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
  ' Some activity...
End Sub

Form2 has CommandButton2 with a click event:
Private Sub CommandButton2_Click()
  ' Another activity...
End Sub

I need to call the TextBox1_DblClick sub from the CommandButton2_Click sub.
How can I make a call like this?

A: Create a new module, add to it the sub with the operations you wish to perform
Sub mySubroutine()
    ' Do stuff
End Sub

Then call this from both of your click handlers
' In Form1
Public Sub TextBox1_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
  mySubroutine
End Sub

' In Form2
Private Sub CommandButton2_Click()
  mySubroutine
End Sub

If you wanted to pass stuff (like text box strings etc) from your forms, then include input arguments in your sub
Sub mySubroutine(str As String, n As Long) ' Passing arguments
    ' Do stuff
End Sub

Then pass those arguments when you make the call from anywhere
' Get a String and Long from data on the form, then call mySubroutine
mySubroutine str:=myString, n:=myLong


text:
Q: Discover devices mono.upnp I'm trying to communicate with my new wemo switch over upnp. On windows this works just fine. Now I'm trying to do the same on android using the mono.upnp lib. Everything looks the same but I cant figuer out how to discover devices on mono.upnp.
Here is the code on windows:
    public static List<WeMoDevice> GetDevices ()
    {
        UPnPDeviceFinder finder = new UPnPDeviceFinder ();
        List<WeMoDevice> foundDevices = new List<WeMoDevice> ();

        string deviceType = "upnp:rootdevice";
        Device devices = finder.FindByType (deviceType, 1);

        foreach (Device device in devices) {
            if (device.Type.StartsWith ("urn:Belkin:")) {
                switch (GetDeviceType (device)) {
                case WeMoDeviceType.Switch:
                    WeMoSwitch wemoSwitch = new WeMoSwitch (device);
                    foundDevices.Add (wemoSwitch);
                    break;

                case WeMoDeviceType.Sensor:
                    WeMoSensor wemoSensor = new WeMoSensor (device);
                    foundDevices.Add (wemoSensor);
                    break;
                default:

                    break;

                }
            }
        }

        return foundDevices;
    }

I already changed the device class to the mono.upnp one but I cant seem to find the equivalent for UPnPDeviceFinder in mono.upnp.

A: Alright finally got it working. Here is the code I used to switch my wemo on and off:
    const string COMMAND_OFF = @"<?xml version=""1.0"" encoding=""utf-8""?><s:Envelope xmlns:s=""http://schemas.xmlsoap.org/soap/envelope/"" s:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/""><s:Body><u:SetBinaryState xmlns:u=""urn:Belkin:service:basicevent:1""><BinaryState>0</BinaryState></u:SetBinaryState></s:Body></s:Envelope>";
    const string COMMAND_ON = @"<?xml version=""1.0"" encoding=""utf-8""?><s:Envelope xmlns:s=""http://schemas.xmlsoap.org/soap/envelope/"" s:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/""><s:Body><u:SetBinaryState xmlns:u=""urn:Belkin:service:basicevent:1""><BinaryState>1</BinaryState></u:SetBinaryState></s:Body></s:Envelope>";

    public void On (string iP, string port)
    {
        SendCommand (COMMAND_ON, iP, port);
    }

    public void Off (string iP, string port)
    {
        SendCommand (COMMAND_OFF, iP, port);
    }

    private void SendCommand (string command, string iP, string port)
    {

        string targetUrl = "http://" + iP + ":" + port + "/upnp/control/basicevent1";

        //  Create the packet and payload to send to the endpoint to get the switch to process the command

        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create (targetUrl);
        request.Method = "POST";
        request.Headers.Add ("SOAPAction", "\"urn:Belkin:service:basicevent:1#SetBinaryState\"");
        request.ContentType = @"text/xml; charset=""utf-8""";
        request.KeepAlive = false;
        Byte[] bytes = UTF8Encoding.ASCII.GetBytes (command);
        request.ContentLength = bytes.Length;
        using (Stream stream = request.GetRequestStream ()) {
            stream.Write (bytes, 0, bytes.Length);
            stream.Close ();
            request.GetResponse ();
        }

        //  HACK: If we don't abort the result the device holds on to the connection sometimes and prevents other commands from being received

        request.Abort ();
    }

    public void GetDevice (string Name, wemoAction action)
    {

        try {

            Client client = new Client ();

            client.BrowseAll (); //Browse all available upnp devices

            client.DeviceAdded += (sender, e) => { //do something when a device is found
                System.Console.WriteLine ("got one!");
                if (e.Device.ToString ().Contains ("urn:Belkin")) {

                    if (e.Device.GetDevice ().FriendlyName.Equals (Name)) {
                        var url = e.Device.GetDevice ().Services.First ().EventUrl;
                        switch (action) {
                        case wemoAction.on:
                            On (url.DnsSafeHost, url.Port.ToString ());
                            break;
                        case wemoAction.off:
                            Off (url.DnsSafeHost, url.Port.ToString ());
                            break;
                        }
                    }

                }

            };

        } catch (Exception ex) {
            System.Console.WriteLine (ex.Message);
        }

    }

The code for sending the on and off packet are from this video: http://www.youtube.com/watch?v=ifzmJFdvNEE


text:
Q: dotnet core wrong client IP address I try to find client IP address with dotnet core. It's needed to find geo locations with freegeoip.net for current user. When I open this page, I got something like this: 89.190.94.34. But my core app return wrong IP. Something like: 172.19.0.5. My app script, for getting client address:
Simply: this.Request.HttpContext.Connection.RemoteIpAddress.ToString()
on localhost it is correctly ::1
Is this script wrong? What is IP 172... and how I can get correct IP address?
Thank you

A: You should know that there are 2 types of IP adresses, pubblic and private. The public address is an address given from you ISP that can be viewed by anyone in the world having an internet connecion (also if they have another ISP), the private address is an address valid only in your LAN, so many people have the same private address in different LANs.
Now clarifying that, the first address you wrote (89.190.94.34) is your pubblic address, and the second (172.19.0.5) is your private one.
I don't really know what you are trying to do, but I hope this helps. I reccomend you to learn more about ranges and other stuff of IPs online.


text:
Q: CSS webkit-image-mask alternative in JavaScript? I'm working on my portfolio, and I would like to mask some pictures with a PNG, that's work with the webkit image mask but, I would like to have the same result in FF & Opera, do you know a JavaScript script to have the same result?
I tried with edge.js but only work with  and not with a background in CSS (I made sprite).
Thank you.

A: Why not simply display the PNG on top of your image?
You can create the element in the HTML after your image, or create it dinamically with JS.
Simply create a DIV and absolute position it on top of your image, then give it the same width and height of your image (or whatever you like), and your PNG as the div's background image, this all via CSS.
You could also use the CSS ::after pseudo-class to style a element without even having to insert it into the DOM via HTML or JS.
http://jsfiddle.net/LuSYQ/1/
And the ::after alternative
http://jsfiddle.net/LuSYQ/11/


text:
Q: Huber Regressor returns inconsistent sign of coefficient I've been trying to perform a Huber Regressor (sklearn.linear_model) on Time Series.
I came across a strange phenomena: at time it returns a very small negative coeff and sometimes positive although the figures change upwards constantly.
For example:
HuberRegressor(epsilon=1.35,max_iter=10000).fit(X=np.arange(12).reshape(-1,1),y=pd.Series([0,0,0,0,0,0,0,0,0,0,0,1])).coef_

array([3.1380359e-08])

HuberRegressor(epsilon=1.35,max_iter=10000).fit(X=np.arange(12).reshape(-1,1),y=pd.Series([0,0,0,0,0,0,0,0,0,0,0,2])).coef_

array([-2.20536164e-10])

HuberRegressor(epsilon=1.35,max_iter=10000000).fit(X=np.arange(12).reshape(-1,1),y=pd.Series([0,0,0,0,0,0,0,0,0,0,0,5])).coef_

array([7.63157014e-07])

HuberRegressor(epsilon=1.35,max_iter=10000).fit(X=np.arange(12).reshape(-1,1),y=pd.Series([0,0,0,0,0,0,0,0,0,0,0,248])).coef_

array([-4.49809127e-07])

So, all I did was raising the last observation (1,2,5,248), and yet the sign of the coefficient changes.
As this is Huber Regression, 1,3,5,248 are all identified as outliers as all others are zeros. Should I identify something different in the model?

A: TL;DR
When adapting your example to reproduce the error I got the feeling that it is due to Float Arithmetic error because you are assessing a null slope using numerical algorithm with float arithmetic.
Float Arithmetic Error
It maybe strange to get the wrong sign if computation were performed with real numbers but this is a common phenomenon with float numbers.
Lets adapt your MCVE to:
import numpy as np
from sklearn import linear_model

u = 1
c = []
x = np.arange(12).reshape(-1,1)
for k in [0, 1, 2, 5, 25, 100, 200, 500, 1000]:
    y = np.array([u]*(len(x)-1)+[k])
    m = linear_model.HuberRegressor(tol=1e-16).fit(X=x, y=y)
    c.append(m.coef_[0])

[-5.923749784709837e-09,
 -4.9322755264475916e-11,
 2.5190368660836694e-10,
 8.3699110105873e-07,
 -4.3671163925160265e-10,
 1.2964166828133428e-08,
 1.5063190859596705e-06,
 1.5063100994140354e-06,
 1.5063152932632047e-06]

I admit that most of returned number in this case are usually too big to be considered as zero, but I still suspect it this the case because changing tol switch does affect the result and changing for a non null slope does return the expected result.
Working Use Case
We can change the data to assess a unitary slope, we get the following results:
c = []
x = np.arange(12).reshape(-1,1)
for k in [0, 1, 2, 5, 25, 100, 200, 500, 1000]:
    y = np.array(list(x[:-1])+[k])
    m = linear_model.HuberRegressor(tol=1e-16).fit(X=x, y=y)
    c.append(m.coef_[0])

[0.9999999423436053,
 0.9999991468916037,
 0.9999999916835522,
 0.9999999916837012,
 1.0000000059171992,
 1.000000006233575,
 1.000000006237059,
 1.000002303772441,
 1.0000023037721706]

Now the information is below or above the unit and this is the expected result.
My intuition is: the test you performed give a strange results because it is at the boundary where machine precision (acceptable value for zero) and algorithm precision have the same magnitude, hence the bad sign. When the value of the coefficient become significantly larger than the algorithm precision, the phenomenon disappear.
This is a common issue with float arithmetic and requires developers to design stable and accurate algorithms which is a complex task. A good reference covering many aspect of it is:

N. J. Higham. Accuracy and Stability of Numerical Algorithms. Society
for Industrial and Applied Mathematics, Philadelphia, PA, USA, second
edition, 2002. ISBN 0-89871-521-0

My advice: you may open an issue on sklearn to highlight this observation, they may add a new test in their unit test suite to cope with this specific use case and provide you more insights on what is going on under the hood.


text:
Q: php5: string inside a pattern to use for preg_match I am using php5 and using preg_match() to extract data on match.
I have a string formed using sprintf and is as :
$name = sprintf("sda%d", 0);

This name has be a string to search in pattern defined as:
$pattern='/$name ([^\/]*)/';

The $pattern is used in preg_match to get data from sda0 string to / token.
When I printed the $pattern I am getting output as /$name ([^/])/*. But I am expecting the output of pattern to be /sda0 ([^/])/*.
Can anyone help me how to use the string inside a pattern string?
Regards,
Sowmya

A: $name will not get data if ' single-quote is used.
Try with double-quotes: $pattern = "/$name ([^\/]*)/";


text:
Q: Update a constraint in postgresql 9.1 database I would like to change "on delete restrict" to "on delete cascade": how can i do it ?
ALTER TABLE T1
ADD CONSTRAINT fk_T1 FOREIGN KEY (id1)
  REFERENCES T2 (id1) MATCH SIMPLE
  ON UPDATE RESTRICT ON DELETE RESTRICT;

A: You have to drop it and recreate it.
ALTER TABLE T1 DROP CONSTRAINT fk_T1;

ALTER TABLE T1 ADD CONSTRAINT fk_T1 FOREIGN KEY (id1)
REFERENCES T2 (id1) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE CASCADE;


text:
Q: Formula for sorting/ranking products by their user ratings I'm trying to get a decent sorting algorithm for my products database. Users can vote for their products with using scores from 0 to 5 (.5 scores are also possible like 2.5). My table structure currently looks like this:
[ProductID] [Title] ... [NumberOfVotes] [TotalPoints] [FinalScore]

Whenever a user votes, I'm calculating the finalscore using a very simple formula like
     (TotalPoints / NumberOfVotes) = FinalScore.
Then I sort the table on FinalScore and NumberOfVotes.
While this works, it's not exactly fair because a product which has only 1 vote of 5 stars can easily come in top rankings.
I'm not very good at statistics or algorithms to get a fair product ranking.
I'm looking for a relatively easy-to-implement formula that's fairer than the method I'm using now.
How can this be done?

A: I found a great post about this here that explains the various options, including thier pros and cons: How Not To Sort By Average Rating but it seems that the correct solution is this...

"Score = Lower bound of Wilson score
  confidence interval for a Bernoulli
  parameter"

seems daunting, but the post includes pseudocode and a clear explanation.

A: You could use median, which is often better a figure than raw average. In addition, you might consider not to give ratings for any item that has less than, say, five votes.


text:
Q: Can any one explain me checkout_index_index.xml layout file in checkout module of magento I cannot understand what is written in this file, from where the design is coming, how it is rendering on the page.
Can any one help me in it.
FOR EXAMPLE THIS CODE.
                              <item name="shipping-step" xsi:type="array">
                                            <item name="component" xsi:type="string">uiComponent</item>
                                            <item name="sortOrder" xsi:type="string">1</item>
                                            <item name="children" xsi:type="array">
                                                <item name="step-config" xsi:type="array">
                                                    <item name="component" xsi:type="string">uiComponent</item>
                                                    <item name="children" xsi:type="array">
                                                        <item name="shipping-rates-validation" xsi:type="array">
                                                            <item name="children" xsi:type="array">
                                                                <!--Step configuration components-->
                                                            </item>
                                                        </item>
                                                    </item>
                                                </item>
                                                <item name="shippingAddress" xsi:type="array">
                                                    <item name="config" xsi:type="array">
                                                        <item name="deps" xsi:type="array">
                                                            <item name="0" xsi:type="string">checkout.steps.shipping-step.step-config</item>
                                                            <item name="1" xsi:type="string">checkoutProvider</item>
                                                        </item>
                                                        <item name="popUpForm" xsi:type="array">
                                                            <item name="element" xsi:type="string">#opc-new-shipping-address</item>
                                                            <item name="options" xsi:type="array">
                                                                <item name="type" xsi:type="string">popup</item>
                                                                <item name="responsive" xsi:type="boolean">true</item>
                                                                <item name="innerScroll" xsi:type="boolean">true</item>
                                                                <item name="title" xsi:type="string" translate="true">Shipping Address</item>
                                                                <item name="trigger" xsi:type="string">opc-new-shipping-address</item>
                                                                <item name="buttons" xsi:type="array">
                                                                    <item name="save" xsi:type="array">
                                                                        <item name="text" xsi:type="string" translate="true">Save Address</item>
                                                                        <item name="class" xsi:type="string">action primary action-save-address</item>
                                                                    </item>
                                                                    <item name="cancel" xsi:type="array">
                                                                        <item name="text" xsi:type="string" translate="true">Cancel</item>
                                                                        <item name="class" xsi:type="string">action secondary action-hide-popup</item>
                                                                    </item>
                                                                </item>
                                                            </item>
                                                        </item>
                                                    </item>
                                                    <item name="component" xsi:type="string">Magento_Checkout/js/view/shipping</item>
                                                    <item name="provider" xsi:type="string">checkoutProvider</item>
                                                    <item name="sortOrder" xsi:type="string">1</item>
                                                    <item name="children" xsi:type="array">
                                                        <item name="customer-email" xsi:type="array">
                                                            <item name="component" xsi:type="string">Magento_Checkout/js/view/form/element/email</item>
                                                            <item name="displayArea" xsi:type="string">customer-email</item>
                                                            <item name="tooltip" xsi:type="array">
                                                                <item name="description" xsi:type="string" translate="true">We'll send your order confirmation here.</item>
                                                            </item>
                                                            <item name="children" xsi:type="array">
                                                                <item name="before-login-form" xsi:type="array">
                                                                    <item name="component" xsi:type="string">uiComponent</item>
                                                                    <item name="displayArea" xsi:type="string">before-login-form</item>
                                                                    <item name="children" xsi:type="array">
                                                                        <!-- before login form fields -->
                                                                    </item>
                                                                </item>
                                                                <item name="additional-login-form-fields" xsi:type="array">
                                                                    <item name="component" xsi:type="string">uiComponent</item>
                                                                    <item name="displayArea" xsi:type="string">additional-login-form-fields</item>
                                                                    <item name="children" xsi:type="array">
                                                                        <!-- additional login form fields -->
                                                                    </item>
                                                                </item>
                                                            </item>
                                                        </item>
                                                        <item name="before-form" xsi:type="array">
                                                            <item name="component" xsi:type="string">uiComponent</item>
                                                            <item name="displayArea" xsi:type="string">before-form</item>
                                                            <item name="children" xsi:type="array">
                                                                <!-- before form fields -->
                                                            </item>
                                                        </item>
                                                        <item name="before-fields" xsi:type="array">
                                                            <item name="component" xsi:type="string">uiComponent</item>
                                                            <item name="displayArea" xsi:type="string">before-fields</item>
                                                            <item name="children" xsi:type="array">
                                                                <!-- before fields -->
                                                            </item>
                                                        </item>
                                                        <item name="address-list" xsi:type="array">
                                                            <item name="component" xsi:type="string">Magento_Checkout/js/view/shipping-address/list</item>
                                                            <item name="displayArea" xsi:type="string">address-list</item>
                                                        </item>
                                                        <item name="address-list-additional-addresses" xsi:type="array">
                                                            <item name="component" xsi:type="string">uiComponent</item>
                                                            <item name="displayArea" xsi:type="string">address-list-additional-addresses</item>
                                                            <item name="children" xsi:type="array">
                                                                <!-- address-list-additional-addresses -->
                                                            </item>
                                                        </item>
                                                        <item name="before-shipping-method-form" xsi:type="array">
                                                            <item name="component" xsi:type="string">uiComponent</item>
                                                            <item name="displayArea" xsi:type="string">before-shipping-method-form</item>
                                                            <item name="children" xsi:type="array">
                                                                <!-- address-list-additional-addresses -->
                                                            </item>
                                                        </item>
                                                        <item name="shipping-address-fieldset" xsi:type="array">
                                                            <item name="component" xsi:type="string">uiComponent</item>
                                                            <item name="config" xsi:type="array">
                                                                <item name="deps" xsi:type="array">
                                                                    <item name="0" xsi:type="string">checkoutProvider</item>
                                                                </item>
                                                            </item>
                                                            <item name="displayArea" xsi:type="string">additional-fieldsets</item>
                                                            <item name="children" xsi:type="array">
                                                                <!-- The following items override configuration of corresponding address attributes -->
                                                                <item name="region" xsi:type="array">
                                                                    <!-- Make region attribute invisible on frontend. Corresponding input element is created by region_id field -->
                                                                    <item name="visible" xsi:type="boolean">false</item>
                                                                </item>
                                                                <item name="region_id" xsi:type="array">
                                                                    <item name="component" xsi:type="string">Magento_Ui/js/form/element/region</item>
                                                                    <item name="config" xsi:type="array">
                                                                        <item name="template" xsi:type="string">ui/form/field</item>
                                                                        <item name="elementTmpl" xsi:type="string">ui/form/element/select</item>
                                                                        <item name="customEntry" xsi:type="string">shippingAddress.region</item>
                                                                    </item>
                                                                    <item name="validation" xsi:type="array">
                                                                        <item name="required-entry" xsi:type="boolean">true</item>
                                                                    </item>
                                                                    <!-- Value of region_id field is filtered by the value of county_id attribute -->
                                                                    <item name="filterBy" xsi:type="array">
                                                                        <item name="target" xsi:type="string"><![CDATA[${ $.provider }:${ $.parentScope }.country_id]]></item>
                                                                        <item name="field" xsi:type="string">country_id</item>
                                                                    </item>
                                                                </item>
                                                                <item name="postcode" xsi:type="array">
                                                                    <!-- post-code field has custom UI component -->
                                                                    <item name="component" xsi:type="string">Magento_Ui/js/form/element/post-code</item>
                                                                    <item name="validation" xsi:type="array">
                                                                        <item name="required-entry" xsi:type="boolean">true</item>
                                                                    </item>
                                                                </item>
                                                                <item name="company" xsi:type="array">
                                                                    <item name="validation" xsi:type="array">
                                                                        <item name="min_text_length" xsi:type="number">0</item>
                                                                    </item>
                                                                </item>
                                                                <item name="fax" xsi:type="array">
                                                                    <item name="validation" xsi:type="array">
                                                                        <item name="min_text_length" xsi:type="number">0</item>
                                                                    </item>
                                                                </item>
                                                                <item name="country_id" xsi:type="array">
                                                                    <item name="sortOrder" xsi:type="string">115</item>
                                                                </item>
                                                                <item name="telephone" xsi:type="array">
                                                                    <item name="config" xsi:type="array">
                                                                        <item name="tooltip" xsi:type="array">
                                                                            <item name="description" xsi:type="string" translate="true">For delivery questions.</item>
                                                                        </item>
                                                                    </item>
                                                                </item>
                                                            </item>
                                                        </item>
                                                    </item>
                                                </item>
                                            </item>
                                        </item>


text:
Q: How to resolve 400 Bad Request error in Postman in a sample MEAN application I am working on a sample MEAN application where in I have started to create the node.js related files and connected the same to MongoDB. I have create a POST call which sends the json to the DB. I tried to test the api using postman but not sure whats wrong, I have checked multiple times, the api throws bad request.Any help on this is much appreciated. Thanks.
Added the relevant route.js, app.js and contact.js files for reference in stackblitz link. Added error in postman for reference.

https://stackblitz.com/edit/node-mlodls?file=app.js

A: Resolved the issue using postman extension. Wondering why the API doesnt work in postman software and works in postman extension


text:
Q: Laravel Eloquent to treat the column 'archived_at' like it does 'deleted_at' I'm trying to get Laravel to treat a newly added column called 'archived_at' the same way it treats 'deleted_at'. That is, when I run a query, I don't want it to pick up any archived records unless I expressly tell it so (i.e., Invoices::onlyArchived()->paginate()). In other words, the archived_at behavior should mimic the soft delete behavior built into Laravel.
I see the soft delete functionality built into Laravel's Builder and Model classes. Here's what I have so far:

*

*Extend Model class and add archived_at functionality in new
class.

*Update app/config.php alias as follows:

    // 'Eloquent'        => 'Illuminate\Database\Eloquent\Model',
    'Eloquent'        => 'CoreExtensions\Model',

I can't seem to figure out how to extend the Builder class and force Laravel to read from the extended Builder class. If I can get that far, I can probably figure out the rest. Any suggestions? Thanks in advance!

A: You probably need only to extend Eloquent and do something like this:
<?php

class BaseModel extends Eloquent {

    public static function withArchived()
    {
        return with(new static)->newQuery(true, true);
    }

    public static function onlyArchived()
    {
        return with(new static)->newQuery(false, false, true);
    }

    /**
     * Get a new query builder for the model's table.
     *
     * @param  bool  $excludeDeleted
     * @return \Illuminate\Database\Eloquent\Builder|static
     */
    public function newQuery($excludeDeleted = true, $excludeArchived = true, $onlyArchived = false)
    {
        $builder = $this->newEloquentBuilder($this->newBaseQueryBuilder());

        // Once we have the query builders, we will set the model instances so the
        // builder can easily access any information it may need from the model
        // while it is constructing and executing various queries against it.
        $builder->setModel($this)->with($this->with);

        if ( ! $onlyArchived)
        {
            if ($excludeDeleted && $this->softDelete)
            {
                $builder->whereNull($this->getQualifiedDeletedAtColumn());
            }

            if ($excludeArchived)
            {
                $builder->whereNull('archived_at');
            }
        }
        else
        {
            $builder->whereNotNull('archived_at');
        }

        return $builder;
    }

}

And then you'll probably be able to:
Invoices::onlyArchived()->paginate();

Invoices::withArchived()->where('customer_id', $customer_id)->paginate();

A: If you are running Laravel 4.2 you can check out these two files, I've created my own traits based on the built-in SoftDelete trait. (It's far more flexible than the answer above.)

*

*Illuminate/Database/Eloquent/SoftDeletingScope.php

*Illuminate/Database/Eloquent/SoftDeletingTrait.php

http://laravel.io/forum/08-14-2014-add-filter-to-builder-on-a-custom-method-call


text:
Q: C++ lzma compression and decompression of large stream by parts I need to do lzma compression and decompression on the fly. I'm receiving a large file via qnetworkmanager in Qt and I need to decompress it as the data stream is downloading.
When I receive part of the data stream I need to decompress it, append to file and than free any used memory during the process. What is the best way to do this?
Now I'm trying with xz-utils, pure c api, maybe someone can suggest a better way?
following code based on this example
UPD2:
extern "C" void *lz_alloc(void *opaque, size_t nmemb, size_t size)
{
void *p = NULL;
try{
    p = new char [size];
}
catch(std::bad_alloc &ba)
{
    p = NULL;
}
return p;
}

extern "C" void lz_free(void *opaque, void *ptr)
{
delete [] (char*)ptr;
}

QByteArray lzCompress(QByteArray data)
{
QByteArray arr;
lzma_check check = LZMA_CHECK_CRC64;
lzma_stream strm = LZMA_STREAM_INIT; /* alloc and init lzma_stream struct */
lzma_allocator al;
al.alloc = lz_alloc;
al.free = lz_free;
strm.allocator = &al;
byte *in_buf;
byte out_buf [OUT_BUF_MAX];
size_t in_len;  /* length of useful data in in_buf */
size_t out_len; /* length of useful data in out_buf */
lzma_ret ret_xz;

/* initialize xz encoder */
ret_xz = lzma_easy_encoder (&strm, 9 | LZMA_PRESET_EXTREME, check);
if (ret_xz != LZMA_OK) {
    return QByteArray();
}

in_len = data.size();
in_buf = (byte*)data.data();
strm.next_in = in_buf;
strm.avail_in = in_len;

do {
    strm.next_out = out_buf;
    strm.avail_out = OUT_BUF_MAX;
    ret_xz = lzma_code (&strm, LZMA_FINISH);

    out_len = OUT_BUF_MAX - strm.avail_out;
    arr.append((char*)out_buf, out_len);
    out_buf[0] = 0;
} while (strm.avail_out == 0);
lzma_end (&strm);
return arr;
}

i have sleeped few hours, and now i thinking more clearly, fixed my wrong code, updated it(it's behave just as qCompress works)
UPD3:
decompression code (qUncompress like behavior )
QByteArray lzUncompress(QByteArray data)
{
lzma_stream strm = LZMA_STREAM_INIT; /* alloc and init lzma_stream struct */
const uint32_t flags = LZMA_TELL_UNSUPPORTED_CHECK | LZMA_CONCATENATED;
const uint64_t memory_limit = UINT64_MAX; /* no memory limit */
byte *in_buf;
uint8_t out_buf [OUT_BUF_MAX];
size_t in_len;  /* length of useful data in in_buf */
size_t out_len; /* length of useful data in out_buf */
lzma_ret ret_xz;
QByteArray arr;

ret_xz = lzma_stream_decoder (&strm, memory_limit, flags);
if (ret_xz != LZMA_OK) {
    return QByteArray();
}

in_len = data.size();
in_buf = (byte*)data.data();

strm.next_in = in_buf;
strm.avail_in = in_len;
do {
    strm.next_out = out_buf;
    strm.avail_out = OUT_BUF_MAX;
    ret_xz = lzma_code (&strm, LZMA_FINISH);

    out_len = OUT_BUF_MAX - strm.avail_out;
    arr.append((char*)out_buf, out_len);
    out_buf[0] = 0;
} while (strm.avail_out == 0);
lzma_end (&strm);
return arr;
}

UPD4:
basic stream decompression class, following code just decompress xz stream downloaded from http server on the fly, exactly what i need:
class lz_stream_decompressor : public QObject
{
Q_OBJECT
public:
lz_stream_decompressor(QNetworkReply *r, QNetworkAccessManager *q, const QString &str, unsigned long sz): flags(LZMA_TELL_UNSUPPORTED_CHECK | LZMA_CONCATENATED), memory_limit(UINT64_MAX), state(0), total_upd_size(sz)
{
    repl = r;
    qnm = q;
    path = str;
    strm.next_in = NULL;
    strm.avail_in = 0;
    strm.total_in = 0;
    strm.next_out = NULL;
    strm.avail_out = 0;
    strm.total_out = 0;
    strm.allocator = NULL;
    strm.internal = NULL;
    strm.reserved_ptr1 = NULL;
    strm.reserved_ptr2 = NULL;
    strm.reserved_ptr3 = NULL;
    strm.reserved_ptr4 = NULL;
    strm.reserved_int1 = 0;
    strm.reserved_int2 = 0;
    strm.reserved_int3 = 0;
    strm.reserved_int4 = 0;
    strm.reserved_enum1 = LZMA_RESERVED_ENUM;
    strm.reserved_enum2 = LZMA_RESERVED_ENUM;
    ret_xz = lzma_stream_decoder (&strm, memory_limit, flags);
    if (ret_xz != LZMA_OK)
    {
        state = -1;
        repl->abort();
    }
    else
    {
        connect(repl, SIGNAL(downloadProgress(qint64,qint64)), SLOT(handle_new_data(qint64,qint64)));
        connect(q, SIGNAL(finished(QNetworkReply*)), SLOT(compressed_file_request_finished(QNetworkReply*)));
        QFile(path).rename(path + ".tmp");
    }
}
~lz_stream_decompressor()
{
/*        if(repl)
        delete repl; */
    lzma_end (&strm);
}
const short get_state()
{
    return state;
}
signals:
void finished();

public slots:
void handle_new_data(qint64 bytesReceived, qint64 bytesTotal);
void compressed_file_request_finished(QNetworkReply*);
private:
QNetworkReply *repl;
QNetworkAccessManager *qnm;
lzma_stream strm;
const uint32_t flags;
const uint64_t memory_limit; /* no memory limit */
short state;
byte *in_buf;
byte out_buf [OUT_BUF_MAX];
size_t in_len;  /* length of useful data in in_buf */
size_t out_len; /* length of useful data in out_buf */
lzma_ret ret_xz;
QString path;
unsigned long &total_upd_size;
};

and realisation:
void lz_stream_decompressor::handle_new_data(qint64 bytesReceived, qint64 bytesTotal)
{
if(repl->error() != QNetworkReply::NoError)
{//TODO: handle error here
    QFile(path).remove();
    QFile(path + ".tmp").rename(path);
    return;
}
total_upd_size -= repl->bytesAvailable();
QByteArray data = repl->readAll();
in_len = data.size();
in_buf = (byte*)data.data();
strm.next_in = in_buf;
strm.avail_in = in_len;

do {
    strm.next_out = out_buf;
    strm.avail_out = OUT_BUF_MAX;
    ret_xz = lzma_code (&strm, LZMA_RUN);
    out_len = OUT_BUF_MAX - strm.avail_out;
    QFile file(path);
    if(file.open(QIODevice::WriteOnly | QIODevice::Append))
    {
        file.write(QByteArray((char*)out_buf, (int)out_len));
        file.close();
    }
    out_buf[0] = 0;
} while (strm.avail_out == 0);
}

void lz_stream_decompressor::compressed_file_request_finished(QNetworkReply* repl)
{
if(repl->error() != QNetworkReply::NoError)
{//TODO: handle error here
    QFile(path).remove();
    QFile(path + ".tmp").rename(path);
    emit finished();
    return;
}
total_upd_size -= repl->bytesAvailable();
QByteArray data = repl->readAll();
in_len = data.size();
in_buf = (byte*)data.data();
strm.next_in = in_buf;
strm.avail_in = in_len;

do {
    strm.next_out = out_buf;
    strm.avail_out = OUT_BUF_MAX;
    ret_xz = lzma_code (&strm, LZMA_FINISH);
    out_len = OUT_BUF_MAX - strm.avail_out;
    QFile file(path);
    if(file.open(QIODevice::WriteOnly | QIODevice::Append))
    {
        file.write(QByteArray((char*)out_buf, (int)out_len));
        file.close();
    }
    out_buf[0] = 0;
} while (strm.avail_out == 0);
repl->deleteLater();
QFile(path + ".tmp").remove();
emit finished();
}

all this based on example from first link, you need to replace commented code parts with your code to do something with uncompressed data.
i would like to see any suggestions to this code
you also need to connect "compressed_file_request_finished" slot to finished signal of qnetworkmanager to finish uncompressed data.
UPD5:
fixed lzCompress and lzUncompress, looks like working fine now, not sure about using LZMA_FULL_FLUSH in handle_new_data, as i read this is what i need, but still not sure, now i adapting existing code to use this...
UPD6:
you also need something like this:
/* read/write buffer sizes */
#define IN_BUF_MAX  409600
#define OUT_BUF_MAX 409600
/* analogous to xz CLI options: -0 to -9 */
#define COMPRESSION_LEVEL 7

/* boolean setting, analogous to xz CLI option: -e */
#define COMPRESSION_EXTREME true

in visible range for this code to work.
UPD7:
updated code, all tested and working, i have found that liblzma not completely thread-safe, i tried to make multi-threaded compression of filelist. and it crashing very often.

A: On this page, you will find the lzma SDK which provides source codes in different languages and some binaries: http://www.7-zip.org/sdk.html
You have two solutions:

*

*Use the C++ source code to decompress the incoming flow

*Use the decoder binaries as an external tool in your app


text:
Q: TinyMCE / Tinybrowser upload tab giving a 404 Just looking for a bit of help with Tinybrowser - I've tried updating it to the latest version but it's still failing. If I click the 'Upload' tab I get a 404.. I'm thinking it's possibly to do with the htaccess, but I'm not too hot with htaccess rules so I can't pinpoint it.
If I visit the page directly (/admin/javascript/tiny_mce/plugins/tinybrowser/upload.php?type=image&tokenget=315af6ee7cf85bc6170760a0c1a5b86d&folder=) I get a 404 as well. If I take off 'folder=' it'll go to the page, if I make it follllder=, it'll go to the page. So for some reason 'folder=' seems to be causing problems. Even if I manually put in a string for the folder var.
The htaccess is as follows:
# default
Options All -Indexes
RewriteEngine On
RewriteBase /

# Make sure there's no way of getting to this file
<FilesMatch "\.htaccess$">
Order deny,allow
Deny from all
Satisfy all
</FilesMatch>

RewriteRule ^login(/*)$ system/login/ [L,QSA]

# Route all other traffic to index.php (front controller)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?_args=$1 [L,QSA]
AddType text/x-component htc

If I remove
RewriteRule ^(.*)$ /index.php?_args=$1 [L,QSA]

I end up getting a 403 forbidden error, but obviously it's not really feasible to remove this line anyway.
Thanks in advance guys

A: I just ran into this as well.
The problem appears to be a security restriction on some servers that relates to the filename of the PHP file, as well as the "folder=" querystring.
I got around it by renaming upload.php to upload_tab.php, and then modifying tinybrowser.php to reference the upload_tab.php file:
if($tinybrowser['allowupload'])
    {
    ?>
<a href="upload_tab.php?type=<?php echo $typenow.$passfolder.$passfeid; ?>"><?php echo TB_UPLOAD; ?>
<?php
    }

This allows you to see the upload window, and submit some files using POST variables.
However, a problem remains...
The particular server I came across also has a similar restriction on a request to upload_file.php with a querystring of 'folder='.  There isn't an easy fix for this, apart from decompiling flexupload.swf (which I tried, but couldn't recompile it) so I couldn't fully resolve the issue.


text:
Q: Spring Boot: can we have parts of request mapping as optional using regex? I have an endpoint with multiple request mappings like:
@PutMapping(path = {
       "/A/{ACode}/B/{BCode}/C/{CCode}/D/{DCode}",
       "/A/{ACode}/B/{BCode}/D/{DCode}",
       "/A/{ACode}/C/{CCode}/D/{DCode}",
       "/A/{ACode}/D/{DCode}"
})

where ACode, BCode, CCode and DCode are all path variables. B, C and their respective codes are optional while A, D and their respective codes are mandatory.
I can call the above API in these ways:
PUT /A/IN/B/delhi/C/central/D/110001
PUT /A/IN/B/delhi/D/110001
PUT /A/IN/C/central/D/110001
PUT /A/IN/D/110001

I'm trying to combine all of these request mappings into a single regex which can match all of these combinations.
I tried using this regex in mapping but it doesn't work:
@PutMapping(path = {
       "A/{ACode:[A-Z]+}(/B/{BCode:[a-z0-9-]+})?(/C/{CCode:[a-z0-9-]+})?/D/{DCode:[a-z0-9-]+}"
})

And this one works, but it doesn't make B, C and respective codes optional, so cannot be used:
@PutMapping(path = {
       "A/{ACode:[A-Z]+}/B/{BCode:[a-z0-9-]+}/C/{CCode:[a-z0-9-]+}/D/{DCode:[a-z0-9-]+}"
})

Is there anything wrong with the regex I used or is there any workaround for achieving this kind of functionality apart from using request params in place of path variables?
Thanks for help!


text:
Q: Keep duplicate entries from two JSON objects in Python I have two JSON objects in a Lambda function (python). I want to compare the  keys from object 2 against the keys in object 1 and remove any entries that are not contained in object 1.
Each object has a few hundred items in it, so a nested for loop will take too long and time out. I found diffpy, but this requires a module imported into my lambda and I would like to, ideally have a native python solution (to minimize the size of my lambda function).
object1 = [{'name': 'apple', 'price': 100}, {'name': 'grape', 'price':
150}, {'name': 'orange', 'price': 40}]

object2 = [{'name': 'apple', 'price': 200}, {'name': 'grape', 'price':
350}, {'name': 'orange', 'price': 40}, {'name': 'mango', 'price': 400}]

In the example above, the expected newObject should have only the name key/value from the first object and the price key/values from both objects. Mango from object 2 is not contained in object 1 so we can disregard.
newObject = [{'name': 'apple', 'priceA': 100, 'priceB': 200}, {'name':
'grape', 'priceA': 150, 'priceB': 350}, {'name': 'orange', 'priceA': 40,
'priceB': 40}]

I have attempted to use the following code to implement:
newHash= {}
newObject = []
for item in object1:
    name = item["name"]
    priceA = item["price"]
    for item in object2:
        if name == item["name"]:
            newHash["name"] = item["name"]
            newHash["priceA"] = priceA
            newHash["priceB"] = item["price"]
            newObject.append(newHash)

A: Unless you modify the structure of your objects the code you showed is as "optimized" as you can probably get, due to the fact you are using a list of dictionaries there is no way to remove the nested loops that will iterate through each list to find the correct dictionary.
Consider using the names as keys in object1 and object2, ie {'apple': 100, 'grape': 150}. This way you will have direct access in order to find the common keys. The structure of the output can stay as you wish.
object1 = {'apple': 100,
           'grape': 150,
           'orange': 40}

object2 = {'apple': 200,
           'grape': 350,
           'orange': 40,
           'mango': 400}

common_keys = object1.keys() & object2.keys()

output = [{'name': key, 'priceA': object1[key], 'priceB': object2[key]}
          for key in common_keys]
print(output)
#  [{'name': 'apple', 'priceA': 100, 'priceB': 200},
#   {'name': 'grape', 'priceA': 150, 'priceB': 350},
#   {'name': 'orange', 'priceA': 40, 'priceB': 40}]

A: Well, as has already been suggested in the comments, the problem is a little incomplete, as we don't know what you want to do if the same name exists in both sets with a different price.
As also noted in the comments, you can use a set object and its .intersection () method to get what you want.
lambda o1,o2: [x for x in o1 if x['name'] in set(y['name'] for y in o1). intersection (set(z['name'] for z in o2))]

That ought to work, on the assumption that the first argument to the lambda takes precedence. You can change the "x for x in o1" to "x for x in o2" to make the second version take precedence.
If you want to exclude things with different prices but the same name, things get a little more complicated. I don't know what your use case is or why the objects are structured as they are, but it might be easier if you did this:
po1={x['name']:x['price'] for x in object1}
po2={x['name']:x['price'] for x in object2}
[{'name':x,'price':po1[x]} for x in set(po1).intersection (set(po2)) if po1[x]==po2[x]]

Obviously that's not a lambda or a one-liner but it's a little more flexible (get rid of the if part to make object1 take precedence instead of excluding conflicting values, for example).


text:
Q: Splitting consecutive similar characters of a specific length in an array of strings I have an array
["ejjjjmmtthh", "zxxuueeg", "aanlljrrrxx", "dqqqaaabbb", "oocccffuucccjjjkkkjyyyeehh"]

and need to extract consecutive characters in each string element of length k (in this case 3) without using regex or groupby.
This is what I have so far:
s = ["ejjjjmmtthh", "zxxuueeg", "aanlljrrrxx", "dqqqaaabbb", "oocccffuucccjjjkkkjyyyeehhh"]
k = 3
output = []
for i in s:
    result = ""
    for j in range(1,len(i)-1):
        if i[j]==i[j-1] or i[j]==i[j+1]:
            result+=i[j]
    if i[-1] == result[-1]:
        result+=i[-1]
    if i[0]==result[0]:
        result=i[0]+result
    output.append(result)
print(output)

#current output = ['jjjjmmtthh', 'xxuuee', 'aallrrrxx', 'qqqaaabbb', 'oocccffuucccjjjkkkyyyeehhh']
#expected outcome(for k =3) = ['rrr','qqq','aaa','bbb','ccc','ccc','jjj','kkk','yyy','hhh']

My questions:

*

*How can I accommodate the k condition?

*Is there a more optimal way to do this?

A: Here I group the letters manually by consecutive same letters. Then I only count them to the result in case they have the same length as k. This works but I am sure there is a more optimal way:
s = ["ejjjjmmtthh", "zxxuueeg", "aanlljrrrxx", "dqqqaaabbb", "oocccffuucccjjjkkkjyyyeehhh"]
k = 3

def _next_group(st):
    if not st:
        return None
    first = st[0]
    res = [first]
    for s in st[1:]:
        if s == first:
            res.append(s)
        else:
            break
    return res

result = []
for st in s:
    while True:
        group = _next_group(st)
        if not group:
            break
        if len(group) == k:
            result.append("".join(group))
        if len(group) == len(st):
            break
        st = st[len(group):]

print(result)

Output:
['rrr', 'qqq', 'aaa', 'bbb', 'ccc', 'ccc', 'jjj', 'kkk', 'yyy', 'hhh']

A: A for-loop approach.
Remark: I suggest a divide-and-conquer solution: focus on a single string (and not on a list of strings) and make a function that works and then generalize it with loops/comprehension...
def repeated_chars(string, k=3):
    out = []
    c, tmp = 0, '' # counter, tmp char
    for char in s:
        if tmp == '':
            tmp = char
            c += 1
            continue

        if tmp == char:
            c += 1
        else:
            if c == k:
                out.append((tmp, c))
            tmp = char
            c = 1

    # last term
    if c == k:
        out.append((tmp, c))

    return [char * i for char, i in out]

data = ['jjjjmmtthh', 'xxuuee', 'aallrrrxx', 'qqqaaabbb', 'oocccffuucccjjjkkkyyyeehhh']

# apply the function to all strings
out = []
for s in data:
    out.extend(repeated_chars(s, k=3))

print(out)
#['rrr', 'qqq', 'aaa', 'bbb', 'ccc', 'ccc', 'jjj', 'kkk', 'yyy', 'hhh']

A: This solution is more readable and not too long. It works for k > 0.
s = ["ejjjjmmtthh", "zxxuueeg", "aanlljrrrxx", "dqqqaaabbb", "oocccffuucccjjjkkkjyyyeehhh"]
k = 3
output = []
for element in s:
    state = "" #State variable (reset on every list item)
    for char in element: #For each character
        if state != "" and char == state[-1]:  # Check if the last character is the same (only if state isn't empty)
            state += char #Add it to the state
        else:
            if len(state) == k: #Otherwise, check if we have k characters
                output.append(state) #Append te result if we do
            state = char #Reset the state
    #If there are no more characters (end of element), check too
    if len(state) == k:
        output.append(state)
print(output)

Output for k = 3
['rrr', 'qqq', 'aaa', 'bbb', 'ccc', 'ccc', 'jjj', 'kkk', 'yyy', 'hhh']

Output for k = 1
['e', 'z', 'g', 'n', 'j', 'd', 'j']

A: Edit: Yes, groubpy shouldn't be used as per requirement, but doing the job requires to groupby in some way (see accepted answer for example), so it seems a good idea to split the responsibilities into multiple functions, as is good practice, by reimplementing a groupby.
groupby seems obvious in that case, if you can't use the one from itertools, just write one.
Also the core function should work on a string, not a list of strings -- just for loop in case you have a list of strings.
Once you have your groubpy it is straightforward:
def extract_groups(s: str, k: int):
    return [group for group in groupby(s) if len(group) == k]

Let's try it out:
input_strings = [
    "ejjjjmmtthh",
    "zxxuueeg",
    "aanlljrrrxx",
    "dqqqaaabbb",
    "oocccffuucccjjjkkkjyyyeehhh",
]

expected_outputs = [
    [],
    [],
    ["rrr"],
    ["qqq", "aaa", "bbb"],
    ["ccc", "ccc", "jjj", "kkk", "yyy", "hhh"],
]

outputs = [extract_groups(s, k=3) for s in input_strings]

print(outputs == expected_outputs)  # True

As it is outputs is a list of groups:
In [  ]: outputs
Out[  ]: [[], [], ['rrr'], ['qqq', 'aaa', 'bbb'], ['ccc', 'ccc', 'jjj', 'kkk', 'yyy', 'hhh']]

If you really want it flat, flatten it:
In [  ]: from itertools import chain
   ... : list(chain.from_iterable(outputs))
Out[  ]: ['rrr', 'qqq', 'aaa', 'bbb', 'ccc', 'ccc', 'jjj', 'kkk', 'yyy', 'hhh']

In [  ]: [group for s in input_strings for group in extract_groups(s, k)]
Out[  ]: ['rrr', 'qqq', 'aaa', 'bbb', 'ccc', 'ccc', 'jjj', 'kkk', 'yyy', 'hhh']

The groupby function for reference:
def groupby(s: str):
    if not s:
        return []

    result = []
    tgt = s[0]
    counter = 1

    for c in s[1:]:
        if c == tgt:
            counter += 1
        else:
            result.append(tgt * counter)
            tgt = c
            counter = 1
    result.append(tgt * counter)

    return result


text:
Q: Only allow certain processes to connect to MS SQL I've lost the source code for a very old application that connects to a MS SQL-server for some SQL queries. Since the login is hard-coded in the application I can't change the username/password on the server.
One day the password will probably be known to the users and we surely need to change it. But how?
One idea is to only allow the old application to do the queries on the SQL server and block out any other application like the query analyzer etc. Can I set process permission somehow?

*

*The SQL server (MS SQL 2005) and application (C++) are on the same machine

*It's too costly to rewrite the old program

Thanks for help!

A: You can't really do this, AFIAK. You could block the SQL ports with Windows Firewall so that only the machine running the application can connect to SQL, which you say is the SQL server itself. Of course, this breaks anything you have that connects using SQL that doesn't run on the SQL server.
Are you saying that the users are also logged into the SQL server (and thus able to run Query Analyzer locally), or are they always remote? If the former, you're out of luck. And what are you doing allowing users to login to the SQL server itself anyway? :-)
Can you try using a hex editor to find the password in the EXE and replace it? If it's encoded, even though you've lost the source, you must remember what algorithm was used to encode it?
You've definitely learned two hard lessons. Don't hardcode passwords, and don't lose things that you don't have backed up. Do you have other important things that aren't being backed up? You may want to do an audit of your backup & restore or DR processes. Or write some, if you don't have any.


text:
Q: Implement NDSolve when I have a very efficient way to compute the right-hand-sides of my coupled ODEs I am trying speed up NDSolve on a set of coupled non-linear second-order ODEs.
x[1]''[t] = f[1][x[1],x[2],....]
x[2]''[t] = f[2][x[1],x[2],....]
:
x[n]''[t].....

No problem here--these can be dropped right into NDSolve.
However, suppose I have very efficient way to compute the f[i] terms all-at-once. Can I tell NDSolve to take advantage of that function?

Here is a concrete "toy" example of what I am asking. (that is, I am asking how to solve a problem of similar character, not this exact problem).
Suppose the force on a particle is proportional to the sum of the lengths to the other particles.  DistanceMatrix is very efficient:
forces[dofs:{p1:{x1_, y1_}, p2:{x2_, y2_}, p3:{x3_, y3_}}] :=
 Total[DistanceMatrix[dofs]] dofs

Here is an example set of degrees of freedom:
vars = Flatten[Table[{x[i][t], y[i][t]}, {i, 3}]]

And this might be my right-hand-side:
 Thread[D[#, {t, 2}] & /@ vars == Table[Inactivate[forces][vars][[i]], {i, 1, 6}]]

I believe that this would calculate force 6 times and not just once.
Is there a way to "thread" the left-hand-side vector of second derivatives over the function force[..]
Thanks, Craig

A: You can use the vectorized version of NDSolveValue. Since you don't provide initial conditions, I made some up:
SeedRandom[1];
sol = NDSolveValue[
    {
    X''[t] == forces[X[t]],
    X[0] == RandomReal[1, {3, 2}],
    X'[0] == RandomReal[1, {3, 2}]
    },
    X,
    {t,0,1}
];

Visualization:
Plot[
    Evaluate @ Table[Indexed[sol[t], {i,j}], {i,3}, {j,2}],
    {t,0,1}
]


text:
Q: no Theme Selector on SQL Developer 17.3 I have been trying to change the theme of SQL Developer, and I am unable to find the theme selector under Environment in the preferences.
has it been removed?

Normally this is where it would be located.

A:
Has it been removed?

It was just renamed

A: If you go to the "Code Editor" then drill down to "PL/SQL Syntax Colors", you can change the color of the background and the font colors for the various "Styles"...
SQL Developer Theme change/modify/save


text:
Q: windows command line giving error on calculation I found this nice little tidbit of code here: https://stackoverflow.com/a/5262637/2128987
@echo off

set starttime=%TIME%
set startcsec=%STARTTIME:~9,2%
set startsecs=%STARTTIME:~6,2%
set startmins=%STARTTIME:~3,2%
set starthour=%STARTTIME:~0,2%
set /a starttime=(%starthour%*60*60*100)+(%startmins%*60*100)+(%startsecs%*100)+(%startcsec%)

:TimeThis
robocopy /e /NFL /NDL /NJH /NJS /nc /ns /np folder%rndfolder% %drvltr%:\f%dirnew%\

set endtime=%time%
set endcsec=%endTIME:~9,2%
set endsecs=%endTIME:~6,2%
set endmins=%endTIME:~3,2%
set endhour=%endTIME:~0,2%
if %endhour% LSS %starthour% set /a endhour+=24
set /a endtime=(%endhour%*60*60*100)+(%endmins%*60*100)+(%endsecs%*100)+(%endcsec%)

set /a timetaken= ( %endtime% - %starttime% )
set /a timetakens= %timetaken% / 100
set timetaken=%timetakens%.%timetaken:~-2%

echo.
echo Took: %timetaken% sec.

As a standalone program it works great. I am using it with a robocopy command basically to determine how long it takes to write a file.
I add one extra variable in it because I want to keep the raw seconds for calculation purposes. So I add the extra line set timeraw=%timetaken%:
set /a timetaken= ( %endtime% - %starttime% )
***set timeraw=%timetaken%***
set /a timetakens= %timetaken% / 100
set timetaken=%timetakens%.%timetaken:~-2%

My batch file also uses setlocal enabledelayedexpansion
Well sometimes it does not properly calculate the "starttime" or "endtime". It's keeps it as the raw time in 08:30:22.35 type format and results in the error:
Invalid number. Numeric constants are either decimal (17),hexadecima (0x11), or octal (021)

Well obviously because it contains non-numeric characters like the : character.
My batch file goes in a continuous loop forever as I am using it to read, write, delete files and folders for a specific torture test condition.
Any idea why it would intermittently not calculate the starttime or endtime variables?
edit:
I made some changes to my overall script. I no longer need enabledelayedexpansion, cleaned up some if then statements, and simplified code a little. But I still occasionally get it where the starttime or endtime variables remain as the raw time format of HH:MM:SS.CS and causes error in calculation.

A: Old question, but there are probably blocks of parentheses and when you change a variable within parentheses then you need to use delayed expansion.
Run this and examine the differences.
@echo off
set a=nothing
   if z==z (
      set a=b
      echo %a%
   )
pause
setlocal enabledelayedexpansion
set a=nothing
   if z==z (
      set a=b
      echo !a!
   )
pause

A: Gee - a question nearly a year old, with no answer.
I'll assume that the problem has now been solved, so as a matter of record, I'd conclude that the
"sometimes it does not properly calculate" is because the hour/minute/second/hundredths will contain "08" or "09" which are not octal numbers.
The solution is
set /a startcsec=1%STARTTIME:~9,2% - 100

and repeat with each of the other 3 start time-segments; then repeat again with the end parts.
In addition, it could be that the hour is being presented with 0s suppressed. In this case, I'd suggest
set starttime=0%TIME: =%
set starttime=%startTIME:~-11%
set /a startcsec=1%STARTTIME:~9,2% - 100

where the first line prefixes the time with a '0', and replaces Space with [nothing]
the second selects just the last 11 characters of the result
and the last is the familiar form, using the resultant hh:mm:ss.cc format.
(obviously, the remainder of the substring-and-calculate method needs also to be implemented)


text:
Q: Explanation for recursive implementation of Josephus problem EDIT: n is the number of persons. k is the kth person being eliminated. So for k=2, every 2nd person is getting eliminated.
int josephus(int n, int k)
{
 if (n == 1)
  return 1;
else
   return (josephus(n - 1, k) + k-1) % n + 1;
}

The code is as simple as it could be. But somehow I am unable to understand this problem (which is a little embarassing to be honest).
The way I am trying to understand it is,

*

*josephus(n,k) gives the final solution for a population of size n and step size k.

*josephus(n,k) can be calculated if we know the solution for josephus(n-1,k). That is in my opinion "optimal substructure property" of dynamic programming.

*I get that we need to do a MOD N so that in case number goes past n, it will again start counting from 1. (i.e. ensure that addition behaves like we are counting in a circle). But why did we add this "k-1"?

The main question is if we know the correct solution of josephus(n-1,k), how are we calculating the solution to josephus(n,k). We have effectively added one more person to the population and somehow adding this k-1 value is giving me the correct solution (let's ignore mod for a moment).
Can anyone explain this to me that how is the optimal substructure property holding at each step in the problem?

A: The key insight that made this solution make sense for me is the following: the result of josephus(n, k) is best not thought of as the number that is the Josephus survivor, but rather as the index of the number that is the Josephus survivor. For example, calling josephus(5, 2) will tell you the index of the person out of a ring of five that ends up surviving.
With that intuition in mind, let's think about how the Josephus problem works by looking at a concrete example. Suppose we want to know josephus(n, 2). You can imagine we have n people lined up like this:
1 2 3 4 5 ... n

The first thing that happens is that person 1 kills person 2, as shown here:
1 X 3 4 5 ... n

Now, we're left with a subproblem of the following form: there are n-1 people remaining, every other person is going to be killed, and the first person who will be doing the stabbing is person 3. In other words, we're left with a ring of people shaped like this:
3 4 5 ... n 1

with k = 2. Now, imagine that we make a recursive call to josephus(n - 1, 2), since we have n - 1 people. This will give back the index of who survives in a line of n - 1 people. Given that we have the index of the person who will survive, and we also know who the starting person is, we can determine which person will be left. Here's how we'll do it.
The starting person in this line is the person who comes right after the person who was last executed. This will be person 3. The 1-indexed position of the survivor in the ring of four people is given by josephus(n - 1, 2). We can therefore walk forward josephus(n - 1, 2) - 1 positions, wrapping around the ring if necessary, to get to our final position. In other words, the survivor is given by position
 (3 + josephus(n - 1, 2) - 1) % n

There's a problem with this above formula, though. If we are indeed using one-indexing, what happens if the final survivor is at position n? In that case, we'd accidentally get back position 0 as our answer, but we really want position n. As a fix to this, we'll use a trick for using mod to wrap around with one-indexing: we'll take the inside quantity (the one-indexed position) and subtract one to get the zero-indexed position. We'll mod that quantity by n to get the zero-indexed position wrapped around. Finally, we'll add back one to get the one-indexed position, wrapped around. That looks like this:
(3 + josephus(n - 1, 2) - 2) % n + 1

The -2 term here therefore comes from two independent -1's: the first -1 is because josephus(n - 1, 2) returns a one-indexed index, so to step forward by the right number of positions we have to take josephus(n - 1, 2) - 1 steps forward. The second -1 comes from the fact that we're using one-indexing rather than zero-indexing.
Let's generalize this to work for arbitrary k, not just k = 2. Suppose we want to know josephus(n, k). In that case, person 1 will stab person k, leaving us with an array like this:
1 2 3 ... k-1 X k+1 ... n

We now essentially need to solve a subproblem where person k+1 comes first:
k+1 k+2 ... n 1 2 ... k-1

So we compute josephus(n - 1, k) to get the one-indexed survivor of a ring of n - 1 people, then shift forward by that many steps:
(k+1 + josephus(n - 1, k) - 1)

We need to worry about the case where we wrap around, so we need to mod by n:
(k+1 + josephus(n - 1, k) - 1) % n

However, we're one-indexed, so we need to use the trick of subtracting 1 from the inside quantity and then adding 1 at the end:
(k+1 + josephus(n - 1, k) - 2) % n + 1

which simplifies to
(k-1 + josephus(n - 1, k)) % n + 1

which is equivalent to
(josephus(n - 1, k) + k-1) % n + 1

as in the solution code.
To summarize: the k-1 term comes from starting at position k+1, adding in josephus(n - 1, k) - 1 to shift forward the appropriate amount, then subtracting one and adding one back in at the end to do the correct wraparound.
Hope this helps!

A: We need to adjust the position by k-1 simply because the starting position has been shift by k after the kth is removed (and the first k-1 are rotated to the end). That is, initial position pos becomes pos-k. If k = 3, (n-1,k) returned pos = 2, the original position should be pos + k = 5.
We replace k with k-1 in the formula because we have to mod(n): k = (k-1) % n + 1


text:
Q: The notification about attempt of opening newer dwg format than it can be opened AutoCAD .NET API [2009-2016]
How can I get the notification about attempt of opening newer DWG format than it can be opened in current AutoCAD?
I've searched the similar events in the DocumentCollection Events and Database Events of the ObjectARX SDK documentation but I found nothing...


text:
Q: How do you configure Kestrel to use a random dynamic port from a defined range of ports Is there any way to configure Kestrel to use a random port from a defined range ( for example from 5500 to 5600)?
public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost().Run();
    }

    public static IWebHost BuildWebHost() =>

        WebHost.CreateDefaultBuilder()
            .UseKestrel()
            .UseUrls("http://127.0.0.1:0") // port zero to use random dynamic port but doesn't respoect the range port
            .UseStartup<Startup>()
            .Build();
}

A: I don't think we are currently support a ranged dynamic port, checked docs  , not saying it is a ranged port
I raised a github issue and you can subscribe that to see if this would be a new feature in the future


text:
Q: gaining a focus of JInternalFrame object What happens when you minimize JInternalFrame object using built-in icon located in the corner (next to maximizing and closing ones)?
I have a JInternalFrame in JDesktopPane and my problem is following:
When I minimize one frame it is being minimized. When I try to re-open the frame via using JMenu it works for first time. When I do this procedure again, the frame is being minimized but not re-opened, but when I click manually on a iconified frame, it shows properly.
I tried to do combination of setSelected, moveToFront, setIcon, setVisible, activateFrame, or requestFocus, but still no effects.
I wonder what happens when you minimize JInternalFrame, what is being set, what should do to get focus of a particular frame, and why the procedure it works for the first time and not others?
thanks

A: Seems to work fine for me
try {

    if (myFrame.isIcon()) {

        myFrame.setIcon(false);
        miDoShowHide.setText("Hide");

    } else {

        myFrame.setIcon(true);
        miDoShowHide.setText("Show");

    }

} catch (Exception exp) {

    exp.printStackTrace();

}

I set up a menu item that would call this functionality.  I tested by using the menu to min, restore, min, restore.  I minimized the frame by the frame control and restored via the menu, minimized by the menu and restored by the frame control.
Also make sure that the JInternalFrame is set to Iconifiable (setIconifiable(true)) otherwise you will experience some strange results


text:
Q: jQuery setting attributes with functions I wrote a simple function:
function addColoredBorder(color) {
    $(".coloredBorder").css({
        border-left: color,
        padding-left: "15px",
        border-radius: "10px"
    });
};

Then in HTML i would call the function, but for some reason, it doesn't accept it.
I know, you could do:
function f_border () {
  return "border:"
}

function f_attribute(x) {
  return x
}

function addColoredBorder() {
    $(".coloredBorder").css(f_border(), f_attribute());
});

But i need it to be as compact and simple for it to be as possible. toggleClass is out of question.
So experts, how can i set color without writing massive amounts of code?
(PS. The second block of code might not be correct at all, but i believe it goes somewhat like that.)

A: Remove the colon from border: in the f_border() function.

A: You are trying to set the property border-left to a color.  However, that is not the correct syntax for border-left.  It should be set to something like 1px solid #333.  Therefore, if you want to write a function to change that do the following:
function addColoredBorder(color) {
    $(".coloredBorder").css({
        'border-left': '1px solid '+color,
        'padding-left': "15px",
        'border-radius': "10px"
    });
};

A: The javascript parser is not happy to have unquoted dashes in your object keys.
    "border-left": color,
    "padding-left": "15px",
    "border-radius": "10px"

or, jQuery supports camel-casing your CSS keys too:
    borderLeft: color,
    paddingLeft: "15px",
    borderRadius: "10px"

A: object literal property names cannot have dashes in them unless they are quoted. So you need to use the camelCase version of the css properties or quote them
So code should look like:
function addColoredBorder(color) {
    $(".coloredBorder").css({
        "borderLeft": color,
        "paddingLeft": "15px",
        "borderRadius": "10px"
    });
};

A: There are syntax errors that causing issues.
 <html>
    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <script type="text/javascript">
            function addColoredBorder(color) {
                $(".coloredBorder").css({
                    'border-color': color,
                    'padding-left': "15px",
                    'border-radius': "10px"
                });
            }
        </script>
    </head>
    <body>
        <div class="coloredBorder" style="border:solid;">
This is a div content
        </div>
        <button id="but1" onclick="addColoredBorder('red')"> apply red color </button>
    </body>
    </html>