text:
Q: How to request json files from server and put? I have datepicker and I have specific days which I set with array..it's okey so far but I want to set these days with json and my question is how to request from server and then put into when I focus datepicker?
if you click my datepicker you will see my specific days (with green and red colors)
I shared my specific days end of the snippet

$(function() {
  var ilktarih = ['2017-03-23'];
  var sontarih = ['2017-04-10']
  var bostarihler = ['2017-03-15', '2017-03-16', '2017-03-17', '2017-03-18', '2017-03-19', '2017-03-20', '2017-03-21', '2017-03-22', '2017-03-23', '2017-03-24', '2017-03-25', '2017-03-26', '2017-03-27', '2017-03-28', '2017-03-29', '2017-03-30'];
  var dolutarihler = ['2017-08-22', '2017-06-23', '2017-06-24', '2017-05-25', '2017-06-26', '2017-10-27', '2017-02-28', '2017-03-01', '2017-03-02', '2017-03-03', '2017-03-04', '2017-03-05', '2017-03-06', '2017-03-07', '2017-03-08', '2017-03-09', '2017-03-10', '2017-03-11', '2017-03-12', '2017-03-13', '2017-03-14'];
  var testtarih = ['04-04-2017', '10-04-2017'];
  var sstarihler = [];

  var dateFormat = "mm/dd/yy",
    from = $("#checkin").datepicker({
      changeMonth: true,
      numberOfMonths: 2,
      firstDay: 1,
      minDate: new Date(ilktarih),
      maxDate: new Date(sontarih),
      onSelect: function(selectedDate) {
        var yenitarih = new Date();

        var date = $(this).datepicker('getDate');
        date.setTime(date.getTime() + (1000 * 60 * 60 * 24))

        $("#checkout").datepicker("option", "minDate", date);
      },

      beforeShowDay: function(date) {
        var y = date.getFullYear().toString(); // get full year
        var m = (date.getMonth() + 1).toString(); // get month.
        var d = date.getDate().toString(); // get Day
        if (m.length == 1) {
          m = '0' + m;
        } // append zero(0) if single digit
        if (d.length == 1) {
          d = '0' + d;
        } // append zero(0) if single digit
        var currDate = y + '-' + m + '-' + d;

        if (jQuery.inArray(currDate, dolutarihler) >= 0) {
          return [false, "ui-highlight"];
        }

        if (jQuery.inArray(currDate, bostarihler) >= 0) {
          return [true, "ui-bos"];
        }

        if (jQuery.inArray(currDate, sstarihler) >= 0) {
          return [false, "ui-ss"];
        } else {
          return [true];
        }

      },
      isTo1: true,
    }).on("change", function() {
      to.datepicker("option", "minDate", getDate(this));
    }),
    to = $("#checkout").datepicker({
      changeMonth: true,
      changeYear: true,
      firstDay: 1,
      numberOfMonths: 2,
      minDate: new Date(ilktarih),
      maxDate: new Date(sontarih),
      onSelect: function(selectedDate) {
        $("#checkin").datepicker("option", "maxDate", selectedDate);
      },
      beforeShowDay: function(date) {
        var y = date.getFullYear().toString(); // get full year
        var m = (date.getMonth() + 1).toString(); // get month.
        var d = date.getDate().toString(); // get Day
        if (m.length == 1) {
          m = '0' + m;
        } // append zero(0) if single digit
        if (d.length == 1) {
          d = '0' + d;
        } // append zero(0) if single digit
        var currDate = y + '-' + m + '-' + d;

        if (jQuery.inArray(currDate, dolutarihler) >= 0) {
          return [true, "ui-highlight-donus"];
        }

        if (jQuery.inArray(currDate, bostarihler) >= 0) {
          return [true, "ui-bos"];
        }

        if (jQuery.inArray(currDate, sstarihler) >= 0) {
          return [true, "ui-ss-donus"];
        } else {
          return [true];
        }

      }
    }).on("change", function() {
      from.datepicker("option", "maxDate", getDate(this));
    });

  function getDate(element) {
    var date;
    try {
      date = $.datepicker.parseDate(dateFormat, element.value);
    } catch (error) {
      date = null;
    }

    return date;
  }
});
.form {
  width: 960px;
  margin: 120px auto;
}

.form input {
  width: 250px;
  padding: 10px;
}

.ui-highlight .ui-state-default {
  background: red !important;
  border-color: red !important;
  color: white !important;
  cursor: no-drop;
}

.ui-bos .ui-state-default {
  background: green !important;
  border-color: green !important;
  color: white !important;
}

.ui-ss .ui-state-default {
  background: yellow !important;
  border-color: yellow !important;
  color: gray !important;
  cursor: help;
}

.ui-ss-donus .ui-state-default {
  background: yellow !important;
  border-color: yellow !important;
  color: gray !important;
  cursor: help;
}

.ui-highlight-donus .ui-state-default {
  background: red !important;
  border-color: red !important;
  color: white !important;
}

