text:
Q: Pass C# variable through URL I have defined a variable in C# as the item selected in a drop down.
string parametername = ddlCarrier.SelectedItem.Text;

I now want to pass this variable in my URL to the next page. How do I do this in the href tag?
<asp:LinkButton href="Table.aspx?parameter=<%parametername%>"  ID="btnSubmit" runat="server">Click Here</asp:LinkButton>

A: Purely Server-Side Approach
Instead of a LinkButton, you might want to consider using a HyperLink or <a> tag as you aren't going to be doing anything with your code-behind:
<asp:HyperLink ID="btnSubmit" runat="server" NavigateUrl="Table.aspx" Text="Navigate"></asp:HyperLink>

Then you can use the NavigateUrl property, which you might want to consider setting within your code-behind :
// This will set up your Navigation URL as expected
btnSubmit.NavigateUrl = String.Format("Table.aspx?parameter={0}",ddlCarrier.SelectedItem.Text);

If you use this approach, you may want to explicitly set that a PostBack occurs when your DropDownList changes so that this value will consistently be correct :
<asp:DropDownList ID="dllCarrier" runat="server" AutoPostBack="True" ...>

Client-Side Approach
However, if you are expecting to be able to change this to reflect the current value of your Carrier DropDownList without a PostBack, then you'll likely need to resort to Javascript to populate the value prior to actually navigating :
<!-- Set your base URL within the method and append the selected value when clicked -->
<asp:Button ID="Example" runat="server" OnClientClick="ClientSideNavigate('Table.aspx'); return false;" Text="Navigate"></asp:Button>
<script>
    function ClientSideNavigate(url) {
        // Get the selected element
        var e = document.getElementById('<%= ddlCarrier.ClientID %>');
        // Navigate
        window.location.href = url + '?parameter=' + e.options[e.selectedIndex].value;
    }
</script>

Or you could just avoid ASP.NET Controls altogether and just use an <button> tag :
<button onclick="ClientSideNavigate('Table.aspx'); return false;">Navigate</button>
<script>
    function ClientSideNavigate(url) {
        // Get the selected element
        var e = document.getElementById('<%= ddlCarrier.ClientID %>');
        // Navigate
        window.location.href = url + '?parameter=' + e.options[e.selectedIndex].value;
    }
</script>

A: You need to handle TextChanged or SelectedIndexChanged event for ddlCarrier and properly set href property of btnSubmit to include ddlCarrier.Text.


text:
Q: Convention for marking methods as pure functions in Java Reading code of some complex application I thought it could often be helpful to recognize if a method has side effects just by looking on its signature. And after inspecting some of such methods I thought it could be nice to mark them as purely functinal or not in order to make life easier for people reading this code in future.
Is there some convention in Java world (javadoc, method naming pattern etc.) which identifies method as pure function?

A: You have the JavaBeans Conventions. See http://docstore.mik.ua/orelly/java-ent/jnut/ch06_02.htm

. The JavaBeans framework facilitates this process by establishing naming conventions. One such convention, for example, is that the getter and setter accessor methods for a property should begin with get and set.

However, you can always javadoc or annotate your methods like for example.
/**
 * This method is read only!
 */
@ReadOnly
public void setX(Object x)

The programmatic/safe way, would be using polymorphism, implementing "read only" and "read/write" interfaces. Related: How to create two interfaces to a Java class one read-only, one read-write?
IMO, if you dont want to mess with interfaces, the JavaBeans convention and/or the javadoc should be enough to guess what functions have side effects or not.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to compare variables' coefficients obtained from lasso? My situation:

*

*small sample size: 116

*binary outcome variable

*long list of explanatory variables: 50

*explanatory variables did not come from the top of my head; their choice was based on the literature.

Following a suggestion to a previous question of mine, I have run LASSO (using R's glmnet package) in order to select the subset of exaplanatory variables that best explain variations in my binary outcome variable.
I have calculated lambda.min through cross-validation (cv.glmnet command) and got the correspondent coefficients for my explanatory variables. For 6 of my total 50 explanatory variables, the coefficients were non-zero. Are those coefficients comparable, i.e. can I say that the variables with the highest ones are the most important? If they are not comparable, can I run logistic regression (using glm) with those 6 variables and then compare them in terms of coefficients and p-values?


text:
Q: Optimize MySQL for Prestashop 1.6 I am running Prestashop 1.6 powered e-shop on VPS with 4GB RAM, 2CPUs, 60GB SSD characteristics. Currently I have about 20000 products in my shop and I am having problems with site loading because mysql queries run long. And when I run htop to analyze processes, I see that mysql consumes 100% of both CPUs. This is the output from mysqltuner:
-------- Performance Metrics -------------------------------------------------
[--] Up for: 1h 29m 9s (241K q [45.109 qps], 319 conn, TX: 318M, RX: 126M)
[--] Reads / Writes: 78% / 22%
[--] Total buffers: 192.0M global + 2.7M per thread (151 max threads)
[OK] Maximum possible memory usage: 597.8M (15% of installed RAM)
[OK] Slow queries: 0% (8/241K)
[OK] Highest usage of available connections: 2% (4/151)
[OK] Key buffer size / total MyISAM indexes: 16.0M/44.9M
[OK] Key buffer hit rate: 99.6% (36M cached / 133K reads)
[OK] Query cache efficiency: 49.6% (101K cached / 205K selects)
[!!] Query cache prunes per day: 1386761
[OK] Sorts requiring temporary tables: 0% (1 temp sorts / 7K sorts)
[!!] Joins performed without indexes: 78
[OK] Temporary tables created on disk: 8% (846 on disk / 9K total)
[OK] Thread cache hit rate: 98% (4 created / 319 connections)
[!!] Table cache hit rate: 10% (340 open / 3K opened)
[OK] Open file limit used: 62% (643/1K)
[OK] Table locks acquired immediately: 100% (239K immediate / 239K locks)

-------- Recommendations -----------------------------------------------------
General recommendations:
    Add skip-innodb to MySQL configuration to disable InnoDB
    MySQL started within last 24 hours - recommendations may be inaccurate
    Enable the slow query log to troubleshoot bad queries
    Adjust your join queries to always utilize indexes
    Increase table_cache gradually to avoid file descriptor limits
Variables to adjust:
    query_cache_size (> 16M)
    join_buffer_size (> 128.0K, or always use indexes with joins)
    table_cache (> 400)

Please suggest any optimization methods.
EDIT:
Slow query output log is here.

A: Here is the second query from your log, looking into others.  To help on this, I slightly restructured to get rid of the subquery and turned into an INNER JOIN.  Also, to help others not knowing your tables, always qualify your field references as table.column or alias.column such as to know where your level_depth, nleft, nright are coming from.  It may help with indexes.
FOR indexes, I would have the following per table.
ps_category, index ON( active, id_category, id_lang, nleft, nright, level_depth )
ps_category_lang, index ON( id_category, id_shop, id_lang )
ps_category_shop, index ON( id_category, id_shop )
ps_category_group, index ON( id_category, id_group )
ps_lang, index ON( id_lang, active )

slightly rewritten query
SELECT
      c.id_parent,
      c.id_category,
      cl.name,
      cl.description,
      cl.link_rewrite
   FROM
      ps_category c
         INNER JOIN ps_category_lang cl
            ON c.id_category = cl.id_category
            AND cl.id_shop = 1
            AND cl.id_lang = 2
         INNER JOIN ps_category_shop cs
            ON c.id_category = cs.id_category
            AND cs.id_shop = 1
         INNER JOIN ps_category_group psg
            ON c.id_category = psg.id_category
            AND psg.id_group = 1
   WHERE
      (  c.active = 1
      OR c.id_category = 2)
      AND c.id_category != 1
      AND level_depth <= 7
      AND nleft >= 350 AND nright <= 351
   ORDER BY
      level_depth ASC,
      cs.position ASC;

Third query.  Notice in this case, some of the key elements that are specific are moved to the top, hence I have them in the key index too, THEN the rest in the where clause (mostly readability adjustments, but helps to see "specific" elements for index advantages )
SELECT
      c.id_category,
      cl.name,
      cl.link_rewrite
   FROM
      ps_category c
         LEFT JOIN ps_category_lang cl
            ON c.id_category = cl.id_category
            AND cl.id_shop = 1
         INNER JOIN ps_category_shop category_shop
            ON c.id_category = category_shop.id_category
            AND category_shop.id_shop = 1
   WHERE
          c.active = 1
      AND cl.id_lang = 2
      AND c.nleft between 2 and 350
      AND c.nright between 351 and 625
      AND c.level_depth > 1
   ORDER BY
      c.level_depth ASC;

The next query you need to confirm what you really wanted...  You have a left-join to the language table, but then add "AND l.active = 1" in the where clause which in-fact would turn it into an INNER JOIN.  If you want it truly to a LEFT-JOIN, move the l.active to the join part such as I adjusted here
SELECT
      l.id_lang,
      c.link_rewrite
   FROM
      ps_category_lang AS c
         LEFT JOIN ps_lang AS l
            ON c.id_lang = l.id_lang
            AND l.active = 1
   WHERE
      c.id_category = 324

Hopefully these indexes and sample clarification / readability of queries might help improve your logs.  If still problems with others, post as needed.
REVISION FOR FIRST QUERY IN SLOW LOG REPORT
In the first query, it appears you are looking for things out of a specific product shop.  However, you are starting the query with the product category and left-joining to products, then to product shops.  Since these products will ultimately be associated with a specific category via the where, it creates an INNER JOIN anyhow.  I would slightly restructure as below
I would have a single index on ps_product_shop ON ( id_shop, active, visibility, id_product, id_category_default )
SELECT
      p.*,
      ps.*,
      stock.out_of_stock,
      IFNULL(stock.quantity, 0) as quantity,
      MAX(pas.id_product_attribute) id_product_attribute,
      pas.minimal_quantity AS product_attribute_minimal_quantity,
      pl.description,
      pl.description_short,
      pl.available_now,
      pl.available_later,
      pl.link_rewrite,
      pl.meta_description,
      pl.meta_keywords,
      pl.meta_title,
      pl.name,
      MAX(image_shop.id_image) id_image,
      il.legend,
      m.name AS manufacturer_name,
      cl.name AS category_default,
      DATEDIFF(ps.`date_add`, DATE_SUB(NOW(),INTERVAL 20 DAY)) > 0 AS new,
      ps.price AS orderprice
   FROM
      ( select @thisLanguage := 1 ) sqlvars,
      ps_product_shop ps
         INNER JOIN ps_product p
            ON ps.id_product = p.id_product

            INNER JOIN ps_category_product cp
               ON id_product = cp.id_product
               AND cp.id_category = 2

            LEFT JOIN ps_product_attribute pa
               ON p.id_product = pa.id_product
               LEFT JOIN ps_product_attribute_shop pas
                  ON pa.id_product_attribute = pas.id_product_attribute
                  AND ps.id_shop = pas.id_shop
                  AND pas.default_on = 1

            LEFT JOIN ps_stock_available stock
               ON p.id_product = stock.id_product
               AND ps.id_shop = stock.id_shop
               AND stock.id_shop_group = 0
               AND stock.id_product_attribute = IFNULL(pas.id_product_attribute, 0)

            LEFT JOIN ps_product_lang pl
               ON p.id_product = pl.id_product
               AND ps.id_shop = pl.id_shop
               AND pl.id_lang = @thisLanguage

            LEFT JOIN ps_image i
               ON p.id_product = i.id_product
               LEFT JOIN ps_image_shop image_shop
                  ON i.id_image = image_shop.id_image
                  AND ps.id_shop = image_shop.id_shop
                  AND image_shop.cover = 1
                  LEFT JOIN ps_image_lang il
                     ON image_shop.id_image = il.id_image
                     AND il.id_lang = @thisLanguage

            LEFT JOIN ps_manufacturer m
               ON p.id_manufacturer = m.id_manufacturer

         LEFT JOIN ps_category_lang cl
            ON ps.id_category_default = cl.id_category
            AND cl.id_shop = ps.id_shop
            AND cl.id_lang = @thisLanguage
   WHERE
          ps.id_shop = 1
      AND ps.active = 1
      AND ps.visibility IN ("both", "catalog")
   GROUP BY
      ps.id_product
   ORDER BY
      cp.position ASC
   LIMIT
      0,8;

As for creating the multiple field index as a single index, example:
CREATE INDEX act_id_lang ON ps_category( active, id_category, id_lang, nleft, nright, level_depth );
give a simple index name... on whatever table... with ALL the keys as they will be effective in the query.

A: You should use mysqltuner after a longer usage time.
This should remove the following message :
 MySQL started within last 24 hours - recommendations may be inaccurate


text:
Q: TSQL: Merge two sets with grouping and concatenation on the values I have two tables with 2+ million rows in each. I need to merge them and the performance is very important.
The flags need to get concatenated after merge.
Table 1
ip       flags
-----------
23.4.2.8  x
94.4.7.3  t
12.5.7.9  x
33.1.2.3  xc

Table 2
ip       flags
-----------
23.4.2.8  y
94.4.7.3  t
99.6.7.9  t

Table 3 - merged flags on both tables
ip       flags
-----------
23.4.2.8  yx  -- merged flags, the order of flags is not important
94.4.7.3  t   -- merged flags, but distinct
12.5.7.9  x
33.1.2.3  xc
99.6.7.9  t

I have this working in C# and wonder if it is possible to do this using SQL. Is there a SQL command that can do this in efficient way?

A: Another option if you don't have SQL Server 2017+ using STUFF and FOR XML PATH() - I think it's good for 2008 +
Here's a SQL Fiddle
SELECT
    ip
    ,STUFF((SELECT  ',' + t.flags
            FROM(
                SELECT ip, flags
                FROM table1
                UNION ALL
                SELECT ip, flags
                FROM table2
                )t
            WHERE t.ip = a.ip
        FOR XML PATH('')), 1, 1, '') AS Flags
FROM
(
    SELECT ip, flags
    FROM table1
    UNION ALL
    SELECT ip, flags
    FROM table2
)a
GROUP BY ip

A: You didn't mention which version of SQL Server you're using, though if it is 2017+ this solution will work for you.
You can accomplish your goal using STRING_AGG. Try the following with your data (create tables based off of your sample data above)
CREATE TABLE #table1(
    ip VARCHAR(100)
    ,flags CHAR(10)
)
GO
CREATE TABLE #table2(
    ip VARCHAR(100)
    ,flags CHAR(10)
)
GO

