text:
Q: Add onlick event listener in look doesnt work js This is how my item html looks like:

green tea

Loan si

      3.45 r

      <button class="quantity-arrow-minus">-</button>

50 г

      <button class="quantity-arrow-plus">+</button>
      <button class="quantity-add-to-basket">В корзину</button>

         Good tea Good teaGood teaGood teaGood tea

I add id on each item in my html markup and then I javascript I take all my items and trying to add onclick event on each of my items but idk why when I clock on each of my plus minus buttons on any item it changes only the last item's value .
var items = document.querySelectorAll('.content__products__item');

for (var i = 1; i < items.length; i++) {
    var btnMinus = document.querySelector('#item' + i + ' .quantity-arrow-minus');
    var btnPlus = document.querySelector('#item' + i + ' .quantity-arrow-plus');
    var input = document.querySelector('#item' + i + ' .quantity-num span');
    var currentPrice = document.querySelector('#item' + i + ' .content__products__item__price span');
    var pricePerGram = currentPrice.textContent / 50;
    btnPlus.onclick = function (e) {
        input.textContent = +input.textContent + 50;
        currentPrice.textContent = (+input.textContent * pricePerGram).toFixed(2);
    }
    btnMinus.onclick = function (e) {
        if (input.textContent > 50) {
            input.textContent = +input.textContent - 50;
            currentPrice.textContent = (+input.textContent * pricePerGram).toFixed(2);
        }
    }
}

Please help!

A: Ok I did it this way:
var items = document.querySelectorAll('.content__products__item');

  items.forEach(function(item, i) {
    var btnMinus = document.querySelector('#item' + n + ' .quantity-arrow-minus');
    var btnPlus = document.querySelector('#item' + n + ' .quantity-arrow-plus');
    var input = document.querySelector('#item' + n + ' .quantity-num span');
    var currentPrice = document.querySelector('#item' + n + ' .content__products__item__price span');
    var pricePerGram = currentPrice.textContent / 50;
    btnPlus.onclick = function(e) {
      input.textContent = +input.textContent + 50;
      currentPrice.textContent = (+input.textContent * pricePerGram).toFixed(2);
    }
     btnMinus.onclick = function(e) {
       if(input.textContent > 50) {
       input.textContent = +input.textContent - 50;
      currentPrice.textContent = (+input.textContent * pricePerGram).toFixed(2);
       }
    }
  });

Now it works good!


text:
Q: Keeping Tab open on postback Hi i have some tabbing which works fine, however on postback the tabbing opens two at once. I was wondering how i can  fix this issue. Here is the javascript i used;
$(".tab_content").hide();

    $("ul.tabs li:first").addClass("active").show();

    $(".tab_content:first").show();

    $("ul.tabs li").click(function() {

        $("ul.tabs li").removeClass("active");

        $(this).addClass("active");

        $(".tab_content").hide();

        var activeTab = $(this).find("a").attr("href");

        $(activeTab).fadeIn();

        return false;

    });

    $('#texttab').click(function() {

        $(".tab_content").addClass("heightone");

        $(".tab_content").removeClass("heighttwo");

        $(".tab_content").removeClass("heightthree");

        $('#tabscontainer').addClass("hone");

        $('#tabscontainer').removeClass("htwo");

        $('#tabscontainer').removeClass("hthree");

    });

    $('#imagetab').click(function() {

        $(".tab_content").addClass("heighttwo");

        $(".tab_content").removeClass("heightone");

        $(".tab_content").removeClass("heightthree");

        $('#tabscontainer').addClass("htwo");

        $('#tabscontainer').removeClass("hone");

        $('#tabscontainer').removeClass("hthree");

        $(".tab_container").css("height","650px");

    });

I tried using this piece of code to maintain it on postback however it does not work;
 $(function() {
        $("#tabscontainer").tabs({
            show: function() {
                var sel = $('#tabscontainer').tabs('option', 'selected');
                $("#<%= HFCurrTabIndex.ClientID %>").val(sel);
            },
            selected: <%= HFCurrTabIndex.Value %>
        });
    });

HTML

Text Update

Text & Image Update

<asp:Button ID="lbtnUpdate" Text="Update" CssClass="button" OnClick="lbtnUpdate_Click" runat="server"></asp:Button>

<asp:Button ID="lbtnUpdateImage" Text="Update" CssClass="button" OnClick="lbtnUpdate_Click" runat="server"></asp:Button>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Formula to check cells and then perform sum action In excel, i need to check the text value of 3 cells, A1, A10 & A20 if either contains a text string CK75 then i need to add together values in cells B1, B10 & B20 and put the answer in Cell B2.
I started with an OR statement but i can only check 2 cells
=OR(B25="CK75 -Al",B27="CK75- Al")

=OR(B25="CK75 -Al",B27="CK75- Al")

I also tried this which works in part
=IF(ISNUMBER(SEARCH("CK75 - ",A20)),SUM(B1+B20),B1)

A: This will do it and return blank if the condition is not met:
=IF(OR(A1="CK75",A10="CK75",A20="CK75"),SUM(B1,B10,B20),"")

A: From the first line of your question (and your second attempt) it appears as though the text string in these cells can contain the substring, rather than exactly be the searchvalue CK75. If that is the case you could do as follow:

The formula I used translates to:
=IF(ISNUMBER(FIND("CK75",A1&A10&A20,1)),SUM(B10,B1,B20),"")

FIND() will trigger on capital/non-capital. If you dont want that to happen you should replace that with SEARCH()


text:
Q: Input type hidden for kendoNumericTextbox It is possible to make this textbox hidden while Im using kendoNumericTextbox on it? Working Demo

$("#sum_of_itemGrid").kendoNumericTextBox({
  spinners: false,
  format: "{0:n2}",
  decimals: 2,
  restrictDecimals: true
});

$("#sum_of_subRecipeGrid").kendoNumericTextBox({
  spinners: false,
  format: "{0:n2}",
  decimals: 2,
  restrictDecimals: true
});
<input type="hidden" id="sum_of_itemGrid" class="k-textbox" />
<input type="hidden" id="sum_of_subRecipeGrid" class="k-textbox" />

I have tried
document.getElementById("sum_of_itemGrid").style.display='block';
document.getElementById("sum_of_itemGrid").style.visibility='visible';

A: Got it, need to use wrapper
$("#sum_of_itemGrid").data("kendoNumericTextBox").wrapper.hide();
$("#sum_of_subRecipeGrid").data("kendoNumericTextBox").wrapper.hide();


text:
Q: Dynamic Cell With Image Resize Issue I have a UITableViewCell that has a UIImageView. Users can post images and they'll display in the UITableView (think similar to social network/media apps).
The problem I have is that after I create my post and I am back at the main UITableView, the cell is not resizing accordingly. But after I scroll and the cell goes off screen it updates to the correct size.
Because I am cropping the images and they can be portrait or landscape I am calculating the ratio of the image, unless they exceed a certain size then I set a constraint constant to a set size.
Here's some code to see what I am trying to do:
override func viewDidLoad() {
    self.myTableView.rowHeight = UITableView.automaticDimension
    self.myTableView.estimatedRowHeight = 500

}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.myTableView.reloadData()
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   cell.myImageView.sd_setImage(with: imageRef, placeholderImage: nil) { (downloadedImage, error, cache, url) in
       if let image = downloadedImage as? UIImage {
           let ratio = image.size.width / image.size.height
           var newHeight = cell.myImageView.frame.width / ratio

            if newHeight >= tableView.frame.width {
                newHeight = tableView.frame.width
            } else {
                newHeight = cell.myImageView.frame.width / ratio
            }

            cell.myImageHeightConstraint.constant = newHeight

            if let indexPath = tableView.indexPath(for: cell) {
                tableView.reloadRows(at: [indexPath], with: .none)
            }
        }
    }
}

Update:
I feel like I'm getting closer but still having some issues. Above I have modified the code. So right now when I make my new post and the table reloads, the cell resizes with a slight animation. That's fine. Preferably I'd like the user NOT to see the cell animate to the correct size. The next issue is when I scroll down some of the cells may need to resize and it causes some jumpiness.


text:
Q: Is there anyway to use BULK INSERT from .txt file and choose specific column to import into SQL? I have a .txt file that consists of around 80 columns and 1,900,000 rows. I want to import specific columns into SQL Server using BULK INSERT and make a new table but I kept getting an error that says the column format is wrong. I also need to keep NULLS since some columns have NULL. I created a new table that consists of all the columns that I chose out of the 80 columns. I tried to import this data through the Import and Export wizard and it took me around 10 hours which is strange, that is why I want to try importing it through query.
My code:
CREATE TABLE IM20190930
(
    FACILITY_NUMBER varchar(255),
    CUSTOMER_NUMBER varchar(255),
    BRANCH_CODE varchar(255),
    ACCOUNT_STATUS varchar(255),
    SEGMENT_RULE_ID varchar(255),
    PD_SEGMENT varchar(255),
    RATING_CODE varchar(255),
    EXCHANGE_RATE varchar(255),
    GROUP_SEGMENT varchar(255),
    DOWNLOAD_DATE varchar(255),
    OUTSTANDING varchar(255),
    BI_COLLECTABILITY varchar(255),
    DAY_PAST_DUE varchar(255)
)

BULK INSERT dbo.IM20190930
FROM 'c:\Users\Emily\Desktop\IM20190930.txt'
WITH
    (FIELDTERMINATOR=',',
     ROWTERMINATOR='|',
     KEEPNULLS)

A: You can use the FORMATFILE = 'format_file_path' option to specify the mapping between file source and table columns.
A format file can be expressed in text or XML.
From the doc


text:
Q: jpgraph x-axis scale in date(Gi) max 2359 not showing data When using the Jpgrap and set the x-axis scale to 2400
$graph->SetScale('intint',0,$max,0,2400);

Then insert data where format key is date('Gi'),Hour minute
$ydata = array(1820=>5000,1955=>1000,2315=>7500);
$lineplot=new LinePlot($ydata);

I do not get any line drawn. only when i use the swatch time (000 ~999) it shows the line.
$ydata = array(154=>5000,587=>1000,768=>7500);

Am i missing something?

A: Okey found the answer myself,
$graph->SetScale('intint',0,$max,0,2400);
$lineplot=new LinePlot($ydata);

needs to be:
$graph->SetScale('intint');
$graph->xaxis->SetTickLabels(array_keys($ydata));
$lineplot=new LinePlot(array_values($ydata));


text:
Q: No suitable driver found for jdbc:mysql://localhost:3306/Testing in JMETER JDBC connection configuration I am configuring JDBC Connection in jmeter 2.8. I am using MySQL database. And also placed mysql-connector-java-5.1.24-bin.jar in jmeter /lib directory.
Problem is when i run the sampler it gives a message

No suitable driver found for jdbc:mysql://localhost:3306/Testing

in Response data tab in Results Tree. I am using Ubuntu OS. Can any one help me out?

A: *

*First of all I would recommend switching to the latest available JMeter version which is 2.13 as for now as newer version will have a number defects fixed including performance upgrades.