.ui-testtarih .ui-state-default {
  background: black !important;
  color: #FFF !important;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet" />

  <input type="text" id="checkin" />
  <input type="text" id="checkout" />
  <input type="submit" value="Search" />

specificdays.json

{
  "ilktarih": [{
    "field": "2017-03-23"
  }, ],
  "sontarih": [{
    "field": "2017-04-10"
  }, ],

  "bostarih": [{
      "field": "2017-03-15"
    },
    {
      "field": "2017-03-16"
    },
    {
      "field": "2017-03-17"
    },
    {
      "field": "2017-03-19"
    },
    {
      "field": "2017-03-20"
    },
    {
      "field": "2017-03-21"
    },
    {
      "field": "2017-03-22"
    },
    {
      "field": "2017-03-22"
    },
    {
      "field": "2017-03-23"
    },
    {
      "field": "2017-03-24"
    },
    {
      "field": "2017-03-25"
    },
    {
      "field": "2017-03-26"
    },
    {
      "field": "2017-03-27"
    },
    {
      "field": "2017-03-28"
    },
    {
      "field": "2017-03-29"
    },
    {
      "field": "2017-03-30"
    },
  ],
  "dolutarih": [

    {
      "field": "2017-08-22"
    },
    {
      "field": "2017-06-23"
    },
    {
      "field": "2017-06-24"
    },
    {
      "field": "2017-05-25"
    },
    {
      "field": "2017-06-26"
    },
    {
      "field": "2017-10-27"
    },
    {
      "field": "2017-02-28"
    },
    {
      "field": "2017-03-01"
    },
    {
      "field": "2017-03-02"
    },
    {
      "field": "2017-03-03"
    },
    {
      "field": "2017-03-04"
    },
    {
      "field": "2017-03-26"
    },
    {
      "field": "2017-03-06"
    },
    {
      "field": "2017-03-07"
    },
    {
      "field": "2017-03-08"
    },
    {
      "field": "2017-03-09"
    },
    {
      "field": "2017-03-10"
    },
    {
      "field": "2017-03-11"
    },
    {
      "field": "2017-03-12"
    },
    {
      "field": "2017-03-13"
    },
    {
      "field": "2017-03-14"
    },
  ]
}

and I can get these days with jquery as below..but I don't have any idea how can apply to my datepicker tor request

$(document).ready(function() {
  $.getJSON("json_data.json", function(data) {
    $.each(data.ilktarih, function() {
      $("ul").append("
" + this['field'] + "
");
    });

    $.each(data.sontarih, function() {
      $("ul").append("
" + this['field'] + "
");
    });

    $.each(data.bostarih, function() {
      $("ul").append("
" + this['field'] + "
");
    });

    $.each(data.dolutarih, function() {
      $("ul").append("
" + this['field'] + "
");
    });
  });

});

CodePen Demo

A: if you want to get some data from the server, you need to do an Ajax call (with application/json result type)
You can check the jquery ajax function in more details :
http://api.jquery.com/jquery.ajax/

A: Read about ajax requests with jquery. Something like this (make request, get data, loop through it, and append to body):
  $.getJSON( "ajax/test.json", function( data ) {
  var items = [];
  $.each( data, function( key, val ) {
    items.push( "
" + val + "
" );
  });

  $( "
", {
    "class": "my-new-list",
    html: items.join( "" )
  }).appendTo( "body" );
});

at start try get json data and display it in console. good luck:)


text:
Q: How do I import .pgn data in PyCharm? For a school project I am creating an artificial neural network that I'm going to train with data from lichess.org, an online chess-playing website that has all of it's 1.5 billion games open source and ready for download.
I downloaded 11 million games as a 10gb text file, and now want to somehow access them in my PyCharm project: Either by assigning it as a string to a variable or any other method that lets me directly change and access that text.
I have already uploaded the pgn to my project in pycharm:

This is a sample of what the pgn looks like inside:

There are about 11 million of those game records.
Thank you very much! Any help would be greatly appreciated.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to retrieve layout_height in code I have a layout that contains several sub-views all which set height like:
<View android:layout_width="fill_parent"
    android:layout_height="18dip"
    android:background="#ff000000" />

How can I retrieve the value stored in layout_height in code?
Ultimately, what I would like to do is being able to adjust the size defined in the layout so I can dynamically change the value defined by layout_height depending on the resolution of the screen resolution and the pixel density.
Is the only way to do so during the onLayout callback?
It would be much easier to redefined the XML on onCreate.
Comments, advices would be much appreciated.
Thanks
JY

A: Acces the View's Layout and then access the 'height' field: View.getLayoutParams().height

A: Should have searched a tad further prior to post a question.
This does the trick it seems...
DisplayMetrics dm = new DisplayMetrics();
    this.getWindowManager().getDefaultDisplay().getMetrics(dm);
    factor_y = (dm.ydpi * dm.heightPixels) / (160 * 480);
    factor_x = (dm.xdpi * dm.widthPixels) / (160 * 320);

LinearLayout layout = (LinearLayout) findViewById(R.id.mainlayout);
for (int i = 0; i < layout.getChildCount(); i++)
{
    View v = layout.getChildAt(i);
    int height = v.getLayoutParams().height;
    if (height > 0)
    {
        v.getLayoutParams().height = (int) ((float) height * factor_y);
    }
    int width = v.getLayoutParams().width;
    if (width > 0)
    {
        v.getLayoutParams().width = (int) ((float) width * factor_x);
    }
}


text:
Q: Solr: Using wildcard for a term having whitespaces I am trying to search for a term that has spaces and a wildcard at the end of it; i.e. name:John S*
Solr is failing to return any result although I have the below entries indexed and are returned when querying *:* from Solr web interface;

*

*John Dow

*Johny English

*John Smith

I am using Sol7.4 with DIH that index my DB, and I am creating a contact search (by name and phone) feature to my web app.
I have followed this thread Solr wildcard query with whitespace however it did not solve the problem;

*

*I have tried changing my field type (for field name) to text_en, text_ws and currently text_general, plus, tried to escape spaces with a backslash "\ " and it did not work.

*Tried Solr "complex phrase query parser" which partially solved the issue, as it will extremely increase the query time, in addition, Solarium is throwing an exception if the term contains spaces at the end i.e. "jhon\ *" and if I try to run the same query from Solr web interface I got no result
http://localhost:8983/solr/collection/select?q{!complexphrase inOrder=true}displayName:John\ *

*Also, tried Prefix Query Parser with no luck

Note: that I have reloaded solr, cleared and re-index my data after each try.
Expected result:

*

*when searching for "John" I should get all the 3 entries:

*

*John Dow

*Johny English

*John Smith

*when searching for "John\ " that will be parsed to "John "; I should get:

*

*John Dow

*John Smith

*and when searching for "John\ S*", I should be getting:

*

*John Smith

Update #1
search.php
...
    $term = str_replace(' ', '\ ', $request_params['term']);
    $query->setQuery('phone:"%1%" OR name:"%1%" OR contact:%2%*', [$request_params['term'], $term]);
    // $query->setQuery('phone:"%1%" OR name:"%1%" OR contact:"%2%*"', [$request_params['term'], $term]);
...

managed-schema
...
  <fieldType name="lowercase" class="solr.TextField" positionIncrementGap="100">
    <analyzer>
      <tokenizer class="solr.KeywordTokenizerFactory"/>
      <filter class="solr.LowerCaseFilterFactory"/>
    </analyzer>
  </fieldType>
...
  <field name="name" type="text_general" multiValued="false" indexed="true" stored="true"/>
  <field name="contact" type="lowercase" indexed="true" stored="true"/>
  <field name="phone" type="string" docValues="false" multiValued="false" indexed="true" required="true" stored="true"/>
  <copyField source="displayName" dest="card"/>
  <!-- <copyField source="phone" dest="card"/> -->
...

A: Use a second field for wildcard matches that has a KeywordTokenizer with a LowercaseFilterFactory attached. Use a copyField instruction to copy the content from the main field into the second, wildcard based field.
That way you can perform regular searches against the regular field, while performing wildcard searches against the field that supports wildcards properly.
Your second example above (John\ *) in effect will probably only match anything that has the token John present (and you're missing a = between the argument name q and the argument itself).


text:
Q: injecting new argument/property value to maven profile in module i have main pom.xml
i like to change from the main mvn command line cli which I'm using and change the :
<argument>${docker.image}</argument>

argument in only in the submodule :
module_y profile NOT module_x
this is the command I'm executing now :
mvn clean install -Ddocker_build=build
<artifactId>foo</artifactId>
<version>b1</version>
<packaging>pom</packaging>

 <properties>
        <docker.image>www.repo.org:8000/${project.artifactId}:${project.version}</docker.image>
 </properties>

 <modules>
        <module>module_x</module>
        <module>module_y</module>
 </modules>

this is the section in the module_x and module_y
<profiles>
        <profile>

            <activation>
                <property>
                    <name>docker_build</name>
                    <value>build</value>
                </property>
                <file>
                    <exists>Dockerfile</exists>
                </file>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.codehaus.mojo</groupId>
                        <artifactId>exec-maven-plugin</artifactId>
                        <version>1.6.0</version>
                        <executions>
                            <execution>
                                <phase>install</phase>
                                <configuration>
                                    <executable>docker</executable>
                                    <arguments>
                                        <argument>build</argument>
                                        <argument>-f</argument>
                                        <argument>${project.basedir}/Dockerfile</argument>
                                        <argument>-t</argument>
                                        <argument>${docker.image}</argument>
                                        <argument>.</argument>
                                    </arguments>
                                </configuration>
                                <goals>
                                    <goal>exec</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
</profiles>

in short, how do i change only the property value  ${docker.image} in profile docker_build in module_y from main mvn run?

A: If you cannot change the POMs, this cannot be done.
The only possible approach would be to build the modules separately (by using -pl module_x -am or something like that) and use different command line parameters in both cases.


text:
Q: Plugin options page: grouping checkboxes I've been using the WordPress Option Page Generator by Jeremy Hixon to help give me a head start with my plugin's option page. I've laid out four different types of checkboxes which the source code can be found here:
https://gist.github.com/factmaven/3896a3aac3888aa5bcddae48d9da5238
However, I'd like to add additional checkboxes in each of the four section that I've made, like so:

Based on the generator, it looks like I would need to add another add_settings_field and another callback function to add more checkboxes; but that looks more tedious than I'd imagine just to add more checkboxes under each section. Is it possible to add additional checkboxes underneath the add_settings_field that I've already created? For example:
public function personal_options_0_callback() {
    printf(
        '<input type="checkbox" name="profile_settings_option_name[personal_options_0]" id="personal_options_0" value="personal_options_0" %s>  Visual Editor',
        ( isset( $this->profile_settings_options['personal_options_0'] ) && $this->profile_settings_options['personal_options_0'] === 'personal_options_0' ) ? 'checked' : ''
    );
    printf(
        '<input type="checkbox" name="profile_settings_option_name[personal_options_1]" id="personal_options_1" value="personal_options_1" %s>  Admin Color Scheme',
        ( isset( $this->profile_settings_options['personal_options_1'] ) && $this->profile_settings_options['personal_options_1'] === 'personal_options_1' ) ? 'checked' : ''
    );
}

Any help or guidance is appreciated. I've never made a plugin options page before, so if there is a simpler way of doing this, I am also open to your recommendation. Thanks.

A: As discussed in the WordPress Support Forums, in some instances, it's easier to develop an array which stores the value value.
To group the checkboxes, I simply copied the same format from the Discussion settings page to get my expected result: a group of checkboxes that are formatted using WordPress' native style. Here's a good template to work off of:

Profile Settings

    <form method="post" action="action_here">

                    Personal Options

                        <fieldset>
                            <legend class="screen-reader-text">Personal Options</legend>

                            <input name="rich_editing" type="checkbox" value="rich_editing" />
                            Visual Editor

                            <input name="admin_color" type="checkbox" value="admin_color" />
                            Admin Color Scheme

                            <input name="comment_shortcuts" type="checkbox" value="comment_shortcuts" />
                            Keyboard Shortcuts

                            <input name="admin_bar_front" type="checkbox" value="admin_bar_front" />
                            Toolbar

                        </fieldset>

                    Name

                        <fieldset>
                            <legend class="screen-reader-text">Name</legend>

                            <input name="first_name" type="checkbox" value="first_name" />
                            First Name

                            <input name="last_name" type="checkbox" value="last_name" />
                            Last Name

                            <input name="nickname" type="checkbox" value="nickname" />
                            Nickname

                            <input name="display_name" type="checkbox" value="display_name" />
                            Display Name

                        </fieldset>

        <?php submit_button(); ?>
    </form>

Result


text:
Q: Cloud availability of short-term "virgin" Windows instances? I have a situation where we on a regular basis need a freshly installed "virgin"  Windows installation to do various work in isolation on, and building one from scratch every time in a vmware instance is getting tedious.
Perhaps there are cloud offerings providing a service allowing to request one or more Windows instances and after a very short while they were available for logging in through Remote Desktop?   After usage they were just recycled without having to pay for a full Windows license every time.
Do this exist for a reasonable price?  What is your personal experiences with this?

A: I don't know about a service, but we need something similar where I work and we will often just clone a VMWare virtual machine that is in the virgin configuration. If you don't need to keep your changed machines because it's just a QA task you can just save a snapshot of the empty machine, do your testing and then go back to the snapshot when you are finished. It only takes a minute or two to restore a snapshot in my experience.

A: There's about 18 bajillion Window VPS hosting services out there.  Just google 'Windows VPS hosting'.  Most VPS hosts let you wipe out and reset the machine to a base state of some sort whenever you want.  Thats one of the big benefits of VPS hosting.
BUT, I agree with the commenters that you'd probbably be better off with a VM and using snapshots.  I do this with VirtualBox all the time.  Thats exactly what its designed for.  The problem with hosted instances is, unless this is the goal, you're getting an OS build specifically catered for web/app hosting.  So that means, for example, Windows 2k8, not Windows 7, and the ram/drive space will be limited.

A: I know that Amazon AWS have Windows AMIs available. I've never used them (whereas their Linux support is fine) and I don't know if the price is suitable for you, but they're there. Login after they're booted is indeed via RDP (I've seen that in the docs).
I've no idea what the details of the licensing side of things are. It wasn't relevant when I was researching this all last year (since we weren't working with Windows apps at the time).

A: Yes, you can do this through Amazon, but if you've got a significant software load time, it'll be slower than working with a VM.  With EC2, you just specify the type of environment you want (they have a variety of pre-configured images), hook it up with some block storage and start installing your software.  Use it for as long as you want, then just throw it away.

A: You can look at Rackspace Cloud Servers if you would like to look at an alternative to Amazon.  I've used them to set up a Windows + SQL Server + IIS box to do some testing and they are pretty reasonably priced if what your doing isn't that bandwidth intensive. There's no windows license to mess with, you just pay by the hour for the windows instance.

A: Try CloudShare, they give 3 instances with the possibility of choosing between various Windows versions. Also you can build and environment and save a snapshot so you can share an online copy of it.
You can change your environment as much as you want, that means you can have short-lived Windows instances for testing your software, or whatever, and then remove the instance and create a brand new Windows clean instance or even upload a VMWare image of yours.
The Pro version is free, it's not a trial and no CC needed.


text:
Q: RecyclerView with GridLayoutManager trying to solve wrap_content I try to solve the following:

*

*using RecyclerView

*with GridLayoutManager

*with fixed cell-widths

*recyclerview resizing only to the necessary height (wrap_content)

I try to use the following code, the problem is that it doesn't work, and I haven't found any working example not mentioning to redraw properly when orientation changes.
public class AutofitRecyclerView extends RecyclerView {
    private MyGridLayoutManager manager;
    private int columnWidth = -1;

    public AutofitRecyclerView(Context context) {
        super(context);
        init(context, null);
    }

    public AutofitRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public AutofitRecyclerView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        if (attrs != null) {
            int[] attrsArray = {
                    android.R.attr.columnWidth
            };
            TypedArray array = context.obtainStyledAttributes(attrs, attrsArray);
            columnWidth = array.getDimensionPixelSize(0, -1);
            array.recycle();
        }

        manager = new MyGridLayoutManager(getContext(), 1);
        setLayoutManager(manager);
    }

    @Override
    protected void onMeasure(int widthSpec, int heightSpec) {
        super.onMeasure(widthSpec, heightSpec);
        if (columnWidth > 0) {

            int mw = getMeasuredWidth();

            int spanCount = Math.max(1, mw / columnWidth);
            manager.setSpanCount(spanCount);
        }

        int numOfFullRows = manager.getItemCount() / manager.getSpanCount();

        if(manager.getItemCount() % manager.getSpanCount() > 0)
        {
            numOfFullRows++;
        }

        if(getChildCount() > 0) {
            int h = 0;
            try {
                h = manager.getChildAt(0).getMeasuredHeight();
            } catch (Exception e) {
                e.printStackTrace();
            }

            if(h != 0) {
                getLayoutParams().height = numOfFullRows * h;
            }
        }
    }
}

A: You'll need to add a custom GridlayoutManager.
Check this https://gist.github.com/ArthurSav/5f80e19d9ba6d562fbd5

A: Based on the code that connector published I came up with the following solution that supports different row / column sizes (though I have admittedly not tested that), takes the sizes of the item decorations into account and handles the different measure modes properly.
Here is the code:
import android.content.Context;
import android.graphics.Rect;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;

public class WrappableGridLayoutManager extends GridLayoutManager {

    public WrappableGridLayoutManager(Context context, int spanCount) {
        super(context, spanCount);
    }

    private int[] measuredSize = new int[2];

    @Override
    public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
        final int widthMode = View.MeasureSpec.getMode(widthSpec);
        final int heightMode = View.MeasureSpec.getMode(heightSpec);
        final int widthSize = View.MeasureSpec.getSize(widthSpec);
        final int heightSize = View.MeasureSpec.getSize(heightSpec);

        int spanWidth = 0;
        int spanHeight = 0;

        int viewWidth = 0;
        int viewHeight = 0;

        int spanCount = getSpanCount();

        for (int i = 0; i < getItemCount(); i++) {

            measureScrapChild(recycler, i, View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED), measuredSize);

            if (i % spanCount == 0) {
                spanWidth = measuredSize[0];
                spanHeight = measuredSize[1];
            } else {
                if (getOrientation() == VERTICAL) {
                    spanWidth += measuredSize[0];
                    spanHeight = Math.max(spanHeight, measuredSize[1]);
                } else {
                    spanWidth = Math.max(spanWidth, measuredSize[0]);
                    spanHeight += measuredSize[1];
                }
            }

            if (i % spanCount == spanCount - 1 || i == getItemCount() - 1) {
                if (getOrientation() == VERTICAL) {
                    viewWidth = Math.max(viewWidth, spanWidth);
                    viewHeight += spanHeight;
                } else {
                    viewWidth += spanWidth;
                    viewHeight = Math.max(viewHeight, spanHeight);
                }
            }
        }

        int finalWidth;
        int finalHeight;

        switch (widthMode) {
            case View.MeasureSpec.EXACTLY:
                finalWidth = widthSize;
                break;
            case View.MeasureSpec.AT_MOST:
                finalWidth = Math.min(widthSize, viewWidth);
                break;
            case View.MeasureSpec.UNSPECIFIED:
                finalWidth = viewWidth;
                break;
            default:
                finalWidth = widthSize;
                break;
        }

        switch (heightMode) {
            case View.MeasureSpec.EXACTLY:
                finalHeight = heightSize;
                break;
            case View.MeasureSpec.AT_MOST:
                finalHeight = Math.min(heightSize, viewHeight);
                break;
            case View.MeasureSpec.UNSPECIFIED:
                finalHeight = viewHeight;
                break;
            default:
                finalHeight = heightSize;
                break;
        }

        setMeasuredDimension(finalWidth, finalHeight);
    }

    private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec, int heightSpec, int[] measuredDimension) {

        View view = null;
        try {
            view = recycler.getViewForPosition(position);
        } catch (Exception ex) {
          // try - catch is needed since support library version 24
        }

        if (view != null) {

            RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();

            int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec, getPaddingLeft() + getPaddingRight(), p.width);
            int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec, getPaddingTop() + getPaddingBottom(), p.height);

            view.measure(childWidthSpec, childHeightSpec);

            measuredDimension[0] = view.getMeasuredWidth() + p.leftMargin + p.rightMargin;
            measuredDimension[1] = view.getMeasuredHeight() + p.bottomMargin + p.topMargin;

            Rect decoratorRect = new Rect();
            calculateItemDecorationsForChild(view, decoratorRect);
            measuredDimension[0] += decoratorRect.left;
            measuredDimension[0] += decoratorRect.right;
            measuredDimension[1] += decoratorRect.top;
            measuredDimension[1] += decoratorRect.bottom;

            recycler.recycleView(view);
        }
    }
}

A: Thanks @nantoka and @arthur for the code, it gave me a good start. Unfortunately, it didn't work well with different spanCount, so i here is my update (Kotlin):
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.Recycler
import com.baziliqo.app.bar.utils.takeIfInstance

class WrappableGridLayoutManager(context: Context?, val preferedSpanCount: Int, @RecyclerView.Orientation orientation: Int = RecyclerView.VERTICAL) :
    GridLayoutManager(context, preferedSpanCount, orientation, false) {

    private val mMeasuredDimension = IntArray(2)

    var measuredWidth = 0
    var measuredHeight = 0

    override fun onMeasure(recycler: Recycler, state: RecyclerView.State, widthSpec: Int, heightSpec: Int) {
        val suitableSpanCount = preferedSpanCount.coerceAtMost(itemCount)
        if (spanCount != suitableSpanCount) {
            spanCount = suitableSpanCount
            return
        }
        val widthMode = View.MeasureSpec.getMode(widthSpec)
        val heightMode = View.MeasureSpec.getMode(heightSpec)
        val widthSize = View.MeasureSpec.getSize(widthSpec)
        val heightSize = View.MeasureSpec.getSize(heightSpec)
        measuredWidth = 0
        measuredHeight = 0
        for (i in 0 until itemCount) {
            measureScrapChild(
                recycler, i,
                View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                mMeasuredDimension
            )
            if (orientation == HORIZONTAL) {
                if (i % spanCount == 0) {
                    measuredWidth += mMeasuredDimension[0]
                }
                if (i < spanCount) {
                    measuredHeight += mMeasuredDimension[1]
                }
            } else {
                if (i % spanCount == 0) {
                    measuredHeight += mMeasuredDimension[1]
                }
                if (i < spanCount) {
                    measuredWidth += mMeasuredDimension[0]
                }
            }
        }
        when (widthMode) {
            View.MeasureSpec.EXACTLY -> measuredWidth = widthSize
            View.MeasureSpec.AT_MOST, View.MeasureSpec.UNSPECIFIED -> {
            }
        }
        when (heightMode) {
            View.MeasureSpec.EXACTLY -> measuredHeight = heightSize
            View.MeasureSpec.AT_MOST, View.MeasureSpec.UNSPECIFIED -> {
            }
        }
        setMeasuredDimension(measuredWidth, measuredHeight)
    }

    private fun measureScrapChild(recycler: Recycler, position: Int, widthSpec: Int, heightSpec: Int, measuredDimension: IntArray) {
        try {
            var view = recycler.getViewForPosition(position) ?: return
            val p = view.layoutParams as RecyclerView.LayoutParams
            val childWidthSpec = ViewGroup.getChildMeasureSpec(
                widthSpec,
                paddingLeft + paddingRight, p.width
            )
            val childHeightSpec = ViewGroup.getChildMeasureSpec(
                heightSpec,
                paddingTop + paddingBottom, p.height
            )
            view.measure(childWidthSpec, childHeightSpec)
            measuredDimension[0] = view.measuredWidth + p.leftMargin + p.rightMargin
            measuredDimension[1] = view.measuredHeight + p.bottomMargin + p.topMargin
            recycler.recycleView(view)
        } catch (e: Exception) {
        }
    }
}


text:
Q: How to sort an array elements? I'm trying to sort an array of string in an angular application that for example contains :
names = ["Eve","Jhon","Maria","Jadon"] and I want to sort them in this order : ["Maria", "Eve", "Jadon", "Jhon"]
I tried
names.sort();

But this will order it into an  ascending order but for me I want to choose the order as I want it to be ! as if I have a table and I want to  sort it's header's items=["id","name","email","fullname","tel"] to ["name","id","email","tel","fullname"].
Do you have any idea?

A: Here's an example how you can create custom sorter function to sort by predefined ordered array

const THIS_ORDER = ["Maria", "Eve", "Jadon", "Jhon"]

const data = ["Eve","Jhon","Maria","Jadon"];

const sorter = (a, b) => THIS_ORDER.indexOf(a) - THIS_ORDER.indexOf(b)

const result = data.sort(sorter)

console.log(result)

A: You can use this,
  const arrToSort = ["Eve","Jhon","Maria","Jadon"]

  const priority = ["Maria", "Eve", "Jadon", "Jhon"];

  const sortedObj = arrToSort.sort((a, b) => {
    const indexOfA = priority.indexOf(a);
    const indexOfB = priority.indexOf(b);
    if (indexOfA < indexOfB) return -1;
    if (indexOfA > indexOfB) return 1;
    return 0;
  });

  console.log(sortedObj);


text:
Q: spring neo4j getting exception Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'neo4jTemplate' defined in class org.springframework.data.neo4j.config.Neo4jConfiguration: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.data.neo4j.support.Neo4jTemplate org.springframework.data.neo4j.config.Neo4jConfiguration.neo4jTemplate() throws java.lang.Exception] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mappingInfrastructure' defined in class org.springframework.data.neo4j.config.Neo4jConfiguration: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.data.neo4j.support.MappingInfrastructureFactoryBean org.springframework.data.neo4j.config.Neo4jConfiguration.mappingInfrastructure() throws java.lang.Exception] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'typeRepresentationStrategyFactory' defined in class org.springframework.data.neo4j.config.Neo4jConfiguration: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.data.neo4j.support.typerepresentation.TypeRepresentationStrategyFactory org.springframework.data.neo4j.config.Neo4jConfiguration.typeRepresentationStrategyFactory() throws java.lang.Exception] threw exception; nested exception is java.lang.AbstractMethodError: org.springframework.data.neo4j.rest.SpringRestGraphDatabase.getAllLabelNames()Ljava/util/Collection;
    ... 4 more
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.data.neo4j.support.Neo4jTemplate org.springframework.data.neo4j.config.Neo4jConfiguration.neo4jTemplate() throws java.lang.Exception] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mappingInfrastructure' defined in class org.springframework.data.neo4j.config.Neo4jConfiguration: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.data.neo4j.support.MappingInfrastructureFactoryBean org.springframework.data.neo4j.config.Neo4jConfiguration.mappingInfrastructure() throws java.lang.Exception] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'typeRepresentationStrategyFactory' defined in class org.springframework.data.neo4j.config.Neo4jConfiguration: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.data.neo4j.support.typerepresentation.TypeRepresentationStrategyFactory org.springframework.data.neo4j.config.Neo4jConfiguration.typeRepresentationStrategyFactory() throws java.lang.Exception] threw exception; nested exception is java.lang.AbstractMethodError: org.springframework.data.neo4j.rest.SpringRestGraphDatabase.getAllLabelNames()Ljava/util/Collection;

    ... 4 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mappingInfrastructure' defined in class org.springframework.data.neo4j.config.Neo4jConfiguration: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.data.neo4j.support.MappingInfrastructureFactoryBean org.springframework.data.neo4j.config.Neo4jConfiguration.mappingInfrastructure() throws java.lang.Exception] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'typeRepresentationStrategyFactory' defined in class org.springframework.data.neo4j.config.Neo4jConfiguration: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.data.neo4j.support.typerepresentation.TypeRepresentationStrategyFactory org.springframework.data.neo4j.config.Neo4jConfiguration.typeRepresentationStrategyFactory() throws java.lang.Exception] threw exception; nested exception is java.lang.AbstractMethodError: org.springframework.data.neo4j.rest.SpringRestGraphDatabase.getAllLabelNames()Ljava/util/Collection;
    ... 4 more

Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.data.neo4j.support.MappingInfrastructureFactoryBean org.springframework.data.neo4j.config.Neo4jConfiguration.mappingInfrastructure() throws java.lang.Exception] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'typeRepresentationStrategyFactory' defined in class org.springframework.data.neo4j.config.Neo4jConfiguration: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.data.neo4j.support.typerepresentation.TypeRepresentationStrategyFactory org.springframework.data.neo4j.config.Neo4jConfiguration.typeRepresentationStrategyFactory() throws java.lang.Exception] threw exception; nested exception is java.lang.AbstractMethodError: org.springframework.data.neo4j.rest.SpringRestGraphDatabase.getAllLabelNames()Ljava/util/Collection;

    ... 4 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'typeRepresentationStrategyFactory' defined in class org.springframework.data.neo4j.config.Neo4jConfiguration: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.data.neo4j.support.typerepresentation.TypeRepresentationStrategyFactory org.springframework.data.neo4j.config.Neo4jConfiguration.typeRepresentationStrategyFactory() throws java.lang.Exception] threw exception; nested exception is java.lang.AbstractMethodError: org.springframework.data.neo4j.rest.SpringRestGraphDatabase.getAllLabelNames()Ljava/util/Collection;

    ... 4 more
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.data.neo4j.support.typerepresentation.TypeRepresentationStrategyFactory org.springframework.data.neo4j.config.Neo4jConfiguration.typeRepresentationStrategyFactory() throws java.lang.Exception] threw exception; nested exception is java.lang.AbstractMethodError: org.springframework.data.neo4j.rest.SpringRestGraphDatabase.getAllLabelNames()Ljava/util/Collection;

    ... 4 more
