text:
Q: Horizontally aligning divs using margins and floats I've got 3 divs - Each of these in a parent div with a width of 100%. CSS:
 .parentDiv {
  height: 454px;
  width: 100% auto;
}
.Div1, .Div2, .Div3{
  display: block;
  position: relative;
  text-align: center;
  height: 434px;
  margin-top: 10px;
  margin-bottom: 10px;
}
.Div1 {
  margin-left: 10px;
  float: left;
  width: 351px;
}
.Div2 {
  width: 351px;
  padding: 0px;
  margin: auto;
  display: block;
}
.Div3 {
  margin-right: 10px;
  float: right;
  width: 351px;
}

The Divs are ordered in the same way they are in the CSS, in the HTML.
Yet, the result of this is that the left element (Div1) is in the correct place, the supposedly centred element is centred (Div2) although it has margins either side of it that fill the entire parent Div. Therefore, I think this causes Div3 to overflow the parent Div and "collapse" vertically.
What I would really like to know is how to align the divs so that there is one on the left, one centred and one on the right. The previous questions regarding similar problems don't seem to help me in this case :/ If there was a way to shorten Div2's margins so that they could allow all of the Divs to remain aligned correctly in the parent div - I would really love to know how (Preferably not using absolute pixel measurements)
This probably made no sense - But I really do appreciate all suggestions/answers :)
Cheers
Additional Explanation:
This is what it is at the moment:
Div1Div2Div3
What I would like:
Div1         Div2          Div3
The length of this is equal to the parentDiv
HTML (For this section)

A: SOLUTION # 1
You may see the JSFIDDLE DEMO.
HTML CODE

        Div 1 - Some text

        Div 2 - Some text

        Dive 3 - Some text

CSS CODE
 .parentDiv {
  height: 454px;
  width: 100% auto;
}
.parentDiv div{
    float:left;
}
.Div1, .Div2, .Div3{
  display: block;
  position: relative;
  text-align: center;
  height: 434px;
  margin-top: 10px;
  margin-bottom: 10px;
  border: 1px solid #c4c4c4;
}
.Div1 {
  margin-left: 10px;
  width: 351px;
}
.Div2 {
  width: 351px;
  padding: 0px;
  display: block;
}
.Div3 {
  margin-right: 10px;
  width: 351px;
}

SOLUTION # 2
Please go through the FIDDLE DEMO.
Here is the complete source code:

*

*I have added margin-left to all 3 divs.

Code:

<meta content="text/html; charset=UTF-8" http-equiv="content-type">

        Div 1 - Some text

        Div 2 - Some text

        Dive 3 - Some text

As you will observe:

*

*I have removed margin from Div2.

*I have added new css for .parentDiv div - so you may please remove the float from other individual divs.

*You may like to remove the BORDER of the divs.

My Suggestion

*I suggest to use Responsive Breakpoints to make your page Responsive.

A: Try to do this on div2:
 .Div2 {
      width: 351px;
      padding: 0px;
      margin: auto;
      display: block;
      margin: 0 auto;
      float: left;
    }

A: If you want a better solution than floating elements, change it for display:inline-block elements.
.parentDiv > div { font-size: 1em; display: inline-block; vertical-align: top; }
.parentDiv { font-size : 0; }

This works responsive and is better than float. Float is only for floated elements, not for design layout. It's a false and most recurrent technique by some front-end developers. Thanks to floats, you can see thousands of tons of clearfix along the pages. It is cruft, crap.

A: Not to worry, managed to finally solve it using some jQuery:
$(document).ready(function(){
    var width = $(".parentDiv").css("width")
    var width = width.replace("px","");
    var width = parseInt(width,10);
    var val1 = width-1073;
    var val2 = val1/2;
    $(".Div2").css("margin-left",val2);
    $(".Div2").css("margin-right",val2);

    $(window).resize(function(){
        var width = $(".parentDiv").css("width");
        var width = width.replace("px","");
        var width = parseInt(width,10);
        if(1073>width) {
            $(".Div3").css("display","hidden")
        }
        else {
            var val1 = width-1073;
            var val2 = val1/2;
            $(".Div2").css("margin-left",val2);
            $(".Div2").css("margin-right",val2);
        }
    });

I know it's not the most efficient nor pretty code ever written (I'm really new to jQuery and Javascript) - But it does work :) I'd like to apologise to anybody who was kind enough to try to decipher my appalling explanations :/
Note that I also set the Child Div's positioning type to absolute, then Div1 as left: 0; and Div3 as right: 0;


text:
Q: C#:docx generated from html by open xml power tools throw pre release 2007 I'm writing code that get the content of Docx file as HTML by using open XML power tools and now I want to convert it back to another docx file. the step that gets contents as HTML works fine but when I generate the docx file from that HTML the file cannot be opened and throws this error

this file was created in a pre-release version of word 2007 and cannot
  be opened in this version

the HTML generated from test docx is

    <meta
      charset="UTF-8" />
    <title>My Page Title</title>
    <meta
      name="Generator"
      content="PowerTools for Open XML" />

با سلام خدمت <<PERSONS.lname>> <<PERSONS.fname>>

مدیر محترم <<OFFICE.name>>

and my code to save the above html as docx is
using (WordprocessingDocument wordDoc =
        WordprocessingDocument.Create(dest_doc_path, WordprocessingDocumentType.Document))
            {

                MainDocumentPart mainPart = wordDoc.AddMainDocumentPart();

                string htmlcontent = htmlTXT.Text;

                using (Stream stream = mainPart.GetStream())
                {
                    byte[] buf = (new UTF8Encoding()).GetBytes(htmlcontent);
                    stream.Write(buf, 0, buf.Length);
                }

                MessageBox.Show("DONE", "done", MessageBoxButton.OK);

            }

A: The answer is simple. You must not insert HTML content into the MainDocumentPart because it is expected to contain a valid Open XML w:document element, e.g., as the following simplified one:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
  <w:body>
    <w:p>
      <w:r>
        <w:t>Hello, world!</w:t>
      </w:r>
    </w:p>
  </w:body>
</w:document>

The error message probably is a little misleading. HTML is simply invalid in this case.
Depending on whether or not you changed the HTML after creating it (with the Open XML PowerTools) from the original Word document, you will have to either transform it back into valid Open XML markup (if you changed it) or simply use the Open XML markup from the original Word document.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Databricks does not recognize all Oracle transformations I am trying to make a conversion from Oracle to Databricks, nothing complex, the data is of the string type ('24 -MAR-11 ') and I am trying to change it to a date type to transform it back to another format ('24 -03-2011') , but I've been trying to find the sentence according to the documentation for a while and I can't find what I'm looking for.
Among the alternatives that I have tried are the following:
date_format('24-MAR-11' as 'DD-MON-YY')
to_date('24-MAR-11', 'dd-MON-yy')
cast('24-MAR-11', date)
cast('24-MAR-11', 'dd-MON-yy')

In Oracle that works, in Databricks it doesn't.
Please recommend me any method?
Thank you very much in advance, I will be attentive to your comments!
Regards!!

A: Use the functions to_date (which converts a string to a date with an optional date format string), and date_format, which formats a date in the given format string to achieve what you want.  The mistake in your code is, the input string for to_date should be in the format of your input string, not the format you want the string to be, ie
%py
from pyspark.sql.functions import *

df = spark.createDataFrame([("24 Mar 11",)], ["xdate"])

df.withColumn("xdate1", to_date("xdate", "dd MMM yy")).show()

df.withColumn("xdate2", date_format( to_date("xdate", "dd MMM yy"), "dd-MM-yyyy")).show()

NB in my first call to to_date I am using the format string dd MMM yy which is the format of your input string 24 Mar 11.  The second call with date_format then displays the string in the desired format.  My results:


text:
Q: Simple flow not updating record I have a very simple flow that is triggered by a process. Everything seems to work fine, except for the record update. I cannot figure out the problem, and have made many changes based on internet advise.
Flow logic:
once the flow is triggered, by updating StageName in an Opp, i loop thru all opps related to a the account ID passed in by the process (account Id related to the opp that was updated).
For each Opp, if the Stage is not equal to 'X. Closed / Lost', I set a Boolean to ''True (default value of bool is 'False').
Once the loop ends, i check the value of the Boolean.
If false, i update the 'account status' field of the account with ID matching the one that was passed in by the process.
There are no errors, and the log appears to be showing that the update happened. any Idea?
Here's the log:

16:06:24.56 (166680841)|FLOW_START_INTERVIEWS_BEGIN|1 16:06:24.56
  (166704078)|FLOW_START_INTERVIEW_BEGIN|742cb60b2b87f8dbf6a227c6b8161f7e9ee76-6189|Set
  Account Status to Dead/Lost 16:06:24.56
  (166742593)|FLOW_VALUE_ASSIGNMENT|742cb60b2b87f8dbf6a227c6b8161f7e9ee76-6189|vOppAccountId|001q000000mVfJvAAK
  16:06:24.56
  (166820403)|FLOW_ELEMENT_BEGIN|742cb60b2b87f8dbf6a227c6b8161f7e9ee76-6189|FlowRecordLookup|Find_all_Opps_related_to_acct
  16:06:24.56
  (166833996)|FLOW_ELEMENT_DEFERRED|FlowRecordLookup|Find_all_Opps_related_to_acct
  16:06:24.56
  (166841067)|FLOW_ELEMENT_END|742cb60b2b87f8dbf6a227c6b8161f7e9ee76-6189|FlowRecordLookup|Find_all_Opps_related_to_acct
  16:06:24.56
  (166850133)|FLOW_START_INTERVIEW_END|742cb60b2b87f8dbf6a227c6b8161f7e9ee76-6189|Set
  Account Status to Dead/Lost 16:06:24.56
  (166877994)|FLOW_BULK_ELEMENT_BEGIN|FlowRecordLookup|Find_all_Opps_related_to_acct
  16:06:24.56
  (247209638)|FLOW_VALUE_ASSIGNMENT|742cb60b2b87f8dbf6a227c6b8161f7e9ee76-6189|vRelatedOpps|[{Id=006q000000EkIz5AAF,
  StageName=X. Closed Lost}] 16:06:24.56
  (247238991)|FLOW_VALUE_ASSIGNMENT|742cb60b2b87f8dbf6a227c6b8161f7e9ee76-6189|Find_all_Opps_related_to_acct|true
  16:06:24.56
  (247264694)|FLOW_BULK_ELEMENT_DETAIL|FlowRecordLookup|Find_all_Opps_related_to_acct|1
  16:06:24.56
  (247324923)|FLOW_BULK_ELEMENT_END|FlowRecordLookup|Find_all_Opps_related_to_acct|1|81
  16:06:24.56
  (247356369)|FLOW_ELEMENT_BEGIN|742cb60b2b87f8dbf6a227c6b8161f7e9ee76-6189|FlowLoop|Loop_thru_Opps
  16:06:24.56
  (247477076)|FLOW_VALUE_ASSIGNMENT|742cb60b2b87f8dbf6a227c6b8161f7e9ee76-6189|Loop_thru_Opps.currentIteration|0
  16:06:24.56
  (247490955)|FLOW_VALUE_ASSIGNMENT|742cb60b2b87f8dbf6a227c6b8161f7e9ee76-6189|vCurrentOpp|{Id=006q000000EkIz5AAF,
  StageName=X. Closed Lost} 16:06:24.56
  (247628434)|FLOW_LOOP_DETAIL|742cb60b2b87f8dbf6a227c6b8161f7e9ee76-6189|0|006q000000EkIz5AAF
  16:06:24.56
  (247645934)|FLOW_ELEMENT_END|742cb60b2b87f8dbf6a227c6b8161f7e9ee76-6189|FlowLoop|Loop_thru_Opps
  16:06:24.56
  (247661147)|FLOW_ELEMENT_BEGIN|742cb60b2b87f8dbf6a227c6b8161f7e9ee76-6189|FlowDecision|is_this_an_open_or_won_opp
  16:06:24.56
  (247886582)|FLOW_RULE_DETAIL|742cb60b2b87f8dbf6a227c6b8161f7e9ee76-6189|Yes|false
  16:06:24.56
  (247896527)|FLOW_VALUE_ASSIGNMENT|742cb60b2b87f8dbf6a227c6b8161f7e9ee76-6189|Yes|false 16:06:24.56
  (247904656)|FLOW_ELEMENT_END|742cb60b2b87f8dbf6a227c6b8161f7e9ee76-6189|FlowDecision|is_this_an_open_or_won_opp
  16:06:24.56 (247928287)|FLOW_START_INTERVIEWS_END|1 16:06:24.56
  (248303505)|FLOW_ACTIONCALL_DETAIL|741cb60b2b87f8dbf6a227c6b8161f7e9ee76-618a|myRule_1_A1|Flows|Set_Account_Status_to_Dead_Lost|true|
  16:06:24.56
  (248318470)|FLOW_VALUE_ASSIGNMENT|741cb60b2b87f8dbf6a227c6b8161f7e9ee76-618a|myRule_1_A1|true
  16:06:24.56
  (248331155)|FLOW_BULK_ELEMENT_END|FlowActionCall|myRule_1_A1|0|181
  16:06:24.56 (248358945)|FLOW_START_INTERVIEWS_END|1 16:06:24.28
  (249271729)|WF_FLOW_ACTION_END|09L4A000000GtOc 16:06:24.28
  (249392011)|WF_ACTIONS_END| Field Update: 1; Flow Trigger: 1;
  16:06:24.28 (249399431)|CODE_UNIT_FINISHED|Workflow:Opportunity
  16:06:24.28 (250386144)|EXECUTION_FINISHED


text:
Q: how to compare the equality of two list elements on ONE TO ONE basis using java8 streams? how to compare the equality of two list elements on ONE TO ONE basis using java8 streams?
    inputNameList = new ArrayList<String>();
    inputNameList.add("ram");
    inputNameList.add("shyam");
    inputNameList.add("hari");

    outputNameList = new ArrayList<String>();
    outputNameList.add("ram");
    outputNameList.add("shyaM");
    outputNameList.add("ram");

when this two lists are compared then the result is 1 because only inputNameList.get(0).equals(outputNameList.get(0))  == true;

A: Seems that you want to find the position of the first mismatch or the list size. You can do this using the stream of indices like this (assuming lists have equal length):
int nMatches = IntStream
         .range(0, inputNameList.size())
         .filter(idx -> !inputNameList.get(idx).equals(outputNameList.get(idx)))
         .findFirst()
         .orElse(inputNameList.size());

A: Assuming both the lists will have equal number of elements, you can make use of IntStream as:
List<String> inputNameList = new ArrayList<String>();
inputNameList.add("ram");
inputNameList.add("shyam");
inputNameList.add("hari");

List<String> outputNameList = new ArrayList<String>();
outputNameList.add("ram");
outputNameList.add("shyaM");
outputNameList.add("ram");

IntStream.range(0,inputNameList.size()).forEach(i -> {
    if(inputNameList.get(i).equals(outputNameList.get(i))) System.out.println(i);
});

This will print the index when elements are equal at that index in the lists. You can modify it as per your requirement.


text:
Q: Uitableview content size issue I have an table view which content size is more than the uiview size i could not able to see the last cell fully as table view is not scrolling up to the tableview cell .

A: If you are using autolayout then you need to set bottom space from super view = 0 in your xib. For more info see in this pic.

And if you are not using autolayout then you can set frame direct of your tableview.

A: Its appear you had set the frame of your UITableView Wrongly, if your UITableView is full screen, set its frame as following:
self.tableView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);

And so on...


text:
Q: ASP MVC EF6 Access foreign key table as list I have 2 tables, codes and countries, with a foreign key constraint on codes.countryid on countries.id - I am using the basic crud given by the controller mvc setup from within visual studio 15 but would like to replace the text input with a select for countryid so that the user can select a country from a dropdown as appose to entering the id as an int.
How do I access a list of the countries through the provided Model? Sample razor code below. Do I need to get the countries list from another model?

            Country
            <select name="CountryId" class="form-control" required>
                <option value="">Please select ...</option>
 /* Model.Countries is not available even after a foreignkey constraint? */
                @foreach(var i in Model.Countries)
                {
                    <option value="@i.id">@i.Name</option>
                }
            </select>
            @Html.ValidationMessageFor(model => model.CountryId, "", new { @class = "text-danger" })
            @Html.LabelFor(model => model.CountryId, htmlAttributes: new { @class = "control-label col-md-2" })

A: You should set a ViewBag variable in the controller action with the list of countries.
Assuming you have a DB Context inside your controller, you should put the following code in your action
ViewBag.CountriesList = new SelectList(_context.countries.ToList(), "Id", "Name");

And use it as below inside your view
 @Html.DropDownListFor(a => a.countryId, (SelectList)ViewBag.CountriesList , htmlAttributes: new { @class = "form-control" })


text:
Q: Modify $index value after each iteration in ng-repeat My requirement is to increment the $index value after each iteration of ng-repeat in angularjs.I tried incrementing using ng-init like this,
but it didn't work and it is incremented at the start of the ng-repeat.Could anyone help me with this?

   offers[$index].title
    offers[$index+1].title

offers[$index+2].title
    offers[$index+3].title
    offers[$index+4].title

The problem I use a row that alternatively displays two title in the first row and in the second row it displays the title of other three offers.The first iteration prints the title in order.But in the second iteration it duplicates the data as $index value is 2.So I need to manipulate the $index value so that it displays the title in order.

A: AngularJs Provide index value for every iteration, you can use that index value and change your count.

Count =  {{count}}

{{x}} {{$index}} Count : {{count+$index}}

Chech That AngularJs Doc Link

A: Try the following:

var myApp = angular.module('myApp', []);
myApp.controller('myController', ['$scope', function($scope){
  $scope.offers = [{title: 'Title 1'},{title: 'Title 2'},{title: 'Title 3'}];
}]);

    {{offers[$index + 0].title}}


text:
Q: Why the v-bind:class does not work, although there are no errors? I wrote a calendar that displays events from a JSON file, and I would like to make the event that is displayed in a few days have a yellow background. I tried using v-bind:class to do this, but the code didn't work. What could be the error?
Code of calendar on GitHub

    <template>

            <transition :name="nameOfClass" >

            </transition>

    </template>


text:
Q: Keeping a single up-to-date keyframe from an RTSP stream I am currently dumping an RTSP stream with the following command:
ffmpeg -hide_banner -loglevel error -i $RTSP_CAMERA -vcodec copy -t $LENGTH -y $FILENAME.mp4
I run this every $LENGTH seconds to get a series of dumped files. The stream runs at 7fps, with a GOP/i/keyframe setting of 7 (so a new keyframe per second).
I now have a requirement to have a recent frame available at an arbitrary time. To be the most efficent, my thought was to keep the latest keyframe or two from the stream (which as above would be 1 per second). My first attempt was to use:
ffmpeg -skip_frame nokey -i $RTSP_CAMERA -f image2 $FILENAME.jpeg
However this complained that $FILENAME wasn't templated. Adding a %02d solved this, but by design resulted in a growing collection of frames with a changing filename. Furthermore, I was getting 7 frames saved per second, which indicated that it was processing and saving every frame.

*Is targeting keyframes actually efficient or would any frame (per second for example) do?

*Is it possible to continuously save frames to the same filename, or would I have to script something external to clean up the older frames?

*Is there a reason why -skip_frame nokey wouldn't work? Note: I have also tried -discard

*Is it possible to have the ffmpeg invocation used to dump the rtsp stream to also save the key frames?

A: image2 is configured as a constant frame-rate muxer so it will attempt to maintain stream frame rate when number of supplied frames is less than the frame rate. -vsync 0 can avoid that. image2 has an option -update to write new images onto the same file.
So, use
ffmpeg -skip_frame nokey -i $RTSP_CAMERA -vsync 0 -f image2 -update 1 $FILENAME.jpeg

BTW, if your source codec is motion jpeg then all frames are keyframes and skip_frame is useless.


text:
Q: Aggregating over a lagged time period in PANDAS I have a multi-index dataframe with indexes for day and stock ticker. Here's a subset:

I want to create several lag variables. I've figured out how to create a one-day lag:
df['Number of Tweets [t-1]'] = df['Number of Tweets'].unstack().shift(1).stack()

Where I'm stuck is in creating a lag variable that aggregates (sums) values over days t-1 through t-3, or t-1 through t-7, or t-1 through t-30. For instance, I would like a column called 'Number of Tweets [sum of t-1 through t-3]'. I have played around with DateOffset and looked into resample but haven't been able to take it further than that. I also can't seem to find any answers in the Cookbook or examples in the documentation that would help. I'm spinning my wheels on this one so would appreciate any help.

A: Use pd.rolling_sum on the shifted data.  To calculate the rolling sum for t-3 through t-1, use a window length of 3 and shift the data by 1 (the default if no parameter is specified).
from pandas import Timestamp