*Second. Make sure that you have MySQL JDBC Driver aka Connector/J in JMeter's classpath. If you don't - download it, unpack and drop mysql-connector-java-x.xx.xx-bin.jar to JMeter's /lib folder. JMeter restart will be required to pick the library up

*Third. Make sure that you provide correct "JDBC Driver Class" in JDBC Connection Configuration. It should be
com.mysql.jdbc.Driver

*See The Real Secret to Building a Database Test Plan With JMeter guide for more details on how to setup JMeter for database load testing.

*Finally. Looking into "localhost" in your JDBC URL, it is not recommended to have load generator (JMeter) and application under test (MySQL) on the same machine, if there is a possibility - use different machines for JMeter and the database to keep results clean as JMeter can consume resources and impact MySQL performance and vice versa.

A: The point 2 is essential here:
"Second. Make sure that you have MySQL JDBC Driver aka Connector/J in JMeter's classpath. If you don't - download it, unpack and drop mysql-connector-java-x.xx.xx-bin.jar to JMeter's /lib folder. JMeter restart will be required to pick the library up"
Please be sure that .jar file is added directly to the lib folder.


text:
Q: A* Search in Python Priority Queue I am trying to write an A* search to solve a maze in Python, however I am struggling to find a built in priority queue that works for this. I am using PriorityQueue at the moment, but it offers no functionality in order to change an items priority, which is a problem in the commented section at the bottom of the algorithm (in the else if statement).
Does anyone have any idea what I could do in that else if block, or what built in priority queue would give me this functionality?
def A_search(maze, start, end):
expanded = 0 # use to track number of nodes expanded by the algorithm
node1 = Node(start,0)
frontier = PriorityQueue()
frontier.put((dist_to_goal(node1,end) + node1.get_cost(), node1))
visited = []
in_frontier = [] # keep track of items in frontier, PriorityQueue has no way to peek
in_frontier.append(node1)
while(True):
    if(frontier == []):
        return(None,expanded)
    curr = (frontier.get())[1]
    in_frontier.remove(curr)
    expanded += 1
    if(curr.get_loc() == end):
        return(curr,expanded)
    visited.append(curr.get_loc())
    neighbors = find_neighbors(maze, curr.get_loc())
    for neighbor in neighbors:
        node_n = Node(neighbor,node1.get_cost()+1)
        node_n.parent = curr
        if(neighbor not in visited) and (node_n not in in_frontier):
            frontier.put((dist_to_goal(node_n,end) + node1.get_cost(), node_n))
            in_frontier.append(node_n)
        # else if node_n is in frontier w/ a higher path cost then replace it w/ current

A: The closest you will find in the built-in libraries is heapq.
After changing the priority you need to call either heapq.heapify (costs O(n) time but will not change A* overall complexity) or use the internal heapq._siftdown function at O(log n) time.

A: Updating the item priority, is discussed in the official python documentation about the heapq module in the priority queue implementation notes: https://docs.python.org/3.7/library/heapq.html#priority-queue-implementation-notes
Using these notes, I managed to write my own PriorityQueue Implementation that supports adding a task and updating it's priority if it exists. It consists in using an entry_finder dict which point to tasks in the priority queue. Updating a task's priority, simply consists in marking the existing task as deleted and inserting it with the new priority.
In this implementation, you can use method add_task
class PriorityQueue():
    REMOVED = '<removed-task>'
    def __init__(self):
        self.pq = []
        self.entry_finder = {}
        self.counter = itertools.count()

    def add_task(self, task, priority=0):
        if task in self.entry_finder:
            self.remove_task(task)
        count = next(self.counter)
        entry = [priority, count, task]
        self.entry_finder[task] = entry
        heappush(self.pq, entry)

    def remove_task(self, task):
        entry = self.entry_finder.pop(task)
        entry[-1] = self.REMOVED

    def pop_task(self):
        while self.pq:
            priority, count, task = heappop(self.pq)
            if task is not self.REMOVED:
                del self.entry_finder[task]
                return task
        return None


text:
Q: How to show one row if it has more rows in inner join and left join query? I have more than one shop  in ps_shop table  and its some of shop have in ps_storeinfo table  but those shop of ps_shop table  are not in ps_storeinfo table  that are needed to insert into ps_storeinfo with user id and shop name. Here  shopname  of  ps_shop table  =  storename in  ps_storeinfo  table. Here I have written sql query for this and I am getting all data but problem is more than one user is coming by my SQL if it have more than one user. I need one user for one shop.
In ps_ employee_shop table user is assigned for shop base on shop id.  And In ps_ employee table is for user.  This is for prestashop 1.6.
My SQL is given below :
$table_prefix = _DB_PREFIX_;

'SELECT ps.*, pe.email, pe.firstname, pe.lastname, pes.id_employee,psi.storename
        FROM '.$table_prefix.'shop ps
        LEFT JOIN '.$table_prefix.'storeinfo psi  ON ps.name = psi.storename
        INNER JOIN '.$table_prefix.'employee_shop pes ON ps.id_shop = pes.id_shop
        INNER JOIN '.$table_prefix.'employee pe ON pes.id_employee = pe.id_employee where ps.id_shop <>1 and pe.id_employee <>1
         GROUP BY pes.id_employee
        ';

Output image is:

A: Well, if more than one entity exists in the table on the right side of the JOIN with the matching ON key any relational DB engine will return one row for each matching entity on the right side, duplicating the left side of the JOIN clause.
In the scenario described you need to decide which user you want to return. The first one sorted alphabetically? The one created most recently?
Based on the answer you will need to use a JOIN with a correlated subquery. Here's an example for getting the employee with the highest value of id_employee:
SELECT
    ps.*, pe.email, pe.firstname, pe.lastname, pes.id_employee,psi.storename
FROM
    '.$table_prefix.'shop ps
    LEFT JOIN '.$table_prefix.'storeinfo psi ON ps.name = psi.storename
    INNER JOIN (
        SELECT
            pe.email, pe.firstname, pe.lastname, pes.id_employee
        FROM
            '.$table_prefix.'employee pe
            '.$table_prefix.'employee_shop pes ON pes.id_employee = pe.id_employee
        WHERE
            pe.id_employee <> 1
            AND ps.id_shop = pes.id_shop
        ORDER BY
            pe.id_employee DESC
        LIMIT 1
    )
WHERE
    ps.id_shop <>1

As you can see what this is really doing is limiting the resulting list of employees to just one record to avoid duplication. In this case the list is ordered by id_employee, but the correct ordering depends on the business logic that needs to be implemented.


text:
Q: Handling of non-file URI According to the manual, Hyperlink "represents a hyperlink that jumps to the specified URI when clicked". OneNote produces hyperlinks that begin with onenote://. In Mathematica, creating a hyperlink to a OneNote page does not work. It returns a message: "The file that you tried to open was not found…"
According to the manual again,  "non-file URI open in a web browser". When I paste the onenote URI in my web browser, it opens the target.
1) Can you confirm this bug in Mathematica?
2) Does anyone know of a workaround?

Steps:
1) In OneNote right click on a page label and select Copy Link to Page. The clipboard contains something like:

onenote:///XXXX#Compound%20expressions,%20Get%20and%20Goto&page-id={7D74D7D4-
  E640-4217-9575-877E08975BED}&end

2) Create a text cell, put some text, select and press Ctrl+Shift+H. Paste the OneNote hyperlink.
3) Click in the hyperlink.

Update
Following this answer, running
Hyperlink["test", MathLink`CallFrontEnd[ FrontEnd`SystemOpen[
 "onenote:///\\\\myComputer\\The%20Notebook&page-id={7D74D7D4E640-4217-9575-877E08975BED}&end"]]]

creates a hyperlink that jumps correctly when it is created. If one clicks on the hyperlink, then nothing happens. On the other hand, running
Button["test", MathLink`CallFrontEnd[ FrontEnd`SystemOpen[
 "onenote:///\\\\myComputer\\The%20Notebook&page-id={7D74D7D4E640-4217-9575-877E08975BED}&end"]]]

creates a button with that works correctly.
I will report this as a bug to Wolfram (in the no so near future).

My workaround
For the sake of …, I'll post this workaround. It produces a hyperlink-looking button.
Button[Style["test","Hyperlink"], MathLink`CallFrontEnd[ FrontEnd`SystemOpen[
  "onenote:///\\\\myComputer\\The%20Notebook&page-id={7D74D7D4E640-4217-9575-877E08975BED}&end"]]
  , Appearance -> None]

A: I can reproduce the problem both on OS X and one Windows, but only with URIs of the form foo:something.  URIs of the form foo://something do work correctly, both with Hyperlink and with SystemOpen.  Your URI is of the :// form, so I am not sure why it doesn't work.
First, let's find out why some URIs don't work with SystemOpen.  Looking at the source of SystemOpen, it performs the following test to see if the string that was passed to it is a proper URI:
uriQ[s_String]:=Which[StringMatchQ[s,"mailto:*"],True,
                      StringMatchQ[s,"file:*"],True,
                      StringMatchQ[s,"paclet:*"],True,
                      StringMatchQ[s,"*://*"],True,True,False]

If the uriQ test returns False, it will auto-prepend file:// to the URI, which explains the error message you see.
The workaround is to pass the URI to the Front End for opening directly, without doing the uriQ test first:
openURI[uri_String] := MathLink`CallFrontEnd[FrontEnd`SystemOpen[uri]]

This works for any URI for me, both on Windows and Mac.
A replacement for Hyperlink is this:
URIlink[name_, uri_] :=
 Button[name, openURI[uri], BaseStyle -> "Hyperlink", Appearance -> "Frameless"]

Another workaround that is not cross-platform is this:

*

*On OS X, Run["open URI"]

*On Windows, Run["start \"\" \"URI\""]


text:
Q: upcoming date of birth issue in query before 1970 with unix time stamp with mysql I need help for this query
Now I am using unix time stamp for saving date of birth of user
I have this query for getting upcoming date of birth for users.
Its working only for after 1970 dob like  1986-09-18 (Y-m-d)
But Its not working before 1970 dob like 1969-09-18 (Y-m-d)
SELECT u.id, u.dob
FROM hrs_employee_details u
WHERE CONCAT( IF( MONTH( FROM_UNIXTIME( u.dob ) ) =1 AND MONTH( CURRENT_DATE( ) ) = 12, YEAR( CURRENT_DATE( ) ) +1, YEAR( CURRENT_DATE( ) ) ) , DATE_FORMAT( FROM_UNIXTIME( u.dob ) , '-%m-%d' ) )
BETWEEN CURRENT_DATE() AND DATE_ADD( CURRENT_DATE() , INTERVAL 14 DAY ) AND u.dob <> '' ;

Please help me ASAP
thanks in advance...

A: MySQL does not support UNIX timestamps for dates prior to 1970-01-01 00:00:00 UTC (i.e. negative timestamps). Function UNIX_TIMESTAMP returns unsigned integer values only and it is unlikely to change. Function FROM_UNIXTIME returns NULL for any negative argument.