Caused by: java.lang.AbstractMethodError: org.springframework.data.neo4j.rest.SpringRestGraphDatabase.getAllLabelNames()Ljava/util/Collection;
    ... 4 more

I am getting this exception,my configuration is :
compile("org.neo4j:neo4j-community:2.0.3")

compile 'org.springframework.data:spring-data-neo4j-rest:3.1.2.RELEASE'

compile 'org.springframework.data:spring-data-neo4j:3.1.2.RELEASE'


text:
Q: Run command on all files within a directory I'm trying to remove multiple XML tags from many files in a folder. I tried sed, but it only works on one file at a time.
This is the sed code I used for removal from individual files. The folder that contains multiple files is called rcv1.
sed -e 's/<[^>]*>//g' sk.xml

a.xml
b.xml
c.xml
d.xml

The code I'm trying to use is:
for file in *.xml do sed -e 's/v[^]*>//g' "$file"

Edit: Prepending find ./ -type f -exec worked in combination with fedorqui's answer:
find ./ -type f -exec sed -i 's/<[^>]*>//g' {} \;

A: If your sed command is working for a given file and you want to do the same for all the files indicated in your file rcv1, just loop through the content of the file as indicated in How can I read a file (data stream, variable) line-by-line (and/or field-by-field)?:
while IFS= read -r file
do
    sed -e 's/<[^>]*>//g' "$file"