INSERT INTO #table1 VALUES
('23.4.2.8','x')
,('94.4.7.3','t')
,('12.5.7.9','x')
,('33.1.2.3','xc')
GO

INSERT INTO #table2 VALUES
 ('23.4.2.8','y')
,('94.4.7.3','t')
,('99.6.7.9','t')

GO

SELECT
    ip
    ,STRING_AGG(RTRIM(flags),',')
FROM
(
    SELECT
        ip
        ,flags
    FROM #table1
    UNION ALL
    SELECT
        ip
        ,flags
    FROM #table2
)a
GROUP BY ip

A: Not sure how wide your tables are, but something like below could work:
SELECT ISNULL(t.IP, t2.IP) AS IP
    , CONCAT(ISNULL(t.flags,''), ISNULL(t2.flags, '')) AS flags
FROM table1 as t
FULL JOIN table2 as t2 ON t.IP = t2.IP

A: Expanding the answer by ssn to clean the duplicate characters.
The performance is really good!
SELECT ISNULL(t.IP, t2.IP) AS IP
    , [dbo].[FN_CLEANDUPCHAR](CONCAT(ISNULL(t.block_reason_code,''), ISNULL(t2.block_reason_code, ''))) AS block_reason_code
FROM ##table1 as t FULL JOIN ##table2 as t2
ON t.IP = t2.IP

And this is the function:
CREATE FUNCTION [dbo].[FN_CLEANDUPCHAR]
(
    @S varchar(20)
)
RETURNS varchar(20)
AS
BEGIN
    SELECT
        @S = CASE WHEN CHARINDEX(SUBSTRING(@s,Number,1),@s) BETWEEN 1 AND Number-1 THEN STUFF(@s,Number,1,'') ELSE @S END
    FROM master.dbo.spt_values
    WHERE Number BETWEEN 2 AND LEN(@s) AND type='P'
    ORDER BY Number DESC

    return @S
END
GO


text:
Q: Getting NLOpt results after optimization failure using Python API I am running an optimization using NLOpt's Python interface. At a certain point, after a number of iterations, I get an nlopt.RoundoffLimited exception. According to the documentation (http://ab-initio.mit.edu/wiki/index.php/NLopt_Reference#Error_codes_.28negative_return_values.29), after such an exception, "the optimization still typically returns a useful result." How do I actually view the intermediate result? I am running code like:
opt = nlopt.opt(...)
# ... some optimization settings
try:
    opt_results = opt.optimize(guess)
except nlopt.RoundoffLimited:
    # How do I get the latest parameters from opt,
    # after the optimization has failed?

I can get the objective value just fine using opt.last_optimize_result(), but I can't find the API call to get the parameters that result in this objective value.
Thanks!

A: I still haven't found a particularly elegant solution, but I'll post this for now in case somebody stumbles upon the same problem. Here is one approach to recovering the previous valid optimization parameters prior to an optimization exception:
# globals
previous_args = None
current_args = None

# objective function
def objective_function(args, gradient):
    global previous_args
    global current_args

    previous_args = current_args
    current_args = args

    # ... the rest of your objective function
    return function_value

# optimization code using objective_function
opt = nlopt.opt(...)

try:
    args = opt.optimize(guess)
except nlopt.RoundoffLimited:
    args = previous_args

    # you should do some sanity checks on args.
    # for example, one reason you may see RoundoffLimited
    # is args on the order of 1e-300 or so.


text:
Q: fatal error two table view in UIview in my app i want to display two table view in an UIViewController but i've a fatal error : fatal error: unexpectedly found nil while unwrapping an Optional value
can someone help me about this?
here is the full code of the uiview

class MyPropertiesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource  {

//table view extended
@IBOutlet weak var extandedTableViex: UITableView!

// table view standart
@IBOutlet weak var standartTableView: UITableView!
//list of data
let stdlist = ["1","2","3", "4","5","6","7","8","9"]

let Extlist = ["E1","E2" ]

//cell indentifier
    let stdcellIdentifier = "stdcell"
let extcellIdentifier = "extcell"

override func viewDidLoad() {
    super.viewDidLoad()
    standartTableView.delegate = self
    standartTableView.dataSource = self

    standartTableView.delegate = self
    standartTableView.dataSource = self

    standartTableView.scrollEnabled = false
    extandedTableViex.scrollEnabled = false

    self.standartTableView.registerClass(GuaranteeCell.self, forCellReuseIdentifier: stdcellIdentifier)
    self.extandedTableViex.registerClass(GuaranteeCell.self, forCellReuseIdentifier: extcellIdentifier)
}

//count cell
  func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if tableView == standartTableView {
        return self.stdlist.count;
    } else {
        return self.Extlist.count;
    }

}

// add cell
   func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    if tableView == standartTableView {
        let cell:GuaranteeCell = self.standartTableView.dequeueReusableCellWithIdentifier(stdcellIdentifier) as! GuaranteeCell
        print("list-element " + self.stdlist[indexPath.row])
           print(indexPath.row)

        cell.guaranteeLabel.text = self.stdlist[indexPath.row]
        return cell
    } else {
        let cell2:GuaranteeCell = self.extandedTableViex.dequeueReusableCellWithIdentifier(extcellIdentifier) as! GuaranteeCell
        cell2.guaranteeLabel.text = String(self.Extlist[indexPath.row])
        return cell2
    }
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { }

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
}

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

}
thanks

A: Check if your cell class is really GuaranteeCell (probably the error is there)