A: As mentioned before, use DATE(TIME) fields for this, it's much easier to work with.
But to get the age of negative timestamps as well:
SELECT DATE_FORMAT(FROM_DAYS(TO_DAYS(NOW())-TO_DAYS(DATE_ADD(FROM_UNIXTIME(0), INTERVAL dob second))), '%Y')+0 AS age FROM hrs_employee_details


text:
Q: How long will a query with two "contains" tests take to execute on the appengine datastore? I have two sets of thirty or forty IDs, set A and set B.  I have a kind of entity that has a field idA (an id that might be in set A) and a field idB (an id that might be in set B).  I want to find all of the entities with idA in set A and idB in set B.
I could perform a query with filters like "A.contains(idA) && B.contains(idB)," but I worry about how much time this would take.  With 30 ids in A, a naive implementation might take 30 comparisons per non-matching entity in the datastore.  Or maybe the datastore sorts A and B before it goes looking, and will only take 4 or 5 comparisons per entity in the datastore.  Or, maybe there's something that google figured out that I haven't, that could quickly skip over entities.
Basically, I'm trying to figure out what the index for such a query looks like, and if this is a terrible kind of query to run.  Maybe it orders by idA, then by idB, and sorts A and B before the query is actually executed?
Main question: with 30-40 elements in A and B, will a query with filters "A.contains(idA) && B.contains(idB)" execute in a reasonable amount of time, or should I try to get this information another way?

A: You are limited to a list of at most thirty items. So this will not currently run on App Egnine, see the Query Filters section.

The contains() operator also performs multiple queries, one for each item in the provided list value where all other filters are the same and the contains() filter is replaced with an equal-to filter. The results are merged, in the order of the items in the list. If a query has more than 1 contains() filter, the query is performed as multiple queries, one for each combination of values in the contains() filters.
A single query containing != or contains() operators is limited to 30 sub-queries.

A: App Engine will expand your query into 30 * 40 = 1200 queries for individual combinations of idA and idB - or at least, it would, if it weren't limited to 30 sub-queries. Obviously, this isn't going to be very efficient.
Alternatives depend on the structure of your datastore. If you tell us what you're trying to achieve, we may be able to suggest alternatives that don't require so many queries.


text:
Q: In MySQL how to set index to the table? In MySQL how to use the Index concept for MySQL tables.

A: Syntax for adding index to existing table.
ALTER TABLE table_name ADD INDEX column_name

A simple example
CREATE TABLE employee_records (name VARCHAR(50), employeeID INT);
CREATE INDEX id_index ON employee_records(employeeID);

creating index while creating table
CREATE TABLE employee_records (
    name VARCHAR(50),
    employeeID INT, INDEX (employeeID)
);

A: To add an index to a table in MySQL:
ALTER TABLE [table name] ADD INDEX ([column name], ...);

A: ALTER TABLE table_name ADD INDEX index_name (col_name)
OR
CREATE INDEX index_name ON table_name(index_name)


text:
Q: Parsing XML files into Pandas dataframes Similar to this question I want to obtain a dataframe from an XML files. Here is my XML file and it is in the file "1.xml".
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE us-patent-application SYSTEM "us-patent-application-v44-2014-04-03.dtd" [ ]>
<us-patent-application lang="EN" dtd-version="v4.4 2014-04-03" file="US20200262283A1-20200820.XML" status="PRODUCTION" id="us-patent-application" country="US" date-produced="20200805" date-publ="20200820">
<us-bibliographic-data-application lang="EN" country="US">
<publication-reference>
<document-id>
<country>US</country>
<doc-number>20200262283</doc-number>
<kind>A1</kind>
<date>20200820</date>
</document-id>
</publication-reference>
<application-reference appl-type="utility">
<document-id>
<country>US</country>
<doc-number>16817919</doc-number>
<date>20200313</date>
</document-id>
</application-reference>
<us-application-series-code>16</us-application-series-code>
<classifications-ipcr>
<classification-ipcr>
<ipc-version-indicator><date>20060101</date></ipc-version-indicator>
<classification-level>A</classification-level>

B

<class>60</class>
<subclass>J</subclass>
11
<subgroup>04</subgroup>
<symbol-position>F</symbol-position>
<classification-value>I</classification-value>
<action-date><date>20200820</date></action-date>
<generating-office><country>US</country></generating-office>
<classification-status>B</classification-status>
<classification-data-source>H</classification-data-source>
</classification-ipcr>
</classifications-ipcr>
<classifications-cpc>

<classification-cpc>
<cpc-version-indicator><date>20130101</date></cpc-version-indicator>

B

<class>60</class>
<subclass>J</subclass>
11
<subgroup>04</subgroup>
<symbol-position>F</symbol-position>
<classification-value>I</classification-value>
<action-date><date>20200820</date></action-date>
<generating-office><country>US</country></generating-office>
<classification-status>B</classification-status>
<classification-data-source>H</classification-data-source>
<scheme-origination-code>C</scheme-origination-code>
</classification-cpc>

</classifications-cpc>
<invention-title id="d2e43">VEHICLE ROOF-MOUNTED SHADING APPARATUS</invention-title>
<us-related-documents>
<continuation>
<relation>
<parent-doc>
<document-id>
<country>US</country>
<doc-number>15598363</doc-number>
<date>20170518</date>
</document-id>
<parent-grant-document>
<document-id>
<country>US</country>
<doc-number>10625588</doc-number>
</document-id>
</parent-grant-document>
</parent-doc>
<child-doc>
<document-id>
<country>US</country>
<doc-number>16817919</doc-number>
</document-id>
</child-doc>
</relation>
</continuation>
<us-provisional-application>
<document-id>
<country>US</country>
<doc-number>62339148</doc-number>
<date>20160520</date>
</document-id>
</us-provisional-application>
</us-related-documents>
<us-parties>
<us-applicants>
<us-applicant sequence="00" app-type="applicant" designation="us-only" applicant-authority-category="assignee">
<addressbook>
<orgname>Shady Spot, Inc.</orgname>
<address>
<city>Piedmont</city>
<state>SC</state>
<country>US</country>
</address>
</addressbook>
<residence>
<country>US</country>
</residence>
</us-applicant>
</us-applicants>
<inventors>
<inventor sequence="00" designation="us-only">
<addressbook>
<last-name>Gurley</last-name>
<first-name>Winifred</first-name>
<address>
<city>Piedmont</city>
<state>SC</state>
<country>US</country>
</address>
</addressbook>
</inventor>
<inventor sequence="01" designation="us-only">
<addressbook>
<last-name>Gurley</last-name>
<first-name>Paul</first-name>
<address>
<city>Piedmont</city>
<state>SC</state>
<country>US</country>
</address>
</addressbook>
</inventor>
</inventors>
</us-parties>
<assignees>
<assignee>
<addressbook>
<orgname>Shady Spot, Inc.</orgname>
<role>02</role>
<address>
<city>Piedmont</city>
<state>SC</state>
<country>US</country>
</address>
</addressbook>
</assignee>
</assignees>
</us-bibliographic-data-application>
<abstract id="abstract">

A self-contained, self-extending, roof-mounted shading apparatus, capable of both vertical and horizontal movement to provide shade for a vehicle.

</abstract>
<drawings id="DRAWINGS">

</drawings>
<description id="description">
<?summary-of-invention description="Summary of Invention" end="lead"?>
<heading id="h-0001" level="1">BACKGROUND OF THE INVENTION</heading>
<heading id="h-0002" level="1">1) Field of the Invention</heading>

The present invention relates to a vehicle roof-mounted shading apparatus, capable of both vertical and horizontal movement, to shade a vehicle from the sun.

<heading id="h-0003" level="1">2) Description of Related Art</heading>

The interior of a car parked outdoors on a hot sunny day can reach very high temperatures in a short period of time. This drastic temperature increase is caused by a combination of hot temperatures outside the car and lack of proper ventilation for the hot air to escape from within and surrounding the exterior of the car. Ultraviolet radiation from the sun also enters through the windshields and windows and heats the air in the car. The front windshield may also act like a magnifying glass, intensifying sun rays.

These extreme conditions not only cause discomfort to the driver and passengers upon re-entering, but may also damage the interior of the car. Two methods that are normally used to reduce temperature build-up in a vehicle are tinting the windows or using sunshades. Tinting the window involves permanently installing a film on the window of the car. In some countries, this is not permitted by law.

There have been a number of efforts to cover parked cars and protect them from very high internal temperatures caused by the sun's rays. To date, these efforts all have had designs that make them best suited for long term parking because of the difficulties one would have in using the various systems. Most sit on the car surface, which is not good for the vehicle's finish and traps heat at the vehicle exterior.

Several efforts have tried to address all problems that could occur, such as rain, snow, hail, sleet, and wind as well as sun rays. Some devices have to be removed and stored in the trunk to operate the car. Other applications have to be wired into the car's electrical system or have parts welded onto the car roof or trunk or would need several people to deploy the device for use. For instance, Patel, U.S. Pat. No. 8,308,217, provides a sun shade for interior use of a vehicle. The shade includes a scissors type extension mechanism but lacks internally supported tubing and is incapable of both vertical and horizontal movement with respect to a vehicle.

While the present subject matter has been described in detail with respect to specific exemplary embodiments and methods thereof, it will be appreciated that those skilled in the art, upon attaining an understanding of the foregoing may readily produce alterations to, variations of, and equivalents to such embodiments. Accordingly, the scope of the present disclosure is by way of example rather than by way of limitation, and the subject disclosure does not preclude inclusion of such modifications, variations and/or additions to the present subject matter as would be readily apparent to one of ordinary skill in the art using the teachings disclosed herein.