done < "rcv1"

It may be that you want to do this to all the files in a given directory, instead of reading them from a file. In this case, loop through the files in the current directory using a for loop:
for file in *
do
    sed -e 's/<[^>]*>//g' "$file"
done

Also, if you want these files to change, you may want to use -i so that the changes occur in-place. That is, the file itself gets modified with the new version. For safety, say sed -i.bak so that a backup file is created.
All together:
sed -i.bak -e 's/<[^>]*>//g' "$file"


text:
Q: Python JSON to dataframe i have json in format
   {
   "projects":[
      {
         "author":{
            "id":163,
            "name":"MyApp",
            "easy_external_id":null
         },
         "sum_time_entries":0,
         "sum_estimated_hours":29,
         "currency":"EUR",
         "custom_fields":[
            {
               "id":42,
               "name":"System",
               "internal_name":null,
               "field_format":"string",
               "value":null
            },
            {
               "id":40,
               "name":"Short describe",
               "internal_name":null,
               "field_format":"string",
               "value":""
            }
         ]
      }
   ]"total_count":1772,
   "offset":0,
   "limit":1
}

And I don't know how to convert this Json "completely" to a dataframe. Respectively, I just want what's in projects. But when I do this:
df = pd.DataFrame(data['projects'])

Although I only get the dataframe from projects, in some columns (for example: author or custom_fields) the format will still remain undecomposed and I would like to decompose it in these columns as well.
can anyone advise?
I expect:

author.id
author.name
author.easy_external_id
sum_time_entries
currency
custom_fields.id
custom_fields.name
etc..

163
MyApp
null
0
EUR
42
System
...

A: Try:
df = pd.json_normalize(data['projects'])

See documentation here.

A: I tried here and it works... I think the problem is in your JSON file. Try doing:
data = {'projects': [{'author': {'id': 163,
    'name': 'MyApp',
    'easy_external_id': None},
   'sum_time_entries': 0,
   'sum_estimated_hours': 29,
   'currency': 'EUR',
   'custom_fields': [{'id': 42,
     'name': 'System',
     'internal_name': None,
     'field_format': 'string',
     'value': None},
    {'id': 40,
     'name': 'Short describe',
     'internal_name': None,
     'field_format': 'string',
     'value': ''}]}],
 'total_count': 1772,
 'offset': 0,
 'limit': 1}


text:
Q: Will java streams sum values of a ConcurrentHashMap in an consistent manner? I have a concurrentHashMap instance that some threads add entries to. The values are integers.
Simultaneously, other threads wish to retrieve the sum of all the values in the map. I wish that these threads see a consistent value. However, it doesn't need to be such that they always see the latest value.
Is the following code thread safe?
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class MyClass {
    private Map<Integer, Integer> values = new ConcurrentHashMap<>();

    public void addValue(Integer key, int value){
        values.put(key, value);
    }

    public long sumOfValues(){
        return values
                .values()
                .stream()
                .mapToInt(Integer::intValue)
                .sum();
    }
}

Will the sum operation be calculated on a consistent set of values?
When the sum operation is happening, will calls to put() be blocked?
Of course I could synchronize the access myself, and even split the read and write locks to allow for concurrent read access and synchronized write access, but I am curious if its necessary when using concurrentHashMap as the collection implementation.

A: The documentation says about ConcurrentHashMap's keySet() and entrySet(): The view's iterators and spliterators are weakly consistent.
Weakly consistent characterized as

*

*they may proceed concurrently with other operations

*they will never throw ConcurrentModificationException

*they are guaranteed to traverse elements as they existed upon construction exactly once, and may (but are not guaranteed to) reflect any modifications subsequent to construction.

So...

Is the following code thread safe?

Yes, in the narrow sense of absent ConcurrentModificationException or internal inconsistencies of the HashMap.

Will the sum operation be calculated on a consistent set of values?

on a weakly consistent set

When the sum operation is happening, will calls to put() be blocked?

No

A: The point of ConcurrentHashMap is that the entries are as independent from one another as possible. There isn't a consistent view of the whole map. Indeed, even size doesn't return a very useful value.

A: If you need to query the sum concurrently, one solution is to write a wrapper class which maintains both the map's state and the sum, using a LongAdder to atomically maintain the sum.
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.LongAdder;

public class MapSum {
    private final ConcurrentMap<Integer, Integer> map = new ConcurrentHashMap<>();
    private final LongAdder sum = new LongAdder();

    public Integer get(Integer k) {
        return map.get(k);
    }

    public Integer put(Integer k, Integer v) {
        Integer[] out = new Integer[1];
        map.compute(k, (_k, old) -> {
            out[0] = old;
            // cast to long to avoid overflow
            sum.add((long) v - (old != null ? old : 0));
            return v;
        });
        return out[0];
    }

    public Integer remove(Integer k) {
        Integer[] out = new Integer[1];
        map.compute(k, (_k, old) -> {
            out[0] = old;
            // cast to long to avoid overflow; -Integer.MIN_VALUE == Integer.MIN_VALUE
            if(old != null) { sum.add(- (long) old); }
            return null;
        });
        return out[0];
    }

    public long sum() {
        return sum.sum();
    }
}

This has the added benefit of querying the sum in O(1) instead of O(n) time. You can add more Map methods if you like, and even implement Map<Integer, Integer> - just be careful to maintain the sum when you change the map's contents in any way.