# Create series
s = pd.Series({(Timestamp('2015-03-30 00:00:00'), 'AAPL'): 2,
 (Timestamp('2015-03-30 00:00:00'), 'IBM'): 3,
 (Timestamp('2015-03-30 00:00:00'), 'TWTR'): 2,
 (Timestamp('2015-03-31 00:00:00'), 'AAPL'): 6,
 (Timestamp('2015-03-31 00:00:00'), 'IBM'): 2,
 (Timestamp('2015-03-31 00:00:00'), 'TWTR'): 7,
 (Timestamp('2015-04-01 00:00:00'), 'AAPL'): 3,
 (Timestamp('2015-04-01 00:00:00'), 'IBM'): 1,
 (Timestamp('2015-04-01 00:00:00'), 'TWTR'): 2,
 (Timestamp('2015-04-02 00:00:00'), 'AAPL'): 6,
 (Timestamp('2015-04-02 00:00:00'), 'IBM'): 8,
 (Timestamp('2015-04-02 00:00:00'), 'TWTR'): 2,
 (Timestamp('2015-04-06 00:00:00'), 'AAPL'): 4,
 (Timestamp('2015-04-06 00:00:00'), 'IBM'): 2,
 (Timestamp('2015-04-06 00:00:00'), 'TWTR'): 6,
 (Timestamp('2015-04-07 00:00:00'), 'AAPL'): 3,
 (Timestamp('2015-04-07 00:00:00'), 'IBM'): 7,
 (Timestamp('2015-04-07 00:00:00'), 'TWTR'): 8})

# View the data more easily:
s.unstack()
            AAPL  IBM  TWTR
Date
2015-03-30     2    3     2
2015-03-31     6    2     7
2015-04-01     3    1     2
2015-04-02     6    8     2
2015-04-06     4    2     6
2015-04-07     3    7     8

# Calculate a rolling sum on date t for dates t-3 through t-1:
result = pd.rolling_sum(s.unstack().shift(), window=3)  # .shift() <=> .shift(1)

>>> result
            AAPL  IBM  TWTR
Date
2015-03-30   NaN  NaN   NaN
2015-03-31   NaN  NaN   NaN
2015-04-01   NaN  NaN   NaN
2015-04-02    11    6    11
2015-04-06    15   11    11
2015-04-07    13   11    10

# Restack the data:
>>> result.stack()
2015-04-02  AAPL    11
            IBM      6
            TWTR    11
2015-04-06  AAPL    15
            IBM     11
            TWTR    11
2015-04-07  AAPL    13
            IBM     11
            TWTR    10


text:
Q: How can I find which device is using all my network bandwidth? Can someone please help me eliminate a problem within my house? There is a device in my house which continues to use all of my router's bandwidth.
How can I find which device it is which is using all of my bandwidth?
I have the Virgin Media Super Hub 3 Router.

A: Consumer grade routers do not usually provide per-connected-device statistics.
Disconnect one device and then monitor available bandwidth. Reconnect that device and repeat with the next until all devices have been checked. If the bandwidth improves when a particular device is disconnected then you have found your culprit. (If not, you may have more than one device consuming excessive bandwidth and will have to try more complex combinations.)


text:
Q: Textbox loses value after postback (ASP - C#) I've been having a tough time with updating my text boxes and could really use some help. So basically, I have a popup panel for the user to select a value that I then populate into a certain text box.
I am certain that the problem is either very simple to solve, or that I'm confused on what post back actually does. Here is a snippit of my code below:
    protected void grvSearchRecords_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (string.Compare(e.CommandName, "EditRow", true) == 0)
        {
            long nMagic2Value = Convert.ToInt64(e.CommandArgument);
            string tmp = GetItem(nMagic2Value, currentTableName);
            textBox1.Text = tmp;
            Debug.WriteLine(textBox1.Text.ToString());
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "SearchRecords", "$(document).ready(function(){ $('#mask, #divSearchRecordsGrid').fadeOut(\"fast\"); });", true);
        }
    }

The "tmp" variable grabs the value I need and assigns it to the text box.
I then run a Debug statement and confirm that the value is correctly assigned to the box. As soon as the function ends, however, that assigned value is lost, and the text box never populates with the new value.

A: Wrap your code around a post back check
if (!IsPostBack)
{
//your code here
}

This will ensure that your code does not run when it is a post back, so your textBox will not be clear.
Post back means that the page is not being rendered for the first time, for example a page refresh.

A: Okay, I just got it working. The textbox I was trying to change was part of a Content tag and nothing else. I enclosed it in an UpdatePanel and added a trigger for my GridView, and now it works!
The joys of learning a new language.


text:
Q: How to sort results by string length on MongoDB I can do it easily on mysql
select * from TABLE order by length(FIELD) asc

How can I do it on MongoDB?

A: MongoDB 3.4 introduces the $strLenCP aggregation operator that finally supports this. An example:
db.collection.aggregate(
    [
        {$project: {
            "field": 1,
            "field_length": { $strLenCP: "$field" }
        }},
        {$sort: {"field_length": -1}},
        {$project: {"field_length": 0}}
    ]
)

A: suppose your schema is something like:
example = {_id: "XXX", text: "YYY"}

db.example.aggregate([
 {$project : {text : 1, length : {$size : "$text"}}},
 {$sort : {length : 1}}
]);

I think this will do the job, but only for mongo 2.6 and above


text:
Q: Google Play Services iOS SDK : Insufficient Permission I did a bit of searching but didn't come up to any solution thus far. We have an iOS based game and we are trying to integrate Google Play Services. Followed the instructions on here:
https://developers.google.com/games/services/ios/quickstart
I have the following permissions set in Google Dev Console: ( probably more then I need )
Drive API
Drive SDK
Google Play Game Management
Google Play Game Services
Google+ API
Google+ Domains API
When I try to sign in with my google email / password, it throws the following on the console even though it authenticates just fine.
This is how I am requesting for permissions and signing in:
GPGManager.sharedInstance().signInWithClientID(GOOGLE_CLIENT_ID, silently: false,
    withExtraScopes: [
        "https://www.googleapis.com/auth/plus.login",
        "https://www.googleapis.com/auth/plus.me",
        "https://www.googleapis.com/auth/userinfo.email",
        "https://www.googleapis.com/auth/userinfo.profile",
        "https://www.googleapis.com/auth/games",
        "https://www.googleapis.com/auth/drive.appdata"
    ]
)
2014-12-20 15:49:17.352 TriviaBurst[24003:2677075] -[PFCommandResult boolValue]: unrecognized selector sent to instance 0x7d974120
2014-12-20 15:52:55.403 TriviaBurst[24003:2679986] INFO: Auth operation started: SIGN IN
2014-12-20 15:52:55.404 TriviaBurst[24003:2679986] INFO: Auth operation SIGN IN finished with status VALID
2014-12-20 15:52:55.408 TriviaBurst[24003:2677075] ERROR: Attempting to get name of an invalid Player
2014-12-20 15:52:55.408 TriviaBurst[24003:2677075] ERROR: Attempting to get avatar URL of an invalid Player
2014-12-20 15:52:55.408 TriviaBurst[24003:2677075] ERROR: Attempting to get id of an invalid Player
2014-12-20 15:52:55.408 TriviaBurst[24003:2677075] ERROR: Attempting to get title of an invalid Player
2014-12-20 15:52:55.408 TriviaBurst[24003:2677075] ERROR: Attempting to get current xp of an invalid Player
2014-12-20 15:52:55.408 TriviaBurst[24003:2677075] ERROR: Attempting to get last level up timestamp of an invalid Player
2014-12-20 15:52:55.408 TriviaBurst[24003:2677075] ERROR: Attempting to get current level of an invalid Player
2014-12-20 15:52:55.408 TriviaBurst[24003:2677075] ERROR: Attempting to get level number of an invalid PlayerLevel
2014-12-20 15:52:55.408 TriviaBurst[24003:2677075] ERROR: Attempting to get minimum xp of an invalid PlayerLevel
2014-12-20 15:52:55.408 TriviaBurst[24003:2677075] ERROR: Attempting to get maximum xp of an invalid PlayerLevel
2014-12-20 15:52:55.415 TriviaBurst[24003:2677075] ERROR: Attempting to get next level of an invalid Player
2014-12-20 15:52:55.416 TriviaBurst[24003:2677075] ERROR: Attempting to get level number of an invalid PlayerLevel
2014-12-20 15:52:55.416 TriviaBurst[24003:2677075] ERROR: Attempting to get minimum xp of an invalid PlayerLevel
2014-12-20 15:52:55.416 TriviaBurst[24003:2677075] ERROR: Attempting to get maximum xp of an invalid PlayerLevel
2014-12-20 15:52:55.527 [Core] (Error) __49-[GPGService executeOperation:completionHandler:]_block_invoke:[main] Server Operation Failed [appstate.states.list]
    Error: The operation couldn't be completed. (Insufficient Permission)
    Error Full: Error Domain=com.google.GTLJSONRPCErrorDomain Code=403 "The operation couldn't be completed. (Insufficient Permission)" UserInfo=0x7a6bfd00 {error=Insufficient Permission, GTLStructuredError=GTLErrorObject 0x7a6be700: {message:"Insufficient Permission" code:403 data:[1]}, NSLocalizedFailureReason=(Insufficient Permission)}
2014-12-20 15:52:55.674 TriviaBurst[24003:2677075] VERBOSE: Automatically seeded event cache.
2014-12-20 15:52:55.746 TriviaBurst[24003:2677075] VERBOSE: Automatically seeded achievement cache.
2014-12-20 15:52:56.138 TriviaBurst[24003:2677075] WARNING: Could not automatically seed snapshot cache.

A: Check the OAuth 2.0 scope in authentication request. It should't be read-only. here is a calendar OAuth 2.0 example.
    // Creates the auth controller for authorizing access to Google Calendar API.
    - (GTMOAuth2ViewControllerTouch *)createAuthController {
        GTMOAuth2ViewControllerTouch *authController;
        NSArray *scopes = [NSArray arrayWithObjects:kGTLAuthScopeCalendar, nil];
        authController = [[GTMOAuth2ViewControllerTouch alloc]
                          initWithScope:[scopes componentsJoinedByString:@" "]
                          clientID:kClientID
                          clientSecret:kClientSecret
                          keychainItemName:kKeychainItemName
                          delegate:self
                          finishedSelector:@selector(viewController:finishedWithAuth:error:)];
    return authController;
}


text:
Q: Get two numbers from a string I need to extract two numbers inside a string. They can look like this:
(0,0)
(122,158)
(1,22)
(883,8)
etc...

So I want to get the first number before the comma and the number after the comma and store them in variables. I can get the first number like this:
myString.split(',')[0][1:])

However, I can't figure out how to get the next number.

Thanks for the help everyone!

A: It should work with something like
myVar.split(',')[0][1:] # = 122 for the string in the second line
myVar.split(',')[1][:-1] # = 158 for the string in the second line