text:
Q: Compare Two Audio(locally stored pre-recorded voice command and recorded from microphone in app) in iOS In-app, I have to compare live recording from previously locally stored voice command if  it matches(not only text but also identified person's voice) then perform necessary action.
1-match voice commands from the same person.
2-match command 's text.
I applied many ways but none are working as per my expectation.
First:
use Speech to text Library like OpenEars,SpeechKit but these libraries convert only text from speech.
Result: Failed As My expectation
Second:(Audio Finger printing)
acrcloud Library : in this library, I record a command and stored that mp3file  on acrcloud server and match with live recording(spoken by me) it doesn't match but when I play the same recording(recorded MP3 file of my voice ) which is uploaded to the acrcloud server then it matches.
Result: Failed As My expectation
API.AI : in this library,it is like speech to text ,I stored some text command on his server and then anyone speaks the same command the result get success.
Result: Failed As My expectation
Please Suggest me how to solve this problem for iOS Application

A: This is how I would approach this If I understand ur requirements correctly:

*

*You will need to compare the audio spectrum of each recording to match the person (Look at the vDSP in Accelerate framework) An FFT analysis with 1024 window should be enough (if not try doubling it for more detail) I would start the comparison with 5-10 peaks in the spectrum and experiment from there.  check out EZAudio for an easy FFT implementation to get you started.

*Use a speech to text library to match the text. Speech accents usually distort their results considerably so I would probably start by trying getting the text from both audio and comparing instead of specifying a command in text to match.
Good luck!

A: http://www.politepix.com/openears/ can be used in objective-c or if you want swift try http://blog.tryolabs.com/2015/06/15/tlsphinx-automatic-speech-recognition-asr-in-swift/. I never used them but they seem to have everything you need. If not try looking for C++ libraries, there should be more options but most probably you'll have to deal with typical porting issues. I really don't recommend you writing one yourself as you'll spend some time learning techiques to then import some signal processing library to then start writing your own algorithm. Except of course if you have the time and interest to do it.
I'd recommend you start integrating your app in the same fashion as voice recognition SW are usually developed: record a bunch of examples, build tests and verify often if things are on/off track.
One of the more important things I learned when doing voice recognition work (both for word recognition and speaker recognition) was that the quality of the recording has a big impact on what you're able to do with it. Make a small batch of recordings in the quietest place you can find, then you'll always have a benchmark to compare to more real life recordings.
Also try to cover all the microphones you'll find in real applications at a later stage, as there's no intrinsic guarantees that all iphone microphones are created equal. I'd expect it to not vary at all across different iphone models but who knows?

A: In general, I think you should use method 1 with some tweak.
For local audio. You add text script version like: 1 audio, source script
For record audio. Use OpenEars,SpeechKit for convert audio to text
Try to compare source script and text for get result. You should mark what text must be stress in source script for best compare result. Sometimes we have word like: wine, wife, white... (try handle this think too)
GLHF


text:
Q: How do I override touch zoom and pan in firefox & chrome with pointer events This goes for other browsers too but primary targets are Firefox and Chrome.
I have registered all pointer event listeners and had to register mouse down and moue up listeners to get the button state changes ( button states in pointer events are not accurate or "chorded" )
But even if I do event.preventDefault() on all pointer:over,enter,down,up,out,and,leave events (except for pointerType mouse for down, as it will disable the mousedown and mouse up listeners) I have remaining issues:
Multi-touch (more than one finger) will be taken over and perform a page-zoom operation rendering multi-touch in my app useless.
If there are scrollbars on the page a single touch will be taken over by the touch pan/scroll operation.
The preventDefault() is not implemented properly with the operating system (ie: windows 10)  and a pointer down over my element will also generate a synthetic mouse down and synthetically move the mouse to the touched location.  I can ignore the synthetic down and up events with messy code) but it places the mouse in unexpected locations and prevents using the mouse and touch simultaneously as separate inputs when desired.  (fixing this will likely require a flag on the DOM element itself and not on a per event basis as the internal event queue will place latency between the OS and the browser dispatched events - I have solved this issue in my native apps )
I am testing with the web developer console so I can log status - I don't know if this influences things.
I have the same touch pan/zoom lack of control on Chrome.
The mouse-up/down behavior is significantly different enough on Chrome vs Firefox to necessitate a separate code path.
PK
For the code junkies - note this is an interface device "front end" for a
"webasm" (game or game of life) engine :)
The objective is to get a "clean raw" event stream for any pointer entering the canvas element ( that is not captured by another element's handler ) Mirror the state of all buttons on all supported devices with captured pointers until capture is lost.  Also to be able to use the mouse and touch (and any other supported devices) as separate devices ignoring all synthetic events and desiring to turn off anything where one device I am listening to is emulated by another device I am listening to (so they don't fight). Also to fully control what is done with the events until capture of the event stream for a pointer is lost.  I would like to capture all touches that go down after and while the "primary" touch goes down on our element for a touch device (tablet, panel, screen etc) and optionally let them "fall through" if they are not used our UI.
Below are the event handlers which are attached to a "canvas" element.  They don't do anything but forward the data to the webasm application. Of course will be cleaned up after it works.  This is Firefox code. :)
canvas.addEventListener('pointerover', this.onPeOED, false);
canvas.addEventListener('pointerenter', this.onPeOED, false);
canvas.addEventListener('pointerdown', this.onPeOED, false);

canvas.addEventListener('pointermove', this.onPeMove, false);

canvas.addEventListener('pointerup', this.onPeUOCL, false);
canvas.addEventListener('pointerout', this.onPeUOCL, false);
canvas.addEventListener('pointercancel', this.onPeUOCL, false);
canvas.addEventListener('pointerleave', this.onPeUOCL, false);

canvas.addEventListener('mousedown', this.onMouseDown, false);
canvas.addEventListener('mouseup', this.onMouseUp, false);

 onPeOED: (function(e) {
    var handled = 0;
    var code = e.type.charCodeAt(7);
    var target = e.currentTarget;
    var posX = e.clientX;
    var posY = e.clientY;

    var flags = (1 << (9 + 16)); // fPointerInside
    if(posX < 0 || posY < 0 || posX >= target.width || posY >= target.height) {
        flags = 0;
    }
    // o == over, e == enter, d == down,

    if(code == 100) { // 100 == 'd'
        flags |= (1 << (10 + 16)); // in contact << 16
    }

    target._mousePointerId_ = -1;

    switch(e.pointerType) {
        case 'mouse':
            target._mousePointerId_ = e.pointerId;
            if(code == 100) { // 100 == 'd' handled by onMouseDown
                target.setPointerCapture(e.pointerId);
                return;
            }
            flags |= 0x0100;  // UID_MOUSE << 8
            break;
        case 'pen':
            flags |= 0x0200;  // UID_STYLUS << 8
            break;
        case 'touch':
            flags |= 0x0300;  // UID_FINGER << 8
            break;
        default:
            Module.print("unknown UID");
            break;
    }

    if(code == 100) { // 100 == 'd'
        target.setPointerCapture(e.pointerId);
    }

    // Module.print("ON uid " + e.pointerType + " " + e.type + " buttons " + e.which + " inside " + ((flags & (1 << (9 + 16))) != 0));

    if(e.buttons != 0) {
        flags |= (e.buttons << 16) | (1 << (10 + 16)); // fPointerInContact
    }

    handled = ccall('onPointerFlagsOn', 'number', EngineConnector.number_11_Sig,
        //  target  type|flags    time      id     screenX  screenY   pageX    pageY   targetX  targetY  pressure
        [   target._CPPHandle_,
            (code | flags),
            e.timeStamp,
            e.pointerId,
            e.screenX,
            e.screenY,
            e.pageX,
            e.pageY,
            posX,
            posY,
            e.pressure
        ]);
    e.preventDefault();
}),

onMouseDown: (function(e) {

    var target = e.currentTarget;
    var posX = e.clientX;
    var posY = e.clientY;

    // Module.print("mouse ME down " + target._mousePointerId_);

    if(target._mousePointerId_ < 0 || posX < 0 || posY < 0 || posX >= target.width || posY >= target.height) {
        Module.print("mouse ignored");
        e.preventDefault();
        return; // ignore downs while outide element
    }
    var wentDown = (e.buttons & (~(target._mouseButtons_)));
    target._mouseButtons_ = e.buttons;

    // Module.print("mouse down " + e.buttons + " went down " + wentDown);

    handled = ccall('onPointerFlagsOn', 'number', EngineConnector.number_11_Sig,
        //  target    type    time      id     screenX  screenY   pageX    pageY   targetX  targetY  pressure
        [   target._CPPHandle_,
          // 'd'  UID_MOUSE                       fPointerInside  fPointerInContact
            (100 | 0x0100 | (1 << (9 + 16)) | (1 << (10 + 16)) | (wentDown << 16)),
            e.timeStamp,
            e.pointerId,
            e.screenX,
            e.screenY,
            e.pageX,
            e.pageY,
            posX,
            posY,
            e.pressure
        ]);
    // e.preventDefault();

}),
fireButtonUp: (function(e, buttons) {

    // Module.print("ME fire up true " + buttons );

    var ptrId = e.currentTarget._mousePointerId_;
    if(ptrId < 0) {
        return;
    }

    ccall('onPointerFlagsOff', 'number', EngineConnector.number_11_Sig,
        //  target    type    time      id     screenX  screenY   pageX    pageY   targetX  targetY  pressure
        [e.currentTarget._CPPHandle_,
            (117 | 0x0100 | (buttons << 16)),  // 117 == 'u' == 'up', 1 == UID_MOUSE
            e.timeStamp,
            ptrId,
            e.screenX,
            e.screenY,
            e.pageX,
            e.pageY,
            e.clientX,
            e.clientY,
            0,
        ]);

}),
// up/leave
onMouseUp: (function(e) {

    var target = e.currentTarget;
    var posX = e.clientX;
    var posY = e.clientY;

    if(posX < 0 || posY < 0 || posX >= target.width || posY >= target.height) {
        // we have to kill ALL the buttons
        EngineConnector.fireButtonUp(e,target._mouseButtons_ | (1 << 10));
        target._mouseButtons_ = 0;
    } else {
        var released = (target._mouseButtons_ & (~e.buttons)); // will leave the one we released
        target._mouseButtons_ = e.buttons;
        if(e.buttons == 0) {
            released |= (1 << 10); // fPointerInContact
        }
        EngineConnector.fireButtonUp(e,(released | (1 << 9)));
    }
    e.preventDefault();

}),

onPeMove: (function(e) {

    var target = e.currentTarget;
    var posX = e.clientX;
    var posY = e.clientY;

    var flags = (1 << 9);
    if(posX < 0 || posY < 0 || posX >= target.width || posY >= target.height) {
        flags = 0;
    }

    var pType =  e.pointerType.charCodeAt(0);
    if(pType == 109) { // 'm' == 109
        // MOUSE
        if(target._mousePointerId_ < 0) {
            e.preventDefault();
            return;
        }
    } else {
        Module.print("move !!!");
    }

    flags |= pType; // 'm', 'p', 't'

    handled = ccall('onPointerMove', 'number', EngineConnector.number_11_Sig,
        //  target    flags time      id     screenX  screenY   pageX    pageY   targetX  targetY  pressure
        [ target._CPPHandle_,
            flags,
            e.timeStamp,
            e.pointerId,
            e.screenX,
            e.screenY,
            e.pageX,
            e.pageY,
            posX,
            posY,
            e.pressure
        ]);
}),
onPeUOCL: (function(e) {

    var code = e.type.charCodeAt(7);
    var target = e.currentTarget;
    target._poinsePointerId_ = -1;

    switch(e.pointerType) {
        case 'mouse':
            target._poinsePointerId_ = e.pointerId;
            if(code == 117) { // 117 == 'u' mouseup handled by mouse event handler
                return;
            }
            code |= 0x0100;  // UID_MOUSE << 8
            // let leave and cancel get reported
            break;
        case 'pen':
            code |= 0x0200;  // UID_STYLUS << 8
            if(code == 117) {
                code |= ((1 << 16) << e.which);
            }
            break;
        case 'touch':
            code |= 0x0300;  // UID_FINGER << 8
            if(code == 117) {
                code |= ((1 << 16) << e.which);
            }
            break;
        default:
            Module.print("unknown UID");
            break;
    }

    var posX = e.clientX;
    var posY = e.clientY;

    if(posX >= 0 && posY >= 0 || posX < target.width || posY < target.height) {
        code |= (1 << (9 + 16));
    }

    // Module.print("off uid " + e.pointerType + " " + e.type + " buttons " + e.which + " inside " + ((code & (1 << (9 + 16))) != 0));

    var handled = 0;

    handled = ccall('onPointerFlagsOff', 'number', EngineConnector.number_11_Sig,
        //  target    type    time      id     screenX  screenY   pageX    pageY   targetX  targetY  pressure
        [e.currentTarget._CPPHandle_,
            code,
            e.timeStamp,
            e.pointerId,
            e.screenX,
            e.screenY,
            e.pageX,
            e.pageY,
            posX,
            posY,
            e.pressure,
        ]);
    e.preventDefault();
}),

A quote from Me when I was working on getting Microsoft to create DirectX almost 30 years ago - it's Deja Vous all over again :)
"For any system to be truly flexible one must be able to implement that system from scratch with the facilities it provides."