text:
Q: How to change the height of an image_view at runtime I tried IMAGEVIEW.getLayoutParams().height = 200. But it is not changing correctly. Is there any other possible way, please give suggestion.

A: use this
 LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(200, 200);
    yourImageView.setLayoutParams(layoutParams);

A: _image_view.getLayoutParams().height = 30;

Hope this helps.
Very Important.
If you're setting the height after the layout has already been 'laid out',
make sure you also call this :
_image_view.requestLayout()

A:  ImageView mImageView = (ImageView)findViewById(R.id.image_view);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(100, 100); // Paramters are (width, height) in pixels
            mImageView.setLayoutParams(layoutParams);

If you want multiple resolution compatibility,
 LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams((int)(getResources().getDimension(R.dimen.image_with)),
                (int) getResources().getDimension(R.dimen.image_height));

dimens.xml under resource
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="image_with">100dp</dimen>
    <dimen name="image_height">100dp</dimen>
</resources>

A: If your imageview already shows the image,
Call:
image_view.requestLayout();

A: At First Check Set ImageView width and height programmatically
You can try with DisplayMetrics Logic .Its more perfect .

A structure describing general information about a display, such as
  its size, density, and font scaling.

   DisplayMetrics metrics = getResources().getDisplayMetrics();

   int DeviceTotalWidth = metrics.widthPixels;
   int DeviceTotalHeight = metrics.heightPixels;

   image_view.getLayoutParams().height= (int) (DeviceTotalHeight*5.25/100); // You can change from here

Another Way
    LinearLayout.LayoutParams layoutParams = new  LinearLayout.LayoutParams(200, 200);
    IMAGEVIEW.setLayoutParams(layoutParams);


text:
Q: De Broglie wavelength of an electron If an electron which already possesses some kinetic energy of $X\rm\,eV$ is further accelerated through a potential difference of $X′\rm\,V$, then is it correct to state that the electron now has a total kinetic energy of $(X+X′)\rm\,eV$? Using this information, am I allowed to substitute this value in the de Broglie equation to find the wavelength of the electron?

A: Yes this is always true.
Bear in mind that if the electron energy is comparable to its rest mass you will need to use the relativistic expression linking its energy and momentum:
$$ E^2 = p^2c^2 + m^2c^4 $$
But apart from this proceed as you describe.


text:
Q: Unable to retrieve data from website with multiple pages I could really use some help regarding a problem I'm facing. I have a project where I'm supposed to fetch the names and prices of some products. I must retrieve data from the first 5 pages of a given category.I'm trying to implement it using R, the rvest package and the SelectorGadget extension to choose the appropriate css selectors. I've written a function to do that:
readDataProject2<-function(){
  url<-readline(prompt="Enter url: ")
  nameTags<-readline(prompt="Enter name tags: ")
  priceTags<-readline(prompt="Enter price tags: ")
  itemNames<-read_html(url)%>%html_nodes(nameTags)%>%html_text()
  itemPrices<-read_html(url)%>%html_nodes(priceTags)%>%html_text()
  itemPrices<-itemPrices[-c(1,2)]
  page<-cbind(itemNames,itemPrices)

}
and here's the page anesishome.gr. From this specific page I can go to the next etc to fetch a total of...240 products. But even when I provide the url for the next page, second page, I keep getting the data of the first page. Needless to say that choosing the option to present 240 in one single page didn't do any good. Can anybody point me to what I'm doing wrong?


text:
Q: What is the most secure hashing algorithm in the .NET framework? The size of the generated hash and the speed of the algorithm are not important. I'm really only interested in it being the most secure option. I don't want to use any third party libraries either.
The version of the .NET framework I'm using if 3.5 if that makes any difference.

A: I would think SHA512 would be your best bet from the built-in hash algorithms. It's the largest hash form of a very secure algorithm.
Also, don't forget to use a salt to help protect the hash against dictionary attacks.

A: You state that the speed of the algorithm is not important, but actually it's essential.
A lot depends on the definition of 'secure', SHA512 is (just about) impossible to reverse, but actually it's fairly easy to brute force attack it.
This is because it is fast - you could think of it as a fundamental design flaw of the SHA 'family' in that they're designed to be very quick.
This is a problem - SHA512 achieves it's design goal of being very fast (it's not much slower than SHA1) but if you're a hacker trying brute force passwords that makes it easier to crack. 10 or even 5 years ago a serious brute force attack would have been out of the question, now it's a couple of fancy graphics cards or some cloud time.
This is where key-stretching algorithms come in - they make the process of building a password hash deliberately slow. Slow enough that users checking an individual hash won't notice but a brute force attack will take too long.
A good example of a key-stretching algorithm is RFC2898 or PBKDF2 - it uses a long salt and executes an SHA algorithm thousands of times to create a hash that's slow to reproduce.
.Net has a native implementation of this: Rfc2898DeriveBytes
They use it for System.Web.Crypto.HashPassword, but you can easily review their source to use that elsewhere.
On my machine now (a fairly rubbish old laptop) a single .Net Rfc2898DeriveBytes hash with 1000 iterations (the default) takes around 50ms, while I can brute force around 250,000 SHA512 hashes in a second.
So in .Net right now the most secure option is to use Rfc2898DeriveBytes.
However RFC2898/PBKDF2 does have a weakness - while it is slow parallel computing is getting cheaper and cheaper and it doesn't take much memory to build each hash. Right now it's pretty un-brute-forceable, but in 5 or 10 years?
So the next generation are algorithms like bcrypt/scrypt that are designed to use a lot of memory for each hash, making parallel executions expensive. While there are .Net implementations there isn't a native one (yet) and I'd be wary of using one until there is - using these will affect loads of things like concurrent log-ons (if used for passwords) and so introduce a lot of risk for early adopters.

A: User asked what is most secure Hashing algorithm in .NET, PBKDF2 is not a hashing algorithm, it is a method of deriving encryption keys and yes the underlying pseudo random function MAY be a hashing algorithm however in Rfc2898DeriveBytes it is actually HMACSHA1 over x passes with each byte of each hash value from each pass XORed with the next (know as key stretching).
So to answer the question currently HMACSHA512 is the most secure hashing algorithm in .NET currently.
If you wish to "hash" passwords, (And I say hash because it is not a direct hash function output) here is an API that takes PBKDF2 and uses HMACSHA512 to derive bytes rather than the Rfc2898DeriveBytes MS implemented using HMACSHA1: https://sourceforge.net/projects/pwdtknet


text:
Q: Shell Script Test Data Output? I'm trying to find a way to generate a random quantity of numbers with a specific amount of numbers after too, for example 1000 which is 4 digits I know how to do this using:
   for i in {1..50}; do echo $((RANDOM%50+50)); done

which gives me an integer data type of 2 digits in length whereas what i'm looking for is something that can give me 200 in length but I don't want to be typing out 200 0's after the number
I want for example a question where I get asked 'How many digits would you like to randomly generate?' then I would input 200 and I would get 50 rows in this case of 200 digit numbers.
Cheers,
Luke.

A: This should work:
$ numbers=50
$ digits=200
$ for ((i=0; i<${numbers}; i++)) ; do for ((j=0; j<${digits}; j++)) ; do echo -n $((RANDOM%10)); done ; echo ; done

UPDATE
Extending to random string generation:
$ numstrings=10
$ numchars=16
$ for((j=0; j<${numstrings}; j++)) ; do cat /dev/urandom | tr -dc 'A-Za-z' | fold -w ${numchars} | head -n 1 ; done
xCzgmBrAAuJBwzHw
eaBMxlpIbkAObhNa
GSYeEYPtlLbdLTFm
NVAacXEaVIRzewJU
YQzrXNXEpvNEaDjW
AoBjxTvnGYjeDAVO
hsJYoCTbqlKTfxKm
qbadlRTlztQxwCCb
XuvawFnxNfQrIaWX
QQyWqxZqUBQuCKQt


text:
Q: Does Sharepoint online have manage content databases similar like Sharepoint 2013 or 2016 I am new to SharePoint.
I would like to migrate WSS_Content databases from SharePoint 2013 to SharePoint online. How can I do it?
Is there any way to migrate those databases to SharePoint online. Or can I point SharePoint online databases to on-premise.
My final outcome is to bring the sharepoint online data and display it in the on-premise SSRS reports.
Thank you in advance

A: SharePoint uses online cloud. Based on your description, I understand that you want to migrate contents from SharePoint 2013 to SharePoint Online. You could use SPMT to migrate contents.
Reference: https://docs.microsoft.com/en-us/sharepointmigration/introducing-the-sharepoint-migration-tool
===================================
If the answer is helpful, please click "√" on the left panel of the answer and kindly upvote it.

A: SharePoint Online is quite different under the hood from SharePoint on-premises, it utilises Azure SQL databases for example.
To migrate your content from SharePoint 2013 to SharePoint Online, you would normally use migration software such as the SharePoint Migration Tool (SPMT) or other third party migration tools such as ShareGate. Alternatively, you can migrate content yourself by writing your own migration functionality, using either the Microsoft Graph API or SharePoint API.


text:
Q: What would be faster - plugin, html or shortcode? I'm curious if anyone has experience with refining their WordPress site to make it as fast for page loading as possible and which approaches work better than others.
For example, lets take adding social media buttons to a footer. What would be fastest? What would be the biggest drag?

*

*Plugin - there are some plugins, including for Genesis, that allow the user to enter a social media URL and then the icon and link are generate in a widget. I'm wondering if this would be a big load in case the CSS and files for all icons sets are loaded instead of just those being used, plus any additional plugin code being run.

*HTML in a widget - With something this simple I thought that the code could be created and added to a text widget, with the images being stored in the theme folders. This can be a little risky because I've seen HTML code in a widget get blown out and clients can accidently edit the wrong piece.

*HTML in the theme - I try to avoid hardcoding elements that the client might want to update, but this seems very efficient, unless it's in a widgetized area by default, in which case would you un-widgetize it?

*Shortcode - with hardcoded elements that would need to be used in a couple of different places, I thought creating a shotcode could be a good option. But does anyone know if shortcodes tend to drag on a site? Do all of the elements within the shortcode file get loaded even if that shortcode is not called on that page? I'm trying to do away with unneeded CSS or scripts whenever necessary, but I don't know if shortcodes will only call the piece being called. Anyone know?
Thanks, any information or advice is greatly appreciated.

A: Personally I use a theme options page which echos out HTML if the admin fills out the information. It isn't the fastest but its great for management and simplicity.