<?detailed-description description="Detailed Description" end="tail"?>
</description>
<us-claim-statement>What is claimed is:</us-claim-statement>
<claims id="claims">
<claim id="CLM-01-19" num="01-19">
<claim-text>1.-19. (canceled)</claim-text>
</claim>
<claim id="CLM-00020" num="00020">
<claim-text>20. A system for providing shade comprising:
<claim-text>a device shell;</claim-text>
<claim-text>a vertical extension unit;</claim-text>
<claim-text>a horizontal extension unit;</claim-text>
<claim-text>a sunshade material;</claim-text>
<claim-text>at least one collapsible tube formed from nested segments; and</claim-text>
<claim-text>an extendable support positioned within the nested segments of the at least one collapsible tube.</claim-text>
</claim-text>
</claim>
<claim id="CLM-00021" num="00021">
<claim-text>21. The system of <claim-ref idref="CLM-00020">claim 20</claim-ref>, wherein the system includes at least one motor for vertical and horizontal movement.</claim-text>
</claim>
<claim id="CLM-00022" num="00022">
<claim-text>22. The system of <claim-ref idref="CLM-00020">claim 20</claim-ref>, wherein the extendable support is affixed to a distal segment of the at least one collapsible tube.</claim-text>
</claim>
<claim id="CLM-00023" num="00023">
<claim-text>23. The system of <claim-ref idref="CLM-00020">claim 20</claim-ref>, wherein the extendable support is a coiled strip.</claim-text>
</claim>
<claim id="CLM-00024" num="00024">
<claim-text>24. The system of <claim-ref idref="CLM-00020">claim 20</claim-ref>, wherein the device shell is hinged and includes a lid.</claim-text>
</claim>
<claim id="CLM-00025" num="00025">
<claim-text>25. The system of <claim-ref idref="CLM-00024">claim 24</claim-ref>, wherein the lid opens when the system raises vertically and closes when the system lowers vertically.</claim-text>
</claim>
<claim id="CLM-00026" num="00026">
<claim-text>26. The system of <claim-ref idref="CLM-00020">claim 20</claim-ref>, wherein vertical extension is achieved via at least one scissor bracket.</claim-text>
</claim>
<claim id="CLM-00027" num="00027">
<claim-text>27. The system of <claim-ref idref="CLM-00020">claim 20</claim-ref>, wherein the system includes at least two vertical extension units.</claim-text>
</claim>
<claim id="CLM-00028" num="00028">
<claim-text>28. The system of <claim-ref idref="CLM-00024">claim 24</claim-ref>, wherein a surface of the lid is contoured.</claim-text>
</claim>
<claim id="CLM-00029" num="00029">
<claim-text>29. The system of <claim-ref idref="CLM-00024">claim 24</claim-ref>, wherein the system may be solar powered, battery powered, or alternating current powered.</claim-text>
</claim>
<claim id="CLM-00030" num="00030">
<claim-text>30. The system of <claim-ref idref="CLM-00024">claim 24</claim-ref>, wherein the system comprises a woven or nonwoven material which contains ultraviolet ray protection.</claim-text>
</claim>
<claim id="CLM-00031" num="00031">
<claim-text>31. The system of <claim-ref idref="CLM-00024">claim 24</claim-ref>, wherein upon retraction of the sunshade material, the sunshade material is gathered by a cuff</claim-text>
</claim>
<claim id="CLM-00032" num="00032">
<claim-text>32. A method for deploying a canopy comprising:
<claim-text>storing a canopy within a device shell;</claim-text>
<claim-text>forming at least one collapsible tube comprising nested segments;</claim-text>
<claim-text>substantially vertically raising a vertical extension unit from the device shell; and</claim-text>
<claim-text>substantially horizontally extending, with respect to the device shell, an extendable support positioned within the nested segments of the at least one collapsible tube to extend and unfold the canopy.</claim-text>
</claim-text>
</claim>
<claim id="CLM-00033" num="00033">
<claim-text>33. The method of <claim-ref idref="CLM-00032">claim 32</claim-ref>, further comprising including at least one motor for vertical and horizontal movement.</claim-text>
</claim>
<claim id="CLM-00034" num="00034">
<claim-text>34. The system of <claim-ref idref="CLM-00032">claim 32</claim-ref>, further comprising affixing the extendable support to a distal segment of the at least one collapsible tube.</claim-text>
</claim>
<claim id="CLM-00035" num="00035">
<claim-text>35. The system of <claim-ref idref="CLM-00032">claim 32</claim-ref>, further comprising wherein the extendable support is a coiled strip.</claim-text>
</claim>
<claim id="CLM-00036" num="00036">
<claim-text>36. The system of <claim-ref idref="CLM-00032">claim 32</claim-ref>, further comprising forming the device shell to be hinged and to include a lid.</claim-text>
</claim>
<claim id="CLM-00037" num="00037">
<claim-text>37. The system of <claim-ref idref="CLM-00036">claim 36</claim-ref>, further comprising opening the lid when the vertical extension unit rises substantially vertically and closing the lid when the vertical extension unit lowers substantially vertically.</claim-text>
</claim>
<claim id="CLM-00038" num="00038">
<claim-text>38. The system of <claim-ref idref="CLM-00032">claim 32</claim-ref>, further comprising achieving vertical extension via at least one scissor bracket.</claim-text>
</claim>
<claim id="CLM-00039" num="00039">
<claim-text>39. The system of <claim-ref idref="CLM-00032">claim 32</claim-ref>, further comprising at least two vertical extension units.</claim-text>
</claim>
<claim id="CLM-00040" num="00040">
<claim-text>40. The system of <claim-ref idref="CLM-00032">claim 32</claim-ref>, further comprising contouring a surface of the lid.</claim-text>
</claim>
</claims>
</us-patent-application>

And here is my code following the first answer to the above mentioned question.
import pandas as pd
import xml.etree.ElementTree as ET

def iter_docs(author):
    author_attr = author.attrib
    #print(author.attrib)
    for doc in author.iter():

        doc_dict = author_attr.copy()
        doc_dict.update(doc.attrib)
        doc_dict['data'] = doc.text
        print(doc_dict)
        yield doc_dict

etree = ET.parse("1.xml") #create an ElementTree object
doc_df = pd.DataFrame(list(iter_docs(etree.getroot())))

print(doc_df.head())

However most of the columns of the data frame are NaN, not to mention that there should be only one row. I think this is because this file has a more complicated format than the one in the referred question. How should I modify the Python code?

A: I have a partial solution you can further look into.
First of all, I don't think the resulting dataframe will have just one row.
You can use pandas-read-xml package
pip install pandas-read-xml

import pandas_read_xml as pdx
from pandas_read_xml import fully_flatten

df = pdx.read_xml('1.xml').T

Will read in the XML file.
If you want to "flatten the data"
df = pdx.read_xml('1.xml').T.pipe(fully_flatten)

will create additional columns and rows as it flattens the data.
Note: If you are working with multiple XML files, say in a ZIP file, you can read all of the XML files at once.
df = pdx.read_xml('patents.zip').T


text:
Q: What part of speech is "how" in "He did not know how he ought to behave"? This is an example under the definition of how in the Oxford Advanced Learner's Dictionary.

He did not know how he ought to behave.

The dictionary lists how as an adverb. I understand this is because it modifies the verb behave, but I think it acts as a noun here.
Suppose we change how to the way.

He did not know the way he ought to behave.

The meaning is still the same, but it looks like the way acts as a noun phrase here.
So, are both how and the way adverbs in this situation or are they nouns? If they are neither, what are they?

A: It's a subordinating conjunction there.
Merriam-Webster "how" conj. 1a
the way or manner in which
asked how they could help
The substitution you made does mean the same thing. It's a reduction of "the way that he ought to behave", which is a noun phrase modified by a subordinate clause.

A:
He did not know [how he ought to behave].

"How" is an adverb here, but it doesn't modify the verb "know".
The bracketed element is an interrogative clause (embedded question) functioning as complement of "know". The meaning is deontic, i.e. it doesn't mean whether he ought to behave but indirectly questions the manner in which he ought to behave.
Thus, the meaning is:
"He did not know the answer to the question 'How ought he to behave?'"
In your suggested alternant
He did not know [the way he ought to behave].
Again the bracketed element is an interrogative clause. It's not a question of not being familiar with the way he ought to behave, but of not knowing how to cognitively find the answer to the question "In what way ought he to behave?"


text:
Q: What is the strategy of query evaluation in DBMS when Limit is used in query? I have following tables in database
post(post_id , user_id , post_text , parsed_text) ;
Comment(comment_id , post_id , user_id , comment_text) ;
friend(id , user_id , friend_id ) ;
group (id , user_id ,group_id ) ;
like  (id, user_id , page_id ) ;

SQL to retrieve data from posts
 $posts =  mysql_query("select * from post where user_id in
(select f_id  from ((select friend_id as f_id from friend  where user_id = 'a')
union (select group_id as f_id  from group  where user_id = 'a')
union (select page_id as f_id   where user_id = 'a'  ))) order by post_id limit 0 , 30");

In these table there are BTREE index on post_id in post table , comment_id in comment table and  id in like , friend , share table ?
How DBMS evaluates this query to get 30 rows .
Is there any way to retrieve data from database from bottom  of the table ? Bottom in the sense id is auto increment so i need to retrieve data from database as
If table has id 'N' then it should start retrieving data as
first 'n-1' th'tupple ,second  'n-2' th tupple ,third 'n-3' th tupple and so on
without using 'ORDER BY' .

This can reduce time complexity for above query .

A: Simplifying down to the post table, for discussion.
Create a unique index on the post_id.
CREATE UNIQUE INDEX recent_post_id ON post(post_id)

Then query the data as such:
SELECT *
FROM post
WHERE user_id IN (your criteria)
ORDER BY post_id DESC
LIMIT 30

Of course, the most overhead may well be your nested collection of rows that you UNION together to get the criteria for recent posts.


text:
Q: Write multiple lines to file without using writelines() in Python3 I am trying to write multiple lines in a file using python, but without using writelines()
For now I planned to do so:
header = ('-' * 42 +
      '\nCREATION DATE: {}\n' +
      'HOSTANME: {}\n' +
      'PYTHON VERSION: {}\n' +
      'SYSTEM: {}\n' +
      'SYSTEM VERSION: {}\n' +
      'SYSTEM RELEASE: {}\n' +
      'MACHINE: {}\n' +
      'PROCESSOR: {}\n' +
      '-' * 42)

file.write(header)

But I don't know if it's the best way to do it.
Thanks in advance.

A: Maybe use a dictionary:
stuff = {
    "CreationDate": "some_date",
    "HostName": "some_host_name",
    "PythonVersion": "some_version",
    # ...
    'Processor': "some_processor"
}

Then your data is stored in a nice, organized fashion. After that, you just need to write some kind of function to convert the dictionary to a string similar to your desired output. Something like this:
header = str()

for key, value in stuff.items():
    header += f'{key}: {value}\n' # use str.format() if don't have f-string support

file.write(f'{'-'*42}\n{header}{'-'*42}')

Hopefully that helps! :)

A: In this situation I would normally use '\n'.join(). You can pass any iterable of strings to '\n'.join() - this of course includes things like list comprehensions and generator comprehensions.
For example, using the dict in Andrew Grass's answer, we could make his example more compact, if that's what you prefer:
header = '\n'.join((f'{key}: {value}' for key, value in stuff.items()))
file.write('\n'.join(('-' * 42, header, '-' * 42)))

Of course, you could go further and put it onto one line, but in my opinion that would be too unreadable.
Here's a similar solution which is compatible with Python 3.5 and below (f-strings were introduced in Python 3.6). This is even more compact, but perhaps slightly harder to read:
header = '\n'.join(map("{0[0]}: {0[1]}".format, stuff.items()))
file.write('\n'.join(('-' * 42, header, '-' * 42)))

You could use itertools.starmap to make that last example a bit prettier:
from itertools import starmap

header = '\n'.join(starmap("{}: {}".format, stuff.items()))
file.write('\n'.join(('-' * 42, header, '-' * 42)))


text:
Q: php Imagemagick jpg black background I have a php script to create jpg thumbnail of pdf as follows;
<?php
$file ="test.pdf";
$im = new imagick(realpath($file).'[0]');
$im->setImageFormat("jpg");
$im->resizeImage(200,200,1,0);
// start buffering
ob_start();
$thumbnail = $im->getImageBlob();
$contents =  ob_get_contents();
ob_end_clean();
echo "<img src='data:image/jpg;base64,".base64_encode($thumbnail)."' />";
?>