This should be the easiest way to do this

A: You could get rid of the parentheses, split the string, and convert each item to an int:
a, b = [int(x) for x in s[1:-1].split(',')]

Of course, if you absolutely sure about the string's format, and don't care about security, you could just eval the string:
a, b = eval(s)

A: You can use ast.literal_eval() to convert your string into a tuple. This will also take care about extra whitespace like '( 123, 158)'.
>>> from ast import literal_eval
>>> tup = literal_eval('(122,158)')
>>> tup[0]
122
>>> tup[1]
158

Or just:
>>> first, second = literal_eval('(122,158)')

A: Multi assignment, stripping the parentheses and splitting will do:
a, b = myString.lstrip('(').rstrip(')').split(',')
# a, b = map(int, (a, b))

A: myVar.split(',')[1][:-1])

will get you the second number

A: The simplest one-liner would be
a, b = (myString[1:-1].split(',')[0], myString[1:-1].split(',')[1])

Gets rid of the parentheses, then splits at the comma.


text:
Q: C# - Check if string contains characters of another string at the same order I would like to check if a string contains the characters of another string (returning true or false), but it needs to be in the "right" order but not necessarily contiguous.
Example:
String firstWord = "arm";
String secondWord = "arandomword"; //TRUE - ARandoMword

String thirdWord = "road"; //FALSE - ARanDOmword

The word "arandomword" contains the letters of the word "road" but it's not possible to write it, because they are not at the right order.
Anyone, please?

A: Use regex. Something simple that passes your tests in linqpad:
void Main()
{
    String firstWord = "arm";
    String secondWord = "arandomword"; //TRUE - ARandoMword

    String thirdWord = "road";

    Regex.IsMatch(secondWord,makeRegex(firstWord.ToCharArray())).Dump();
}

// Define other methods and classes here
String makeRegex(char[] chars)
{
    StringBuilder sb = new StringBuilder();
    foreach (var element in chars.Select(c => Regex.Escape(c.ToString()))
        .Select(c => c + ".*"))
    {
        sb.Append(element);
    }
    return sb.ToString();
}

A: you could define an extension method like this:
public static class StringExtensions
{
    public static bool ContainsWord(this string word, string otherword)
    {
        int currentIndex = 0;

        foreach(var character in otherword)
        {
            if ((currentIndex = word.IndexOf(character, currentIndex)) == -1)
                return false;
        }

        return true;
    }
}

and call it as expressive as:
String firstWord = "arm";
String secondWord = "arandomword"; //TRUE - ARandoMword
String thirdWord = "road"; //FALSE - ARanDOmword

var ret = secondWord.ContainsWord(firstWord); // true
var ret2 = thirdWord.ContainsWord(firstWord); // false

A: Something like this?
bool HasLettersInOrder(string firstWord, string secondWord)
{
    int lastPos = -1;
    foreach (char c in firstWord)
    {
        lastPos++;
        while (lastPos < secondWord.Length && secondWord[lastPos] != c)
            lastPos++;
        if (lastPos == secondWord.Length)
            return false;
    }
    return true;
}

A: I can not check right now, but something along the lines:
int i = 0, j = 0;

while(i < first.Length && j < second.Length)
{
   while(first[i] != second[j] && j < second.Length) j++;
   i++;
   j++
}

bool b = i == first.Length;

A: Thanks for all the replies. I've tried and tried and I did it my way. Definitively it's not the shortest way to do it, but at least it's working:
    public static Boolean checkWords(String smallerWord, String biggerWord)
    {
        int position = 0;
        bool gotFirst = false;
        bool gotAnother = false;
        int positionBigger = 0;
        String word = "";

        for(int positionSmaller = 0; positionSmaller < smallerWord.Length; positionSmaller++)
        {
            if(!gotFirst)
            {
                if(biggerWord.Contains(smallerWord[positionSmaller].ToString()))
                {
                    position = biggerWord.IndexOf(smallerWord[positionSmaller].ToString());
                    gotFirst = true;
                    word = smallerWord[positionSmaller].ToString();
                }
            }
            else
            {
                gotAnother = false;
                positionBigger = position + 1;

                while(!gotAnother)
                {
                    if(positionBigger < biggerWord.Length)
                    {
                        if(biggerWord[positionBigger].ToString().Equals(smallerWord[positionSmaller].ToString()))
                        {
                            position = positionBigger;
                            gotAnother = true;
                            word += smallerWord[positionSmaller].ToString();
                        }
                        else
                        {
                            positionBigger++;
                        }
                    }
                    else
                    {
                        gotAnother = true;
                    }
                }
            }
        }

        if(smallerWord.Equals(word))
        {
            return true;
        }
        else
        {
            return false;
        }
    }


text:
Q: BigQuery | How to select * from previously defined CTE in the same query? I have the below SQL query which I want to run on BigQuery.
I am constantly getting error : Unrecognized name: nojoin on the start of the select statement of CTE named onejoin.
Please help. It works for uom_conversion.* in nojoin CTE but nojoin.* doesnt work in onejoin CTE.
WITH uom_conversion AS
(
select a.*,
case when a.sales_unit in ('EA','ZIN') and b.unit = 'CSE' then ifnull(a.order_quan*b.bic_zconvfac,0.0) else a.order_quan end as cse_order_quan,
from `dev-amea-analyt-datal-svc-db.dev_amea_h_sapbw_ptc_otc.v_sales_order_items_amea` as a
left join `dev-amea-analyt-datal-svc-db.dev_amea_h_sapbw_mst.v_mat_unit_otc_amea` as b
on a.material = b.material and a.sales_unit = b.bic_zaltunit
),
nojoin AS
(
SELECT uom_conversion.*,
case when unit_of_wt = 'KG' and doc_type = 'ZOR' then net_wgt_dl end as ship_ord_kg_mysg_osa
from uom_conversion
),
onejoin AS
(
SELECT nojoin.*,
case when orders.doc_type = 'ZOR' and orders.reason_rej = '0' and delivs.biczdelv_itm = '0' and orders.unit_of_wt = 'KG' then orders.net_wgt_dl end as ship_ooqty_kg_mysg_osa
from nojoin as orders
left join `dev-amea-analyt-datal-svc-db.dev_amea_r_sapbw_ap_ptc_otc.v_sales_delivery_items_ap` delivs
on orders.doc_number = delivs.doc_number
),
twojoins AS
(
SELECT onejoin.*
case when orders.doc_type = 'ZOR' and orders.reason_rej = '0' and delivs.biczdelv_itm != '0' and bills.bill_num = '' and orders.unit_of_wt = 'KG' then orders.net_wgt_dl end as ship_nsord_kg_mysg_osa,
from onejoin as orders
left join `dev-amea-analyt-datal-svc-db.dev_amea_r_sapbw_ap_ptc_otc.v_sales_delivery_items_ap` as delivs
on orders.doc_number = delivs.doc_number
left join `dev-amea-analyt-datal-svc-db.dev_amea_r_sapbw_ap_ptc_otc.v_sales_billing_items_ap` as bills
on orders.doc_number = bills.doc_number
)
SELECT *
from twojoins


text:
Q: java.io.IOException: UT010029: Stream is closed How to Resove below Error:
ERROR [com.test.filter.AuthenticationFilter] (default task-6) displayUpdateUser:Error occurred while displaying the Update User page.: java.io.IOException: UT010029: Stream is closed
    at io.undertow.servlet.spec.ServletOutputStreamImpl.write(ServletOutputStreamImpl.java:136)
    at java.io.ByteArrayOutputStream.writeTo(ByteArrayOutputStream.java:167)
    at org.springframework.web.servlet.view.AbstractView.writeToResponse(AbstractView.java:468)
    at org.springframework.web.servlet.view.document.AbstractPdfView.renderMergedOutputModel(AbstractPdfView.java:82)
    at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:303)
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1243)
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1027)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:971)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:968)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:870)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:844)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:86)
    at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:130)
    at com.test.filter.AuthenticationFilter.doFilter(AuthenticationFilter.java:66)
    at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:60)
    at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:132)
    at io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:85)
    at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
    at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
    at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
    at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
    at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
    at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:58)
    at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:72)
    at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
    at io.undertow.security.handlers.SecurityInitialHandler.handleRequest(SecurityInitialHandler.java:76)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.servlet.handlers.ServletInitialHandler.jrHandle(ServletInitialHandler.java)
    at org.zeroturnaround.javarebel.integration.servlet.undertow.cbp.ServletInitialHandlerCBP.handleRequest(ServletInitialHandlerCBP.java:101)
    at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:282)
    at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:261)
    at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:80)
    at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:172)
    at io.undertow.server.Connectors.executeRootHandler(Connectors.java:199)
    at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:774)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

code:
    document.open();
    PDFGenerator.createSummaryTable(document, table, dataList, relPath);
    document.close();
    pdfWriter.close();
    os.flush();
    os.close();

    byte b[] = os.toByteArray();
    ByteArrayOutputStream os1 = new ByteArrayOutputStream();
    PdfReader pdfReader = new PdfReader(b);
    PdfStamper pdfStamper = new PdfStamper(pdfReader, os1);
    pdfStamper.setViewerPreferences(PdfWriter.PDFXNONE);
    pdfStamper.setViewerPreferences(PdfWriter.HideMenubar);
    pdfStamper.setViewerPreferences(PdfWriter.HideToolbar);
    pdfStamper.setViewerPreferences(PdfWriter.HideWindowUI);
    PdfWriter pdfWriter1 = pdfStamper.getWriter();

    pdfWriter1.addJavaScript(getPrintJS());
    pdfReader.close();
    pdfStamper.close();
    os1.flush();
    os1.close();

    OutputStream os2 = httpServletResponse.getOutputStream();
    os2.write(os1.toByteArray());
    os2.flush();
    os2.close();

A: You Close o1 and after that you read use it again:
os1.close(); //<--- close

OutputStream os2 = httpServletResponse.getOutputStream();
os2.write(os1.toByteArray());  //<--- use os1


text:
Q: How to display label when table view is empty I am trying to figure out how to display a message within a table view when the table is empty. I would like it to say something like: "You haven't added any transactions yet. Tap the add button to get started.". Obviously I would need it to revert back to this message if the user deletes all of the cells, too.
This is the code that I currently have in my table view controller:
class ThirdViewController: UITableViewController {

override func viewWillAppear(animated: Bool) {
    self.tableView.reloadData()
}

override func viewDidLoad() {
    super.viewDidLoad()

    // Uncomment the following line to preserve selection between presentations
    // self.clearsSelectionOnViewWillAppear = false

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// #pragma mark - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView?) -> Int {
    // #warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1
}

override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete method implementation.
    // Return the number of rows in the section.
    return arrayObject.paymentsArray().count
}