A: Unfortunately, there's not a black-and-white answer here, because there's a variety of factors that come into play.
For example, server-side rendering of content is in many cases actually faster than rendering on the front-end, but that's largely dependent on the speed of your server. If you're on cheap, sharing hosting (like many of us are), server-side can be slower.
There are 7 things I recommend everyone do to improve site performance:

*

*Concatenate. Combining like files together.

*Minify. Removing the spacing, line breaks and comments from files.

*Smush. Removing unneeded data from image files.

*Icon Fonts. Icon fonts are a lighter, faster alternative to image-based icons.

*Compress. Reduce file size by up to 70 percent.

*Cache. Telling browsers to keep static assets stored locally so that they doesn't have to be re-downloaded every time they visit your site.

*Page Structure. Adjusting the location of CSS and JavaScript files for faster rendering.

If you'd like to learn more about any of these, I've written a pretty detailed article on faster WordPress sites. I've personally used these tips to create multiple sites that load in less than 2 seconds on cheap, shared hosting.
http://gomakethings.com/high-performance-websites/

A: 1- Html & PHP : for social media you put them in other file like social-Blox.php then call it by
    <?php include(locate_template( 'templates/social-Blox.php' ));?>

now you have the social in separated file you can use it in many places and it still very light no plugin load or any thing
after this inside the social-Blox.php
you dont add only html NO .
the parts that will be changed later you can use ACF or theme options ...
to make them dynamic for example the links for facebook and twitter ... etc .
<a href="<?php the_field("facebook",105); ?>" class="icoFacebook a_t" title="Facebook">

the fields that need change for example social media I add them to custom page like " general page " so the client change them from there this I use that values every where like in this and that files ...
here you are reusing blocks of files ... and reusing data ... with one control panel .
2- widget & short code : I don't like this it need more time to develop its not easy to reuse and to let client use it its a little  hard
3- Plugin plugins always big problem for performance the less you use of them the better ...

*

*there is big famous plugins you can not replace or recreate like AFC , mailPoet ...

*there is small plugins but have some idea you need ok take the plugin its mostly 1 files take the PHP you need and the css & JS you need and add it to BOlX as I explain before ( in this case you will take max 50% of the plugin code ) and now the code is your not close box with process you dont need of problems you dont know ...


text:
Q: How to repaint automatically after event like button click? After I click a button I want some of the components of the JPanel to be removed and some new ones to be created.
I'm able to remove and add the new ones, but the JPanel doesn't repaint itself. Only after I do something manually, like change the frame size, the frame "refreshes" and I get what I want.
Here's the relevant part of the code, in this example it initiates the components by the given date:
private ClassName() {
    date = Date.getToday();
    init(date.toString());
}

private void lastDayActionPerformed(ActionEvent evt) {
    this.removeAll();
    date = date.getYesterday();
    init(date.toString());
}

A: If you want the component to re-layout and repaint after the button has been pushed and after it modifies the state of your GUI, then directly call within your ActionListener's code:
private void lastDayActionPerformed(ActionEvent evt) {
    this.removeAll();
    date = date.getYesterday();
    init(date.toString());
    revalidate();  // re-lays out child components
    repaint();    // repaints the component
}

But, it really sounds like you really want to use a CardLayout to swap views for you since this is exactly what this class was created for.


text:
Q: Is there a programmatic method to view bluetooth devices that are blocked? A device can be blocked like so:
bluetoothctl block FC:69:47:7C:9D:A3
Is there a programmatic method to list devices which have already been blocked?

A: Yes, check the info file:
grep Blocked /var/lib/bluetooth/*/FC:69:47:7C:9D:A3/info

It will return:
Blocked=true

A: The documented way to interface with the BlueZ Bluetooth stack is with the D-Bus API. The D-Bus API allows most languages to interface with it if the language has D-Bus bindings.
Here is an example using Python and the pydbus library:
import pydbus

dev_iface = 'org.bluez.Device1'
bus = pydbus.SystemBus()
mngr = bus.get('org.bluez', '/')

mngd_objs = mngr.GetManagedObjects()

for path, info in mngd_objs.items():
    blocked = info.get(dev_iface, {}).get('Blocked')
    if blocked is not None:
        address = info.get(dev_iface, {}).get('Address')
        print(f'[{address}] is {"Blocked" if blocked else "Not Blocked"}')

The BlueZ device API is documented at:
https://git.kernel.org/pub/scm/bluetooth/bluez.git/tree/doc/device-api.txt


text:
Q: Is there any tool for Java's Spring MVC like ASP.NET MVC's Glimpse? Comming from .NET world, I would like to know if there is something like http://getglimpse.com/ to use in a Java Spring MVC project.
Does anyone know?

A: Spring Insight allows you to look at the performance and internals of Spring web apps: http://www.springsource.org/insight

A: You can use JavaMelody. This is good profiling framework for Java EE applications.
You can annotate Spring beans and collect statistics about execution time, perfomance and erros.
Also JM provides posiblities for monitoring HTTP requests/respnses and DB loading.


text:
Q: Setting a button image depending on another variable? Swift so I'm very new to swift. I currently have 16 buttons all set to individual outlets box1,box2,box3 etc.
Each box I have set a tag and what I am trying to do is set the image of a particular box based off another integer variable to determine which box I'm changing.
So say I do a calculation and index = 4.
Is there a way I can then set box(index).setImage?
I understand this probably isn't the best way to do it or even possible, maybe I can set each button to an array of objects instead? Any tips would be great.

A: If you want to set the image of button through some tag then you don't need any outlets for the buttons.
You can change your button image by finding the button through viewWithTag() property.
Here is the code
var button = self.view.viewWithTag(Your_Calculated_Index) as! UIButton
button.setImage(Your_Image, for: .normal)

A: You can try this. You need to create an array for the button.
@IBOutlet var allbtns: [UIButton]!

for buttons in allbtns{
    if buttons.tag == 4{
        print("Button 4 ");
        buttons.setImage(UIImage(named: "imagname"), for: UIControlState.normal)
    }else{
        print("Other buttons except 4 ");
    }
}


text:
Q: Passing arguments to shortcuts through start+run? I've been making shortcuts to thing I use often so I don't have a cluttered taskbar. I have shortcuts for games, thunderbird, etc, and just type winkey+r tb for thunderbird or winkey+r wa x^2+2x+3 dx to search wolfram alpha.
I've tried passing arguments through shortcuts, for example this is one I got to work:
Shortcut name: wa
Shortcut target: C:..\chrome.exe "http://www.wolframalpha.com/input/?i=
I wish I could do %1, because it does put a space in there and I can't get this one working:
Shortcut name: kill
Shortcut target: taskkill /IM "
The shortcuts for some reason don't want to keep the arguments
So after shortcuts started failing me, I wanted to try bat files, but I needed to hide them. So I tried the vb script that a lot of people use. The only problem is that I have to use a batch file to start the other batch file invisibly, thus making it useless. If I try to start it with a shortcut, the arguments don't come up!
Does anyone have a solution to this?

A: Use start in a batch file to run another program non-blocking (so your batch file will terminate and the windows will close afterwards).
You should be able to use %1, but this will only pass the first argument. Use quotes if you need to pass arguments containing spaces, but you could be needed to remove them when calling other programs. For use with URLs you probably will have to encode the URL before passing it (eg. in your wolfram alpha shortcut).


text:
Q: Frequently getting attacks on admin-ajax.php, wp-cron.php, xmlrpc.php and wp-login.php I am running more than 500 WordPress website in my shared server, Frequently I am getting attacks on admin-ajax.php, wp-cron.php, xmlrpc.php and wp-login.php files. Due to that our server load is getting more than 100.
Is there is any way to avoid the spamming request to this respective file.
hits are coming from 1000s of IP addresses from various countries and different ranges, So blocking them is not easy.
Currently I am blocking those file in .htaccess, Apart of from this I need any alternative solution.


text:
Q: Bing translator exception while integrating with java application I am trying to integrate bing translator in my java application. I have registered to Microsoft azure cognitive service and Microsoft market place.
while executing below code
import com.memetix.mst.language.Language;
import com.memetix.mst.translate.Translate;

public class Main {
    public static void main(String[] args) {
        try{
            Translate.setClientId(/* my Client Id */);
            Translate.setClientSecret(/* my Client Secret */);

            String translatedText = Translate.execute("Bonjour le monde", Language.FRENCH, Language.ENGLISH);

            System.out.println(translatedText);
        }
        catch(Exception e) {
            System.err.println("Exception: " + e.getMessage());
        }
    }
}

I am getting below exception:
Page NoException in thread "main" java.lang.Exception: [microsoft-translator-api] Error retrieving translation : Server returned HTTP response code: 400 for URL: https://datamarket.accesscontrol.windows.net/v2/OAuth2-13
    at com.memetix.mst.MicrosoftTranslatorAPI.retrieveString(MicrosoftTranslatorAPI.java:202)
    at com.memetix.mst.translate.Translate.execute(Translate.java:61)
    at test.SimpleExcelTranalator.main(SimpleExcelTranalator.java:44)