A: I'm surprised no no-one mentioned this.
The solution is canvas.setAttribute('style','touch-action: none');
https://developer.mozilla.org/en-US/docs/Web/CSS/touch-action
BTW On Chrome works 99% properly.
Firefox will still pass though synthetic clicks which I have to put in nasty event timing code to filter out.
Both fail to disable Windows 10 Mouse from Touch emulation rendering it impossible to use the mouse and touch at the same time.  I have not found a way for the user to disable this on windows 10.  In any case I don't want to disable it system wide but only when tapping and touch/dragging on the canvas element.


text:
Q: jQuery doesn't work when delivered with flask but works otherwise I'm pretty new to python, even less experienced with flask, and I cannot figure out this issue. I have the following simple web page with jQuery functionality that works great when I double click the file and open it in a browser:
<!DOCTYPE html>

This is a non-jQuery div

This div should update with jQuery

    <button id="updateBtn">update</button>

However, when flask delivers the web page on localhost:5000, the jQuery functionality is no longer present. My python is as follows:
from flask import Flask, render_template
app = Flask(__name__)

@app.route('/')
def render():
    return render_template("jquery_test.html")

if __name__ == "__main__":
    app.run(port=5000, debug=True)

My app's file tree is:
/AJAX_practice
    ajax_practice.py
    /templates
        jquery-3.3.1.js
        jquery_test.html

I was trying to follow this tutorial when I couldn't get the "echo" button to work. In my efforts to debug, I have slowly chipped away and drastically simplified the program to the above code to see why I cannot get my jQuery to work through flask. I am still at a loss. I am running the flask app by pressing F5 in IDLE, with no errors in Python 2.7.13 Shell, and the Terminal (from which I started IDLE with $ sudo idle) showing:
my ip - - [date and time] "GET / HTTP/1.1" 200 -
my ip - - [date and time] "GET /jquery-3.3.1.js HTTP/1.1" 404 -

From this, my best guess is that flask cannot find the jquery.3.3.1.js file, though I have tried putting it everywhere in the file tree with no luck. I cannot use the script src to https for jQuery dependencies, as my server will eventually be on a non-internet connected LAN. Am I on the right track? If so, how does flask find and/or navigate jQuery dependencies? Can anyone point me towards some documentation that might help my fundamental understanding of this issue?
Any help on this matter would be greatly appreciated.

A: You are trying to serve JavaScript file from templates folder. Add a static folder and use that to serve static content.
in your case create a directory structure like "static/js/jquery.min.js"
and then add script reference like this

See this :
http://exploreflask.com/en/latest/static.html
If you don't want to keep it in "static" folder and use another local directory you can use  send_from_directory as shown in this example :
https://stackoverflow.com/a/20648053/2118215

A: This has always worked for me with Flask in the past:

'static' is the name of the folder it's in (and the 'static' folder is in the root of my project). You can edit this to suit your preferred structure and naming, so change 'static' to 'templates' if that's where you'd rather keep your jquery file, although I would recommend keeping it in a separate folder from your HTML templates, purely in the interests of keeping your project well organised.

A: I believe the path to jquery should be /templates/jquery-3.3.1.js
On me flask server when i serve jquery it has the full path from the home directory: /static/js/jquery.min.js


text:
Q: Create Jar With External Libraries(Intellij Idea 2017) I created a simple application using IntelliJ.I exported my project to a jar file and Every Thing was fine and jar file worked properly. Now I decide to use jfoenix.jar in my project for button and text fields.I add a jfoenix to my project and it works fine in the intellij environment but when I export my project to the jar it doesn't work(I click on the jar file which is created and nothing happens). I know my problem is related to the jfoenix.jar library because it seems that it doesn't attach to my project properly but I don't know how to attach external libraries like jfoenix.jar to my project for creating a jar file of the project. Maybe I did something wrong in my steps.
I follow below steps to create jar in IntelliJ:
1-Project Structure->build artifact->select the main class->Ok.
2-Build->Build Artifacts
I check this post "Adding external library to artifact jar in IntelliJ IDEA" but my problem doesn't solve with the solution. If I omit the Jfoenix from the artifact it works properly but when I attach it in the artifact jar file does not work at all.

A: Apparently, the issue was with running on Java 9, similar to the one reported here. The solution is to either run on Java 8 or use the Jfoenix jar version built specifically for Java 9.


text:
Q: Single page: set elements at bottom of page in any browser or device I am developing a website where I have a top menu and a background image with some text on the home page. This covers the whole screen. BUT at the bottom of the screen there have to be 3 blocks who show up at the bottom of any screen or device. I am able to to this for Chrome but for Firefox for example the blocks are way far down at IE the same... What I want:

I am currently doing applying following code on the div containing the 3 blocks:
position: relative;
top: -150px;

But as mentioned above in another browser this div shows up to low so the user won't see it until he scrolls...
Any solutions here?

A: Simple change:
position: fixed;
bottom: 0;

Better idea to wrap it inside another <div class="bottom-stuff"> and give the rules to .bottom-stuff.


text:
Q: Spring AOP pass String argument of a controller method I have a controller class with one RequestMapping method which is taking String arguments. I want to pass this argument by using Spring AOP but its failing, I am getting null value when I am printing the value.
Tried with the below provided solution but its working with map but not with String.
Spring AOP pass argument of a controller method
@Controller
public class WelcomeController {
    @Autowired
    private FamilyService familyService;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public ModelAndView welcomePage(String welcomeMessage) {
        FamilyVO allFamilyMembers = familyService.getAllFamilyMembers();
        ModelAndView modelAndView = new ModelAndView("Index", "family", allFamilyMembers);
        List<String> familyMemberAges = new ArrayList<String>();
        for (int i = 0; i <= 100; i++) {
            familyMemberAges.add("" + i);
        }
        modelAndView.addObject("familyMemberAges", familyMemberAges);
        System.out.println(welcomeMessage);
        return modelAndView;
    }
}

@Component
@Aspect
public class WelcomeControllerAspect {
    @Before("execution(* com.kalavakuri.webmvc.web.controller.WelcomeController.welcomePage(..))")
    public void beforeWelcomePage(JoinPoint joinPoint) {
        joinPoint.getArgs()[0] = "Hellow";
        System.out.println(joinPoint.getArgs().length);
        System.out.println("Before welcomepage");
    }
}

I am expecting the value "Hello" when I print it in Controller class but printing null.

A: A @Before advice is not meant to manipulate method parameters. In the example you linked to it only works because the argument is a mutable object, namely a Map. A String is immutable, though, you cannot edit it.
Having said that, what should you do? Use an @Around advice which was designed for that kind of thing. There you can decide how you want to proceed, e.g.

*

*call the original method with original parameters,

*call the original method with changed parameters,

*do something before and/or after calling the original,

*don't call the original method but return another result instead,

*handle exceptions in the original method

*or any mix of the above which makes sense (maybe you have multiple cases and if-else or switch-case).

I also suggest not to work directly on the Object[] of JoinPoint.getArgs() but to bind the relevant method parameter(s) to a named and type-safe advice parameter via args(). Try this:
package de.scrum_master.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class WelcomeControllerAspect {
  @Around(
    "execution(* com.kalavakuri.webmvc.web.controller.WelcomeController.welcomePage(..)) && " +
    "args(welcomeMessage)"
  )
  public Object beforeWelcomePage(ProceedingJoinPoint joinPoint, String welcomeMessage) throws Throwable {
    System.out.println(joinPoint + " -> " + welcomeMessage);
    return joinPoint.proceed(new Object[] { "Hello AOP!" });
  }
}

A: You should use an @Around advice instead of a @Before.
See this answer for more details.


text:
Q: need help writing this compound trigger i have a column in my table that i need to update on insert or update, i can't do it with a simple trigger because the new value has to be SELECTED from the same table and other tables (which would generate trigger is mutating error).
my solution was to use a compound trigger, after a little bit of documentation i wrote this code:
CREATE OR REPLACE TRIGGER update_contract_n FOR
    INSERT OR UPDATE ON contract
COMPOUND TRIGGER
    v_n VARCHAR(70);
    AFTER EACH ROW IS BEGIN
        v_n := object_contract(:new.id_contract);
    END AFTER EACH ROW;
    AFTER STATEMENT IS BEGIN
        UPDATE contract
        SET
            n = v_n
        WHERE
            id_contract = :new.id_contract;
    END AFTER STATEMENT;
END update_contract_n;

the function object_contract() joins 4 tables one of which is the table contract and returns a varchar.
when i compile the trigger code i get this error :
pls-00679 trigger binds not allowed in before/after statement section

but i don't know what i'm doing wrong since the variable binding was done in AFTER EACH ROW section not in AFTER STATEMENT.
any help would be appreciated (fixing or rewriting the code), a simple guide on how to use a compound trigger would also be appreciated.
EDIT:
i found the problem, i was referencing :new.id_contract in AFTER STATEMENT and i fixed it, but now i am getting  table is mutating trigger/function may not see it
how can i fix that?


text:
Q: Kibana server is not ready yet(Mac m1) I trying to use docker container :elastic search and kibana. \But keep face to this word "Kibana server is not ready yet", when I connect to the web (http://localhost:5601/)

my system:

*

*Mac m1 os

*docker version : 20.10.22, build 3a2c30b

Below is my yaml file
version: '3.6'
services:
  es01:
    image: docker.elastic.co/elasticsearch/elasticsearch:7.16.2
    platform:linux/amd64
    container_name: es01
    environment:
      - node.name=es01
      - cluster.name=es-docker-cluster
      - discovery.seed_hosts=es02,es03
      - cluster.initial_master_nodes=es01,es02,es03
      - bootstrap.memory_lock=true
      - "ES_JAVA_OPTS=-Xms1g -Xmx1g"
    ulimits:
      memlock:
        soft: -1
        hard: -1
    volumes:
      - data01:/usr/share/elasticsearch/data
    ports:
      - 9200:9200
    networks:
      - elastic
  kibana:
    image: docker.elastic.co/kibana/kibana:7.16.1
    platform: linux/amd64
    container_name: kibana
    ports:
      - 5601:5601
    environment:
      - ELASTICSEARCH_HOSTS=["http://es01:9200"]
    depends_on:
      - es01
    networks:
      - elastic

volumes:
  data01:
    driver: local
networks:
  elastic:
    driver: bridge

docker ps -a : looks fine.
I have no idea what is wrong.
please let me know.


text:
Q: Regular Expression to match outer brackets but ignoring comment lines with brackets I'm trying to create a regular expression to match outer brackets but ignoring brackets from comment lines inside the outer brackets.
Example string:
(
this is an example;
// this is a comment line with an '(' in it and should be ignored
this is (another) line;
)

My current regex:
\(((?>\((?<c>)|[^()]+|\)(?<-c>))*(?(c)(?!)))\)

this is, what i get:
(' in it and should be ignored
this is (another) line;
)

but i need this:
this is an example;
// this is a commentline with an '(' in it and should be ignored
this is (another) line;

A: Here are the ways to do this.

*

*Using (?<=\()(.*?)(?=\)) Demo which uses look around assertions.

*Using \((.*?)\) Demo which uses captured group. Capture \1.
Note: Use DOTOALL flag s to allow . matching newlines.
Fixed your demo using lazy quantifier ?.

The above regex would work in many cases. After a lot of other specifications by the OP here is the final demo.
Final Demo

A: Try this
\((([^)]+)|(\/\/[^\n]+\n))\)


text:
Q: take-while and java-time/iterate creating odd results I'm using clojure.java-time version 0.3.2 and I have a TemporalAdjuster defined like this:
(def next-pay-day
  (reify java.time.temporal.TemporalAdjuster
    (adjustInto [this temporal]
      (let [local-date (java.time.LocalDate/from temporal)
            day-of-month (j/as local-date :day-of-month)
            last-day-of-month (j/as (j/adjust local-date :last-day-of-month) :day-of-month)]
        (cond
          (= day-of-month last-day-of-month)
          (j/plus local-date (j/days 14))

          (< day-of-month 14)
          (j/plus local-date (j/days (- 14 day-of-month)))

          :else
          (j/adjust local-date :last-day-of-month))))))

Which works something like this:
=> (require '[pto-calculator.logic.pay-periods :as p])
nil
=> (require '[java-time :as j])
nil
=> (take 4 (j/iterate j/adjust (j/local-date 2019 3 3) p/next-pay-day))
(#object[java.time.LocalDate 0x74e53020 "2019-03-03"] #object[java.time.LocalDate 0x49980a "2019-03-14"] #object[java.time.LocalDate 0x2e332a36 "2019-03-31"] #object[java.time.LocalDate 0x5e7aaec6 "2019-04-14"])

I'm trying to generate a list of pay days between today and t, where t is some LocalDate in the future. I have this, but the problem is it seems  to work for some dates (April 15th):
=> (take-while #(= 1 (compare (j/local-date 2019 4 15) %)) (j/iterate j/adjust (j/local-date 2019 3 3) p/next-pay-period))
(#object[java.time.LocalDate 0xc994eb6 "2019-03-03"] #object[java.time.LocalDate 0x3ec8e48 "2019-03-14"] #object[java.time.LocalDate 0x1bddd9d5 "2019-03-31"] #object[java.time.LocalDate 0x133ed931 "2019-04-14"])
; Last date is 2019-04-14 (expected)

But not for others (April 18th):
=> (take-while #(= 1 (compare (j/local-date 2019 4 18) %)) (j/iterate j/adjust (j/local-date 2019 3 3) p/next-pay-period))
(#object[java.time.LocalDate 0x7f0ac64b "2019-03-03"] #object[java.time.LocalDate 0x1f1d3684 "2019-03-14"] #object[java.time.LocalDate 0x70415bc3 "2019-03-31"])
; Last date is 2019-03-31 (unexpected, should be 2019-04-14)

Why is the operation cutting short for April 18th, but working fine for April 15th?

A: compare does not always return 1, 0, or -1. So, instead of:
#(= 1 (compare (j/local-date 2019 4 15) %))

try:
#(pos? (compare (j/local-date 2019 4 15) %))


text:
Q: How to print screen in Remote Desktop Client (RDS) on Mac OS X? I'm using version 2.1.0 of Remote Desktop Client on my MacBook Pro with Mac OS X Snow Leopard (version 10.6). How do I use the fn or cmd call to simulate a print screen on the remote system?

A: Alt+Page Up replaces Alt+Tab to "tab" through running applications in the RDP window.
Alt+Page Up+Numpad + takes a screen print of the remote desktop (just like using PrintScrn on a local computer).
Alt+Page Up+Numpad - takes a screen print of the active window inside the RDP window (just like using Alt+PrintScrn on the desktop).

A: Warning: This may close the current application for some users
I believe what you're looking for is Fn+Option+F4.  This gives me a "print screen" command inside the Windows RDP session to trigger application like SnagIt.
Pressing Fn gives you the straight function keys inside the RDP session, or at least this has worked for my MBP keyboard.

A: if you click on the RDC menu at top of screen on OSX,  click on preferences,  then keyboard,  you should have a Mac shortcut of option f4 (default)  i actually remapped mine to option 1 (as i couldn't get option f4 to work on the standard bluetooth keyboard,  but obviously you can map to whatever you like

A: Easy way: PDF what you want a shot of then use "take a snapshot" from the pdf and just hit paste where you need it.  Saves it to the PC clipboard thru your mac.
Your welcome :-)

A: Here's an alternative solution to Oliver's answer for those that have those "half" mac keyboards without number pads,
From within the RDP Windows screen, Start > All Programs > Accessories > Ease of Use > On-Screen Keyboard.
This onscreen keyboard has all of the keys you need including Print Screen.

A: You may find that your RDS admin has provided a separate snipping tool to provide this function - my session certainly has this. Checking the app, it seems to be part of the Windows Server 2008 R2 Standard server release.

A: *

*Press Command+Space ⌘ commandSpace (Windows+Space ⊞ WinSpace when plugging a PC keyboard).  Alternatively, move the mouse to the top of the screen to bring up the MacOS system ribbon (Mojave here) and click the looking glass icon  on the right.  Observe the transparent input field in the middle of the screen.

*Type "screenshot" and click the "screenshot.app" result.  The screenshot app will launch, offering to select the screen area to snapshot.

*The shutter button resides in the bottom of the screen, in a transparent block of large icons.

A: Faster alternative solution / remote machine is Win7: on remote machine, open Start menu (hit cmd on Mac keyboard), type "osk" (wihout quotes), make sure "osk.exe" is highlighted, hit Enter on Mac keyboard. (osk.exe = On Screen Keyboard).

A: In the Citrix remote session on a mac, move your mouse to the top of the screen. The Citrix menu bar will drop down.
Click in this order,
Devices->Keyboard->Send Key->Print Screen
If you use the windows on screen keyboard as in a previous answer it will include a photo of the keyboard. If you do the citrix menu option it just takes the entire screen the way you want.

A: Yet another alternative is the following.
If you have the Send to OneNote tool (part of MS Office) running on your remote Windows machine, then an easy solution is to hit COMMAND+S, select the region you would like to copy and subsequently click Copy to Clipboard.
This has the benefit of selecting only a part of the screen.

A: On my wired Apple-Keyboard, i can use F13 as an equivalent to the PrintScreen-Key on windows.

A: Have been struggling with this since some time on my Mac with a citrix client opening my work Windows machine.
Finally figured a solution that works for apps like Snagit.
Open the settings/preferences of the screen-capture app (in my case Snagit), and change the hotkey.
I changed it to F1. You can use any hotkey of your choice.
And now the print-screen works marvellously on my Windows remote desktop from my Macbook.


text:
Q: How to synchronously update mapbox gl style? Context:
I have an application that steps through an array that contains arrays of feature IDs that I want to style every 100ms or when a user clicks a back/forward button. My current implementation uses a custom event listener where I update the index of the outer array to get a new set of features. I start by using removeFeatureState() to clear the feature states and then for each of the feature ids in the new inner array I use setFeatureState() to control the styling.
Code:
document.addEventListener('update', function (e) {
            var algo_step = run_data[run_index];
            map.removeFeatureState(
                {source: 'precincts'});

            if (algo_step.feasible){
                let district_ix = 0;
                for(center in algo_step.partition){
                    algo_step.partition[center].forEach(precinct =>
                        map.setFeatureState(
                            { source: 'precincts', id: precinct },
                            { district_n : district_ix }
                        ));
                    district_ix++;
                }
            }
            else{
                algo_step.area.forEach(precinct =>
                    map.setFeatureState(
                        { source: 'precincts', id: precinct },
                        { infeasible : true }
                    ));
            }
        }, false);

Problem: When I run the application the styling sometimes does not update correctly. My current understanding is that this is because of asynchronous updates to the feature state not happening before the map is rendered but I am not positive.
Expected Behavior

(sometimes) Observed Behavior

Therefore I think that I can solve this problem if I can update the map synchronously and/or at the end of the event listener render the map with all of the feature-states updated. Based on https://github.com/mapbox/mapbox-gl-js/issues/7893 it is not clear if this is currently implemented.
Any ideas on how to fix this issue?

A: It's a bit hard to say without seeing it in action, but it sounds like some kind of race condition that happens when your update function sometimes takes more than 100ms?
One thing you could try is waiting for the idle event, and skipping updates occasionally.
Something like this:
let idle = true;
map.on('idle', {
  idle = true;
});
window.setInterval(() => {
  if (!idle) {
    return; // still processing something, let's skip
  }
  idle = false;
  var algo_step = run_data[run_index];
  // ... rest of update function
}, 100);


text:
Q: C# Многопоточность using System.IO;
using System.Net;
using System.Text;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace Class1
{
    class Program
    {
        private static int Threads = 2;
        private static string FileToRead = "File.txt";
        private static string Target = "admin";

        private static string[] ReadFile = System.IO.File.ReadAllLines(FileToRead);

        private static void StartThreads()
        {
            System.Threading.Thread newThread;
            newThread = new Thread(new ThreadStart(Scanner));
            newThread.Start();
        }

        public static void Scanner()
        {
            foreach (string Line in ReadFile)
            {
                if (Line == Target)
                {
                    Console.Write("" + Line + " == " + Target + "\r\n");
                    Thread.Sleep(5000);
                }
                else if (Line != Target)
                {
                    Console.Write("" + Line + " != " + Target + "\r\n");
                }
            }
        }

        static void Main(string[] args)
        {
            for (int i = 0; i < Threads; i++)
            {
                    StartThreads();
            }
        }
    }
}

Принцип действия код выше.
Заходит строитель на стройку и видит кучу кирпичей берет один кирпич и несет его нормально на склад, пока возвращался подумал а почему бы не взять 2 кирпича двумя руками в каждую по одному подошел к куче и взял 2 кирпича, задумался и сходил 2 раза на склад с кирпичами в руках, взял 4 кирпича 2 в каждую ногу 2 в каждую руку понес и опять задумался и сходит 4 раза на склад, как сделать чтобы строитель брал например по 2 кирпича в каждую руку и нормально относил на склад, затем возвращался еще за 2.
код ищет строку в файле сверяет её с переменной "Target" и выводит на экран.
проблема с потоками если задать потоков 1 все будет нормально, если 2 то код будет обрабатывать одну и туже строку 2 раза если 3 то тоже ... и так далее ...
как решить проблему?)
сколько раз уже задавал вопрос где только не задавал никто толком не ответил если и ответил то не помогло.
A: У Вас проблема в том, что каждый поток заново перебирает весь набор строк. Нужно чтобы перебор работал независимо в каждом потоке. Для этого проще всего использоваться перечислитель массива ReadFile. Т.е. до старте потоков делаете var iterator = ReadFile.GetEnumerator() и передаете его в качестве параметра в функцию Scanner (или, чтобы сохранить стиль, объявляете глобально). Внутри функции Scanner вместо foreach последовательно выбираете элементы из итератора. Итератор является совместно используемым ресурсом, поэтому обращение к его методам надо защитить с помощью оператора lock:
string nextString;

while (true) {

    lock (iterator)
    {
        if (!iterator.MoveNext())
            break; //если строки кончились - выходим из цикла
        nextString = iterator.Current;
    }
    doSomethingWith(nextString);
}

A: лочить надо просто. почитайте про lock(){}
и надо не форыч использовать, а енумератор и его лочить и при его помощить коллекцию в потоках перебирать.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Thread[] threads = new Thread[Environment.ProcessorCount];

            for (int i = 0; i < threads.Length; i++)
            {
                threads[i] = new Thread(new ThreadStart(startThread));
                threads[i].Start();
            }

        }

        private static string[] bla = new string[] { "", "", "", "", "", "", "", "",     "", "", "", "" };
        private static IEnumerator tmp = bla.GetEnumerator();

        private static  void startThread()
        {
            bool exit;
            do{
                string workstr;
                lock (tmp)
                {
                    if (tmp.MoveNext())
                        workstr = tmp.Current as string;
                    else
                        exit = true;
                }
                // обработка строки
            }while (!exit);
        }
    }
}

примерно так, дальше допилите как надо по этому примеру. надеюсь, помог.. не проверял только - корпаратив был, не до этого :)


text:
Q: Change the RequestFormat globally for every routes in Symfony 2 application Is there a way to change the default html RequestFormat for all my routes in the application?
This might work, but I need to set this to each individual route:
article_show:
  pattern:  /articles/{culture}/{year}/{title}.{_format}
  defaults: { _controller: AcmeDemoBundle:Article:show, _format: %global_format% }


text:
Q: Hibernate + JPA + jTDS + SQL Server = Unicode Problems I maintain a piece of software that runs as a Servlet and can make use of MySQL, Oracle or SQL Server as the DB backend - depending on what the Customer wants to use.
Everything works perfectly with MySQL and Oracle, and SQL Server works great too, except I cannot insert/update Unicode sequences into the database.
I can do a manual insert in SQL Server Management Studio of a unicode sequence like this
INSERT INTO mytable (msg) VALUES (N'Modern Standard Hindi (मानक हिन्दी), is a standardised and Sanskritised register of the Hindustani language.')

This data is output in my software correctly, so this verifies that the database and the web front end can both handle unicode no problem.
And here's my connection string
jdbc:jtds:sqlserver://<server ip>:1433/MyDb

As I said, Oracle and MySQL work perfectly using this setup. What's different about SQL Server?
Note: I also tried the official Microsoft-provided JDBC driver with exactly the same results.
If it makes a difference, I'm using JPA Repositories to do my DB interactions. The whole webapp is also set up as a SpringMVC application.
Edit: I also tried adding useUnicode=true;characterEncoding=UTF-8 to the end of my connection string with the same results

A: You may need to specify in your connection string that you're using Unicode, and also what encoding you're using. Maybe something like this?
jdbc:jtds:sqlserver://<server_ip>:1433;databaseName=MyDb;useUnicode=true;characterEncoding=UTF-8

A: So there was one thing I left off my original question.
I had the system set up with Spring Security and a CharacterEncodingFilter in the filter chain to force UTF-8 in all requests and responses, but I had it set up in the afterSpringSecurityChain section of my web security initializer.
I moved the filter into the beforeSpringSecurityChain method and boom - everything UTF-8 works perfectly with all DB vendors.
I ended up not adding any params to my connection string or anything either. It was literally just the filter that I changed.


text:
Q: Can a PUT perform a merge on an entity without using a custom PUT operation? I would like to implement a PUT request that merges data.
For example:
I have an entity Article where the content property is "Lorem Ipsum. " and when I perform a PUT on that entity with content = "Hey !" I would like to the end result to be "Lorem Ipsum. Hey !".
Is that possible to do without a custom PUT operation?

A: Even though it's not possible with a standard PUT, you can always write a wrapper to do it for you :)
public void PutWithConcatenation(string contentToConcatenate)
{
    // use GET request here
    string articleContent = GetArticle().content;
    string concatenatedContent = articleContent + contentToConcatenate;

    // use PUT request here
    UpdateArticle(concatenatedContent);
}

PutWithConcatenation("Hey!");

```

A:
I would like to implement a PUT request that merges data.

Unfortunately, that's not what PUT means; so you have two problems -- first, because you aren't using the standard meaning for PUT, you are going to have to craft your own bespoke implementation.  Second, general purpose components aren't going to know about your hijacking of PUT semantics, so you are leaving yourself exposed -- any loss of property will be attributed to your violation of the semantics.
Much better to use PUT for PUT, and use something else (POST, PATCH), when you want merge.
There is a registered MERGE method;  is part of the WebDAV specification.  You could review that spec to see if the defined semantics are close to what you want.


text:
Q: Access: selecting multiple values in a multiselect listbox based on a previous selected value Sorry if this is a question which is ask many times, but im new to access and have no idea how this matter is called.
In Access I have 3 tables. The first one is Projects
Table Projects has many columns, one of them is Project_Name.
Second table is WBS
Table WBS has also many columns, one of them is WBS_Name and other is Project (which is a dropdown based on Project_Name from table 1).
Sample:
WBS table sample
The third is Orders, here is where im stuck.
Table Orders has a column called Order_Name, also in this table I have a column called Project (which is also based on Project_Name from table 1. The last column (WBS_Product) is a multiselect listbox with values from WBS_Name from table 2.
Order table sample
Now in this third table I want to see in the WBS_Product row only the values available for selection based on the Project selected in the second column.

A: You REALLY should be using forms if you want to customize your data entry like this. Because you're entering data directly into the tables, I don't believe this is possible.


text:
Q: Replace a string in one file with another string in another file I have a text file with several lines and want to replace strings that match certain values. I opted to use a dictionary to store the string-to-be-replaced as the key, and the replacement as the value. The dictionary was created by opening another text file (template.txt) that has two columns separated by a single Tab:

140101002   name44
140101030   name2
140101004   name3
140101058   name94

The input file (input.txt) has the following text:
...text... <!-- 140101002 --> ...text...
...text... <!-- 140101030 --> ...text...
...text... <!-- 140101004 --> ...text...
...text... <!-- 140101058 --> ...text...

and I want to search for the strings in the template.txt first column (like 140101002) and replace it with the strings in the second column (like name44), so that the output file (output.txt) will look like this:
...text... <!-- name44 --> ...text...
...text... <!-- name2 --> ...text...
...text... <!-- name3 --> ...text...
...text... <!-- name94 --> ...text...

I have tried fixing this several times but cannot get it to work as intended:
fhand = open("/home/Documents/input.txt")
template = open("/home/Documents/template.txt")
fout = open("/home/Documents/output.txt","w")

# store the values in the dictionary:
templateDict = dict()
for line in template:
  lineList = line.split("\t")
  templateDict[lineList[0]] = lineList[1]

# replacement:
for line in fhand:
  for key in templateDict:
    if key in line2:
      line2 = line2.replace(key,templateDict[key])
  fout.write(line2) # write to output.txt

fout.close()

A: You can read the first file into a dictionary, and then use re.sub:
import re
d = dict(re.split('\s+', i.strip('\n')) for i in open('filename.txt'))
content = [i.strip('\n') for i in open('filename2.txt')]
with open('results.txt', 'w') as f:
  f.write('\n'.join(re.sub('(?<=\<\!\-\-\s)\d+(?=\s\-\-\>)', lambda x:d[x.group()], i) for i in content))

Output:
...text... <!-- name44 --> ...text...
...text... <!-- name2 --> ...text...
...text... <!-- name3 --> ...text...
...text... <!-- name94 --> ...text...

A: I had to strip the newline character before splitting the line into a list.
fhand = open("/home/Documents/input.txt")
template = open("/home/Documents/template.txt")
fout = open("/home/Documents/output.txt","w")

# store the values in the dictionary:
templateDict = dict()
for line in template:
  lineList = line.strip("\n").split("\t")
  templateDict[lineList[0]] = lineList[1]

# replacement:
for line in fhand:
  for key in templateDict:
    if key in line:
      line = line.replace(key,templateDict[key])
  fout.write(line) # write to output.txt

fout.close()


text:
Q: Convert Excel subtotal rows to columns in R data frames I am trying to read into R Excel spreadsheets that include time-entry rows grouped by employee, which look like this when the groups are collapsed (the commas are used here to delimit columns):
Column A    Column B

Alice

2015-01-01  8
2015-01-02  7.5
2015-01-03  6

Bob

2015-01-02  6
2015-01-03  8

I am able to read the spreadsheets into data frames using the xlsx::read.xlsx2 function, but I have been unable to figure out how to convert the subtotal rows into a column, so that the data frame looks like this:
Alice   2015-01-01  8
Alice   2015-01-02  7.5
Alice   2015-01-03  6
Bob     2015-01-02  6
Bob     2015-01-03  8

I tried looking at reshape and dplyr, but I couldn't figure out if they could help.  Can someone please point me in the right direction?

A: May be this helps
library(dplyr)
library(tidyr)
#read the file using `readLines`
lines <- readLines('file.csv')
#remove the empty elements
lines1 <- lines[lines!='']
#create a grouping index based on the occurrence of non-numeric elements
indx <- cumsum(grepl('^[A-Za-z]', lines1))
#create another index for finding the position of non-numeric element
indx1 <- grep('^[A-Za-z]', lines1)
#split the lines based on the grouping index
lst <- setNames(split(lines1[-indx1], indx[-indx1]), lines1[indx1])
#use unnest from tidyr and split the `x` column into two
unnest(lst, Name) %>%
           extract(x, c('Date', 'val'), '(.*),(.*)', convert=TRUE)
#   Name       Date val
#1 Alice 2015-01-01   8
#2 Alice 2015-01-02 7.5
#3 Alice 2015-01-03   6
#4   Bob 2015-01-02   6
#5   Bob 2015-01-03   8

Or you could use base R.
#read the data using `read.csv` or `read.xlsx2`.  Here `,` is the delimiter
d1 <- read.csv('file.csv', header=FALSE, stringsAsFactors=FALSE)
#second column `V2` will have `NAs` for corresponding words in `V1`
indx <- is.na(d1$V2)
#subset the dataset by removing the `NA` rows
d2 <- d1[!indx,]
#use one of the aggregating functions
#remove the first element for each group
d2$names <-  unlist(tapply(rep(d1$V1[indx], tabulate(cumsum(indx))),
             cumsum(indx), FUN=tail,-1), use.names=FALSE)
d2
#         V1  V2 names
#2 2015-01-01 8.0 Alice
#3 2015-01-02 7.5 Alice
#4 2015-01-03 6.0 Alice
#6 2015-01-02 6.0   Bob
#7 2015-01-03 8.0   Bob


text:
Q: How to print a christmas tree in Java, by calling methods? I neeed help with the following problem.
This program has three outputs: one triangle, and two christmas trees. I have been successful with printing the triangle, but I can't figure out how to get my tree work. Here is the link to the exercise 40: https://materiaalit.github.io/2013-oo-programming/part1/week-2/
Please note, this is not my hoomework. I am learning how to code by myself, at home.
Here is the code:
public static void xmasTree(int height) {

    for (int i = 1; i <= height; i++ ) {
        printWhitespaces(height - 1);
        printStars( i );

    }
 for( int j = 2; j <= height; j++ ){
            printWhitespaces ( height - j );
            printStars ( j - 1 );
        }

}

This must be the final output:
            *
           ***
          *****
         *******
        *********
       ***********
      *************
     ***************
    *****************
   *******************
           ***
           ***

But I get this:
            *
            **
            ***
            ****
            *****
            ******
            *******
            ********
            *********
            **********
           *
          **
         ***
        ****
       *****
      ******
     *******
    ********
   *********

A: First of all, get used to using 0 as the first value in your loops, not 1. It takes some getting used to but it'll feel natural after 5 or 6 years :-)
You've certainly got a logic problem there. Each line for the top part of the tree should start at height - i -1 (not height - 1) and contain i * 2 + 1 stars (not i).
Similar issue with the trunk but I'll leave that with you as an exercise (since that's the point!).

A: Write down what you need to do.
Each line consist of spaces for indentation, and stars for the tree, so write down how many of each you need.
Since you'll be using a loop, e.g. counting from 0 to height - 1, write down the iterator value too
                      height = 10
         *            9 spaces,  1 stars, i = 0
        ***           8 spaces,  3 stars, i = 1
       *****          7 spaces,  5 stars, i = 2
      *******         6 spaces,  7 stars, i = 3
     *********        5 spaces,  9 stars, i = 4
    ***********       4 spaces, 11 stars, i = 5
   *************      3 spaces, 13 stars, i = 6
  ***************     2 spaces, 15 stars, i = 7
 *****************    1 spaces, 17 stars, i = 8
*******************   0 spaces, 19 stars, i = 9
        ***           8 spaces,  3 stars
        ***           8 spaces,  3 stars

Now see if you can discern the pattern:
spaces = height - 1 - i
stars = 2 * i + 1

For the trunk, you loop 2 times, use height - 2 spaces, and 3 stars, unless of course the trunk needs to somehow size with the tree height, but you didn't specify any rules for that.

A: public static void xmasTree(int height) {

    // cone
    for (int i = 1; i <= height; i++ ) {
        printWhitespaces(height - i);
        printStars( i );
        printStars( i-1 );
        System.out.println();
    }

    // trunk
    for(int i=1 ; i<=4; i++){
        printWhitespaces(height - height/4 -1);
        printStars(height/2);
        System.out.println();
    }

}

Explanation:
For printing the cone:
____h-1__*__h-1____    // h-i. Here, the number of stars = 2i-1. The star at position i becomes the midpoint
___h-1__***___h-1__
__h-2__*****__h-2__
and so on
For the trunk (assuming width changes):
__h/4__*****__h/4__    // width of the trunk = h/2
__h/4__*****__h/4__
and so on.
But as stated in the other answers, better to start with 0 in loops:
public static void xmasTree(int height) {

    // cone
    for (int i = 0; i < height; i++ ) {
        printWhitespaces(height - i - 1);
        printStars( i+1 );
        printStars( i );
        System.out.println();
    }

    // trunk
    for(int i = 0 ; i<4; i++){
        printWhitespaces(height - height/4 -1);
        printStars(height/2);
        System.out.println();
    }

}


text:
Q: Send push message to Messenger bot users I want to be able to send push messages to my Messenger bot's users at any time. I get the user ID thanks to:
event.sender.id

Then I try to send this POST request according to the Messenger doc. It returns "success" but I don't receive any message. The bot is in development.
curl -X POST -H "Content-Type: application/json" -d '{
  "recipient": {
    "id": "1451521288246029" // this is my sender id
  },
  "message": {
    "text": "hello, world!"
  }
}' "https://graph.facebook.com/v2.6/me/messenger_profile?access_token=<TOKEN>"

Any idea how to be able to send a push message?

A: Problem solved, I was using the "messenger_profile" endpoint instead of the "messages" one.


text:
Q: iOS web app to call mobile safari share function? This is a longshot, but is it possible via HTML/JavaScript e.g. For a standalone iOS web app to call the share function found in mobile safari?
E.g on a web page a user clicks a link that then calls for share to fb, twitter, email screen to pop up.

A: No. There is no access to that functionality from a webpage or a standalone web app. You can, of course, add FB/Twitter/etc sharing to your pages yourself.


text:
Q: What is the difference between the TelemetryConfiguration.CreateDefault and the new TelemetryConfiguration()? What is the difference between the TelemetryConfiguration.CreateDefault and the new TelemetryConfiguration()?
I am talking about the types from the Microsoft.ApplicationInsights.Extensibility namespace. Both seem to work the same.

A: If you are using the TelemetryConfiguration() then you have to manually set the ConnectionString property, but the TelemetryConfiguration.CreateDefault() factory method loads the ApplicationInsights.config file if it exists and some defaults.


text:
Q: Service worker: caching cross-domain response with all static assets as well I am currently working on a proof-of-concept for a project but I just can't get my head around

*

*documentation

*and implementation :)

The case is as follows:
I have my main app (React) that has a list of links. All of them link to a specific page.
These links open up in an iframe.
That's all basically.
So my app runs on "app.domain.com" and the forms urls are like "pages.domain.com/pages/pageA.html" etc.
What I need to do in this poc is to make these pages offline available, including(!) the assets for this pages (css/js/img)
I already created a simple service worker.
const CACHE_NAME = "poc-forms";

self.addEventListener("install", (event) => {
  console.log("sw installing…");
});

self.addEventListener("activate", (event) => {
  console.log("sw now ready to handle fetches");
  event.waitUntil(caches.open(CACHE_NAME).then(() => self.clients.claim()));
});

self.addEventListener("fetch", (event) => {
  const url = new URL(event.request.url);

  if (url.pathname.includes("forms")) {
    event.respondWith(
      (async function () {
        var cache = await caches.open(CACHE_NAME);
        var cachedFiles = await cache.match(event.request);
        if (cachedFiles) {
          return cachedFiles;
        } else {
          try {
            var response = await fetch(event.request);
            await cache.put(event.request, response.clone());
            return response;
          } catch (e) {
            console.log(" something when wrong!");
          }
        }
      })()
    );
  }
});

It fetches the request and checks if it's already in the cache or not.
If it's not, cache it.
This works.
But where I'm stuck:

*

*how can I also store the css and js that are needed for the pages as well? Do I need find a way to get all links and loop over them, fetch them and store them?

*I heard about Google Workbox, also went through the documentation but it's just not clear to me, like how to transform my current SW into something that works with workbox, with the whole registerRoute-thing on a fetch...

*the service worker will only capture the fetches when the page is refreshed. The clients.claim() should fix this, but it doesn't actually...

If someone out there could help me out with this, much appreciated!
thanks,
Mario

A: The Service Worker APIs do not allow for a service worker registered on app.domain.com to control either navigation requests or subresource requests associated with an <iframe> that is hosted on pages.domain.com. That's not something that Workbox can help with—it's just not possible.
From the perspective of the service worker, an <iframe> with a different origin than the host page is equivalent to a new window or tab with a different origin. The service worker can't "see" or take control of it.

A: Ok, we ended up using a different approach, because the app we are loading inside the iframe exposed an api apparently, where we can hook into.
To cache the entire page, with all the assets, this was the code that worked for me:
importScripts(
  "https://storage.googleapis.com/workbox-cdn/releases/5.1.2/workbox-sw.js"
);

const { skipWaiting, clientsClaim } = workbox.core;
const { registerRoute } = workbox.routing;
const { StaleWhileRevalidate } = workbox.strategies;

skipWaiting();
clientsClaim();

registerRoute(
  ({ request }) => {
    console.log(" request ", request.destination);
    return (
request.destination === "iframe" ||
      request.destination === "document" ||
      request.destination === "image" ||
      request.destination === "script" ||
      request.destination === "style" ||
      request.destination === "font"
    );
  },
  new StaleWhileRevalidate()
);

A: Also, this might help others, small variant of what I want to accomplish:
Why isn't my offline cached subdomain page not loading when called from other subdomain?


text:
Q: SQL Server FOR XML PATH: Set xml-declaration or processing instruction "xml-stylesheet" on top I want to set a processing instruction to include a stylesheet on top of an XML:
The same issue was with the xml-declaration (e.g. <?xml version="1.0" encoding="utf-8"?>)
Desired result:
<?xml-stylesheet type="text/xsl" href="stylesheet.xsl"?>
<TestPath>
  <Test>Test</Test>
  <SomeMore>SomeMore</SomeMore>
</TestPath>

My research brought me to node test syntax and processing-instruction().
This
SELECT 'type="text/xsl" href="stylesheet.xsl"' AS [processing-instruction(xml-stylesheet)]
      ,'Test' AS Test
      ,'SomeMore' AS SomeMore
FOR XML PATH('TestPath')

produces this:
<TestPath>
  <?xml-stylesheet type="text/xsl" href="stylesheet.xsl"?>
  <Test>Test</Test>
  <SomeMore>SomeMore</SomeMore>
</TestPath>

All hints I found tell me to convert the XML to VARCHAR, concatenate it "manually" and convert it back to XML. But this is - how to say - ugly?
This works obviously:
SELECT CAST(
'<?xml-stylesheet type="text/xsl" href="stylesheet.xsl"?>
<TestPath>
  <Test>Test</Test>
  <SomeMore>SomeMore</SomeMore>
</TestPath>' AS XML);

Is there a chance to solve this?

A: There is another way, which will need two steps but don't need you to treat the XML as string anywhere in the process :
declare @result XML =
(
    SELECT
        'Test' AS Test,
        'SomeMore' AS SomeMore
    FOR XML PATH('TestPath')
)
set @result.modify('
    insert <?xml-stylesheet type="text/xsl" href="stylesheet.xsl"?>
    before /*[1]
')

Sqlfiddle Demo
The XQuery expression passed to modify() function tells SQL Server to insert the processing instruction node before the root element of the XML.
UPDATE :
Found another alternative based on the following thread : Merge the two xml fragments into one? . I personally prefer this way :
SELECT CONVERT(XML, '<?xml-stylesheet type="text/xsl" href="stylesheet.xsl"?>'),
(
    SELECT
        'Test' AS Test,
        'SomeMore' AS SomeMore
    FOR XML PATH('TestPath')
)
FOR XML PATH('')

Sqlfiddle Demo

A: As it came out, har07's great answer does not work with an XML-declaration. The only way I could find was this:
DECLARE @ExistingXML XML=
(
    SELECT
        'Test' AS Test,
        'SomeMore' AS SomeMore
    FOR XML PATH('TestPath'),TYPE
);

DECLARE @XmlWithDeclaration NVARCHAR(MAX)=
(
    SELECT N'<?xml version="1.0" encoding="UTF-8"?>'
           +
           CAST(@ExistingXml AS NVARCHAR(MAX))
);
SELECT @XmlWithDeclaration;

You must stay in the string line after this step, any conversion to real XML will either give an error (when the encoding is other then UTF-16) or will omit this xml-declaration.


text:
Q: Can i use Coinbase API with dynamic web application without using Maven? I'm new in Coinbase, but little confused. I get stuck every time with Coinbase API. Have a look at this API .. https://github.com/coinbase/coinbase-java
I want to make a project with this API using JSP. Where customer could play a role with Bitcoin. But If you see this API, it generally says to use Maven. But i don't know Maven. I've good handling at jsp and servlet. Simply i just know to create a project as "dynamic web project" into Eclipse.
So, Is it possible to use Coinbase API with dynamic web project without using Maven anymore. Please help.
Help, would be appreciated!

A: Yes, you can just download jar from maven repository http://mvnrepository.com/artifact/com.coinbase.api/coinbase-java/1.5.0 (and all its dependencies...). I highly recommend for you to learn what is maven (or gradle) and just use it to control your libraries. The best solution for now is to just install maven and git and follow the steps in Manual section on this page. It will produce for you ready to use jar lib which you can add to your project. The $YOUR_JAR_DIRECTORY change with folder where you want to build this lib.


text:
Q: add www alias to site subdomains I want to add www alias to my subdomains such that www.subdomain.domain.com, points to the same content as subdomain.domain.com
In my DNS record I currently have the following
A  --mysiteip--
sudomain1 IN CNAME domain.com.
subdomaine2 IN CNAME domain.com.
www IN A --mysiteip--
In my Apache config I create virtualhosts for each subdomains, wehre I have the following in each hosts : ServerName subdomain1.mysite.com
                ServerAlias www.subdomain1.mysite.com
When I access subdomain1.mysite.com, I get served the proper content.
I tried adding www.subdomain1 IN CNAME domain.com. in my DNS record, which does not seem to be working. Can anyone point me in the correct direction?

A: My solution was indeed correct. I just needed for the DNS to propagate, which took longer than usual.


text:
Q: Is there a way we might face race condition when running async tasks on serial queue Suppose if multiple async tasks running in a serial queue are accessing a same shared resource, are there any chances we might face race condition?

A: Following the comment I've added, this is taken from Apple doc. In bold I put the emphasis to what you are looking for.

Serial queues (also known as private dispatch queues) execute one task
  at a time in the order in which they are added to the queue. The
  currently executing task runs on a distinct thread (which can vary
  from task to task) that is managed by the dispatch queue. Serial
  queues are often used to synchronize access to a specific resource.

If you are using  a concurrent queue instead you could have a race condition. You can prevent it using dispatch barriers, for example. See Grand Central Dispatch In-Depth: Part 1/2 for more details.
For NSOperation and NSOperationQueue the same applies. NSOperationQueue can be made serial with maxConcurrentOperationCount set to 1. In addition, using dependencies through operations, you can synchronize the access to a shared resource.

A: No you can not run into a race condition, see what I did there, when running async tasks on a serial queue due to the fact that the type of queue has to deal with the ways the tasks are executed and while synchrony and asynchrony has to deal with the responsiveness of your application when completing an expensive task.
The reason it is easy to run into a race condition when on a concurrrent queue because on a concurrent queue tasks are allowed to be executed at the same time therefore different threads sometimes may be "racing" to perform an action and in all actuality they are overwriting the previous threads work due to the threads performing the same action. Where as on a serial queue tasks are executed one at a time so two threads cant race to complete a task because it happens in sequential order. Hope that helps!


text:
Q: How to click table row invoke modal except one column cell Borrowed the code from the other question How can i show data using a modal when clicking a table row (using bootstrap)
I modified a little bit and here is a new issue:
There is one column I am using select to set the value (Status), every time I try to select he value and set it, since the entire row invoke the modal, so does this cell as well, how to ensure that the table row still invoke the modal, but when I choose any cell in the Status column, I can set the value (no modal show up)? Is this possible?
HTML:
    Orders
<table class="table table-striped"

    ID
    Customer
    Status

        1
        24234234

            <select>
                <option value="A">A</option>
                <option value="B">B</option>
                <option value="C">C</option>
            </select>

        2
        24234234

            <select>
                <option value="A">A</option>
                <option value="B">B</option>
                <option value="C">C</option>
            </select>

        3
        24234234

            <select>
                <option value="A">A</option>
                <option value="B">B</option>
                <option value="C">C</option>
            </select>

    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>

Order

    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>

JS:
$(function(){
$('#orderModal').modal({
    keyboard: true,
    backdrop: "static",
    show:false,

}).on('show', function(){
      var getIdFromRow = $(event.target).closest('tr').data('id');
    //make your ajax call populate items or what even you need
    $(this).find('#orderDetails').html($(' Order Id selected: ' + getIdFromRow  + ''))
});

});
Here is the jsfiddle: http://jsfiddle.net/bootstrap1987/padA5/
Thanks,


text:
Q: How to change a text label from outside the 'Form.h'? I'm a C++-CLI beginner and I have to get familiar with some simple things.
I made a form with 1 label and 1 button.
I want to change the text of the label by clicking on the button and calling some text via a void in another cpp class (changetext.cpp)
Structure:
Form1.h //just a regular form code with 1 label and 1 button handler at the end
#pragma once

namespace ms {

using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;

/// <summary>
/// Summary for Form1
/// </summary>
public ref class Form1 : public System::Windows::Forms::Form
{
public:
    Form1(void)
    {
        InitializeComponent();
        //
        //TODO: Add the constructor code here
        //
    }

public:
    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    ~Form1()
    {
        if (components)
        {
            delete components;
        }
    }
public: System::Windows::Forms::Label^  label1;
private: System::Windows::Forms::Button^  button1;
public:
public:

public:
    /// <summary>
    /// Required designer variable.
    /// </summary>
    System::ComponentModel::Container ^components;

    #pragma region Windows Form Designer generated code
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    void InitializeComponent(void)
    {
        this->label1 = (gcnew System::Windows::Forms::Label());
        this->button1 = (gcnew System::Windows::Forms::Button());
        this->SuspendLayout();
        //
        // label1
        //
        this->label1->AutoSize = true;
        this->label1->Location = System::Drawing::Point(313, 140);
        this->label1->Name = L"label1";
        this->label1->Size = System::Drawing::Size(35, 13);
        this->label1->TabIndex = 0;
        this->label1->Text = L"label1";
        //
        // button1
        //
        this->button1->Location = System::Drawing::Point(101, 117);
        this->button1->Name = L"button1";
        this->button1->Size = System::Drawing::Size(100, 58);
        this->button1->TabIndex = 1;
        this->button1->Text = L"button1";
        this->button1->UseVisualStyleBackColor = true;
        this->button1->Click += gcnew System::EventHandler(this,               &Form1::button1_Click);
        //
        // Form1
        //
        this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
        this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
        this->ClientSize = System::Drawing::Size(467, 262);
        this->Controls->Add(this->button1);
        this->Controls->Add(this->label1);
        this->Name = L"Form1";
        this->Text = L"Form1";
        this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
        this->ResumeLayout(false);
        this->PerformLayout();

    }
    #pragma endregion
public: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {

         }
private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {

             changetext my = new changetext();
             my.changeText();

         }
};
    }

ms.cpp (main) //just creates the form
// ms.cpp : main project file.

#include "stdafx.h"
#include "Form1.h"

using namespace ms;

[STAThreadAttribute]
int main(array<System::String ^> ^args)
{
// Enabling Windows XP visual effects before any controls are created
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);

// Create the main window and run it
Application::Run(gcnew Form1());
return 0;
}

changetext.cpp
#include "stdafx.h"
#include "Form1.h"

int number;

void changeText()
{
number = 5;
Form1.label1->Text=number;

}

I am making a little mistake somewhere and I guess it has to do with header files, I'm used to code in java so headerfiles are not my cup of tea yet.

A: This is what to do:
Create getter in changetext.cpp
#include "stdafx.h"
#include "Form1.h"

int number = 5;

void getNumber()
{
return number;
}

Create header.h
#pragma once
void getNumber();

Include header.h and edit Form1.h
    #pragma once
#include header.h

namespace ms {

using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;

/// <summary>
/// Summary for Form1
/// </summary>
public ref class Form1 : public System::Windows::Forms::Form
{
public:
    Form1(void)
    {
        InitializeComponent();
        //
        //TODO: Add the constructor code here
        //
    }

public:
    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    ~Form1()
    {
        if (components)
        {
            delete components;
        }
    }
public: System::Windows::Forms::Label^  label1;
private: System::Windows::Forms::Button^  button1;
public:
public:

public:
    /// <summary>
    /// Required designer variable.
    /// </summary>
    System::ComponentModel::Container ^components;

    #pragma region Windows Form Designer generated code
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    void InitializeComponent(void)
    {
        this->label1 = (gcnew System::Windows::Forms::Label());
        this->button1 = (gcnew System::Windows::Forms::Button());
        this->SuspendLayout();
        //
        // label1
        //
        this->label1->AutoSize = true;
        this->label1->Location = System::Drawing::Point(313, 140);
        this->label1->Name = L"label1";
        this->label1->Size = System::Drawing::Size(35, 13);
        this->label1->TabIndex = 0;
        this->label1->Text = L"label1";
        //
        // button1
        //
        this->button1->Location = System::Drawing::Point(101, 117);
        this->button1->Name = L"button1";
        this->button1->Size = System::Drawing::Size(100, 58);
        this->button1->TabIndex = 1;
        this->button1->Text = L"button1";
        this->button1->UseVisualStyleBackColor = true;
        this->button1->Click += gcnew System::EventHandler(this,&Form1::button1_Click);
        //
        // Form1
        //
        this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
        this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
        this->ClientSize = System::Drawing::Size(467, 262);
        this->Controls->Add(this->button1);
        this->Controls->Add(this->label1);
        this->Name = L"Form1";
        this->Text = L"Form1";
        this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
        this->ResumeLayout(false);
        this->PerformLayout();

    }
#pragma endregion
public: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {

         }
private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {

label1->Text=""+getNumber();

}
};
}


text:
Q: When i post some content to a Page on Facebook with the Graph API, it is only visible to me I post some content to page in facebook with Graph API.But this post not published for another people.They dont see all post posted by my app.Only I saw them! What is my problem?
permisions of user access_token
// my post's content
post_to_fb_page([
    'message' => 'My message',
    'link' => 'my url'
]);

my post posted by my app
My post posted by my app is public,but it not show for another people, and if i post my facebook account, it is show for all people.

A: Your App is not public, go to your App dashboard and make sure the switch in the upper right corner is activated and it says "Status: Live". Posts made by Apps that are not live do not show up for regular users.


text:
Q: How to show Bootstrap 3 popover scroll only when needed I have this popover, with a scroll bar
HTML

<a href="#" data-toggle="popover" title="Notifications" data-html="true" data-content="
Notification 1

Notification 2

Notification 3

Notification 4

Show all

">Notification

CSS
.popover-body {
  height: 200px;
  overflow-y: auto;
 }

I want to show the scroll bar only when needed, that is only when the height of the popover-content go over the height of 200px. At the time the scroll bar is always displayed, but is not clickable (of course) when the height is less than 200px.
How can i do it?
Any help would be greatly appreciated. Thanks!

A: You can use overflow:auto . Read more about overflow property here

A: Set overflow-y to auto. This will show the scroll only when the content crosses 200px height.
"overflow-y: auto;"

This should work.

A: After opening the popover, write a settimeout and calucate the height of the popover by css.
If height is more than required, add
$("popover-content").css("max-height", "200px");
$("popover-content").css("overflow-y", "auto");

This will help :)