override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
    var cell:CustomTransactionTableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as CustomTransactionTableViewCell
    cell.paymentNameLabel.text = (arrayObject.paymentsArray().objectAtIndex(indexPath.row)) as String
    cell.costLabel.text = (arrayObject.costArray().objectAtIndex(indexPath.row)) as String
    cell.dateLabel.text = (arrayObject.dateArray().objectAtIndex(indexPath.row)) as String

    if arrayObject.imageArray().objectAtIndex(indexPath.row) as NSObject == 0 {
        cell.paymentArrowImage.hidden = false
        cell.creditArrowImage.hidden = true
    } else if arrayObject.imageArray().objectAtIndex(indexPath.row) as NSObject == 1 {
        cell.creditArrowImage.hidden = false
        cell.paymentArrowImage.hidden = true
    }

    return cell
}

override func tableView(tableView: UITableView!, canEditRowAtIndexPath indexPath: NSIndexPath!) -> Bool {
    return true
}

override func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) {
    if (editingStyle == UITableViewCellEditingStyle.Delete) {

        if let tv=tableView {
            arrayDataCost.removeObjectAtIndex(indexPath!.row)
            arrayDataImage.removeObjectAtIndex(indexPath!.row)
            arrayDataPayments.removeObjectAtIndex(indexPath!.row)
            arrayDataDate.removeObjectAtIndex(indexPath!.row)
            tv.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        }
    }
}
}

Any help would be much appreciated!

A: func numberOfSectionsInTableView(tableView: UITableView) -> Int {
       var numOfSection: NSInteger = 0
        if array.count > 0
{
            self.tableView.backgroundView = nil
            numOfSection = 1
         }
else
{
            var noDataLabel: UILabel = UILabel(frame: CGRectMake(0, 0, self.tableView.bounds.size.width, self.tableView.bounds.size.height))
            noDataLabel.text = "No Data Available"
            noDataLabel.textColor = UIColor(red: 22.0/255.0, green: 106.0/255.0, blue: 176.0/255.0, alpha: 1.0)
            noDataLabel.textAlignment = NSTextAlignment.Center
            self.tableView.backgroundView = noDataLabel
          }
        return numOfSection
  }

A: You might want to set the backgroundView to a UILabel (Or some view you made when the table is empty
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if self.numberOfRow == 0{
        var emptyLabel = UILabel(frame: CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height))
        emptyLabel.text = "No Data"
        emptyLabel.textAlignment = NSTextAlignment.Center
        self.tableView.backgroundView = emptyLabel
        self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        return 0
    } else {
        return self.numberOfRow
    }
}

something like this works fine for me

A: Override your viewDidLoad() method like this:
override func viewDidLoad() {
    super.viewDidLoad()

    self.view.addSubview(self.yourLabel);

    if arrayObject.paymentsArray().count > 0 {
         self.tableView.hidden = NO;
         self.yourLabel.hidden = YES;
    } else {
         self.tableView.hidden = YES;
         self.yourLabel.hidden = NO;
    }
}

A: You can either hide the tableView and unhide the label, or display some sort of animation that reduces the alpha of one of the views for a 'fade' effect.

A: You can use this method. No function limit
Swift3
    if tableView.visibleCells.isEmpty{
            //tableview is not data
           print("can not found data")
     }else{
         //do somethings

    }

A: I needed to achieve the same thing. This is what i did.
var label: UILabel {
    let label = UILabel(frame: tableView.bounds)
    label.text = "empty"
    return label
}

override func viewDidLoad() {
    tableView.backgroundView = UIView(frame: tableView.bounds)
    tableView.backgroundView?.addSubview(noPlacesMessageLabel)
}


text:
Q: Rephrase a multiparameter SDE indexed by time and space as an infinite dimensional SDE indexed by time Let $\mathcal V_t\subseteq\mathbb R^3$ be the bounded space occupied by a closed particle system at $t\ge 0$ and $$[0,\infty)\ni t\mapsto X_t\in\mathcal V_t\tag 1$$ be the movement of a fixed particle $X_0\in\mathcal V_0$ over time. Assuming that the motion of $X_0$ is perturbed by space-time white noise, we may assume that $${\rm d}X_t=v_t{\rm d}t+\xi_t{\rm d}B_t\;\;\;\text{for all }t\ge 0\tag 2$$ for a smooth resolved velocity $v$, a random unresolved component $\xi=(\xi^1,\xi^2,\xi^3)$ and a $\mathbb R^3$-valued Brownian motion $(B_t)_{t\ge 0}$.

Letting $\Phi_t(X_0):=X_t$ and $u_t(X_t):=v_t$, we obtain $${\rm d}u=\left(\partial_tu+(u\cdot\nabla)u+\frac 12\langle C,C\rangle u\right){\rm d}t+\nabla u\cdot\xi_t{\rm d}B_t\;\;\;\text{for }t\ge 0\tag 3$$ with $C:=\sum_{i=1}^3\xi^i\partial_i$ and $u=u_t(X_t)$ by a well-known Itō formula.

Instead of considering the multiparameter SDE $(3)$ for the $\mathbb R^3$-valued process $u$ indexed by time and space, I would like to write down an infinite dimensional SDE for a process indexed by time only and taking values in a infinite dimensional Hilbert space $H$ of functions in space.
$H$ will be some Sobolev space, e.g. $H=H_0^1(\mathcal V\to\mathbb R^3)$ where $\mathcal V$ is the union of the $\mathcal V_t$ up to some finite time $T\ge 0$ (which is assumed to be bounded and open).

What do I need to do? I tried to perturb the fluid flow map $\Phi$ by a $H$-valued cylindrical Brownian motion $(W_t)_{0\le t\le T}$, i.e. I've tried to assume that $${\rm d}\Phi_t=u_t(\Phi_t){\rm d}t+\xi_t(\Phi_t){\rm d}W_t\;\;\;\text{for all }t\in [0,T]\;,\tag 4$$ but I don't know how I need to proceed. I think I need to apply some kind of Itō formula in order to find an expression for $u_t(\Phi_t)$ as I did with $(2)$ to obtain $(3)$.


text:
Q: Extract multiple Words using regex on excel data I have a dataset in Excel:
column1
 Bank A : 12
 Bank B : 40
 Bank C : 55

where it contains only a single row with Bank A, B and C information inside one cell.
How would I be able to use regex in Python to create 3 columns whereby my new dataset is:
 Bank A     Bank B      Bank C
  12          40          55

Thank You!

A: You could do it with the following regex:
(.*?)\s:\s(\d+)

Regex Demo
Or using this regex to be more forgiving with the spaces before and after the :
(.*?)(?:\s+)?:(?:\s+)?(\d+)

Regex Demo
Explanation:
(.*?)    # For Group 1, match every character
\s:\s    # until reaching a space + : + space
(\d+)    # For Group 2, match every digit

Then with your python code you can access contents of Group 1 and 2 using the Match.group() method and build the columns as you need.


text:
Q: Apache: reverse proxy to process PHP from another server I have the following setup:

*

*Plain-Server: Delivering php-files as plain text

*Proxy-Server: Asking the Plain-Server for the php file and parsing it.

Now my question: How do I configure the Proxy-Server (a fully configurable apache 2.2 with PHP 5.3) to interpret the plain php files from Plain-Server?
Example: Given a small php script "hello.php" on Plain-Server (accessible throw http://plainserver/hello.php):
<?php
echo "Hello World";
?>

Plain-Server only outputs it as plain text, no parsing of php-code.
On the Proxy-Server the file "hello.php" does not exist. But when requesting hello.php from Proxy-Server it should get the hello.php from Plain-Server with mod_proxy (Reverse Proxy). It should also parse and execute the php, saying only "Hello World".
The Reverse Proxy is already running, but the execution of php code not working. I tried mod_filter, but couldn't is work. Any ideas how to that?

A: You may consider instead sharing the php files from your source server via an nfs mount or something similar to your target server.  Tricking the proxy server into doing what you ask seems like the long way around the barn?

A: I totally agree with jskaggz,
you could build some awfull tricks building some apps that fetch the remote page ,
dowload it into a local file and then redirect the user to that page that could be executed...
but there is a milion security issues and things that might go wrong with that...
Can't you just convert the 'plain server' to a php excuting server and do some traditional reverse proxying
on your 'proxy server'
maybe using mod_proxy:
http://www.apachetutor.org/admin/reverseproxies ?

A: Answered this on the ServerFault version of this thread: https://serverfault.com/a/399671/48061


text:
Q: mariadb access outer column in subquery I have an issue with the following query that it is working on Mariadb 10.1.48 but it is not on 10.2.40.
It returns the following error

Error Code: 1054. Unknown column 'c.id' in 'where clause'

SELECT
    p.id AS pid,
    p.name AS pname,
    c.id AS cid,
    c.contract_code AS contr_code,
    c.type AS ctype,
    e.id AS eid,
    e.state AS estate,
    e.pay_code AS epay_code,
    COUNT(z.id) AS damages,
    rp.id AS resp_id,
    rp.name AS resp_name,
    rp.surname AS resp_surname,
    IF(CURDATE() BETWEEN DATE_ADD(e.starts_pay_date, INTERVAL 23 DAY) AND DATE_ADD(e.starts_pay_date, INTERVAL 1 MONTH) AND e.state = 1, 1, 0) AS ending
FROM `contracts` AS c,
    `customers` AS p,
    `cash` AS e
LEFT JOIN `damage` z ON e.contract_id = z.contract_id AND z.state = 1
LEFT JOIN `customers` rp ON rp.id = (
    SELECT MAX(p1.id) resp
    FROM `customers` AS p1,
        `contract_responsible` AS r
    WHERE c.id = r.contract_id AND p1.id = r.resp_id )
WHERE e.starts_pay_date <= '2021-09-08 23:59:59' AND c.customer_id = p.id AND e.contract_id = c.id
GROUP BY e.id
ORDER BY e.inserted_date DESC
LIMIT 50 OFFSET 0

I know that it has to do with accessing outer column in a subquery, but I cannot understand why it used to work and now it is NOT!
Can you suggest a workaround?


text:
Q: How to find unreferenced objects in scala I'm trying to create a map of all objects extending a specific class. I want to have access to this list before the objects are used in any other way. I tried this code:
import scala.collection.mutable

abstract class Registered(tag:String) {
    Registered.registry(getClass.getName) = tag
    val x = 1
}

object Registered {
    val registry = mutable.Map[String, String]()
}

object objA extends Registered("foo")

object objB extends Registered("bar")

object TheMain {
    def main(args:Array[String]) {
        listem
        touchem
        listem
    }
    def listem = {
        println(s"listing ${Registered.registry.size} entries:")
        for ((k,v) <- Registered.registry) yield println(s"$k: $v")
    }
    def touchem = {
        val x = objA.x + objB.x
    }
}

which outputs:
listing 0 entries:
listing 2 entries:
objB$: bar
objA$: foo

I need the first line to also list 2 entries. I know this doesn't work because the map is always empty: object initialization is lazy and so I cannot refer to an object until it has been referenced some other way.
What is a good way to create such a registry? Can (Should) I do this using reflection somehow?

A: This is more of an answer to what you add in the comment than to the original question: "In my case I want to look at all objects of a given type and use one with a specific tag. This tag comes from a command line argument."
Why not just create the object dynamically in that case? Like this, maybe:
class Registered(tag:String)

object Registered {
    val registry = mutable.Map[String,String]
    def apply(tag: String) = registered.getOrElseUpdate(tag, new Registered(tag))
}

Or, you insist on statically created instances, you can do this (and not even need the registry):
sealed class Registered(tag:String)
object objA extends Registered("foo")
object objB extends Registered("bar")
object Registered {
    def apply(tag: String) = tag match {
        case "foo" => objA
        case "bar" => objB
        case _ => throw new InvalidArgumentException("Unknown tag: %s".format(x))
    }
}

A: Take a look at the Reflections library.  You should be able to do something like this to find all classes in some.package.name that inherit from class Thingy:
def getThingies(): Set[Class[_ <: Thingy]] = {
  val reflections = new Reflections("some.package.name");
  reflections.getSubTypesOf(classOf[Thingy]);
}

Of course, you could specify classOf[Object] to get all classes in the package.  You can also search for packages that have certain annotations.


text:
Q: How to use EF connection string and ADO.Net connection string in same project In normal EF connection string which I use is like this:
<add name="NorthwindEntities"
     connectionString="metadata=res://*/Models.Model1.csdl|res://*/Models.Model1.ssdl|res://*/Models.Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=******;initial catalog=******;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework""
     providerName="System.Data.EntityClient" />

But when I try to add Ado.Net Membership system in the current project, the connection string have to be like this:
<add name="MembershipEntities"
     connectionString="data source=*****;initial catalog=*****;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"
     providerName="System.Data.EntityClient" />

How to handle this situation?
I'm putting this question with solution for anyone else's benefit.

A: the problem, when add the connection string name here (connectionStringName):
<membership>
          <providers>
              <clear/>
              <add name="AspNetSqlMembershipProvider"
                  type="System.Web.Security.SqlMembershipProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
                  connectionStringName="NorthwindEntities"
                  enablePasswordRetrieval="false"
                  enablePasswordReset="true"
                  requiresQuestionAndAnswer="true"
                  applicationName="/"
                  requiresUniqueEmail="true"
                  passwordFormat="Hashed"
                  maxInvalidPasswordAttempts="5"
                  minRequiredPasswordLength="3"
                  minRequiredNonalphanumericCharacters="0"
                  passwordAttemptWindow="10"
                  passwordStrengthRegularExpression="" />
          </providers>
      </membership>

it brings this error: "Keyword Not Supported: Metadata"
to solve this error we need add another connection string in   node. and change connectionstring name  connectionStringName="MembershipEntities"
<connectionStrings>
    <add name="NorthwindEntities" connectionString="metadata=res://*/Models.Model1.csdl|res://*/Models.Model1.ssdl|res://*/Models.Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=*****;initial catalog=*****;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
    <add name="MembershipEntities" connectionString="data source=*****;initial catalog=*****;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.EntityClient" />
  </connectionStrings>


text:
Q: Semantically, what is a forum? I'm building a forum from scratch as a project, and I'm trying to make it as well-formed and standards-based as possible. Thus far, I've come up with

*

*Using a table

*Using an unordered list with headings for the relevant data

*Using a table for post data (author, title, date, post number) inside a list of posts, with a sub-list of threads

Are there other options I should consider? If not, which of the above would be most semantically correct

A: If you choose to go for the more traditional forum look, then semantically the list of threads should be displayed as a table because it is tabular data (has rows, columns, and headers). The posts of the thread itself should probably be displayed as an ordered list because posts are ordered by date.

A: Some more features of common forums:

*

*# times viewed

*Last posted author/thread where applicable

*stickied (stays at the top, always)

*"poll" threads

*announcement threads (appear on all forums always at the top)

*subforums

*"upvoting" thread replies as "helpful" (aka kudos system)


text:
Q: Origin of "over-the-road trucking" I recently learned about the phrase "over-the-road trucking", which is commonly used in the US to refer to long-distance trucking (normally with large semi-trailer trucks) as opposed to smaller trucks making short-distance deliveries.
However, I'm uncertain about the origin of this phrase and how it came to mean long-distance trucking. After all, unless the truck is offroading, all trucking is "over-the-road". Merriam-Webster unhelpfully defines the etymology as:

from the phrase over the road

How did this phrase originate?

A: The expression over-the-road  dates  back to the 40s:

1940s; earliest use found in The Sun. (Lexico.com)

It was  in those  years that the first long distance and interstate roads were built, and the concept of "over the road" conveyed the idea of long distances.

In 1944 – while World War II was still going on – Congress passed the Federal-Aid Highway Act, and committed the nation to building a modern, four-lane interstate highway system across the country. The highway administration mapped out 40,000 miles of interstate.

Trucks. One of the arguments for the interstate highway system was that it would help farmers get their produce from rural areas to city markets quickly and efficiently. Ironically, trucks have never been able to match the low per ton per mile cost of railroads in transporting food. But the speed and flexibility of trucks won the battle for farm to market transportation.

(livinghistoryfarm.org)

A: Interesting turn of phrase, over-the-road trucking, you wouldn't think it meant long distance driving. In British English "over the road", without hyphens,  would refer to a precise place, e.g. Have you been to the pub over the road? Meaning there's a good pub on the other side of the road.
I must admit to never having heard of its American meaning until today. I doubt I will ever use it, but next time I come across it, I'll know better.
By Googling, I unearthed the following snippets

source: The Termination Report of the National War Labor Board: 1942-1945

November 26 1943
Opinion
The instant case concerning over-the-road trucking was certified to the War Labor Board on November 23 1942. Thereafter it was assigned to the Trucking Commission for hearing and decision A hearing was held on February 5 1943…

An earlier instance was reported in the 1920s, which might indicate how the term came to be coined

On October 9, 1926, in conference with Mr. Albright, he said. "The Cooke road can go to hell as far as I am concerned; as long as Doctor Tanzier operates his trucks over the road I will never spend another cent on it." I told him that I knew he had a personal quarrel with Doctor Tanzier, but that his attitude was rather hard on the rest of us. He answered "Well that is the way I feel about it." Doctor Tanzier heads a company that this year has completed a copper smelter in the district.

and in 1927

No other purpose for the road was suggested. My own opinion is that on account of the steep grades and the large number of switchbacks which would have to be made in certain portions of the road, the hauling of freight over the road at the best season of the year would be a difficult task

Driving trucks over the road, suggest a public major road. Wikipedia tells us the plans for building a highway system in the USA was first created in 1922.

In the US, the Federal Aid Highway Act of 1921 (Phipps Act) enacted a fund to create an extensive highway system. In 1922, the first blueprint for a national highway system (the Pershing Map) was published.

From trucks travelling/driving  over the road in the 1920s to the 1940s over-the-road trucking the distance was brief.

A: Over-the-road trucking appears to come from the literal meaning of the words as you have found, although this particular phrasing is not as common nowadays compared to on the roads or by road (or using road attributively, as in road trip). Consider some 19th-century examples from Google Books and COHA:

One or more of the most trustworthy among them had only to make a tour over the road, and through the hamlets in which they were harbored within the circuit of ten or twenty miles. — Guy Rivers: A Tale of Georgia, William Gilmore Simms, 1834

The horse and the wagon, bearing its charming freight of two pretty girls, moved swiftly and safely over the road to the Beach. — Life and Sayings of Mrs. Partington and Others of the Family, B.P. Shillaber (ed.), 1854

The train shrieked into the station, and we were soon rushing over the road to New Haven…. — An American Girl Abroad, Adeline Trafton, 1880

[T]he vegetables were bruised and rendered less valuable, and their value impaired, by hauling over the road. — Galveston H&SA Railway Co. v. Baudat, Court of Civil Appeals of Texas, May 18, 1899

As for truck, that word in reference to a small sled or barrow for carrying a heavy weight dates to at least the 17th century according to the OED, and as a verb meaning to convey by truck from the late 19th century (not to be conflated with the sense of truck referring to commerce or trade).

1891 The Echo 10 Mar. 3/2 — On the quays..the snow is a foot deep, and trucking from the sheds to the ship has been delayed.

1909 Dundee Advertiser 24 Nov. 7 — Miners..have struck work owing to a difference with the management regarding the trucking of coal.

When horseless trucks first appeared, frequently distinguished as auto trucks or motor trucks, they were not suitable for more than deliveries around town. The state of automotive engineering was primitive in that era, but even more so was what passed for intercity roads in the U.S. and Canada, compared against the extensive network of canals and railroads built over the previous century.
As such, I believe over the road became a fixed expression because it was a novel mode when such hauling began in earnest during World War I, when the railroads were heavily congested and could not keep up with demand. The OED's earliest attestation for over-the-road in reference to long-distance freight transportation by road is from 1945:

1945 Baltimore Sun 24 Oct. 14-0/8   Approximately 1500 members of Local 557, Freight Drivers and Helpers..yesterday went on strike which threatens to halt..practically all over-the-road, inter-city hauling into and out of Baltimore.

The long-haul road transportation industry did not really flourish until the construction of the Interstate Highway System starting in the 1950s, and that is when trucking became trucking as we know it today.


text:
Q: Full width floatingactionbutton in flutter? How can I implement a full width floatingactionbutton without using padding in bottom of the screen in flutter

A: You can use a different approach. You can implement the same using stack.
Stack(
children: <Widget>[
        Align(
      alignment: Alignment.bottomCenter,
      child: Container(
        width: MediaQuery.of(context).size.width,
        height: 55,
        child: FloatingActionButton.extended(
          onPressed: () {

          },
          backgroundColor: Colors.green,
          icon: Icon( Icons.add),
          label: Text(
            'ADD',
            style: TextStyle(fontSize: 18),
          ),
          shape: RoundedRectangleBorder(),
        ),
      ),
    )
]
)


text:
Q: Relational algebra and Relational Calculus Operator(opCode,opName)
Journey(opCode,destionationCode,price)
Destination(destinationCode,destinationName,distance)
write a Relational Algebra to list all the name that do not have operator
my attempt
T1- project opCode(Operator) - project opCode(Journey)
 project destinationName(T1 natural join Destination)

A:
π<destinationName>( Destination ⋈
                   (π<destinationCode>(Destination) - π<destinationCode>(Journey) ))

Or it might be more succinct to use AntiJoin aka AntiSemiJoin aka SemiDifference aka Not Matching -- depending if your dialect of the Algebra allows it

π<destinationName>( Destination ▷ Journey )


text:
Q: Why does CoreMotion authorization message appear in background in iOS 8 " Would like to access your motion activity" I have an app that uses a CoreMotion Pedometer in iOS 8, and at first lauch, the app appears to freeze up until one presses the home button.
Upon exiting to the home screen, the app then shows a message " Would like to access your motion activity". And if you press ok and go back into the app, everything works fine.
What I want to understand is why the OS is asking this message in the background. Why should I have to first exit the app, answer the dialog, and then go back into the app. In the past, this dialog box would pop up inside the app and the user could press okay and continue. Is this some iOS8 specific functionality?

A: Had the same issue. Try putting the corresponding code into -(void)viewDidAppear:(BOOL)animated;.


text:
Q: Dictionary-Based Named Entity Recognition with zero edit distance: LingPipe, Lucene or what? I'm trying to perform a dictionary-based NER on some documents. My dictionary, regardless of the datatype, consists of key-value pairs of strings. I want to search for all the keys in the document, and return the corresponding value for that key whenever a match occurs.
The problem is, my dictionary is fairly large: ~7 million key-values - average length of keys: 8 and average length of values: 20 characters.
I've tried LingPipe with MapDictionary but on my desired environment setup, it runs out of memory after 200,000 rows are inserted. I don't know clearly why LingPipe uses a map and not a hashmap in their algorithm.
So the thing is, I don't have any previous experience with Lucene and I want to know if it makes such thing with such number possible in an easier way.
ps. I've already tried chunking the data into several dictionaries and writing them on disk but it's relatively slow.
Thanks for any help.
Cheers
Parsa

A: I suppose if you wanted to reuse LingPipe's ExactDictionaryChunker to do the NER, you could override their MapDictionary to store & retrieve from your choice of key/value database instead of their ObjectToSet (which does extend HashMap, by the way).
Lucene/solr can be used as a key/value store, but if you don't need the extra searching capabilities, just a pure look-up, other options might be better for what you're doing.


text:
Q: figuring Golf Handicap Presently we use the following formula and it works great:
=IF(COUNTIF(D4:AB4,">0")<3,C4,IF((((SUM(D4:AB4)-(COUNTIF(D4:AB4,">0")*36))/COUNTIF(D4:AB4,">0")))*0.9>20,20,(((SUM(D4:AB4)-(COUNTIF(D4:AB4,">0")*36))/COUNTIF(D4:AB4,">0")))*0.9))

What is says is you must golf at least 3 times before the formula will recalculate a new handicap otherwise you are stuck with (C4) what you started with and we only use 90% of your average to compute your handicap.
However after many weeks of play ones handicap hardly changes due to the vast amount of entries; to keep the handicap current we want it to to use the 5 most current scores and yet do all the rest the formula presently does.
Because people miss or are absent there will no postings in some weeks so then we want it skip the blanks and just use the posted weeks

A: you could use the formula:
=MIN(IF(COUNTIF(D4:AB4,">0")<3,C4,IF(COUNTIF(D4:AB4,">0")<=5,SUM(IF(D4:AB4>0,D4:AB4-36))/COUNTIF(D4:AB4,">0"),SUM(IF(COLUMN(D4:AB4)=LARGE(IF(D4:AB4>0,COLUMN(D4:AB4)),ROW($1:$5)),D4:AB4-36)/5))*0.9),20)

This is an array formula and must be confirmed with ctrl+shift+enter!

This fomula simply can be copied down as you need it.
The order of actions:

*

*If the value which is picked is higher than 20, then show just 20 (also if 21+ is at C4)

*

*less than 3 entries:

*

*pick the value from C4

*more than or equal to 3 entries

*

*less then or equal to 5 entries

*

*subtract 36 from each value which is bigger 0

*sum up everything

*divide by the amount of numbers

*more than 5 entries

*

*if value is > 0 then show column number

*get the 5 biggest column numbers out of that list

*if the column number of the column is in that list: return the value subtracted by 36

*sum up everything

*divide by five

*multiply by 0.9


text:
Q: Can I use jQuery to detect if any CSS styles exist for an ID? I'm looking for a way to check if any CSS styles are applied to an(y) ID and if not, remove the ID attribute.
Example:
HTML

Welcome

CSS
#content-67 {
  width: 100%;
  height: 100%;
}

The desired outcome would be the removing the ID attribute for H2, because no styles for #headline-23 exist.

Welcome

I've been using this rather inefficient solution, which doesn't do the job very well, because it doesn't check the CSS files.
jQuery('div,span,h1,h2,h3,h4,h5,h6,a,p,img').not('#xyz).removeAttr('id');

Could this be done with jQuery or does it need a different solution?
Thanks!


text:
Q: Using templated function to read numbers from CSV file I'm wondering if there is an elegant way of writing a single function that reads list of numbers (int or double) into a vector using a templated function?
Here is what I usually do:
template<class VecType>
vector<VecType> read_vector(const string& file){
    vector<VecType> vec;

    ifstream indata;
    indata.open(file);

    string line;

    while (getline(indata, line)) {
        stringstream lineStream(line);
        string cell;
        while (std::getline(lineStream, cell, ',')) {
            vec.push_back(stod(cell));
        }
    }

    indata.close();

    return vec;
}

My problem is with the stoi or stod part. How to handle this nicely here?
What I usually do, is to use stod and let the conversion happen automatically from double to int if the VecType is int for example. But there should be much better way to do this, right?

A: You could have specialized template:
template <class T> T from_string(const std::string&);

template <> int from_string<int>(const std::string& s) { return stoi(s); }
template <> double from_string<double>(const std::string& s)  { return stod(s); }

and use vec.push_back(from_string<VecType>(cell));


text:
Q: Can't Extract work with All? I've got a data structure that consists of a long list of triples; each triple consists of a number, a two-element pair, and a two-element pair. Symbolically, I can represent this data structure as {{t1, {x1, y1}, {vx1, vy1}}, {t2, {x2, y2}, {vx2, vy2}}, ...}.
I want to extract just the tN and yN values as pairs, to end up with a list like this: {{t1, y1}, {t2, y2}, ...}. I can think of several ways to do this, including: pulling the tN out into one variable, the yN out into another, packaging the two together into a list, and transposing; or, flattening and using Part. However, the outermost list is likely to be very long, and I want to minimize list rearrangement and copying.
It seems like Extract should do the job. And it would, too, except that it throws an error whenever I try to use All as a position specification. When I try this:
traj = {{t1, {x1, y1}, {vx1, vy1}}, {t2, {x2, y2}, {vx2, vy2}}, {t3, {x3, y3}, {vx3, vy3}}};
Extract[traj, {{All, 1}, {All, 2, 2}}]

I get a "Position specification… is not applicable" error. The same thing happens if I try the ;; syntax. However, the following work (although they only produce one pair, not the entire list of pairs):
Extract[traj, {{1, 1}, {1, 2, 2}}]
(* ==> {t1, y1} *)

Extract[traj, {{-1, 1}, {-1, 2, 2}}]
(* ==> {t3, y3} *)

The best solution I've come up with so far is:
Extract[traj, {{#, 1}, {#, 2, 2}}] & /@ Range[Length[traj]]

But the question remains: Is there no way to make Extract take All, or something that has the equivalent functionality? I am flabbergasted that Extract differs from Part in this one small but important way.

A: Yet another way using the operator form of Extract:
Map[Extract[{{1}, {2, 2}}], traj]
(* {{t1, y1}, {t2, y2}, {t3, y3}} *)

A: Use destructuring.
helper[{t_, {_, y_}, _}] := {t, y}
helper /@ traj

{{t1, y1}, {t2, y2}, {t3, y3}}

A: I would approach this with Part (shorthand [[ ]]) rather than Extract:
Thread[{traj[[All, 1]], traj[[All, 2, 2]]}]
{{t1, y1}, {t2, y2}, {t3, y3}}

A: MapAt is the only function I know that allows a list position to contain All. You could exploit that fact:
Reap[MapAt[Sow, traj, {{All, 1}, {All, 2, 2}}]][[2, 1]]

However, I like the following workaround better:
traj[[Sequence @@ #]] & /@ {{All, 1}, {All, 2, 2}}


text:
Q: Disappearing after pressing in 'react-native-svg' I use SvgCss from react-native-svg for displaying and changing the color of several external svgs.
I put onPress on it and it works as expected in most cases. but I noticed that some svgs have weird behavior after pressing on them. for example the below svg disappears after pressing!
what's the problem here?
<svg xmlns="http://www.w3.org/2000/svg" width="188" height="195" viewBox="0 0 188 195">
    <defs>
        <clipPath id="sjkzt87o0a">
            <path fill="none" stroke="#707070" d="M0 0H188V195H0z" transform="translate(277 228)"/>
        </clipPath>
    </defs>
    <g clip-path="url(#sjkzt87o0a)" transform="translate(-277 -228)">
        <g>
            <path fill="currentColor" d="M424.413 141.66A183.073 183.073 0 0 0 241.34 324.733h139.35a43.723 43.723 0 0 1 87.445 0h139.35A183.073 183.073 0 0 0 424.413 141.66z" transform="rotate(14 -112.125 652.114) rotate(-14 269.633 431.384)"/>
            <path d="M-419.71-981.787a184.43 184.43 0 0 1-5.317-36.7 182.149 182.149 0 0 1 2.037-35.924 183.1 183.1 0 0 1 8.855-34.257 184.4 184.4 0 0 1 15.136-31.7 184.393 184.393 0 0 1 20.881-28.245 183.1 183.1 0 0 1 26.09-23.9 182.158 182.158 0 0 1 30.763-18.664 184.426 184.426 0 0 1 34.9-12.535 183.84 183.84 0 0 1 44.431-5.482 182.2 182.2 0 0 1 36.685 3.741 183.411 183.411 0 0 1 34.685 10.834 184.485 184.485 0 0 1 31.712 17.342 184.062 184.062 0 0 1 27.767 23.265 182.161 182.161 0 0 0-127.848-52.183 183.849 183.849 0 0 0-44.432 5.482c-96.058 23.95-156.256 121.918-134.191 218.387l-2.153.537zm220.059-54.867a43.8 43.8 0 0 0-10-18.771 43.609 43.609 0 0 1 7.076 8.251 43.559 43.559 0 0 1 4.9 10.028l-1.974.492z" transform="rotate(14 -112.125 652.114) translate(636.09 1316.532)" style="mix-blend-mode:multiply;isolation:isolate" fill="#bfbfbf"/>
        </g>
    </g>
</svg>

I also tried SvgXml , SvgUri, SvgCssUri, no changes.
here is the code:
import React, { useEffect, useState } from 'react';
import Axios from 'axios';
import { Text } from 'native-base';
import { SvgCss } from 'react-native-svg';

const PaintObject = ({ svg, objData }) => {
  const [color, setcolor] = useState(objData.initial_color);
  const [svgfile, setsvgfile] = useState('');

  useEffect(() => {
    Axios.get(svg).then(({ data }) => {
      setsvgfile(data);
    });
  }, []);

  if (svgfile !== '') {
    return (
      <SvgCss
        width={`${objData.width}%`}
        height={`${objData.width}%`}
        style={{
          color,
          position: 'absolute',
          top: `${objData.y}%`,
          left: `${objData.x}%`,
        }}
        xml={[...svgfile].join('')}
        onPress={()=> setcolor('green')}
      />
    );
  }
  return (<Text>{ }</Text>);
};

export default PaintObject;

A: You have better wrap SVG into TouchableOpacity or TouchableWithoutFeedback
I use this site for converting svg to react-native-svg

import React from 'react';
import Svg, { Path, SvgProps } from 'react-native-svg';

export const Mic = (props: SvgProps) => (
  <Svg width={24} height={24} viewBox="0 0 24 24" fill="none" {...props}>
    <Path
      d="M12 14c1.66 0 2.99-1.34 2.99-3L15 5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3zm5.3-3c0 3-2.54 5.1-5.3 5.1S6.7 14 6.7 11H5c0 3.41 2.72 6.23 6 6.72V21h2v-3.28c3.28-.48 6-3.3 6-6.72h-1.7z"
      fill={props.fill ? props.fill : '#000'}
      fillOpacity={props.fill ? 1 : 0.6}
    />
  </Svg>
);


text:
Q: Como mudar a ordem do índice array javascript Como faço para mudar uma ordem de array. Exemplo: Possuo um array com seguinte sintaxe:
arr = [h5,ul,h5,ul,h5,ul,h5,ul,];
A finalidade é mudar a ordem de exibição do html, por exemplo o h5 cerveja /h5 com sua respectiva ul seja exbida primeiro. Preciso de uma sintaxe em que eu possa mudar a ordem livremente
veja:
jQuery
$(document).ready(function(){
var elems = $(".departamento h5, .departamento ul");
var move = jQuery.makeArray( elems );

Array.prototype.move = function (old_index, new_index) {
  if (new_index >= this.length) {
    var k = new_index - this.length;
    while ((k--) + 1) {
        this.push(undefined);
    }
  }
  this.splice(new_index, 0, this.splice(old_index, 1)[0]);
  return this;
};
$( move ).appendTo( ".departamento" );

});

HTML

vinho

vinho tinto

cerveja

cerveja sem alcool

licor

licor vermelho

cafe

cafeina

A: De acordo com esta resposta, https://stackoverflow.com/questions/5306680/move-an-array-element-from-one-array-position-to-another, você pode usar este código:
Array.prototype.move = function (old_index, new_index) {
  if (new_index >= this.length) {
    var k = new_index - this.length;
    while ((k--) + 1) {
        this.push(undefined);
    }
  }
  this.splice(new_index, 0, this.splice(old_index, 1)[0]);
};

Desta forma, o código para usar o método acima ficaria:
[1, 2, 3].move(0, 1) # retorna [2, 1, 3]

Se você quiser retornar uma cópia, e não modificar o array original, troca na última linha o "splice" por "slice".

UPDATE
Ao invés de criar este método move na classe de domínio base Array de todo o javascript, você pode implementar o método somente no seu array.
Neste caso, teríamos um método para alterar a ordem do seu array com os elementos, e outro para renderizar o novo formato, ou seja, alterar o DOM quando a reordenação estiver feita. Com isso, escrevi dois métodos:
$(document).ready(function(){
    var elems = $(".departamento h5, .departamento ul");

    elems.changeOrder = function (old_index, new_index) {
      if (new_index >= this.length) {
        var k = new_index - this.length;
        while ((k--) + 1) {
            this.push(undefined);
        }
      }
      this.splice(new_index, 0, this.splice(old_index, 1)[0]);
    };

    elems.reflux = function(){
        var newListOfElements = this.clone();
        var oldListOfElements = $(this.selector);
        for(var i=0; i < newListOfElements.length; i++){
            $(newListOfElements[i]).insertAfter(oldListOfElements[i]);
        }
        $(oldListOfElements).remove();
    }

    elems.changeOrder(2, 0); // [2] == Titulo Cerveja vai para [0]
    elems.changeOrder(3, 1); // [3] == Lista de cervejas vai para [1]

    elems.reflux(); // Após trocar a ordem, refaz o DOM de acordo com a ordem;
});

O primeiro, #changeOrder, é um método que contém o mesmo código do Array#move acima. O segundo é o método #reflux(). Basicamente, ele insere novos elementos clones na tela considerando a nova ordenação e depois apaga os elementos velhos, da ordenação antiga.
Coloquei o código aqui: http://jsfiddle.net/rkzs8teg/2/
UPDATE 2
Na verdade, um código mais otimizado para o método #reflux seria assim:
    elems.reflux = function(){
        var oldListOfElements = $(this.selector),
        newListOfElements = this.clone();
        $(newListOfElements).insertAfter(oldListOfElements.last());
        $(oldListOfElements).remove();
    }

Segue a utilização dele: http://jsfiddle.net/rkzs8teg/3/


text:
Q: Passing same value of method to multiple forms In my window application I have orderNumber that need to be passed to another form. This order number is generated by the code which I will put below. I am trying to pass only 1 identical order number to two locations but unfortunately, two different order number passed to both location. How can I make that only one order number is passed to both location.
Code that generates the order number:
public string orderNumber()
        {
           string ord = "ORD" + get_next_id() + DateTime.Now.Year;
           return ord;

       }

 public int get_next_id()
        {
            OleDbConnection objConnection = null;
            OleDbCommand objCmd = null;
            String sql;
            int res;

            // Create and open the connection object
            objConnection = new OleDbConnection(connString);

            objConnection.Open();
            sql = "SELECT IIF(MAX(Customer.NumGenerate) IS NULL,100,MAX(Customer.NumGenerate)) as v_max FROM Customer;";
            objCmd = new OleDbCommand(sql, objConnection);
            res = (int)objCmd.ExecuteScalar();
            ++res;
            objConnection.Close();
            return res;
        }

In the first form the following insert method uses the order number:
private void SaveAllListItems()
        {
            string listItems = string.Empty;
            foreach (var listBoxItem in listBox1.Items)
            {

                listItems += listBoxItem.ToString();

                if (listBox1.Items.IndexOf(listBoxItem) < listBox1.Items.Count - 1)
                {
                    listItems += ", ";
                }
            }

            InsertUser(maskedTextBox1.Text, comboBox1.Text, maskedTextBox2.Text, maskedTextBox3.Text, maskedTextBox4.Text, maskedTextBox5.Text,
                       maskedTextBox6.Text, maskedTextBox7.Text, maskedTextBox8.Text, maskedTextBox9.Text, listItems, DateTime.Now, maskedTextBox10.Text, orderNumber(), get_next_id());

;
        }

In second form I want to use the same order number which is being used to insert user. right now I have the following code which is not working as form1 has different order number and form 2 has different.
 private void FindOrder()
        {

            Form1 m = new Form1();
            string number = m.orderNumber();
          //  string number = "ORD1012013";

            string InvSql = "SELECT  (Customer.[Title] + SPACE(2)  + Customer.[Customer's Name]) as CustomerName, Customer.[Customer's Ebayname], Customer.[Email Address], Customer.[Phone Number], (Customer.[Address 1] + SPACE(2)  +Customer.[Address 2] + SPACE(2)  + Customer.[City] + SPACE(2)  + Customer.[Post Code]+  SPACE(2)  + Customer.[Country]) as Address, Customer.[Item Purchased], Customer.[Purchased Date], Customer.[Total Price], Customer.[OrderNumber] FROM Customer WHERE Customer.[OrderNumber]= '" + number + "'";

            OleDbConnection cnn = new OleDbConnection(connString);
            OleDbCommand cmdOrder = new OleDbCommand(InvSql, cnn);
            cnn.Open();

            OleDbDataReader rdrOrder = cmdOrder.ExecuteReader();

            rdrOrder.Read();
            custName.Text = rdrOrder["CustomerName"].ToString();
            ebayName.Text = rdrOrder["Customer's Ebayname"].ToString();
            email.Text = rdrOrder["Email Address"].ToString();
            phone.Text = rdrOrder["Phone Number"].ToString();
            address.Text = rdrOrder["Address"].ToString();
            item.Text = rdrOrder["Item Purchased"].ToString();
            date.Text = Convert.ToString(Convert.ToDateTime(rdrOrder["Purchased Date"]));
            price.Text = rdrOrder["Total Price"].ToString();
            order.Text = rdrOrder["OrderNumber"].ToString();

            rdrOrder.Close();
            cnn.Close();
        }

How can I pass same order number to both location?

A: Data can be passed between forms in different ways.
Here's a good tutorial on how to do that.The Constructor and Property approach is easier to implement.
You dont seem to be saving the orderid on the form1 class
Declare a variable for the OrderID on Form1 class
string OrderId;

Modify your exisiting Method
public string orderNumber()
{
  OrderId = "ORD" + OrderId + DateTime.Now.Year;
}

And then follow the Constructor Approach to pass over the value to PrintForm
Again declare a variable for orderID inside the PrintForm class
string OrderId;

Change your PrintForm Constructor to this
public PrintForm(string value)
{
  InitializeComponent();
  OrderId=value;
}

on Form1 Button click event
private void button1_Click(object sender, System.EventArgs e)
{
    PrintForm frm=new PrintForm(OrderId);
    PrintForm.Show();
}

A: Create a container class with a static property in the same namespace:
class clsDummy
 {
  internal static string ptyValue { get; set; }
 }

you can assign this property where you are getting order id:
public string orderNumber()
 {
   string ord = "ORD" + get_next_id() + DateTime.Now.Year;
   clsDummy.ptyValue =ord ;
   return ord;
 }

after that where ever you want to access just check value inside : clsDummy.ptyValue