Caused by: java.io.IOException: Server returned HTTP response code: 400 for URL: https://datamarket.accesscontrol.windows.net/v2/OAuth2-13
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection$10.run(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection$10.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.net.www.protocol.http.HttpURLConnection.getChainedException(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
    at com.memetix.mst.MicrosoftTranslatorAPI.getToken(MicrosoftTranslatorAPI.java:139)
    at com.memetix.mst.MicrosoftTranslatorAPI.retrieveResponse(MicrosoftTranslatorAPI.java:160)
    at com.memetix.mst.MicrosoftTranslatorAPI.retrieveString(MicrosoftTranslatorAPI.java:199)
    ... 2 more
Caused by: java.io.IOException: Server returned HTTP response code: 400 for URL: https://datamarket.accesscontrol.windows.net/v2/OAuth2-13
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at java.net.HttpURLConnection.getResponseCode(Unknown Source)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source)
    at com.memetix.mst.MicrosoftTranslatorAPI.getToken(MicrosoftTranslatorAPI.java:138)
    ... 4 more

A: The datamarket url is where you get your client id and secret from. Is that where you're sending your translation request to? Should be something like
http://api.microsofttranslator.com/v2/Http.svc/Translate?
Also datamarket is being deprecated. You have to switch to Azure Cognitive Services
http://docs.microsofttranslator.com/text-translate.html

A: According to your referenced package com.memetix.mst.language.* in your code, I searched and found its source code on GitHub, repository on Maven, and an old repository on GoogleCode. I reviewed its source code, and discovered it wrappered the MS Translator Text API from Azure old datamarket web site. The library is out of date with the old REST API, the old website shows "THE MICROSOFT TRANSLATOR API IS NOW AVAILABLE ON THE AZURE PORTAL" and "IMPORTANT: An Azure account is required. Read the steps to get started on the portal here." So first you need to have an Azure subscription to create a Translator Text API service on Azure portal, then write code to call the new REST API. You can refer to my answer for the two other SO threads as below to know how to use the new REST API and call it via my sample code.

*

*My answer for MS Translator returns empty response when used with Azure token shows the new REST API usage.

*My answer for Microsoft Translator API Java, How to get client new ID with Azure which includes my sample code, it shows how to call the new REST API in Java.

Hope it helps.


text:
Q: pandas append each element of list as new row I have a dataframe with columns first. I have many lists, and I want each element of the list to be added as a new row.
for example if I have a DataFrame with a column first, and I have multiple lists, such that each element of each list, I want as a new row.
So If the lists are [1,2,3] and [4,5,6], my dataframe will have 6 rows.
the desired output is:
0    1
1    2
2    3
3    4
4    5
5    6
Name: first, dtype: int64

I tried:
table = pd.DataFrame(columns=['first', 'second'])
my_list = [1,2,3]
my_list2 = [4,5,6]
table['first'] = table['first'].append(pd.Series(my_list))
table['first'] = table['first'].append(pd.Series(my_list2))

But I get ValueError: cannot reindex from a duplicate axis.


text:
Q: Use Aggregate function in order by of LINQ I want to use SUM(Quantity) in order by clause here -
var top3Order = (from order in ekartEntities.Orders
                         join inventory in ekartEntities.Inventories on order.InventoryId equals inventory.InventoryId
                         group order by new
                         {
                             inventory.InventoryId,
                             inventory.Guid,
                             order.Quantity
                         } into g
                         orderby g.Key.Quantity descending //sum(Quantity)
                         select g.Key.Guid).Take(3).ToList();

How can I achieve that?

A: Nothing prevents you from using .Sum() here. Here's a working example :
var top3Order = (from order in ekartEntities.Orders
                 join inventory in ekartEntities.Inventories on order.InventoryId equals inventory.InventoryId
                 group order by new
                 {
                     inventory.InventoryId,
                     inventory.Guid,
                     order.Quantity
                 } into g
                 orderby g.Sum(o => o.Quantity) descending
                 select g.Key.Guid).Take(3).ToList();


text:
Q: Sinon.JS stub a function that resolves a promise I want to use Sinon to stub a function that uses callbacks which resolve a promise:
const callback = (err, data) => {
      if (err) {
        reject(err);
      } else {
        resolve(data);
      }
    });

stub.me({}, callback);

I tried:
var stub = {
  me: sinon.stub().yieldsTo("resolve", "my_data"),
};

but I keep getting mocha timeouts.
The code doesn't define a const for callback. It's all in the stub.me function call. I just wrote it like that so it would be clear to read.
It's also wrapped in a new Promise((resolve,reject) => {} ); block.

A: This was due to a scope error. Per the docks for aws-sdk-mock, AWS service needs to be initialized in the function.
Does not work:
var AWS      = require('aws-sdk');
var sns      = AWS.SNS();
var dynamoDb = AWS.DynamoDB();

exports.handler = function(event, context) {
  // do something with the services e.g. sns.publish
}

Works:
var AWS = require('aws-sdk');

exports.handler = function(event, context) {
  var sns      = AWS.SNS();
  var dynamoDb = AWS.DynamoDB();
  // do something with the services e.g. sns.publish
}


text:
Q: FInding saved fiddles in new Sencha Fiddle I cannot find my saved fiddles in the new Sencha Fiddle :

I used to be able to click on my name in the top right corner and get a list of saved fiddles.
I can no longer find my saved fiddles.

A: Use the search function and enter your own username in the Author field.


text:
Q: Como gerar código indentado? Como imprimir código indentado quando eu dou um echo pelo PHP?
digamos que a estrutura está assim:
echo
'
'.
    '
'.
        '
'.
            ''.
            '	'.
        '
'.
    '
'.
'
';

quando eu vou for ver no código fonte da página, o PHP acaba printando o resultado em uma linha.

há como printa-lo indentado no código fonte?

A: Uma forma muito boa de se imprimir o HTML é utilizando strings no formato Heredoc, que possui a vantagem de não precisar escapar as aspas, exemplo:
echo <<<EOT

                oi

EOT;

Aviso:
  É muito importante verificar que a linha do identificador de fechamento não contenha nenhum outro caracter, exceto, possivelmente um ponto e vírgula (;). O que significa que o identificador não pode ser indentado, e que não pode haver nenhum espaço ou tabulações antes ou depois do ponto e vírgula. [Leia mais]

Você também pode fechar as tags do PHP e adicionar seu HTML sem problemas, até mesmo em loops e condições:
<?php
    $var = "Hello World";
?>

    <?php
        if (!empty($var) ){
            for ($i=0; $i < 3; $i++) {
    ?>

                <?php echo $var; ?>

    <?php
            } // É essencial fechar as chaves do for
        }     // e do if
    ?>

<?php
    /* Continua o código */
?>

A: Se o seu objetivo é só visualizar o código fonte, você pode utilizar o developer tools que vem com os navegadores.
No Google Chrome, aperte F12 e será aberta na parte inferior o código indentado corretamente:

Agora se você precisa gerar um código já indentado, você precisa deixar isso claro para o PHP, pois os espaços no seu código não são traduzidos para o retorno do echo.
Existem várias formas de fazer isso, como pode ver nas diversas respostas.
Outra forma (nada elegante) de fazer isso é usar os caracteres especiais \t (tabulação) e \n (nova linha):
<?php

echo
    "
\n".
    "\t
\n".
    "\t\t
\n".
    "\t\t\t\n".
    "\t\t\t	\n".
    "\t\t
\n".
    "\t
\n".
    "
\n";

Veja aqui o resultado.
Pessoalmente, eu prefiro usar heredocs como apontado pela resposta do @KaduAmaral.

A: É bem simples:
echo
"
\n".
"
\n".
"
\n".
"            \n".
"            	\n".
"
\n".
"
\n".
"
\n";

Tem outras maneiras de fazer isto mas mantive o padrão que você usou. A única modificação é incluir os espaços dentro da string. O que está fora não é impresso. Note que para fazer pular linha foi necessário usar o \n. E para usar o \n teve que usar aspas duplas.
Ou se preferir (eu prefiro):
echo
'

';

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.

A: Para intentar textos dentro de uma string você pode usar a combinação de caracters de escape \t, o que irá adicionar uma tabulação para cada grupo de \t. É o mesmo efeito de digitar a tecla TAB do teclado.
Para adicionar quebras de linha utiliza-se a combinação de caracteres de escape \n ou \r\n em alguns casos.
Por exemplo, a string abaixo
"
\n\t
\n\t\tIsso é um parágrafo\n\t
\n\<\div>"

é equivalente ao código abaixo:

        Isso é um parágrafo

<\div>


text:
Q: Random down voting? Anyone else feel that there is random down voting?
A recent example: How to use transactions with the Entity Framework?
Almost 2 year old answer, accepted, 10 upvotes, then a down vote.

A: The thing that makes Stack Overflow (and, really, all web resources) so useful is the persistence of data. Thus, no matter how long it has been since a particular question was asked, if someone runs into a similar problem, they may find it.
According to the timeline, there was an upvote to another answer, a comment on that answer, and a downvote on your answer all in one recent day. The comment/upvote combo indicates that someone basically had that problem and found that answer helpful. In fact, Kim's answer has been receiving upvotes for a while, so that question is getting a fair amount of viewing activity in spite of its age.
The downvote is not necessarily related to that user - it could've been anyone who found your answer dissatisfactory. Point is, no matter the age, people browse and run into these things. And apparently someone did not find your answer useful. It can be considered "random" in the sense that you didn't see it coming, but it's not all that unexpected in the system as a whole.

A: Perhaps someone who agrees with Miguel Vitorino's comment:

Be careful with TransactionScope. It introduces dependencies on MS DTC which is a pain to configure and carries a hefty performance price. Once you have more than one transaction inside the TransactionScope it will initiate a distributed transaction. It will no longer be just a plain DbTransaction running on the used provider. Also, if you are using a database provider other than Sql Server it is likely it won't support distributed transactions...

Otherwise I wouldn't sweat a single (or even 2) downvote, it happens.


text:
Q: After setting layout constant for label it stops working I have a table view with automaticDimension for height and 2 cells.
One cell has a read more button, which updates the layout constraint constant for a label (as IBOutlet). It works fine and the cell height updates depending on the label height, but when I try to update the layout constraint first time on cellForRowAt method delegate it works, but after that it stops working from the read more button (and the layout constraint outlet doesn't become nil).
    if cellType == .movie {
        let movieCell = cell as! MovieDescriptionCell
        movieCell.updateCellWith(movie: selectedMovie!)
        movieCell.infoLabelHeight.constant = 200. ***(here is the problem, if I don't have this the read more button works)***
        movieCell.readMorePressedBlock = { [weak self] (tag) in
            guard let strongSelf = self else { return }
            DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(70), execute: {
                strongSelf.tableView.reloadData()
            })
        }
    }

@IBOutlet var infoLabelHeight: NSLayoutConstraint!

  @IBAction func onReadMoreButton(button: UIButton) {
    self.readMoreState = !self.readMoreState
    setReadMoreImageFor(state: readMoreState)

    let infoText = self.infoLabel.text
    let expectedHeight = infoText?.height(withConstrainedWidth: infoLabelWidth.constant, font: self.infoTextFont) ?? self.infoDefaultHeight

    self.infoLabelHeight.constant = self.readMoreState ? expectedHeight : self.infoDefaultHeight

    readMorePressedBlock?(button.tag)
}

How can I make this work? If I delete the line "movieCell.infoLabelHeight.constant = 200" the read more button works, but I need to set the constant at the beginning too.
Thanks.

A: I found a solution, if I set the layout constraint in awakeFromNib method the read more button works (the possibility to change the constraint again)
override func awakeFromNib() {
    super.awakeFromNib()

    self.infoLabelHeight.constant = 200
}


text:
Q: Update UI html from async list I'm trying to understand what I made.
I have a async list of items (different number each time). I'm trying to set each of them as different div using *ngFor
details.html

                {{sentence.name}}

DetailsComponent.ts
@Component({
    selector: 'app-details',
    templateUrl: 'details.html',
    styleUrls: ['details.scss']
})
export class DetailsComponent implements OnInit {
  sentences: string[];

  constructor(private data: DetailsService, private ravenDataService: RavenDataService) { }

  ngOnInit(): void {
    this.data.sentences.subscribe(sentences => {
      console.log(sentences);
      this.sentences = sentences;
    });
  }
}

I can see the log after few seconds that printed with my sentences but it's not update my HTML page.
I also tried to use the async pipe with no success

A: I think it's just a typo, please try with async pipe and don't use subscribe.
@Component({
    selector: 'app-details',
    templateUrl: 'details.html',
    styleUrls: ['details.scss']
})
export class DetailsComponent implements OnInit {
  sentences$;

  constructor(private data: DetailsService, private ravenDataService: RavenDataService) { }

  ngOnInit(): void {
    this.sentences$ = this.data.sentences
  }
}

and

Always mark your streams with $ sign at the end, it's a common convention


text:
Q: htaccess editing to avoid duplicating in my website  i have this .htaccess code

<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} ^einfogarden.com$
RewriteRule (.*) http://www.einfogarden.com/$1 [R=301,L]