But the resulting jpg have black background instead of white.. How can I fix this??

A: None of the previously posted answers worked for me however the below did:
$image = new Imagick;

$image->setResolution(300, 300);

$image->readImage("{$originalPath}[0]");

$image->setImageFormat('jpg');

$image->scaleImage(500, 500, true);

$image->setImageAlphaChannel(Imagick::VIRTUALPIXELMETHOD_WHITE);

As I'm using the Laravel framework I then take the converted image and store it using Laravels filesystem.
Storage::put($storePath, $image->getImageBlob());

Update: So I recently changed OS and whereas this previously worked on my Ubuntu machine on my Mac certain images were still coming out black.
I had to change the script to the below:
$image = new Imagick;

$image->setResolution(300, 300);

$image->setBackgroundColor('white');

$image->readImage("{$originalPath}[0]");

$image->setImageFormat('jpg');

$image->scaleImage(500, 500, true);

$image->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);

$image->setImageAlphaChannel(Imagick::ALPHACHANNEL_REMOVE);

Seems important to set the background colour before reading in the image. I also flatten any possible layers and remove the alpha channel. I feel like I tried ALPHACHANNEL_REMOVE on my Ubuntu machine and it didn't work so hopefully between these answers readers can find something that works for them.

A: If your version of Imagick is not up to date, the setImageBackgroundColor may be wrong.
Swap the following line
$im->setImageBackgroundColor("red");

to this (Imagick version >= 2.1.0)
$im->setBackgroundColor(new ImagickPixel("red"));

or (Imagick version < 2.1.0)
$im->setBackgroundColor("red");

A: I solved it by;
$im = new imagick(realpath($file).'[0]');
$im->setCompression(Imagick::COMPRESSION_JPEG);
$im->setCompressionQuality(100);
$im->setImageFormat("jpeg");
$im->writeImage("imagename.jpg");

A: Simply adding this prevents the JPG to be created with a black background
-alpha off

A: change this code $im->setimageformat("jpg"); to this code
$im->setimageformat("png"); if you face a background colour issue.

A: Just use flattenImages() right after creating a new imagick():
$im = new Imagick('file.pdf[0]');
$im = $im->flattenImages();

Edit: The flattenImages method has been deprecated & removed. Use
$im = $im->mergeImageLayers( imagick::LAYERMETHOD_FLATTEN );

A: After endless attempts to append a pdf file with a jpeg image without getting black areas, I found the solution: the function transformImageColorspace
Used in this order works perfectly:
$im = new Imagick();
$im->readImage("file.pdf");

$im->transformImageColorspace(Imagick::COLORSPACE_SRGB);

$im->setImageFormat('jpeg');
$im->writeImage('image.jpg');

A: I would like to add to the excellent and helpful answers by saying that a slightly different approach is required if your PDF has multiple pages.
Something I was surprised to discover is that the Imagick class implements Iterable, which means you can run it through a foreach loop and operate on each page in turn (which it turns out is necessary because the layer, colour, and alpha channel changes appear to only take effect on the last page) which will be presented to you as a separate Imagick object:
$im = new Imagick('path/to/file.pdf');
foreach ($im as $c => $page)
{
    // do what you need to do with each page and then...
    $im->writeImage('path/to/image-'.$c.'.jpg');
}


text:
Q: Share xampp on lan I just installed XAMPP 7.2.5 on my Windows 10 x64 computer.
When I type localhost in my browser, i go into XAMPP dashboard page and anything is OK.
I want to access dashboard page (htdocs folder actually) from other devices in same network (LAN), but cannot do this!
I have static IP address on this PC (192.168.1.100), when i type this IP address in browser of my Android phone (or another windows pc on local network), and get this error: "192.168.1.100 is unreachable"
I tried this solutions but not helped:

*

*Turn off windows defender firewall (I have not any Antivirus but
Default windows defender)

*Add exception for tcp 80 port to inbound firewall rules
I search the internet and stackoverflow for 5 hours but noting found!
I tried lot of solutions about httpd.conf but nothing help me.

EDIT
I run XAMPP Control Panel with administrator permission, Now i can access htdocs from other windows computer, but still cannot access it from Android device!

A: It's the solution worked for me:

*

*Disable your UAC from control panel (Low Level - Don't warn).

*Run XAMPP control panel as Administrator.


text:
Q: Accessing Fragment's views after inflating What I need to achieve
A screen displaying a ListView, which can be replaced by an error screen in case of problems  (missing connection, server unavailable and the like).
I need to be able to switch (programmatically) back and forth between these two screens.
Requirements
The main screen must be a Fragment.
This is because my application is composed of several sections, each one accessible from the navigation drawer.
What I have done so far
The main fragment class is named AllQueuesFragment: its XML layout consists of a FrameLayout, which I use in combination with the FragmentManager to switch between ErrorFragment (containing the error message) and QueuesViewFragment (containing the ListView).
public class AllQueuesFragment extends Fragment
{
    public AllQueuesFragment()
    {
        super();
    }

    @Override
    public void onStart()
    {
        super.onStart();

        // Show the right fragment based on connectivity status
        checkConnection();
    }

    public void checkConnection()
    {
        final NetworkManager netManager = NetworkManager.getInstance(this.getActivity());

        if (netManager.isConnected())
            showQueues();
        else
            showNoConnection();
    }

    public void showNoConnection()
    {
        ErrorFragment fragNoConnection = new ErrorFragment();
        displayFragment(fragNoConnection);

        fragNoConnection.setTitle(R.string.text_no_connection);
        fragNoConnection.setIcon(R.drawable.thatfeel);
        fragNoConnection.setLoaderVisibility(false);
    }

    public void showQueues()
    {
        QueuesViewFragment fragQueuesView = new QueuesViewFragment();
        displayFragment(fragQueuesView);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        // Inflate the view
        View rootView = inflater.inflate(R.layout.fragment_allqueues, container, false);

        return rootView;
    }

    // Displays a new fragment
    public void displayFragment(Fragment fragment)
    {
        if (fragment != null)
        {
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
        }
    }
}

The error screen is the following:
public class ErrorFragment extends Fragment
{
    private TextView textTitle;

    public ErrorFragment()
    {
        super();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        // Inflate the view
        View rootView = inflater.inflate(R.layout.fragment_error, container, false);

        // Get the widgets
        textTitle = (TextView)rootView.findViewById( R.id.fragment_error_text );

        return rootView;
    }

    // Set methods
    public void setTitle(int id) { textTitle.setText(id); }
}

The problem
The setTitle() method gets called before the layout is ready, and as a result, a NullPointerException is thrown.
class AllQueuesFragment
{
    ....

    public void displayFragment(Fragment fragment)
    {
        if (fragment != null)
        {
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
        }
    }

    public void showNoConnection()
    {
        ErrorFragment fragNoConnection = new ErrorFragment();
        displayFragment(fragNoConnection);

        // PROBLEM HERE: Before calling setTitle(), I must be sure that ErrorFragment's
        // layout is inflated!
        fragNoConnection.setTitle(R.string.text_no_connection);
    }

    ....
}

class ErrorFragment
{
    ....
    public void setTitle(String value) { textTitle.setText(value); }
    ....
}

I can't call setTitle() directly from ErrorFragment::onCreateView(), because I don't know beforehand which message I need to show.
How can I ensure that fragNoConnection has completed its layouting?
Is there a better way to achieve my goal?
Unsatisfying workaround
The only workaround I can think of is to use a buffer to defer the actual call:
class ErrorFragment
{
    // This string will hold the title until the layout is inflated
    private String titleBuffer;
    private TextView textTitle = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        // Inflate the view
        View rootView = inflater.inflate(R.layout.fragment_error, container, false);

        // Get the widgets
        textTitle = (TextView)rootView.findViewById( R.id.fragment_error_text );

        // Do the actual set
        setTitle(titleBuffer);

        return rootView;
    }

    ....

    public void setTitle(String value)
    {
            titleBuffer = value;

            // If the layout is not inflated, defer the actual set
            if (textTitle != null)
                    textTitle.setText(titleBuffer);
    }
    ....
}

but I don't like this solution very much (the code above is simplified; ErrorFragment has more properties).
Advices?
Thanks in advance

A: You need to have a callback method in your ErrorFragment and when the view is inflated you then call the method in your callback interface in the onViewCreated and set the title.
sample:
in ErroFragment
 public class ErroFragment extends Fragment
{
    static interface ErrorDone{
        public void doneInflating();
    }

    private TextView textTitle;
    private ErrorDone ed;

    public ErroFragment()
    {
        super();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        // Inflate the view
        View rootView = inflater.inflate(R.layout.fragment_error, container, false);

        // Get the widgets
        textTitle = (TextView)rootView.findViewById( R.id.fragment_error_text );

        return rootView;
    }

    // Set methods
    public void setTitle(int id) { textTitle.setText(id); }
    public void setInterFace(ErrorDone er){ this.ed = er; }
}

Then you implement the interface in your AllQueuesFragment
 public class AllQueuesFragment extends Fragment implements ErroFragment.ErrorDone

It will generate method doneInflating
and you need to set the interface:
 public void showNoConnection()
 {
        ErrorFragment fragNoConnection = new ErrorFragment();
        displayFragment(fragNoConnection);
        fragNoConnection.setInterFace(this);
 }

And in the generated method(doneInflating) of the AllQueuesFragment you then set the title in there:
public void doneInflating(){
        fragNoConnection.setTitle(R.string.text_no_connection);
        fragNoConnection.setIcon(R.drawable.thatfeel);
        fragNoConnection.setLoaderVisibility(false);
}

A: This is exactly the type of thing arguments are supposed to be used for:
public void showNoConnection() {
    ErrorFragment fragNoConnection = new ErrorFragment();
    Bundle args = new Bundle();
    //you can also use putInt here if you'd rather pass a string resource id, along with anything else you can stick into a Bundle
    args.putString("title", "some title");
    fragNoConnection.setArguments(args);
    displayFragment(fragNoConnection);
}

Then in ErrorFragment
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_error, container, false);

    TextView textTitle = (TextView)rootView.findViewById( R.id.fragment_error_text );
    //now retrieve the argument...
    textTitle.setText(getArguments().getString("title"));

    return rootView;
}

The Fragment will even remember it's arguments after an orientation change.
If you feel like being pedantic, you can create a static factory method within ErrorFragment that takes the title as an argument and then creates the Fragment and adds the argument, that way you can achieve proper encapsulation :)

A: If you want to be sure that the FragmentTransaction is commited and effective, you can use the executePendingTransactions method:
    FragmentManager fragmentManager = getFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
    fragmentManager.executePendingTransactions();

But,  the right way to do it is to send the title value to the Fragment when instantiating it. This is the default pattern when you create a Fragment from your IDE (eclipse or Android Studio)