RewriteCond %{THE_REQUEST} \s/+single\.php\?title=([^\s&]+) [NC]
RewriteRule ^ %1/? [R=302,L,NE]

# convert %20 to -
RewriteRule "^(\S*) +(\S* .*)$" $1-$2 [N,NE]
RewriteRule "^(\S*) (\S*)$" $1-$2 [L,R=302,NE]

## Adding a trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{THE_REQUEST} \s/+(.*?)[^/][?\s]
RewriteRule [^/]$ %{REQUEST_URI}/ [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+?)/?$ single.php?title=$1 [NE,L,QSA]
</IfModule>

where i convert the 20% with -
but the problem is the backslash "/" in the end is repeated according to the "-" number, how can i get just one backslash

A: Have your rules like this:
Options +FollowSymLinks
RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} ^einfogarden.com$
RewriteRule (.*) http://www.einfogarden.com/$1 [R=301,L]

RewriteCond %{THE_REQUEST} \s/+single\.php\?title=([^\s&]+) [NC]
RewriteRule ^ %1/? [R=302,L,NE]

## Adding a trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{THE_REQUEST} \s/+(.*?)[^/][?\s]
RewriteRule [^/]$ %{REQUEST_URI}/ [L,R=302]

# convert %20 to -
RewriteRule "^(\S*) +(\S* .*)$" $1-$2 [L,NE]
RewriteRule "^(\S*) (\S*)$" $1-$2 [L,R=302,NE]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+?)/?$ single.php?title=$1 [NE,L,QSA]

i.e rearrange and remove N flag.


text:
Q: Updating UITableView when returning from edit form, refresh entire table datasource or the row that was edited? I have a UITableView filled with data from a JSON datasource in my viewDidLoad().  I'm storing this JSON data in a dictionary at the top of my view controller code:
class InventoryListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet var inventoryListTableView: UITableView!
    let textCellIdentifier = "textCell";
    var warehouseItems: [Inventory] = [];  //array for my items

    override func viewDidLoad() {
        super.viewDidLoad()

        inventoryListTableView.dataSource = self;
        inventoryListTableView.delegate = self;

        loadTableViewWithJSON();  //this loads my data into the warehouseItems dictionary created above

    }
...
}

Here's my loadTableViewWithJSON()
func loadTableViewWithJSON() {
        let urlString = "http://url.php";
        let session = NSURLSession.sharedSession();
        let url = NSURL(string: urlString)!;

        session.dataTaskWithURL(url) { (data: NSData?, response:NSURLResponse?, error: NSError?) -> Void in
            if let responseData = data {
                do {
                    let json = try NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.AllowFragments) as! Dictionary<String, AnyObject>;

                    //                        print(json);

                    if let inventoryDictionary = json["inventory"] as? [Dictionary<String, AnyObject>] {
                        //                        print(inventoryDictionary);

                        for anItem in inventoryDictionary {

                            //                            print(anItem["quantityOnHand"] as? Int);  //works

                            if let id = anItem["id"] as? Int, let item = anItem["item"] as? String, let description = anItem["description"] as? String, let quantityOnHand = anItem["quantityOnHand"] as? Int, let supplierId = anItem["supplier_id"] as? Int, let supplierName = anItem["supplierName"] as? String {

                                let item = Inventory(id: id, item: item, description: description, quantityOnHand: quantityOnHand, supplierId: supplierId, supplierName: supplierName);
                                //                                print(item);

                                self.warehouseItems.append(item);
                            }
                        }
                        //                        print(self.warehouseItems[0].description); //works
                        dispatch_async(dispatch_get_main_queue(), {
                            self.inventoryListTableView.reloadData();
                        })
                    }
                } catch {
                    print("Could not serialize");
                }
            }

            }.resume()
        }

Tapping one of the items segues into another view for editing the item that was tapped.  When the fields are changed and the item edited there is a big green check that calls a rest API and updates the data in my database (that my UITableView gets from).  Now when I click the Back button in my NavigationController it returns to the previous screen with my UITableView, but the values aren't updated.  I've tried running tableView.reloadData() in my viewWillAppear() but nothing works.  I've also tried calling my function that grabs the data from JSON but of course that just adds the updated data to the end of my tableView and I have an old copy of the data, and a fresh underneath.
My question is, should I just clear my UITableView and run my function that grabs the data once more?  Or should I just update the single row with the new data?  I thought updating the single row would be better for less overhead on my restful API.  Or would it be better to detect when I'm coming back from my editing view controller and reload all the data?
I've tried this but it doesn't work:
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated);
        // loadTableViewWithJSON(); // this duplicates the data in the tableview
        inventoryListTableView.reloadData();
    }

And my cellForRowAtIndexPath :
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath) as UITableViewCell;
        let row = indexPath.row;
        cell.textLabel!.text = "\(warehouseItems[row].item) -->  \(warehouseItems[row].quantityOnHand) on hand"

        cell.detailTextLabel!.text = warehouseItems[row].description;

        return cell;
    }

A: When you call loadTableViewWithJSON(), you're calling self.warehouseItems.append(item) which simply appends to the existing array.  This is why you're seeing duplicate data in your tableView.
Add warehouseItems = [] to the top of you session.dataTaskWithURL(url) response block.  This will clear out the array so you can rebuild it from scratch with the updated data.
func loadTableViewWithJSON() {
    let urlString = "http://url.php";
    let session = NSURLSession.sharedSession();
    let url = NSURL(string: urlString)!;

    session.dataTaskWithURL(url) { (data: NSData?, response:NSURLResponse?, error: NSError?) -> Void in
        if let responseData = data {
            warehouseItems = []

Once you make those changes, the following should work for you.
override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    loadTableViewWithJSON()
    inventoryListTableView.reloadData()
}

Final note, semicolons are not needed in Swift, we're free!


text:
Q: How to delete a local notification in iPhone I am making an application that sets a local notification.
Thankfully I was able to set the local notification but I don't know how to delete the notification which is set by my application.
The XCode does provide functionality of delete with removeAllNotifications but you cannot remove specific notifications set by the application.
Thanks a lot.

A: You asked this question twice, so I'm answering on both questions in the hopes of it reaching you:
Cancel all local notifications with this code:
[[UIApplication sharedApplication] cancelAllLocalNotifications];

Cancel one local notification with this line of code:
[[UIApplication sharedApplication] cancelLocalNotification:theNotification];

where theNotification is a UILocalNotification object, so in order to cancel a specific notification you need to hold on to it's UILocalNotification.

You can find more stuff in apple's documentation.

A: helloou, look, in swift you can create a local notification :
var notif = UILocalNotification()
        notif.timeZone = NSTimeZone.defaultTimeZone()

        let morningOfChristmasComponents = NSDateComponents()
        morningOfChristmasComponents.year = 2016
        morningOfChristmasComponents.month = 03
        morningOfChristmasComponents.day = 30
        morningOfChristmasComponents.hour = 15
        morningOfChristmasComponents.minute = 59
        morningOfChristmasComponents.second = 0

        let morningOfChristmas = NSCalendar.currentCalendar().dateFromComponents(morningOfChristmasComponents)!

        let formatter = NSDateFormatter()
        formatter.dateStyle = NSDateFormatterStyle.LongStyle
        formatter.timeStyle = .MediumStyle

        let dateString = formatter.stringFromDate(morningOfChristmas)

        notif.fireDate = morningOfChristmas
        notif.alertBody = "alarma wolf"
        notif.userInfo = ["identificador": "wolf"]
        UIApplication.sharedApplication().scheduleLocalNotification(notif)
        print("alarma fijada para \(dateString)")

loo the userInfo is a indeitifer to you local notification, now, if you want delete a specific local notificaction please try:
var uidtodelete = "wolf"
        var app:UIApplication = UIApplication.sharedApplication()
        for oneEvent in app.scheduledLocalNotifications! {
            var notification = oneEvent as UILocalNotification
            let userInfoCurrent = notification.userInfo! as! [String:AnyObject]
            let uid = userInfoCurrent["identificador"]! as! String
            if uid == uidtodelete {
                //Cancelling local notification
                app.cancelLocalNotification(notification)
                break;
            }
        }

look the method, above, userInfoCurrent is the identificator of your's local notification, and uitodelete is a string that contain the specific key of the locla notification that you want delete...
aaaa... if you want to delete all local notification you can use
UIApplication.sharedApplication().cancelAllLocalNotifications()
oki
I hope you serve yourself or someone else this information..
good bye, andforgive my bad English

A: [[UIApplication sharedApplication] cancelLocalNotification:notification]

A: You can cancel notification by following function:[[UIApplication sharedApplication]cancelNotification:object Of your UILocalNotification]

A: If you are using User Notifications framework, available since iOS 10.0, given the identifier you provided is foo:
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: "foo")
UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: "foo")

Or in Objective-C :
[[UNUserNotificationCenter currentNotificationCenter] removePendingNotificationRequestsWithIdentifiers:@[@"foo"]];
[[UNUserNotificationCenter currentNotificationCenter] removeDeliveredNotificationsWithIdentifiers:@[@"foo"]];