text:
Q: Data Access Layer: Exposing List<>: bad idea? I am currently coding a simple Data Access Layer, and I was wondering which type I should expose to the other layers.
I am going to internally implement the Data as a List<>, but I remember reading something about not exposing the List type to the consumers if not needed.
public List<User> GetAllUsers() // non C# users: that means List of User :)

Do you know why (google didn't help)? What do you usually expose for that kind of stuff? IList? IEnumerable?

A: Usually it's best to expose the least powerful interface that the user can still meaningfully work with. If the user just needs some enumerable data, return IEnumerable<User>. If that's not enough because the user needs to be able to modify the list (attention! shouldn't often be the case), return an IList<User>.
/EDIT:
Joel asks a valid question in his comment: Why indeed expose the least powerful interface instead of granting the user maximum power? (paraphrased)
The idea behind this is that the method returning the data might not expect the user to modify its content: Another method of the class might still expect the list to be non-empty after a reference to it was returned. Imagine the user removes all data from the list. The other method now has to make an additional check that ele might have been unnecessary.
More importantly, this exposes parts of the internal implementation through the return type. If I need to change the implementation in the future so that it no longer uses an IList container, I have a problem: I either need to change the method contract, introducing a build-breaking change. Or I need to copy the data into a list container.
As an example, imagine that an efficient implementation uses a Dictionary and just returns the Values collection which doesn't implement IList.

A: Definitely an ISomething.  Using an interface will reduce coupling and make it easier to change details of your data layer's implementation down the road.  Which interface depends on the circumstances.  IList is good, but sometimes you may need ICollection functionality or want to specify values that are ReadOnly.

A: You should think carefully before returning IEnumerable. If the underlying code is using "yield" to generate the IEnumerable, or is using LINQ, then you'll end up holding open any resources used.
You should copy the IEnumerable into another IEnumerable before returning it. By using IList, you make this a requirement, so that nobody can inadvertently return an IEnumerable.
On the other hand, returning an IList implies to the caller that they can change the returned list.


text:
Q: Passing 2D array and vector of string as argument to function I have written two function in which I am passing vector of string to a particular function (PrintStringVector) just to print content and in second function, passing the array of pointers to print the content.The first function is working fine but second one is giving error which is below the my code.
#include <cmath>
#include <stdlib.h>
#include <cstdio>
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int n;

void PrintStringVector(vector<string> & v){

    for(int i=0;i<v.size();i++){ cout<<v[i]<<endl;}

}

void PrintStringArray(const char *arr[n]){

    for(int i=0;i<n;i++){ cout<<arr[i]<<endl;}

}

int main() {

    vector<string>  vec;
    cin>>n;
    const char *arr[n];

    for(int i=0;i<n;i++){
        string str;
        cin>>str;
        vec.push_back(str);
        arr[i]=str.c_str();
    }

    PrintStringVector(vec);
    PrintStringArray(arr);

    return 0;
}

ERRORS:
        vinod@vinod-Inspiron-3537:~/Documents/hackerrank$ g++       passing_vector_of_string_or_passing_2d_array.cpp
        passing_vector_of_string_or_passing_2d_array.cpp:17:35: error: expected ',' or '...' before 'arr'
        void PrintStringArray(const char* arr[n]){
                                           ^
        passing_vector_of_string_or_passing_2d_array.cpp: In function 'void PrintStringArray(const char*)':
        passing_vector_of_string_or_passing_2d_array.cpp:19:33: error: 'arr' was not declared in this scope
        for(int i=0;i<n;i++){ cout<<arr[i]<<endl;}
                                         ^
        passing_vector_of_string_or_passing_2d_array.cpp: In function 'int main()':
        passing_vector_of_string_or_passing_2d_array.cpp:40:25: error: cannot convert 'const char**' to 'const char*' for argument '1' to 'void PrintStringArray(const char*)'
        PrintStringArray(arr);

A: In C++ you cannot have VLA (variable length arrays). Since the size of the array arr is only known at runtime you cannot use it as a size of a fixed size array. You should use new to allocate it. E.g.
const char **arr = new const char*[n];

Also modify the function signature like this
void PrintStringArray(const char *arr[]){

or like this
void PrintStringArray(const char **arr){

Finally remember to delete arr once you are finished with it.
delete[] arr;

A: const char *arr[n]

This is not a valid declaration (unless n is a constant expression). C++ has no variable length arrays.
"But it works for me inside main!'
That's because g++ implements an extension to C++. This extension does not seem compatible with C variable-length arrays, and is generally buggy. Don't use it.
"But how can I have comparable functionality?"
Use std::vector. Do not use pointers, new[] and delete[] unless you know extremely well why you need these low-level primitives.


text:
Q: Allow update on single field in firestore I want to give a user the right to update a document. But ONLY if the user updates one specific field of this document. All other fields shouldn't be changed by this user.
Is this possible in firestore?
I tried something like this:
function isUpdateToOpenField(attr) {
    return attr == get(/databases/$(database)/documents/stores/$(store)).data.open;
}

allow update: if isUpdateToOpenField(request.resource.data);

But I don't know how to compare if the update corresponds to the right field.

A: You can use :
allow update: if request.resource.data.diff(resource.data).affectedKeys().hasOnly(["fieldToBeUpdated"]);

OR
allow update: if request.resource.data.diff(resource.data).affectedKeys() == ["fieldToBeUpdated"].toSet;

You can replace affectedKeys() with addedKeys() , removedKeys() or changedKeys() depending upon your use case.
affectedKeys() as the name suggests is equivalent to using all the three together.
For more details please read the docs here https://firebase.google.com/docs/reference/rules/rules.MapDiff

A: Since writeFields is deprecated and should not be used, you will have to examine request.resource.data.  However, it always contains all of the fields of the written document (it's final state).  This means that you will have to compare all of the fields of the written document to the fields of the original document in resource.data in order to make sure that only the ones that changed are the ones that you allow to be changed.
Currently this requires an explicit check for every field that could possibly be written, which is not fun to implement.  The Firebase team is looking into ways of making this sort of rule easier to express by allowing you to diff the data maps of the "before" and "after" documents.

A: Since request.resource.data will show the future object after the write - the only way is to check every field using the following:
   function notUpdating(field) {
     return !(field in request.resource.data)
      || resource.data[field] == request.resource.data[field]
   }

   allow update: if notUpdating('title') && notUpdating('description')

Make sure you validate that the user doesn't update all of the fields except the field you want him to have access to

A: Map diffs in the Rules language were introduced to solve this:
function isUpdateToOpenField() {
    return request.resource.data.diff(resource.data).affectedKeys().hasOnly(['open']);
}

allow update: if isUpdateToOpenField();

A: Update: Instead of writeFields, you can now use Map.diff()
Check out the writeFields variable for security rules:
allow update: if ((request.writeFields.size() == 1) && ('open' in request.writeFields));

A: the same answer of "Scott Crossen" with little change, to be more genric

function isUpdateToOpenField(attr) {
    return request.resource.data.diff(resource.data).affectedKeys().hasOnly([attr]);
}

allow update: if isUpdateToOpenField('open');


text:
Q: Position DIV below fixed div with variable height Here is the Problem:
Lets say I have something like this:

And I would like to have the #below div, below the #top div, but not use margin-top, since the #top div will have different sizes.
Also, the #below div can vary in size, and should scroll beneath the #top div.
Does anybody have an idea how to realize that?
Greets - Chris

A: This is fairly simple with jQuery if the top div's height is fixed after the page renders.
$(document).ready(function() {
    $('#below').css('top', $('#top').outerHeight());
});

That will assign the css top property of the below element equal to the full height of the top element. Other layout factors may cause that to not be the correct value for top, in which case you'll have to determine the correct way to identify the top value, but the principal is the same and in the simple case, this will work without modification.

A: This is the same answer as @hemp, just with the addition of the div constantly updating it's position, by putting the jquery-css inside a function that runs when you resize.
    $(document).ready(function() {
        function SomeFunction() {
            $('#below').css('top', $('#top').outerHeight());
        }
        window.onresize = SomeFunction;
    });

A: I have created this jquery plugin to solve a similar issue I was having where I had a middle container (tabular data) and I wanted the header to fix to the top of the page when the list was scrolled (the list is variable size).  One of the issues was, when the header became fixed, the content below it would jump up the page (not good).  This plugin compensates for the "fixed" element and allows the content below it to position and scroll as it should.
Here is the link to this jquery plugin that may solve this problem:
https://github.com/bigspotteddog/ScrollToFixed
The description of this plugin is as follows:
This plugin is used to fix elements to the top of the page, if the element would have scrolled out of view, vertically; however, it does allow the element to continue to move left or right with the horizontal scroll.
Given an option marginTop, the element will stop moving vertically upward once the vertical scroll has reached the target position; but, the element will still move horizontally as the page is scrolled left or right. Once the page has been scrolled back down passed the target position, the element will be restored to its original position on the page.
This plugin has been tested in Firefox 3/4, Google Chrome 10/11, Safari 5, and Internet Explorer 8/9.
Usage for your particular case:

$(document).ready(function() {
    $('#top').scrollToFixed();
});


text:
Q: Not able to create an XStream Outbound Server in Oracle for the Debezium Kafka Connector I am following the instructions in the Official Debezium Documentation for Oracle Kafka connector. In the step where I have to create an outbound server, it throws the following exception:
ORA-65024: Pluggable database  is not open

I have successfully followed all the previous steps in the link. But, being fairly new to Oracle, I failed to come to a conclusion by googling this error. I am using the following command in the SQL Plus to do so which throws the aforementioned error while logged in as c##xstrmadmin user as a sysdba:
DECLARE
  tables  DBMS_UTILITY.UNCL_ARRAY;
  schemas DBMS_UTILITY.UNCL_ARRAY;
BEGIN
    tables(1)  := NULL;
    schemas(1) := 'debezium';
  DBMS_XSTREAM_ADM.CREATE_OUTBOUND(
    server_name     =>  'dbzxout',
    table_names     =>  tables,
    schema_names    =>  schemas);
END;
/

I also created a new Pluggable Database which is open in this case. I haven't yet applied for the GoldenGate Licence. Might there be a chance that this error is due to the unavailability of the licence? If so, any link which provides a trial version of GoldenGate setup and its instructions would be highly recommended. Trial version because we are currently using it for testing.
Tried the above in Oracle 18c and 12c

A: alter pluggable database ORCLPDB1 open;


text:
Q: Error: Actions must be plain objects. Use custom middleware for async actions. How to solve it? I am having this error in react-redux. I don't know how to solve it. I wanted to send a param which is taken from an api to another api and fetch results.
This is my store
import { createStore, applyMiddleware, compose } from "redux";
import thunk from "redux-thunk";
import { composeWithDevTools } from "redux-devtools-extension";
import rootReducer from "./Reducers/rootReducer";

const store = createStore(
  rootReducer,
  {},
  compose(applyMiddleware(thunk), composeWithDevTools())
);

export default store;

This is my reducer code:
import * as types from "../Actions/types";

const initialState = {
  posts: [],
  table: [],
};

const postReducer = (state = initialState, action) => {
  switch (action.type) {
    case types.FETCH_DATA:
      return {
        ...state,
        posts: action.payload,
      };
    case types.FETCH_TABLE:
      return {
        ...state,
        table: action.payload,
      };
    default:
      return {
        ...state,
      };
  }
};

export default postReducer;

This is my action code
export const getData = (from_userpart) => async (dispatch) => {
  try {
    const { data } = await api.getData(from_userpart);
    dispatch({
      type: types.FETCH_TABLE,
      payload: data,
    });
  } catch (error) {
    console.log(error);
  }
};

When i use this code on the parent component,it works but i want to use that in my child component but it gives this error as i mentioned on the label. How to solve that?
useEffect(() => {
    dispatch(getData(phone));
  }, [dispatch]);

A: Change the setting of your store, your enhancer should come second.
let composeEnhancers = null
if (process.env.NODE_ENV === 'development') {
  composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose
} else {
  composeEnhancers = compose
}
const store = createStore(
  rootReducer,
  composeEnhancers(applyMiddleware(thunk))
);

A: I've noticed that i had imported my function from api folder not the action one. It works now


text:
Q: How to use local push notification in cocos2d-x I am making a game using cocod2d-x, i am a beginner so i don't know how to push local notification in my game.
Can you help me resolve this problem?
Thanks all.

A: to set a local notification in Ios, you have to edit applicationDidEnterBackground method in  your appcontroller.mm class.. take a look at the code below...
- (void)applicationDidEnterBackground:(UIApplication *)application {

    NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];

    // Get the current date
    //NSDate *pickerDate = [self.datePicker date];
    NSDate *now = [NSDate date];
    //NSCalendar *calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];

    // Break the date up into components
    NSDateComponents *dateComponents = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit )
                                                   fromDate:now];
    NSDateComponents *timeComponents = [calendar components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit )
                                                   fromDate:now];

    // Set up the fire time

    NSDateComponents *dateComps = [[NSDateComponents alloc] init];
    [dateComps setDay:[dateComponents day]];
    [dateComps setMonth:[dateComponents month]];
    [dateComps setYear:[dateComponents year]];
    [dateComps setHour:[timeComponents hour]];
    [dateComps setMinute:[timeComponents minute]+_notificationTimeMinutes];
    [dateComps setSecond:([timeComponents second]+_notificationTimeSeconds)];
    NSDate *itemDate = [calendar dateFromComponents:dateComps];
    [dateComps release];

    UILocalNotification *localNotif = [[UILocalNotification alloc] init];
    if (localNotif == nil)
        return;
    localNotif.fireDate = itemDate;
    localNotif.timeZone = [NSTimeZone defaultTimeZone];

    localNotif.alertBody=@"Your local notification message";
    // Set the action button
    localNotif.alertAction = @"View";
    NSLog(@"setAlarm Called : %@",itemDate);
    //localNotif.hasAction = NO;
    localNotif.soundName = UILocalNotificationDefaultSoundName;
    localNotif.applicationIconBadgeNumber = [UIApplication sharedApplication].applicationIconBadgeNumber+1;
    localNotif.repeatInterval = NSWeekCalendarUnit;
    //[UIApplication sharedApplication].applicationIconBadgeNumber += 1;
    // Specify custom data for the notification
    NSDictionary *infoDict = [NSDictionary dictionaryWithObject:@"someValue" forKey:@"someKey"];
    localNotif.userInfo = infoDict;

    // Schedule the notification
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
    [localNotif release];

In above code _notificationTimeSeconds is in seconds and _notificationTimeMinutes is in minutes similarly you can add hours and days or months after which you want your notification to appear.. you add your message in "your local notification message"


text:
Q: JavaScript - Forms - Validating numbers and email I am not great with scripting or coding, so I'm really sorry if this is a silly question.
I have a form:
<form name="userinfo" action="validform.html" method="post" onsubmit="return validateForm()">
    <fieldset>
        <legend>Personal Information</legend>

        First Name:
        <input type="text" id="firstname" name="firstname">

        Surname:
        <input type="text" id="surname" name="surname">

        Tel No:
        <input type="tel" id="tel" name="tel">

        Email:
        <input type="email" id="email" name="tel">

        Password:
        <input type="password" id="password" name="password">

        <input type="submit" value="Submit!">
    </fieldset>
</form>

The form works great.
I would like to validate the Tel No, so that only digits between 0-9 can be entered.  I'm not worried about length or anything rock n roll like that.  I just want to make sure that users enter in numbers, then I can expand on that.  Here is my code:
function validateNumber()
{
        var a=document.forms["userinfo"]["tel"].value;
        var patt=new RegExp("[0-9]");

        if (a==null || a=="")
        {
         document.getElementById('tel_required').innerHTML="required";
        }
        else if (patt==null || patt !== RegExp )
        {
             document.getElementById('tel_required').innerHTML="numbers only allowed";
        }
}

I suspect I have something fundamentally wrong in my else if statement ((patt==null || patt !== RegExp )) or that it's even constructed correctly, or that it should even be an else if statement!!  But I can't even seem to get the logic quite right in my head.
Any help would be great.  Thanks, and again sorry if this is a silly question.
Here is the full JavaScript code I have so far:
function validateForm()
    {
        var a=document.forms["userinfo"]["firstname"].value;

        if (a==null || a=="")
                {
                    document.getElementById('firstname_required').innerHTML="required";
                }

        var a=document.forms["userinfo"]["surname"].value;

        if (a==null || a=="")
            {
                document.getElementById('surname_required').innerHTML="required";
            }

validateNumber()
validateEmail()

        var a=document.forms["userinfo"]["password"].value;

        if (a==null || a=="")
            {
                document.getElementById('password_required').innerHTML="required";
                return false;
            }

    }

function validateNumber()
{
var a=document.forms["userinfo"]["tel"].value;
var patt=new RegExp("[0-9]");

if (a==null || a=="")
            {
                document.getElementById('tel_required').innerHTML="required";
            }

 if (patt==null || patt !== RegExp )
            {
                document.getElementById('tel_required').innerHTML="numbers only allowed";
            }
}

function validateEmail()
{
var a=document.forms["userinfo"]["email"].value;
var patt=new RegExp("/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/");

if (a==null || a=="")
            {
                document.getElementById('email_required').innerHTML="required";
            }
}

A: If you are lucky enough to be HTML5, you might be able to get away with
<input type="number">

Try input type=number to see the HTML5 version in action.
else try below code
function validateNumber()
{
        var a=document.forms["userinfo"]["tel"].value;

        if (a==null || a=="")
        {
         document.getElementById('tel_required').innerHTML="required";
        }
        else if (/[^\d]/.test(a))
        {

             document.getElementById('tel_required').innerHTML="numbers only allowed";
        }
    else {
         document.getElementById('tel_required').innerHTML="input OK";
         }
    }

A: As Novocaine88 says, you should also allow spaces.
if (!/[^\d ]/.test(a)) {
    //OK
} else {
    //not OK - contains character(s) other than numbers/spaces
}

Note the simpler method of declaring a regular expression, also, via the literal /pattern/ rather than the constructor.


text:
Q: Open a file with Batch Script Dears,
I 'm facing some difficulties trying to create a batch script to open a specific excel file with variable name.
@ECHO OFF
for /f %%x in ('wmic path win32_localtime get /format:list ^| findstr "="')
do set %%x
set today=%Year%%Month%%Day%
"C:\xxx\xxx\Desktop\FileName" + today-1 + ".xlsx"

The path includes two pieces:
Fix piece :"C:\xxx\xxx\Desktop\FileName"
Variable piece: yesterday's date in format "YYYYMMDD" without any separation between year,month or day.
thanks for your help!

A: I'd use powershell as a tool to do the date calculation:
:: Q:\Test\2018\10\11\SO_52760062.cmd
@ECHO OFF
for /f "usebackq" %%A in (`
  powershell -NoP -C "(Get-Date).AddDays(-1).ToString('yyyyMMdd')"
`) Do Set Yesterday=%%A
echo "C:\xxx\xxx\Desktop\FileName%Yesterday%.xlsx"

Sample output:
> Q:\Test\2018\10\11\SO_52760062.cmd
"C:\xxx\xxx\Desktop\FileName20181010.xlsx"


text:
Q: Call function in jQuery from AJAX response I'm battling with a question for quite some time and I'm unable to find the answer. I'm using Script# with jQuery. In Script# I've defined the following functions:
(function($) {
    ////////////////////////////////////////////////////////////////////////////////
    // Scrn

    window.Scrn = function Scrn() {
    }
    Scrn.openSuccess = function Scrn$openSuccess(txt) {
        /// <param name="txt" type="String">
        /// </param>
        $('#alrtS').css('display', 'block');
        $('#alrtS span').html(txt);
    }
    Scrn.openModal = function Scrn$openModal(cap, txt) {
        /// <param name="cap" type="String">
        /// </param>
        /// <param name="txt" type="String">
        /// </param>
        $('#frmModalLabel').html(cap);
        $('#frmModalBody').html(txt);
        $("#frmModal").modal("show");
    }

    Scrn.registerClass('Scrn');
})(jQuery);

From another script I make an AJAX request on which a piece of Javascript is returned.
(function($) {
    clsAJAX.fnAJAX = function clsAJAX$fnAJAX(hash) {
        var sdata = {};
        sdata.script = scrp;
        sdata.page = true;
        jqAO.data = sdata;
        jqAO.dataType = 'script';
        jqAO.cache = true;
        jqAO.url = url;
        jqAO.success = function(data, textStatus, request) {
        };
        $.ajax(jqAO);
    }
})(jQuery);

My question is, how can the response Javascript call the code inside the jQuery function? E.g: The server returns a Javascript code
Scrn.openSuccess("test");doucment.title="foo page";

Then I'll get an error that the function Scrn.openSuccess doesn't exist. So, what should the returned code be like to call Scrn.openSuccess()?
As for why there's a lot of odd variables like jqAO, Script# doesn't support direct input.

A: You have to create the ajax as a function which can be called from other scopes
(function ($) {
    //create a named function reference in the global scope so that script in another scopes can use it
    window.myAjax = function () {
        var sdata = {};
        sdata.script = scrp;
        sdata.page = true;
        jqAO.data = sdata;
        jqAO.dataType = 'script';
        jqAO.cache = true;
        jqAO.url = url;
        jqAO.success = function (data, textStatus, request) {};
        $.ajax(jqAO);
    }

    myAjax();
})(jQuery);

then in the other script just call
myAjax()

A: So, here is the result, I changed the syntax of your code, more object oriented, you don't need to name the functions if they are object methods
(function($) {
   // Scrn
    window.Scrn = {
        openSuccess : function(txt) {
            /// <param name="txt" type="String">
            /// </param>
            $('#alrtS').css('display', 'block');
            $('#alrtS span').html(txt);
        },
        openModal : function(cap, txt) {
            /// <param name="cap" type="String">
            /// </param>
            /// <param name="txt" type="String">
            /// </param>
            $('#frmModalLabel').html(cap);
            $('#frmModalBody').html(txt);
            $("#frmModal").modal("show");
        }
    }
    clsAJAXX = {
        fnAJAX : function(hash,successHandler,errorHandler) {
            // Data sent to server I guess
            var sdata = {};
            sdata.script = "";
            sdata.page = true;
            // Ajax request parameters
            var jqAO = {};
            jqAO.data = sdata;
            jqAO.dataType = 'script';
            jqAO.cache = true;
            jqAO.url = "http://dummy.com/getmyscript.jsp";
            jqAO.success = successHandler;
            jqAO.error = errorHandler;
            $.ajax(jqAO);
        }
    }
    //Call
    clsAJAXX.fnAJAX("myhash",Scrn.openSuccess,null);
})(jQuery);

DEMO : http://jsfiddle.net/AjYF2/
This demo shows the call of success handler in the AJAX function - It is just an example as I commented the Jquery Ajax call (need a proper url so) and replaced it by a call.

A: Seems like it wasn't that complicated.
Returned Javascript code:
$(function(){ Scrn.openSuccess("test");doucment.title="foo page"; });


text:
Q: Mac Client LoginWindow fails but SSH Works I'm upgrading my desktop clients to use Mac OS X 10.6.2, and I'm having real trouble. Network users can't login using the login window. This works fine with 10.5.x clients.
I can also ssh as a network user to the affected computer and it works great. I just can't use the GUI login window.
Here's what I've tried:

*

*I set the Login Options using the Accounts PreferencePane. I enabled network login and my OD master was set as the "Network Account Server."

*Login window didn't work.

*Restart. Didn't work.

*Disabled and re-enabled "allow network users to log in at login window". Didn't work. Restarted. Didn't work.

*Checked server OD security settings. Restarted server. Doesn't work.

Again, I can login via SSH, but the GUI login window doesn't work!
Any suggestions?

A: Here are some things to look at:

*

*On the login window, underneath where it says Mac OS X, there will be some text -- I think the default is the computer's host name.  Click on it several times.  Does it show that 'Network Accounts are Available?' with a green indicator?

*Is there anything interesting in /var/log/system.log or /var/log/secure.log? (Sometimes it is nice to ssh into the box, run tail -f on one of those files, and watch what happens when you log in).

*Are you able to log in graphically/via ssh with a local account?

*The fact that you can authenticate via ssh is a good sign, which seems to indicate that you are bound to the directory properly.  Nevertheless, what does using dscl tell you?

*If you run the command mcxquery in a terminal on the machine, do you get anything other than
Error 'no data found' (-4584) running compositor for user: (user)  group: (null)  computer: =

*Just to verify: These same clients worked fine before you upgraded to 10.6?  Which OS is your server running?

A: The key clue in this puzzle was the EAPOL connection. This is responsible for 802.1X authentication, which is needed for our wireless network. Of course this is a desktop computer and had wireless disabled.
However, when I investigated the AirPort "Advanced" settings, I saw that there was a "LoginWindow" profile for 802.1X. In short, the Mac was attempting to authenticate to the wireless network with the login user/password. Of course that failed. Removing this 802.1X setting solved the problem.
I don't know why this only happened after the 10.6 upgrade.
Here's Apple's KB article:
KB3326 - Network Preferences for 802.1X

At the login screen, one enters a name
  and password. If LoginWindow can't
  find a local user account with that
  name, it initiates an 802.1X session
  using the same name and password and
  in the case of an 802.11 network, it
  associates to the wireless network.
  After the 802.1X authentication
  completes, LoginWindow authenticates
  the user against the directory
  service. If that authentication
  succeeds, the user is logged in.

So for Google purposes... here's the secure.log:
Dec 16 12:20:39 tritium SecurityAgent[171]: Network Authentication will be attempted

Dec 16 12:20:39 tritium SecurityAgent[171]: Attempting EAPOL connection

Dec 16 12:20:39 tritium SecurityAgent[171]: EAPOLConnectTimeout = 60.000000

Dec 16 12:20:39 tritium SecurityAgent[171]: DSBindTimeout = 60.000000

Dec 16 12:20:39 tritium SecurityAgent[171]: EAPOL NOT connected


text:
Q: How to apply Map when the shape of the argument depends on the input? I would like to apply Map[f] (for some function f) to the output of another function, which usually outputs a list. But that other function is defined using Piecewise, and so depending on the input, mathematica may not be able to determine which case to apply. When that happens, Map[f] does not apply f to the list elements, but to the arguments of Piecewise, which is not what I want.
In case the above explanation is not clear, here is an example of the behavior that I am talking about:
f[x_] := x^2
li[n_] := Piecewise[{{Range[n, n + 10], n > 0}}, Range[-n, -n + 10]]
li[5]
(* {5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15} *)

li[-5]
(* {1, 2, 3, 4, 5} *)

f /@ li[-5]
(* {25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225} *)

li[n] // InputForm

(* Piecewise[
     {{{n, 1 + n, 2 + n, 3 + n, 4 + n, 5 + n, 6 + n, 7 + n, 8 + n, 9 + n, 10 + n}, n > 0}},
     {-n, 1 - n, 2 - n, 3 - n, 4 - n, 5 - n, 6 - n, 7 - n, 8 - n, 9 - n, 10 - n}
    ] *)

f /@ li[n] // InputForm
(* Piecewise[
     {{{n^2, (1 + n)^2, (2 + n)^2, (3 + n)^2, (4 + n)^2, (5 + n)^2, (6 + n)^2, (7 + n)^2, (8 + n)^2, (9 + n)^2, (10 + n)^2}, (n > 0)^2}},
     {n^2, (1 - n)^2, (2 - n)^2, (3 - n)^2, (4 - n)^2, (5 - n)^2, (6 - n)^2, (7 - n)^2, (8 - n)^2, (9 - n)^2, (10 - n)^2}
    ]  *)

f /@ li[n] /. n -> -5 // InputForm
(* Piecewise[{{{25, 16, 9, 4, 1, 0, 1, 4, 9, 16, 25}, False^2}},
     {25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225}] *)

I understand why this happens, as the Map is evaluated before the rule application. I know that in this case, I can apply the rule before mapping f. But in general, this is not something that I can do. For example, I might want to define a function g by:
g[n_] := f /@ li[n]

Then calling g[x] with a variable x (rather than a concrete number) fails.
I thought of applying Listable to f. However, in my particular case, f is a function that turns lists into other lists, so Listable is not desirable. Something like that:
f[{x_, y_}] := {x - y, x + y}
SetAttributes[f, Listable]
f[{1, 2}]
(* {f[1], f[2]} *)

A: You may use Composition.
With f as in OP
ClearAll[f]
f[{x_, y_}] := {x - y, x + y}

and lip some function that gives pairs
ClearAll[lip]
lip[n_] := Partition[Range[Abs@n, Abs@n + 9], 2]

In shorthand
ClearAll[g]
g[n_] := Map[f]@*lip@n

or longhand
ClearAll[h]
h[n_] := Composition[Map[f], lip][n]

Then both g and h give
g[n]

{{-1, 1 + 2 Abs[n]}, {-1, 5 + 2 Abs[n]}, {-1, 9 + 2 Abs[n]}, {-1, 13 + 2 Abs[n]}, {-1, 17 + 2 Abs[n]}}

and
g[n] /. n -> 5

{{-1, 11}, {-1, 15}, {-1, 19}, {-1, 23}, {-1, 27}}

Hope this helps.

A: The function at the end of the OP cannot be applied to li[n] because, li[] does not return lists of length 2.  It's rather confusing.  Here's a way so that f will map itself over a list if the list contains lists, no matter what the "shape of the argument" is (e.g. length of the list, non-list, etc.).
li[n_] := Piecewise[{{Range[n, n + 10], n > 0}}, Range[-n, -n + 10]]

f // ClearAll;
f[v_?VectorQ] := Accumulate[v]; (* main definition *)
f[a_List] := f /@ a;            (* maps f *)
f[x_?NumericQ] := {x};          (* seemed to go with Accumulate *)

The li[] example (it doesn't make sense to map the second f):
g = f[li[x]]
(*
f[Piecewise[{
   {{x, 1+x, 2+x, 3+x, 4+x, 5+x, 6+x, 7+x, 8+x, 9+x, 10+x}, x > 0}},
  {-x, 1-x, 2-x, 3-x, 4-x, 5-x, 6-x, 7-x, 8-x, 9-x, 10-x}]]
*)

g /. x -> 3
(*  {3, 7, 12, 18, 25, 33, 42, 52, 63, 75, 88}  *)

g /. x -> -1
(*  {1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66}  *)

Here's a piecewise function in which f should be mapped in one case but not the other:
li2[n_] := Piecewise[
  {{Table[Range[n, n + k], {k, 4}], n > 0}},
  Range[-n, -n + 10]]

g2 = f[li2[x]];
g2 /. x -> 1
g2 /. x -> -1
(*
{{1, 3}, {1, 3, 6}, {1, 3, 6, 10}, {1, 3, 6, 10, 15}}
{1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66}
*)

Turning on tracing for f shows how f is evaluated on lists of lists:
On@f;
f[{1, {2, 3}, {4, 5, {6, 7, 8}}}]
(*
f::trace :  f[{1,{2,3},{4,5,{6,7,8}}}] --> f/@{1,{2,3},{4,5,{6,7,8}}}. >>
f::trace :  f[1] --> {1}. >>
f::trace :  f[{2,3}] --> Accumulate[{2,3}]. >>
f::trace :  f[{4,5,{6,7,8}}] --> f/@{4,5,{6,7,8}}. >>
f::trace :  f[4] --> {4}. >>
f::trace :  f[5] --> {5}. >>
f::trace :  f[{6,7,8}] --> Accumulate[{6,7,8}]. >>

{{1}, {2, 5}, {{4}, {5}, {6, 13, 21}}}
*)

Even if f is not defined to handle exactly the cases the OP has in mind, most likely a solution may be found to handle them by defining f with appropriate patterns.


text:
Q: Is there a performance difference between creating startup queues vs dynamic queue in ActiveMQ? Most of the examples that I seem to run into are using dynamic queues instead of queue defined during activemq startup (see activemq.xml file). Is there a significant degradation in performance if I use dynamic queue generation?

A: No. It really can be ignored performance-wise


text:
Q: Needed to take the full path of the uploaded file from client Machine I just needed to take the full path of the uploaded file from client Machine.
I tried
strDir = Upload1.PostedFile.FileName

strDir = System.IO.Path.GetFullPath(Upload1.PostedFile.FileName)

with upload control, but it doesn't work that kind.
I too know that security concerns will not allow the server to be aware of the file path, but are there any other alternate options to retrieve the file path. If yes please reply to the post....

A: You cannot, unless you create/register a protocol handler that can communicate with the OS, or perhaps create an ActiveX control (works only with IE) or a Java applet. Browsers don't natively communicate with the computer.

A: Don't waste your time.
For security reasons browsers do no allow get client path, ie JavaScript in browser has no access to the File System, however using HTML5 File API, only Firefox provides a mozFullPath property, but fortunately if you try to get the value it returns an empty string: