text:
Q: Space between two rows in a table? Is this possible via CSS?
I'm trying
tr.classname {
  border-spacing: 5em;
}

to no avail. Maybe I'm doing something wrong?

A: I stumbled upon this while struggling with a similar issue. I've found Varun Natraaj's answer to be quite helpful, but I would use a transparent border instead.
td { border: 1em solid transparent; }

Transparent borders still have width.

A: From Mozilla Developer Network:

The border-spacing CSS property specifies the distance between the borders of adjacent cells (only for the separated borders model). This is equivalent to the cellspacing attribute in presentational HTML, but an optional second value can be used to set different horizontal and vertical spacing.

That last part is often overseen. Example:
.your-table {
    border-collapse: separate; /* allow spacing between cell borders */
    border-spacing: 0 5px; /* NOTE: syntax is <horizontal value> <vertical value> */

UPDATE
I now understand that the OP wants specific, seperate rows to have increased spacing. I've added a setup with tbody elements that accomplishes that without ruining the semantics. However, I'm not sure if it is supported on all browsers. I made it in Chrome.
The example below is for showing how you can make it look like the table exists of seperate rows, full blown css sweetness. Also gave the first row more spacing with the tbody setup. Feel free to use!
Support notice: IE8+, Chrome, Firefox, Safari, Opera 4+

.spacing-table {
  font-family: 'Helvetica', 'Arial', sans-serif;
  font-size: 15px;
  border-collapse: separate;
  table-layout: fixed;
  width: 80%;
  border-spacing: 0 5px; /* this is the ultimate fix */
}
.spacing-table th {
  text-align: left;
  padding: 5px 15px;
}
.spacing-table td {
  border-width: 3px 0;
  width: 50%;
  border-color: darkred;
  border-style: solid;
  background-color: red;
  color: white;
  padding: 5px 15px;
}
.spacing-table td:first-child {
  border-left-width: 3px;
  border-radius: 5px 0 0 5px;
}
.spacing-table td:last-child {
  border-right-width: 3px;
  border-radius: 0 5px 5px 0;
}
.spacing-table thead {
  display: table;
  table-layout: fixed;
  width: 100%;
}
.spacing-table tbody {
  display: table;
  table-layout: fixed;
  width: 100%;
  border-spacing: 0 10px;
}

        Lead singer
        Band

        Bono
        U2

        Chris Martin
        Coldplay

        Mick Jagger
        Rolling Stones

        John Lennon
        The Beatles

A: The correct way to give spacing for tables is to use cellpadding and cellspacing e.g.

A: You may try to add separator row:
html:

css:
table tr.separator { height: 10px; }

A: Works for most latest browsers in 2015. Simple solution. It doesn't work for transparent, but unlike Thoronwen's answer, I can't get transparent to render with any size.
    tr {
      border-bottom:5em solid white;
    }

A: table { border-collapse: separate; border-spacing: 0 1em; }

A: You need to use padding on your td elements. Something like this should do the trick. You can, of course, get the same result using a top padding instead of a bottom padding.
In the CSS code below, the greater-than sign means that the padding is only applied to td elements that are direct children to tr elements with the class spaceUnder. This will make it possible to use nested tables. (Cell C and D in the example code.) I'm not too sure about browser support for the direct child selector (think IE 6), but it shouldn't break the code in any modern browsers.

/* Apply padding to td elements that are direct children of the tr elements with class spaceUnder. */

tr.spaceUnder>td {
  padding-bottom: 1em;
}

      A
      B

      C
      D

      E
      F

This should render somewhat like this:
+---+---+
| A | B |
+---+---+
| C | D |
|   |   |
+---+---+
| E | F |
+---+---+

A: Best way is to add  with a height attribute:

You can read more about colspan here.
In the following example, our table is green and our td with the height attribute is yellow:

            Lorem

            Ipsum

            Sit

            Amet

A: In the parent table, try setting
border-collapse: separate;
border-spacing: 5em;

Plus a border declaration, and see if this achieves your desired effect.
Beware, though, that IE doesn't support the "separated borders" model.

A: You can't change the margin of a table cell. But you CAN change the padding. Change the padding of the TD, which will make the cell larger and push the text away from the side with the increased padding. If you have border lines, however, it still won't be exactly what you want.

A: Take a look at the border-collapse: separate attribute (default) and the border-spacing property.
First, you have to seperate them with border-collapse, then you can define the space between columns and rows with border-spacing .
Both of these CSS properties are actually well-supported on every browser, see here.

table     {border-collapse: separate;  border-spacing: 10px 20px;}

table,
table td,
table th  {border: 1px solid black;}

    Some text - 1
    Some text - 1

    Some text - 2
    Some text - 2

    Some text - 3
    Some text - 3

A: Simply put div inside the td and set the following styles of div:
margin-bottom: 20px;
height: 40px;
float: left;
width: 100%;

A: you can do something like on your table :
table {
  border-collapse: separate;
  border-spacing: 0 15px;
}

table selective: as it will select all tables, so if you want to select single table you can do likewise

For the above html you can do like this, note that for specific table if you want then you can use the below approach.
.res {
      border-collapse: separate;
      border-spacing: 0 15px;
    }

Reference:https://www.w3docs.com/snippets/css/how-to-create-space-between-rows-in-the-table.html

A: Ok, you can do
tr.classname td {background-color:red; border-bottom: 5em solid white}

Make sure the background color is set on the td rather than the row. This should work across most browsers... (Chrome, ie & ff tested)

A: You have table with id albums with any data... I have omitted the trs and tds

In the css:
table#albums
{
    border-collapse:separate;
    border-spacing:0 5px;
}

A: You need to set border-collapse: separate; on the table; most browser default stylesheets start at border-collapse: collapse;, which ditches border spacing.
Also, border-spacing: goes on the TD, not the TR.
Try:

A	B

C	D

A: You can fill the  elements with
 elements, and apply any margin to those divs that you like.  For a visual space between the rows, you can use a repeating background image on the
 element.  (This was the solution I just used today, and it appears to work in both IE6 and FireFox 3, though I didn't test it any further.)
Also, if you're averse to modifying your server code to put
s inside the s, you can use jQuery (or something similar) to dynamically wrap the  contents in a
, enabling you to apply the CSS as desired.

A: I realize this is an answer to an old thread and may not be the solution requested, but while all the suggested solutions did not do what I needed, this solution worked for me.
I had 2 table cells, one with background color, the other with a border color. The above solutions remove the border, so the cell on the right would appear to be floating in mid-air.
The solution that did the trick was to replace the table, tr and td with divs and corresponding classes: table would be div id="table_replacer", tr would be div class="tr_replacer" and td would be div class="td_replacer" (change closing tags to divs as well obviously)
To get the solution for my problem the css is:
#table_replacer{display:table;}
.tr_replacer {border: 1px solid #123456;margin-bottom: 5px;}/*DO NOT USE display:table-row! It will destroy the border and the margin*/
.td_replacer{display:table-cell;}

Hope this helps someone.

A: The appearance of a row gap can be achieved by using a bottom border on the cells where there should be the next gap, i.e. border-bottom:solid white 5px;

Here is the code to create the screenshot:

Group	Item	Row

G-1	a1	1

G-2	b1	2

G-2	b2	3

G-2	b3	4

G-3	c1	5

G-3	c2	6

A: .table {
 border-collapse: separate;
 border-spacing: 0 1rem;
}

This works well for me to give a vertical margin/spacing between tables.
Reference: https://www.w3docs.com/snippets/css/how-to-create-space-between-rows-in-the-table.html

A: You can use line-height in the table:

A: since I have a background image behind the table, faking it with white padding wouldn't work. I opted to put an empty row in-between each row of content:

then use css to give the spacer rows a certain height and transparent background.

A: tr {
    display: block;
    margin-bottom: 5px;
}

A: A too late answer :)
If you apply float to tr elements, you can space between two rows with margin attribute.
table tr{
float: left
width: 100%;
}

tr.classname {
margin-bottom:5px;
}

A: For creating an illusion of spacing between rows, apply background color to row and then create a thick border with white color so that a "space" is created :)
tr
{
   background-color: #FFD700;
   border: 10px solid white;
}

A: Modern solution involving display:grid with grid-gap.
A modern solution to create a table would be using CSS grid or flexbox.
To add space between rows and columns, one can use grid-gap: [vertical] [horizontal].
To prevent "too thick / double border" with zero grid-gap, one can add margin: -1px to the cell styling. Worth noticing: you will need this hack only if you have both borders and grid-gap of zero.

my-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 10px 0px;
}

my-item {
  border: 2px solid #c60965;
  background: #ffc000;
  color: #c60965;
  margin: -1px;

  font-size: 20px;
  display: flex;
  justify-content: center;
  align-items: center;

}
<my-grid>
  <my-item>1</my-item>
  <my-item>2</my-item>
  <my-item>3</my-item>
  <my-item>4</my-item>
  <my-item>5</my-item>
</my-grid>

Space between columns is achieved in the same way. For example, 20px space between columns and 10px space between rows is done with this syntax: grid-gap: 10px 20px;.
Space inside rows / columns is achieved with paddings.

Tweakable demo
Below is an interactive demo, where you can tweak grid-gap, padding and turn on/off margin hack to see what changes.
Bonus: at the bottom you can find what code to insert for such behavior (regarding grid-gap, padding and margin hack)

<my-grid> <my-item>Cell number one</my-item> <my-item>Cell number two</my-item> <my-item>Cell number three</my-item> <my-item>Cell number four</my-item> <my-item>Cell number five</my-item></my-grid><cus><dev-grid><txt>Space between rows:</txt><input type="range" min="0" max="20" value="0"><txt>Space between cols:</txt><input type="range" min="0" max="20" value="0"><txt>Padding (rows)</txt><input type="range" min="0" max="20" value="0"><txt>Padding (cols):</txt><input type="range" min="0" max="20" value="0"><txt>Margin hack:</txt> <input class="hack" type="checkbox" checked> <tt>on</tt></dev-grid></cus><d>Code to implement this:</d>

A: Here's a simple and elegant solution, with a few caveats:

*

*You can't actually make the gaps transparent, you need to give them a specific color.

*You can't round the corners of the borders above & below the gaps

*You need to know the padding and borders of your table cells

With that in mind, try this:
td {padding:5px 8px;border:2px solid blue;background:#E0E0E0}  /* lets say the cells all have this padding and border, and the gaps should be white */

tr.gapbefore td {overflow:visible}
tr.gapbefore td::before,
tr.gapbefore th::before
{
  content:"";
  display:block;
  position:relative;
  z-index:1;
  width:auto;
  height:0;
  padding:0;
  margin:-5px -10px 5px;  /* 5px = cell top padding, 10px = (cell side padding)+(cell side border width)+(table side border width) */
  border-top:16px solid white;  /* the size & color of the gap you want */
  border-bottom:2px solid blue; /* this replaces the cell's top border, so should be the same as that. DOUBLE IT if using border-collapse:separate */
}

What you're actually doing is sticking a rectangular ::before block into the top of all the cells in the row you want preceded by a gap.  These blocks stick out of the cells a bit to overlap the existing borders, hiding them.  These blocks are just a top and bottom border sandwiched together:  The top border forms the gap, and the bottom border re-creates the appearance of the cells' original top border.
Note that if you have a border around the table itself as well as the cells, you'll need to further increase the horizontal -ve margin of of your 'blocks'.  So for a 4px table border, you'd instead use:
margin:-5px -12px 5px;     /* 14px = original 10px + 2px for 'uncollapsed' part of table border */

And if your table uses border-collapse:separate instead of border-collapse:collapse, then you'll need to (a) use the full table border width:
margin:-5px -14px 5px;     /* 14px = original 10px + 4px full width of table border */

... and also (b) replace the double-width of border that now needs to appear below the gap:
border-bottom:4px solid blue;     /* i.e. 4px = cell top border + previous row's bottom border */

The technique is easily adapted to a .gapafter version, if you prefer, or to creating vertical (column) gaps instead of row gaps.
Here's a codepen where you can see it in action:  https://codepen.io/anon/pen/agqPpW

A: doing this shown above...
table tr{ float: left width: 100%; }  tr.classname { margin-bottom:5px; }

removes vertical column alignment so be careful how you use it

A: Here this works smoothly:
#myOwnTable td { padding: 6px 0 6px 0;}

I suppose you could work out a more finely-grained layout by specifying which td if need be.

A: Have you tried:
tr.classname { margin-bottom:5em; }

Alternatively, each td can be adjusted as well:
td.classname { margin-bottom:5em; }

or
 td.classname { padding-bottom:5em; }


text:
Q: How does LOESS work in STL Decomposition Algorithm? I am trying to write a SQL program to calculate STL Decomposition of monthly time series data. In going through the algorithm in the original paper, inner loop step 2 has the detrended series grouped by sub cycle (in my case groups of months) to which LOESS smoothing is applied to produce estimated values for the data set + 6 months on either side.
How does one apply Loess to sub-series groups and produce the required estimated series?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Add an iterative legend to a python function I have 2 functions, 'one function calling other' to plot some curves. What I want is to have legends in these functions that can be seen as one in the final plot, but I am unable to achieve that. Can someone help me with this? Code below (works fine without the label/legend lines).
import matplotlib.colors as mcolors
from matplotlib.patches import Polygon

def gradient_fill(x, y, fill_color=None, ax=None, label = None, **kwargs):
    """
    Plot a line with a linear alpha gradient filled beneath it.

    Parameters
    ----------
    x, y : array-like
        The data values of the line.
    """
    if ax is None:
        ax = plt.gca()

    line, = ax.plot(x, y, **kwargs, color='black', lw = 1.5)
    if fill_color is None:
        fill_color = line.get_color()

    zorder = line.get_zorder()
    alpha = line.get_alpha()
    alpha = 1.0 if alpha is None else alpha

    z = np.empty((100, 1, 4), dtype=float)
    rgb = mcolors.colorConverter.to_rgb(fill_color)
    z[:,:,:3] = rgb
    z[:,:,-1] = np.linspace(0, alpha, 100)[:,None]

    xmin, xmax, ymin, ymax = x.min(), x.max(), y.min(), y.max()
    im = ax.imshow(z, aspect='auto', extent=[xmin, xmax, ymin, ymax*1.12],
                   origin='lower', zorder=zorder,alpha = 0.8, label = label)
    ax.legend([str(label)])
    xy = np.column_stack([x, y])
    xy = np.vstack([[xmin, ymin], xy, [xmax, ymin], [xmin, ymin]])
    clip_path = Polygon(xy, facecolor='none', edgecolor= None, closed=True)
    ax.add_patch(clip_path)
    im.set_clip_path(clip_path)
    ax.autoscale(True)
    return line, im

def gaussian_kde(data,bandwidth = 20,x_range_st = -50,x_range_end = 1000, N = 1000, fill_color = None, label = None):
    from sklearn.neighbors import KernelDensity
    # instantiate and fit the KDE model
    kde = KernelDensity(bandwidth=bandwidth, kernel='gaussian')
    kde.fit(data[:, None])
    x_d = np.linspace(x_range_st, x_range_end, N)
    # score_samples returns the log of the probability density
    logprob = kde.score_samples(x_d[:, None])
    #plt.fill_between(x_d, np.exp(logprob), alpha=0.5)
    gradient_fill(x_d,np.exp(logprob), fill_color = fill_color, label = label)
    plt.gca().invert_yaxis()

Example of the code:
gaussian_kde(data1, label = 'Apple')
gaussian_kde(data2, label = 'Banana', fill_color = 'red')
gaussian_kde(data3, label = 'Mango', fill_color = 'green')

I want to add label directly in the gaussian_kde function so that it appears in the final figure. The error I get with the code TypeError: zip argument #2 must support iteration. The code works fine, but only displays the last label. Can someone provide some guidance on how to get all the labels as also defined in the figure?


text:
Q: How to determine encoding of an ByteArrayOutputStream? I need to convert ByteArrayOutputStream  to String but I can't figure out the encoding. Please help ? I tried Using ICUJ library but It only works for input stream. A conversion from byte array to input stream is also fine.
Here's a sample of what I'm getting using the default encoding. Clearly the new lines are not supposed be there.
<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n

   \n

      \n
      <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">
      \n

      \n            \n

   \n       \n
\n
   <col>
   </col>\n

      \n

      \n

   \n

      \n

      \n

   \n

      \n

         \n

\n
Dec 23, 2013, 7:11 PM

         \n
\n

      \n

   \n
\n

   \n

   \n

The following items have errors:\n

   \n
\n

   \n

   Chart (id = 12):

\n

A:
I tried Using ICUJ library but It only works for input stream.

You can get the byte array from the ByteArrayOutputStream, and then wrap it in a ByteArrayInputStream ... and pass that to the ICUJ method.

(Bear in mind that there is a chance that ICUJ will intuit the wrong encoding.  Or that the bytes might not represent text in any known encoding.)

A: It won't much help but java.nio.charset.CharsetDecoder has a detectedCharset() method to auto identify charset of character encoded bytes. But unfortunately current impl of CharSetDecoder in Java SE7 (the one that is received by calling the method Charset.newDecoder()) is not an auto detecting charset decoder so calling detectedCharSet() method throws UnsupportedOperationException.


text:
Q: why does super function exactly use in my code? My problem is about why exactly was super(CommentManager, self) used in
 code below. couldn't that instance object in filter_by_instance just be used instead?
class CommentManager(Models.Manager):
    def filter_by_instance(self, instance):
       content_type = ContentType.objects.get_for_model(instance.__class__)
       obj_id = instance.id
       qs = super(CommentManager, self).filter(content_type=content_type,
                                         object_id=obj_id).filter(parent=None)
       return qs

Couldn't it be something like this:
class CommentManager(Models.Manager):
    def filter_by_instance(self, instance):
       content_type = ContentType.objects.get_for_model(instance.__class__)
       obj_id = instance.id
       qs = instance.filter(content_type=content_type,
                                         object_id=obj_id).filter(parent=None)
       return qs

A: When you override a method and run super().method() you're making sure the parent method will run. In your case it seems you're creating a method that it'll call the parent class method filter so instead of using Model.objects.filter() you can use Model.objects.filter_by_instance() and that will run the .filter() behind the scenes.


text:
Q: SQL Server: Count distinct dates in a group I'm still new to SQL so I may be doing this wrong but...
I need to get a distinct count of appointment dates. So John for cust.id 1 should have a count of 3 appointment dates and Sara should have a count of 2 appointment dates for cust.id 1.
Temp table (EC):
 |cust.id | emp_name | emp_id |   APPT_DATE    | Procedure_Code | something1|
 |:------:|:--------:|:------:|:--------------:|:--------------:|:---------:|
 |    1   |   john   |  100   |  2/2 00:00:00  |      a0        |    w/e    |
 |    1   |   john   |  100   |  2/3 00:00:00  |      b1        |    w/e    |
 |    1   |   john   |  100   |  2/4 00:00:00  |      c2        |    w/e    |
 |    1   |   Sara   |  200   |  2/2 00:00:00  |      d3        |    w/e    |
 |    1   |   Sara   |  200   |  2/3 00:00:00  |      e4        |    w/e    |

Answer I'm looking for:
 | cust.id | emp_name | emp_id | CNT |   APPT_DATE   | Procedure_Code |
 |:-------:|:--------:|:------:|:---:|:-------------:|:--------------:|
 |    1    |   john   |   100  |  3  |  2/2 00:00:00 |     a0101      |
 |    1    |   john   |   100  |  3  |  2/3 00:00:00 |     b1234      |
 |    1    |   john   |   100  |  3  |  2/4 00:00:00 |     c0101      |
 |    1    |   Sara   |   200  |  2  |  2/2 00:00:00 |     d0101      |
 |    1    |   Sara   |   200  |  2  |  2/3 00:00:00 |     e1234      |

My Code:
SELECT cust_id
       ,emp_name
       ,emp_id
       ,COUNT(DISTINCT APPT_DATE)
           OVER (PARTITION BY cust_id, APPT_DATE) AS CNT
       ,APPT_DATE
       ,Procedure_Code
FROM #EC
ORDER BY cust_id

A: select a.*,b.CNT
from(
    SELECT cust_id
           ,emp_name
           ,
           ,APPT_DATE
           ,Procedure_Code
    FROM #EC
     ) as a inner join (select count(distinct appt_date)as cnt, emp_id from #EC group by emp_id)as b
  on a.emp_id = b.emp_id

I think the above code can help you.

A: remove APPT_DATE from PARTITION BY
COUNT(DISTINCT APPT_DATE)
           OVER (PARTITION BY cust_id) AS CNT

EDIT 1 : change to CROSS APPLY (DISTINCT with OVER() is not allowed)
FROM #EC e
CROSS APPLY
(
    SELECT COUNT(DISTINCT APPT_DATE) as CNT
    FROM   #EC x
    WHERE  x.cust_id = e.cust_id
    AND    x.emp_id  = e.emp_id
) c

A: May be something like below should help:
select ec.cust_id, ec.emp_name, ec.emp_id, t.cnt, ec.APPT_DATE, ec.Procedure_Code
from #EC ec
join
(
    SELECT cust_id, emp_id ,COUNT(distinct APPT_DATE) CNT
    FROM #EC
    group BY cust_id, emp_id
) t
on ec.cust_id = t.cust_id and ec.emp_id = t.emp_id

A: I see from the comments that the count of dates should be distinct by both cust_id and emp_id..
SELECT cust_id
       ,emp_name
       ,emp_id
       ,oat1.Count_Appt_Date
       ,APPT_DATE
       ,Procedure_Code
FROM #EC
OUTER APPLY (SELECT ec2.cust_id
                  , ec2.emp_id
                  , COUNT(DISTINCT(CONVERT(date, ec2.[APPT_DATE]))) AS Count_Appt_Date
             FROM #EC ec2
             WHERE ec2.cust_id = #EC.cust_id
               AND ec2.emp_id = #EC.emp_id
             GROUP BY ec2.cust_id, ec2.emp_id) oat1
ORDER BY cust_id


text:
Q: Work out value between two numbers from percentage. For example I have a minimum number 200, a maximum number 680, and a percentage between 0% and 100%. How do I work out the value between 200 and 680 when the percentage is 30% (or any other between 0 and 100)?
Sorry if this has been asked before, I couldn't find anything and thanks in advance.

A: If you take $x=680-200=480$ and then you find the percentage of $x$, you will have your answer by adding $200$ to previous result.

A: $$y=\frac { 480 }{ 100 } p+200$$
For $p=30 $ you have $y=\frac { 480 }{ 100 } 30+200 = 344$

A: Well another way to look about it could be you find difference between maximum value and minimum value which is rightly calculated as 480 in first question. Then you can divide 480 in 100 equal parts of size 4.8.
Now if you have to find 30% you simply find it as:
 200+4.8*30 = 344.
If you ever need more help in such questions you can count on algebrahomeworkhelp.info
Once they really saved me from being expelled.


text:
Q: Is 1 bigger than 0.99999...... or they are equal? Here is question which always disturbs me. Could somebody help me?

Is 1 bigger than 0.99999...... or they are equal?

Thanks for your help.

A: They are equal. Suppose not. Then $|1-0.\dot{9}|=c>0$. However, $|1-0.\dot{9}|$ is less than any given positive number, this is not possible as $c$ is a fixed positive number.

A: Hint:
$10 \cdot 0.(9) = 9.(9)$


text:
Q: Trouble passing data from TableViewCell labels to a ViewController I am trying to pass data from the selected cell of an "Events" table view, to a "Details" View Controller. I have looked at various questions similar to mine, but I can't seem to properly apply it to my code. I also used labels, instead of a Subtitle style. There is also an image that needs to be passed.
my view controller looks like this:
import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

@IBOutlet var tableView: UITableView!

    var names = ["BTown Diner", "Dunnkirk", "Chocolate Mousse", "Lil Wayne", "Annie", "Campus Squad Social"]
    var details = ["Free drink with meal after 12 AM", "LADIES drink free", "10% off all ice cream!", "Lil 500 concert", "an IU Theater Production", "Bring your Squad to the Campus Squad Social"]
    var images = [UIImage(named: "btown"), UIImage(named: "dunn"), UIImage(named: "choco"), UIImage(named: "lilwayne"), UIImage(named: "default"), UIImage(named: "default")]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

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

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return names.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CustomCell

        cell.name.text = names[indexPath.row]
        cell.detail.text = details[indexPath.row]
        cell.photo.image = images[indexPath.row]

        return cell
    }

    var valueToPass:String!

    func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
        println("You selected cell #\(indexPath.row)!")

        // Get Cell Label
        let indexPath = tableView.indexPathForSelectedRow();
        let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!;

        valueToPass = currentCell.textLabel.text
        performSegueWithIdentifier("detailsSegue", sender: self)

    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

        if (segue.identifier == "detailsSegue") {

            // initialize new view controller and cast it as your view controller
            var viewController = segue.destinationViewController as detailsViewController
            // your new view controller should have property that will store passed value
            viewController.passedValue = valueToPass
        }

    }

}

and here is my customCell.swift file:
import UIKit

class CustomCell: UITableViewCell {

    @IBOutlet var photo: UIImageView!
    @IBOutlet var name: UILabel!
    @IBOutlet var detail: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

I am very new to Swift, and it has proven to be very challenging for me. I'm really not a coder, however a project demands that I complete some of the coding for an application that I am the UI/UIX designer of. Thank you for your help in advance!

A: Try to register your "CustomCell" with the name "cell"
override func viewDidLoad() {
        super.viewDidLoad()
        tableView.registerNib(UINib(nibName: "CustomCell", bundle: nil), forCellReuseIdentifier: "cell")
    }

A: Here is a slight variation on your code starting with the main view controller...
import UIKit

class EventTableViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate {

    var names = ["BTown Diner", "Dunnkirk", "Chocolate Mousse", "Lil Wayne", "Annie", "Campus Squad Social"]
    var details = ["Free drink with meal after 12 AM", "LADIES drink free", "10% off all ice cream!", "Lil 500 concert", "an IU Theater Production", "Bring your Squad to the Campus Squad Social"]
    var images = [UIImage(named: "btown"), UIImage(named: "dunn"), UIImage(named: "choco"), UIImage(named: "lilwayne"), UIImage(named: "default"), UIImage(named: "default")]

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return names.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CustomCell
        cell.name.text = names[indexPath.row]
        cell.detail.text = details[indexPath.row]
        cell.photo.image = images[indexPath.row]
        return cell
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

        if segue.identifier == "detailsSegue" {
            guard let eventVC = segue.destinationViewController as? DetailsViewController,
                  let eventIndex = tableView.indexPathForSelectedRow?.row else {
                      return
                  }
            eventVC.eventName = names[eventIndex]
            eventVC.eventDetail = details[eventIndex]
            eventVC.eventPhoto = images[eventIndex]
        }
    }
}

and then a sample detailsViewController...
import UIKit

class DetailsViewController: UIViewController {

    var eventName: String = ""
    var eventDetail: String = ""
    var eventPhoto: UIImage!

    override func viewDidLoad() {
        super.viewDidLoad()

        print(eventName)
        print(eventDetail)
    }
}

You were off to a good start.  Hope this helps get you the rest of the way.


text:
Q: Security certificate for forums.linuxmint.com On forums.linuxmint.com there seems to be on and off problems with the security certificate.  One minute the security certificate seemed to be acceptable and 5 minutes later it wasn't.  For me, it has been on and off like this for the last 24 hours.
I have never run into anything like this before.
There is no issue with my CMOS battery (as far as my computer clock being off).  Is there anything else that I should look into?
I don't notice any issue with other sites.

A: The problem has nothing to do with clocks.
The certificate is fully valid on its own, but browsers refuse to accept it because it was issued for a different domain name than you're trying to visit – it's meant for the main Linux Mint website, not for the forums. Chrome actually tells you so:

As does Firefox:

Note that the rejected certificate is quite new (issued yesterday and valid until Dec 2020), meanwhile the actual www.linuxmint.com site has a certificate expiring at Jan 2020.
So the most likely conclusion is that the sysadmins ordered a new certificate for the main website, then accidentally deployed it to the wrong web server.

A:
ne minute the security certificate seemed to be acceptable and 5 minutes later it wasn't. For me, it has been on and off like this for the last 24 hours.

The certificate is indeed invalid.  I have never been to the site before you submitted this question, and every browser I have attempted to use indicates the certificate is invalid.

There is no issue with my CMOS battery (as far as my computer clock being off). Is there anything else that I should look into?

The problem is with the certificate, not the client, there is nothing you can do to resolve the error other than ignoring it.
The certificate is invalid for the domain you are asking about.
The subject alternative name does not include the subdomain forums.linuxmint.com

*

*Not Critical

*DNS name=linuxmint.com

*DNS name=www.linuxmint.com

The domain is currently only valid for linuxmint.com and www.linuxmint.com, when you visit the main domain, it does NOT generate an error.

A: The certificate just was updated a few days ago.
It might be an issue with cache somewhere between you and the website.
They use Google and CloudFlare caching services, either of these could be having a delay updating their copy of the certificate.  If you encounter a problem hit "reload" up to three (3) times to force an update through the entire cache chain.
As of insuring your system is staying up to date on time, your CMOS clock is not very reliable, and Operating Systems don't use it for more than booting their software clock.  I recommend that instead, you set your system to  synchronize off of a public NTP time server on boot and on a regular basis while booted.  (Every 4-24 hours depending on how accurate you need your time to be.)


text:
Q: How to change a specific character from upper case to lower case using awk or sed or python? I have a line with string of characters (BCCDDDCDCCDDDDDDABCDABCABDBACBDCAACCBBCABACBCCABCACBCDCCCBDBACDCBBCBCBCCCACADAACCABABADBCBAABBBCCBB)
I'd like to replace a specific character (for e.g, 4th character) to lower case.
I have tried with this awk command;
awk '{for (i=1; i<=NF; ++i) { $i=toupper(substr($i,1,1)) tolower(substr($i,2)); } print }' input > output

input file contains the string
"BCCDDDCDCCDDDDDDABCDABCABDBACBDCAACCBBCABACBCCABCACBCDCCCBDBACDCBBCBCBCCCACADAACCABABADBCBAABBBCCBB"

This awk command gives this output:
"Bccdddcdccddddddabcdabcabdbacbdcaaccbbcabacbccabcacbcdcccbdbacdcbbcbcbcccacadaaccababadbcbaabbbccbb"

How do I change all the other characters to lowercase except the 4th character?

A: On that line you can use something like this. Through -F '' every letter is now a field which can be accessed with $i.
$ cat line
BCCDDDCDCCDDDDDDABCDABCABDBACBDCAACCBBCABACBCCABCACBCDCCCBDBACDCBBCBCBCCCACADAACCABABADBCBAABBBCCBB

$ awk -F '' '{ for(i=1;i<=NF;++i){
    if(i!=4){
      printf("%s",tolower($i))}
    else{
      printf("%s",$i)} } print "" }' line
bccDddcdccddddddabcdabcabdbacbdcaaccbbcabacbccabcacbcdcccbdbacdcbbcbcbcccacadaaccababadbcbaabbbccbb

A: With GNU sed, would you please try:
sed -E 's/(.{3})(.)/\1\L\2/' YourFile

With python, assuming the variable s is assigned to the line,
print(s[0:3] + s[3:4].lower() + s[4:])

A: An example in python of a function that makes it, I let you understand the logic and adapt it to your problem.
def f(s):
    # your result
    res = ""

    # iterate though each character in the string
    for i in range(0, len(s)):

        # on some condition, here 4th character, you add a lowercase character to your result
        if(i == 3):
            res += s[i].lower()

        # on some other conditions an upper case character...
        elif condition_2_to_create:
            res += s[i].upper()

        # or just the character as it is in the string without modification
        else:
            res += s[i]

    # Then return your result
    return res

A: Change 4th letter of every line to lowercase:
gawk '{$0 = substr($0,1,3) tolower(substr($0,4,1)) substr($0,5)} 1' YourFile

Or:
gawk -F '' '{$4=tolower($4)} 1' OFS='' YourFile

Or with Perl:
perl -pne 'substr($_,4,1) = lc(substr($_,4,1))' YourFile


text:
Q: How to convert a long value into DateTime format dd:mm:yyy hh:mm:ss in Groovy How can i convert a long value to DateTime in groovy.
The thins i tried.
def time= new Long(LastModifiedDate + timeLeft)
def time_main= time/ 1000;  where time is a long value
            def time:final= time+ 3600 + time_main;
            LocalDateTime dateTime = LocalDateTime.ofEpochSecond(Finish2, 0, ZoneOffset.UTC);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss", Locale.ENGLISH);
            String formattedDate = dateTime.format(formatter);
            test.setFinishingTime(formattedDate);

laster I am writing into SQl table having datetime2(0) format using setFinishingTime. I get the conversion error. please help.
For reference the setFinishingTime is declare as:
public Date getFinishingTime()
    {
        return getPropertyContainer().getDate(FINISHING_TIME, -1)
    }

    public void setFinishingTime(Date finishingTime)
    {
        getPropertyContainer().setDate(FINISHING_TIME, finishingTime)
    }

and FINISHING_TIME is declared as in other class:
public static final Date FINISHING_TIME = "FinishingTime"

How can i convert long into Date/DateTime format suitable for SQL table. Thank you.


text:
Q: what if the two wires of a single twisted pair are different in length? For example, one wire of a twisted pair is longer than the other wire (imbalance starts from the middle of the twisted pair, everything is balanced before the middle point). What problems will it cause?

A: The inverted signal will be phase shifted compared to the non-inverted. If the imbalance is a significant portion of the wavelength, there will be noise issues. Noise is emitted because the EM fields of the signals don't cancel each other like they do on a matched pair.

A: For a diff pair, having a mismatch not only reduces the data eye pattern margin, but it also causes common-mode current for the uncancelled portion of the signal. This will show up as noise on the ground reference alongside the pair and can be a big EMI headache.
This is a huge problem for example with HDMI on the driver side: unequal trace length adding differential skew to the pairs, resulting in common-mode noise at harmonics of the data rate. One remedy is to apply common-mode diff filters to knock down this non-cancelled noise component.


text:
Q: Bash | curl | curls 2 URL's then stops I am trying to write a simple bash script that will use a list from a text document and curl each URL that is on the list in order to see what the contents of each URL is. It allows me to cURL 2 sites and creates the text documents for the rest however it only downloads the first 2. I have already manage to write the script that pulls there IP's and places them in a seperate file using the grep command.  At first i tried
#!/bin/bash
for var in `cat host.txt`; do
curl -s $var >> /tmp/ping/html/$var.html
done

I have tried with and without the silent switch. I then tried the following:
#!/bin/bash
for var in `head -2 host.txt`; do
curl $var >> /tmp/ping/html/$var.html
wait
done
for var in `head -4 host.txt | tail -2`; do
curl $var >> /tmp/ping/html/$var.html
done

This would try and do them all at the same time again stopping after 2
#!/bin/bash
for var in `head -2 host.txt`; do
curl $var >> /tmp/ping/html/$var.html
done
wait
for var in `head -4 host.txt | tail -2`; do
curl $var >> /tmp/ping/html/$var.html
done

This would do the same, I am new to bash scripting and only know some of the basics, any help would be appreciated

A: You pipe into $var, which could result in a wrong filename, because of the two slashes in the URL. Additionally i would quote the URL. For Example it works with the basename of the URL.
#!/bin/bash
for var in `cat host.txt`; do
  name=$(basename $var)
  curl -v -s "$var" -o "/tmp/ping/html/$name.html"
done

You may also want to skip blank lines and Comments (#)
#!/bin/bash

file="host.txt"
curl="curl"

while read -r line
  do
    [[ $line = \#* ]] || [[  -z "${line}" ]]  && continue
    filename=$(basename $line)
    $curl -s "$line" >> "/tmp/ping/html/$filename.html"
done < "$file"

A: Start with the simple: verify that you are in fact iterating over the entire list:
# This is the recommended way to iterate over the file. See
# http://mywiki.wooledge.org/BashFAQ/001
while read -r var; do
    echo "$var"
done < hosts.txt

Then add in the call to curl, checking its exit status
while read -r var; do
    echo "$var"
    curl "$var" >> /tmp/ping/html/$var.html || echo "curl failed: $?"
done < hosts.txt


text:
Q: Hovering over navigation bar item shows content with lower z-index When user is hovering over one of the links in menu, the background behind the menu is showing. This wrong rendering is only in Chrome, and only on one specific pc, so it is a bit hard for me to debug as for me and other computers I tried it, it worked without problem.
On the picture you can see that the map which is behind the menu is visible when hovering over menu item. But it is not only the map, also anything that is under it. The text of the menu item when hovered is visible, with white background and it can be clicked. Only some area around it is corrupted.

I'm using Yamm megamenu for Bootstrap
and standard Bootstrap 3.3 dropdown menu.
This is part of the code for the menu (it is generated in php as it is a plugin for yii)

Menu item

     Menu item megamenu

Megamenu subheader

                                   Menu item with problems

Other menu item

Other menu item

Other menu item

Css
.dropdown-menu {
position: absolute;
top: 100%;
left: 0;
z-index: 1000;
display: none;
float: left;
min-width: 160px;
padding: 5px 0;
margin: 2px 0 0;
list-style: none;
font-size: 14px;
text-align: left;
background-color: #ffffff;
border: 1px solid #cccccc;
border: 1px solid rgba(0, 0, 0, 0.15);
border-radius: 4px;
-webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
background-clip: padding-box;
}

.dropdown-menu {
z-index:100010;

}


text:
Q: Getting the error as ERROR: The Compose file './docker-compose.yml' is invalid because: Unsupported config option for services: 'db' while composing docker-compose.yml
services:
  db:
    image: postgres
    environment:
      - POSTGRES_PASSWORD=mydbsecretpassword
  wordpress:
    image: wordpress
    ports:
      - "8085:80"

While composing the file I am getting the error:
ERROR: The Compose file './docker-compose.yml' is invalid because:
Unsupported config option for services: 'db'

Docker version is 18.09.5
Docker compose version is 1.17.1

A: Try adding the compose version: at the top -
version: '3.5'
services:
  db:
    image: postgres
    environment:
      - POSTGRES_PASSWORD="mydbsecretpassword"
  wordpress:
    image: wordpress
    ports:
      - "8085:80"

Version compatibility - https://docs.docker.com/compose/compose-file/compose-versioning/


text:
Q: Is It possible to "extend" a guest network using an AP? My TP-link modem/router comes with the guest network feature;
I was wondering: if I use an AP (connected via Ethernet cable + unmanaged switch to the router) to bring the WiFi to the second floor of my house, the guest network will be available there? Or will be available only the "classic" local one?
I'm asking because I prefer to not connect my gaming console and my friend's phones directly to the main network for safety reasons.
Hope to find an easy way to extend the area of the guest network to the upper floor of the house.

A: It depends:

*

*If the TP-link router guest network feature can only be accessed via WiFi, you must extend the signal for guest WiFi SSID directly (via a WiFi extender).

*If the router lets you access the guest network via an Ethernet port, you can also connect the AP to the port dedicated to the guest network. However, you can not use the same (unmanaged) switch for your regular and your guest network unless it has a VLAN feature.

A: Does it need to be an AP?
You should be able to extend the range of a wifi network with... a range extender.
The router will determine the network, the range extender just makes the "wifi bubble" bigger.
Yes, you can do this with an AP, as long as the information of the guest network is available to the AP. You'll just have two "wifi bubbles"... your client will move from one AP (the router) to another AP.


text:
Q: C# string does not contain I am trying to delete items from a list 'scholarships' that do not contain string 'States' in its 'Student_state'attribute.
if (States != "")
            {
                scholarships.RemoveAll(s => !s.Student_state.Contains(States));
                scholarships.RemoveAll(s => s.Student_state == null);
            }

The ! character did not accomplish this. Any ideas?

A: Is it possible a case sensitivity issue?  String.Contains does a case sensitive test.  I have used the following to achieve a case insensitive test in the past:
(s.Student_state.IndexOf(States, StringComparison.CurrentCultureIgnoreCase) == -1)

A: You are testing for the variable States, not the string "States" (unless of course that variable is "States").
Your code should be:
if (States != "")
{
  scholarships.RemoveAll(s => !s.Student_state.Contains("States"));
  scholarships.RemoveAll(s => s.Student_state == null);
}

A: Could you try this? The sequence of statements is important here.
if (States != "")
{
    scholarships.RemoveAll(s => s.Student_state == null);
    scholarships.RemoveAll(s => !s.Student_state.Contains("States"));
}

A: How about only select the ones you want?
if (States != "")
{
    scholarships = scholarships.Where(s=> !string.IsNullOrEmpty(s.Student_state) && s.Student_state.Contains(States)).ToList();
}


text:
Q: Remove previous selection highlighting in RichTextBox without scrolling I have a form with a RichTextBox (RTB) and a listBox.
When the end user selects an item in the listbox, any matched text in the RTB is highlighted (full code removed for brevity).
re = New Regex(txtToFind)

For Each m In re.Matches(rtbMain.Text)
    rtbMain.[Select](m.Index, m.Length)
    rtbMain.SelectionColor = Color.White
    rtbMain.SelectionBackColor = System.Drawing.SystemColors.Highlight
Next

When the user left mouse clicks in the RTB I want the previously highlighted text to be cleared.  This is the standard windows behaviour - If you manually select some text in an RTB with the mouse, it is highlighted, click anywhere back in the RTB and the highlighting disappears. My programatically selected text remains selected.
I have some partially working code (below). I can clear all the highlighted text, but it is by process of selecting everything, changing the colour back and then deselecting it again.  I know it is not efficient, the RTB flickers and I am sure it is not the correct way to do it.  Can I emulate the standard windows behaviour?
Also using my code, it scrolls to the first line when entering the RTB a second time.
I get around this the first time by returning the top visible line index before clearing the text and then selecting that line again afterwards and using ScrollToCaret().  This only works on the first pass.  Subsequent MouseDown events select the top row regardless of where the user has clicked so nothing can be manually highlighted in the RTB.
Private Sub rtbMain_MouseDown(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles rtbMain.MouseDown

    Dim topIndex As Integer = rtbMain.GetCharIndexFromPosition(New System.Drawing.Point(1, 1))
    Dim topLine As Integer = rtbMain.GetLineFromCharIndex(topIndex)

    If e.Button = Windows.Forms.MouseButtons.Right Then
        'Do nothing (Context Menu)
    Else
        rtbMain.SelectAll()
        rtbMain.SelectionColor = Color.Black
        rtbMain.SelectionBackColor = Color.White
        rtbMain.DeselectAll()
        rtbMain.Select(topIndex, 0)
        rtbMain.ScrollToCaret()
    End If

End Sub

I need my code to emulate the standard windows behaviour - clear selected text highlighting on MouseDown and leave the mouse cursor where the user has clicked.
Any help anyone can offer is gratefully appreciated.

A: I think you may be overthinking this one.
In the right click event, try RtbMain.SelectionLength = 0


text:
Q: Spark Structured Streaming - Using Kudu as Source I want to use PySpark in order to stream a Kudu table, process the streaming data and stream it back into another Kudu table.
Below is the driver code I've been trying out
from pyspark.sql import SparkSession

spark = SparkSession \
    .builder \
    .appName("Kudu-stream") \
    .getOrCreate()

df = spark \
    .readStream \
    .format("org.apache.kudu.spark.kudu") \
    .option("kudu.master","example:7051") \
    .option("kudu.table","db.source_test") \
    .load()

def saveToKudu(batchDF, batchID):
  batchDF.write \
  .format("org.apache.kudu.spark.kudu") \
  .option("kudu.master","example:7051") \
  .option("kudu.table","db.sink_test") \
  .mode("append") \
  .save()

query = df \
  .writeStream \
  .outputMode("append") \
  .foreachBatch(saveToKudu) \
  .option("checkpointLocation","hdfs://example:8020/path/to/checkpoint/") \
  .start()

query.awaitTermination()

This is the error message I've been getting.
py4j.protocol.Py4JJavaError: An error occurred while calling o40.load.
: java.lang.UnsupportedOperationException: Data source org.apache.kudu.spark.kudu does not support streamed reading

Is there a way to readStream directly from a Kudu table?
Extra: is it possible to writeStream to Kudu without using foreach or foreachBatch?


text:
Q: Magento - Programatically retrieve and set admin users status For a custom extension I'm building I need to be able to set and retrieve the status of an administrator user (not a customer) in Magento. I imagine you could achieve this like so;
$id; // ID of user stored here
$user = $mage->getadminuser($id); // store the user as an object or array in a variable with ID
$user->getStatus(); // return either true or false?
$user->setStatus(active or not active); // activate or deactivate the user

If anyone could provide me with the code to do this or documentation where I can find this easily?
Thanks!

A: $id = 5;
$admin = Mage::getModel('admin/user')->load($id);
if ($admin->getId()){
    $admin->setIsActive(1);//or 0
    $admin->save();
}


text:
Q: How to find all the prime factors in a unsigned long long integer? I have a assignment to find all the prime factors of a number...
I need to write a function that takes a number and tells me all the prime factors of the number. For example:

*

*n=350 prime factors:2 5 5 7

(I pass to the function a number in the range 0 to 18446744073709551615 - the maximum number is largest number that fits in a 64-bit unsigned long long integer.)

A: That's a hard problem, and one of the main reasons for all the research into quantum computers. Take a look at Shor's Algorithm. Simple brute-force without optimizations would take something like 1000 years, although in this specific case (64-bit integers), you should be able to reduce your run-time to just a few minutes.
Assuming you have a trivial case of (at most) one large prime factor, you can speed up significantly by doing something like counting up from 2 and trying each number (multiple times if it works; 12 would be 2, 2, and 3 for example). After you find a factor, reduce your target number by that factor and test if the new target is prime.
To speed it up further, you could do processing across multiple threads, with each in charge of a range of divisors. You could run primality testers on one or more threads, providing primes to the testing thread so you are only trying to divide by prime numbers.
You could even search from the top of the range down, if you think the person providing the value is trying to be tricksome, although with the density of prime numbers being so much higher at the low end, this likely will not help.
The main thing to remember, though, that the largest possible factor of X, besides for X itself, is the square-root of X. Each time you find a factor, the largest possible remaining factor decreases significantly.


text:
Q: Receive UDP datagram on raw socket? I'm trying to write my own implementation of UDP in ruby for educational purposes using raw sockets.
Here's what I have so far:
require 'socket'

addr = Socket.pack_sockaddr_in(4567, '127.0.0.1')

socket = Socket.new(
  Socket::PF_INET,
  Socket::SOCK_RAW,
  Socket::IPPROTO_RAW
)

socket.bind(addr)
socket.recvfrom(1024)

I am testing it like so:
require 'socket'

udp = UDPSocket.new
udp.send "Hello World", 0, "127.0.0.1", 4567

But the call to recvfrom is blocking indefinitely.
If I change it to this:
socket = Socket.new(
  Socket::PF_INET,
  Socket::SOCK_DGRAM,
  Socket::IPPROTO_UDP
)

It of course works because this is the system-level way to accept UDP packets.
How can I receive UDP packets on a raw socket?
To be clear: I want to handle the actual UDP protocol (decoding the datagram & doing a checksum) myself!

A: Raw sockets work at IP level. You cannot bind a raw socket to a port. You can bind to a local address with bind or to an interface by setting the proper socket options (I don't know how to do it in Ruby, in C you call setsockopt. Instead of IPPROTO_RAW you should use IPPROTO_UDP in protocol.You will receive all UDP datagrams received on that IP address or that interface if the socket is bound to it.


text:
Q: Finite Characteristic of a Ring If $H$ is a ring and it has a finite non-zero characteristic $p$ then ring is finite.
I couldn't any counter example for this claim. Can anyone help me please?

A: Consider the ring of polynomials with coefficients in $\mathbb{Z}/p$ it has characteristic $p$ and it is infinite.


text:
Q: Can I hide default points of interests in MapKit with SwiftUI like parks, restaurants etc? I want to use my own map annotations and I am trying to hide default annotations from Map.
I found this to remove every default annotation from the map view
let configuration = MKStandardMapConfiguration()
configuration.pointOfInterestFilter = MKPointOfInterestFilter(including: [])

But how do I apply this configuration to my map view in SwiftUI?
import SwiftUI
import MapKit

@available(iOS 16.0, *)
struct MyMapView: View {
    init (){
        let configuration = MKStandardMapConfiguration()
        configuration.pointOfInterestFilter = MKPointOfInterestFilter(including: [])
    }

    @State private var region = MKCoordinateRegion(
        center: CLLocationCoordinate2D(
            latitude: 41.59710,
            longitude: -74.14976),
        span: MKCoordinateSpan(
            latitudeDelta: 0.0125,
            longitudeDelta: 0.0125)
        )

    var body: some View {
        Map(coordinateRegion: $region)
            .edgesIgnoringSafeArea(.all)
            .disabled(true)
    }
}

A: The SwiftUI Map view doesn't support this functionality. To get a map that can do this you'd need to use an MKMapView which is in UIKit. Here's an example of how to use it in SwiftUI
import SwiftUI
import MapKit

struct ContentView: View {
    var body: some View {
        MapView()
            .edgesIgnoringSafeArea(.all)
            .disabled(true)
    }
}

struct MapView: UIViewRepresentable {

    let configuration: MKStandardMapConfiguration

    private var center: CLLocationCoordinate2D {
        CLLocationCoordinate2D(latitude: 41.59710, longitude: -74.14976)
    }

    private var coordinateSpan: MKCoordinateSpan {
        MKCoordinateSpan(latitudeDelta: 0.0125, longitudeDelta: 0.0125)
    }

    init() {
        configuration = MKStandardMapConfiguration()
        configuration.pointOfInterestFilter = MKPointOfInterestFilter(including: [])
    }

    func makeUIView(context: Context) -> MKMapView {
        let mapView = MKMapView()
        mapView.region = MKCoordinateRegion(center: center, span: coordinateSpan)
        mapView.preferredConfiguration = configuration

        return mapView
    }

    func updateUIView(_ uiView: MKMapView, context: Context) { }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}


text:
Q: slight url mismatch while publishing java 6 maven webapp to tomcat from netbeans Honestly I've started this small maven webapp using eclipse 3.6 (STS) and i found it so complicated that i had to switch to netbeans.I really wanted to use eclipse but these are reality on the ground.So at the end of everything I'll like to have an eclipse version of the same project. thanks
I set up the maven webapp using the embedded archetype, and use cargo plugin to take care of the deployment.basically there is only hello world index.jsp in the project.after picking pom configuration here and there my pom finally is like  this .
while it started publishing after i restart the IDE, it's publishing to http://localhost:8080/ but for me I'm expecting it at http://localhost:8080/mvnTestWebap
so here are my questions

*

*Question 1 :  How can i correct that?

*Question 2 : I believe my pom is tied to netbeans too much, how can i achieve the publishing to tomcat result but having a portable pom?Can anyone suggest a rewrite that can run on eclipse?

*Question 3 : what correspond to netbeans "run" in eclipse?

A: *

*probably by some deployment descriptor editing.

*don't really understand the point. by default netbeans uses it's own embedded IDE way of deployment. That's not creating a pom tied to netbeans in any way. You can use that in eclipse or IDE or command line to build the project. The deployment part of the web app is specific to the server being used and the IDE being used.
You can also tell netbeans to execute your cargo plugin on executing the Run/Debug/Profile action (bypassing the netbeans default behaviour)

*run basically performs a redeploy of the app on the server of choice. There has to be an equivalent on eclipse.


text:
Q: How two zip two sets into a map in Java I have a Set A:
[{name: a,value: 10},
 {name: b,value: 11}]

and Set B:
[{name: a,value: 100},
 {name: b,value: 110}]

Then, I want get Map C:
{{name: a,value: 10}:{name: a,value: 100},
 {name: b,value: 11}:{name: b,value: 110}}

The key and the the value of each Entry in Map C are equal, which means that the key and the value has the same "name", through different "value"s.
I found guava's Sets is useful, but lack of such functions.
I know this is one way to do that:
public static <T> Map<T, T> zip(Set<T> s1, Set<T> s2) {
    Map<T, T> map = new HashMap<>();
    for (T e1 : s1) {
        for (T e2 : s2) {
            if (e1.equals(e2)) {
                map.put(e1, e2);
                break;
            }
        }
    }
    return map;
}

Is there any convenient way to zip two sets in Java?

A: You could try this, for this to work override equals and hashcode with field name
public static <T> Map<T, T> zip(Set<T> s1, Set<T> s2) {
    return s1.stream()
             .filter(s2::contains)
             .collect(Collectors.toMap(k -> k, v -> s2.stream().filter(s -> s.equals(v)).findFirst().get()));
}

A: The implementation you specified has complexity O(n^2). You can write it as O(n) as follows:
public static <T> Map<T, T> zip(Set<T> s1, Set<T> s2) {
    Map<T, T> map = new HashMap<>();
    for (T e1 : s1) {
      T e2 = s2.get(e1) {
         if (e1.equals(e2)) {
            map.put(e1, e2);
            break;
        }
    }
    return map;
}

This is O(n) because get() uses hashing to find the element. For this to work correctly, you need to implement hashCode() and equals() for the actual type passed as T to behave properly:
class Actual {
  private String name;
  private String value;
  ...
  public int hashCode() {
    return name.hashCode()
  }
  public boolean equals(Object o) {
    if (!(o instanceof Actual)) {
      return false;
    }
    Actual other = (Actual)o;
    return name.equals(other.name);
  }
}


text:
Q: I have a UITextField for customCell for UITableView. On TapGesture of UITextField, I need to display checkmark on right side of UITableViewCell I have a UITextField for customCell for UITableView.
On TapGesture of UITextField, I need to display checkmark on right side of UITableViewCell.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

PreferenceCellWithTextBox *cell = (PreferenceCellWithTextBox *)[tableView dequeueReusableCellWithIdentifier:@"PreferenceCellIdentifier"];

if (cell == nil)
{
    NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"PreferenceCellWithTextBox"
        owner:nil
        options:nil];

    for (id currentObject in topLevelObjects)
    {
        if ([currentObject isKindOfClass:[UITableViewCell class]])
        {

            cell=(PreferenceCellWithTextBox *)currentObject;
            break;
        }
    }

    if([self.checkedIndexPath isEqual:indexPath])
    {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    else
    {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }

        UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(forwardToDidSelect:)];
        [cell.userIdTextField addGestureRecognizer:tap];

}

return cell;
}

Here, I am writing for Tap Gesture. and It gets called only once. It should not happen like that. It should get called whenever I may touch UITextField which is on UITableViewCell.
 -(void)forwardToDidSelect:(UITapGestureRecognizer *)tap
{

[self tableView:self.userIdSuggestiontableView didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];

}

Here, I have written code for did select row. On Select of any row, I want to display the Checkmark.and remove checkmark from previous one.
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

if(self.checkedIndexPath)

{
    PreferenceCellWithTextBox* uncheckCell =(PreferenceCellWithTextBox *) [tableView
                                    cellForRowAtIndexPath:self.checkedIndexPath];

    uncheckCell.accessoryType = UITableViewCellAccessoryNone;

}
if([self.checkedIndexPath isEqual:indexPath])

{
    self.checkedIndexPath = nil;
}
else
{

    PreferenceCellWithTextBox* cell = (PreferenceCellWithTextBox*)[tableView cellForRowAtIndexPath:indexPath];

    cell.accessoryType = UITableViewCellAccessoryCheckmark;
    self.checkedIndexPath = indexPath;

}

}


text:
Q: How can I print full cl.exe path in my vcxproj file? For a custom build target, I would like to have full path with correct version of cl.exe which is being called in ClCompile target.
From retrieve path to cl.exe, I get it is %VCINSTALLDIR%\bin\x86\Hostx86\cl.exe or %VCINSTALLDIR%\bin\x64\Hostx64\cl.exe, But I do not want to write program for x84 vs x64 logic.
In VCTargets\Microsoft.CppCommon.Targets, I find that there is property ToolExe and ToolPath are being set to $(CLToolExe) and $(CLToolPath).
Overriding these properties also changed the path to compiler successfully for me, so it's correct that these are the properties names. Override Compiler in MSBuild
But when I try printing %(CL.ToolPath) or $(CLToolPath) in my custom target exec class, it prints nothing. I also looked in Visual Studio and couldn't find where it was being set.
Is there a variable which can provide cl.exe full path or is there any way I can print property ToolPath of CL Task in my custom target?

A: 1) If you already uses the $(CLToolExe) and $(CLToolPath) to set your new cl.exe and then want to get the full path of it, you should use this $(CLToolPath)$(CLToolExe) to get the new value rather than %(CL.ToolPath)(there is no such way like this).
This is my test result:
Actually, you can overwrite these properties directly under your xxx.csporj file rather than in Microsoft.CppCommon.Targets file and when you build your project, it will use the new cl.exe.

Then, I use a custom target to get the value:
<Target Name="test123" AfterTargets="ClCompile">
        <Exec Command="$(CLToolPath)$(CLToolExe)" />
        <Message Importance="high" Text="$(CLToolPath)$(CLToolExe)"></Message>
</Target>

2) If you did not change to the new value and use the default cl.exe without any changes, you should use $(ClCompilerPath) to get the default value.
 <Target Name="test123" AfterTargets="ClCompile">
       <Message Importance="high" Text="$(ClCompilerPath)"></Message>
 </Target>

Note: $(ClCompilerPath) cannot get the new value of $(CLToolPath)$(CLToolExe) since they are not related and can only get the default value.


text:
Q: Transposing data from multiple rows into a single row multiple columns using DYNAMIC MYSQL PIVOT This question is different from what have been searching on in that it selects from more than one column  before creating the pivot table
I have a table structure similar to this
CREATE TABLE score (
id int,
reg_id varchar(5),
test1 int(5),
exam int(5),
subject int(5),
term VARCHAR(5)
)

CREATE TABLE subject (
    id int,
    subject_name varchar(5)
    )

I want to be able to select more than one  value e.g test1 and exam into different column in the DYNAMIC MYSQL PIVOT TABLE
I have seen similar example like MySQL pivot row into dynamic number of columns
, MySQL pivot table query with dynamic columns but they seems to be selecting only 1 matching value into the dynamic pivot table.  I have tried  writing something like this
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'SUM(case when subject = ''',
      subject,
      ''' then test1 end)AS `',
      (select subject_name from subject where id=subject), '`',

        'SUM(case when subject = ''',
      subject,
      ''' then exam end)AS `',
      (select subject_name from subject where id=subject), '`'
    )
  ) INTO @sql
FROM
  scores;
SET @sql = CONCAT('SELECT reg_id, ', @sql, '
                  FROM scores  where term="First term"
                   GROUP BY reg_id');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

but it is not working thank you
I want an output similar to this after the tranpose.
regid-------maths test----maths exam-----english test------english exam
3m ---------    10    -----   23     ----     12         ------- 59


text:
Q: useContext not working for me with Typescript I am trying to implement useContext with Typescript, but unfortunately I'm getting an error
Code sample :
import React, { createContext, useContext, useState } from "react";

type IUser = {
  email: String;
  isAuthorized: boolean;
};
const user: IUser = { email: "", isAuthorized: false };
export const AppContext = createContext<IUser>(user);

const appcontextprodivder = (props: any) => {
  //const [appdata, setappdata] =  useState<IUser>(user);

  const [userstate, setuserstate] = useState<IUser>(user);

  const login = (useremail: string) => {
    setuserstate({ email: useremail, isAuthorized: true });
  };

  const logout = () => {
    setuserstate({ email: "", isAuthorized: false });
  };

  const updaateemail = (email: string) => {
    setuserstate({ ...userstate, email: "" });
  };

  return (
    <AppContext.Provider value={{ userstate, login, logout }}>
      {props.children}
    </AppContext.Provider>
  );
};
export default appcontextprodivder;

I'm getting this error:

Type '{ userstate: IUser; login: (useremail: string) => void; logout: () => void; }' is not assignable to type 'IUser'.
Object literal may only specify known properties, and 'userstate' does not exist in type 'IUser'

Code screenshot:

A: Please, try this instead. The issues I noticed are

*

*Wrong component name i.e appcontextprovider should not be in lowercase

*The IUser was passed like the entire state, but that needed to be part of another state for login and logout to work

import React, {
  createContext,
  useContext,
  useState
} from "react";

type IUser = {
  email: String;
  isAuthorized: boolean;
};

type ContextType = {
  userstate: IUser;
  login: (arg: string) => void;
  logout: () => void
}

const user: IUser = {
  email: "",
  isAuthorized: false
};
export const AppContext = createContext < ContextType | null > (null);

const AppContextProvider = (props: any) => {
  //const [appdata, setappdata] =  useState<IUser>(user);
  const [userstate, setuserstate] = useState < IUser > (user);

  const login = (useremail: string) => {
    setuserstate({
      email: useremail,
      isAuthorized: true
    });
  };

  const logout = () => {
    setuserstate({
      email: "",
      isAuthorized: false
    });
  };

  const updaateemail = (email: string) => {
    setuserstate({ ...userstate,
      email: ""
    });
  };

  return ( <
    AppContext.Provider value = {
      {
        userstate,
        login,
        logout
      }
    } > {
      props.children
    } <
    /AppContext.Provider>
  );
};
export default AppContextProvider;


text:
Q: How to Import a CSV file into an entity automatically? Is there a way to import a CSV file into a CRM record automatically, say when the CSV file is created?
The plan is that this CSV file would have some cost center hours inside and job number which corresponds to a certain record already created in CRM.
And uploading this CSV would then update this record.
Please help me to solve this problem

A: You can import data both using UI and code in D365.
Also there are plenty of tools solving exactly same problem: KingswaySoft SSIS, Scribe, etc.
But it looks like buying 3rd party software might be overkill in your scenario. You can use Windows task scheduler and write a few PowerShell scripts to implement it.
Where to start:

*

*https://learn.microsoft.com/en-us/dynamics365/customerengagement/on-premises/developer/import-data

*https://learn.microsoft.com/en-us/dynamics365/customerengagement/on-premises/developer/sample-import-data-complex-data-map

*https://github.com/seanmcne/Microsoft.Xrm.Data.PowerShell

*https://learn.microsoft.com/en-us/dynamics365/customerengagement/on-premises/developer/define-alternate-keys-entity


text:
Q: Using XML snippets in Maven Polyglot As a polyglot maven user, I have maven configuration snippet written in xml
For example
Listing 1. Using maven-jar-plugin to modify MANIFEST.MF
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <configuration>
                <archive>
                    <manifest>
                        <addClasspath>true</addClasspath>
                        <classpathPrefix>lib/</classpathPrefix>
                        <mainClass>com.mypackage.MyClass</mainClass>
                    </manifest>
                </archive>
            </configuration>
        </plugin>

taken from http://www.ibm.com/developerworks/library/j-5things13/
How can I use it in ,say, my pom.yaml ?
straightforward translation fails
$ mvn io.takari.polyglot:polyglot-translate-plugin:translate -Dinput=maven-jar-plugin.xml -Doutput=maven-jar-plugin.yaml
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building maven-translating-snippets 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- polyglot-translate-plugin:0.1.15:translate (default-cli) @ maven-translating-snippets ---
[INFO] Translating D:\Workspaces\STS-373\maven-translating-snippets\maven-jar-plugin.xml -> D:\Workspaces\STS-373\maven-translating-snippets\maven-jar-plugin.yaml
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.466 s
[INFO] Finished at: 2016-04-19T10:00:29+08:00
[INFO] Final Memory: 6M/155M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal io.takari.polyglot:polyglot-translate-plugin:0.1.15:translate (default-cli) on project maven-translating-snippets: Error translating maven-jar-plugin.xml -> maven-jar-plugin.yaml: Expected root element 'project' but found 'plugin' (position: START_TAG seen \t\t\t<plugin>... @1:11) -> [Help 1]
[ERROR]

A: I was able to migrate my pom.xml using the official doc
I wrote something about how I did it and the problems I encountered here


text:
Q: How to get contacts from gmail account? Previously i was using following service to get my contacts from my Gmail account.
https://github.com/google/gtm-oauth2
But this API uses embedded browser to login and it will going to deprecated in short time.
Now, i need to use new way to authorise use and contacts from gmail account.
I'm able to login in Google account through following service.
https://github.com/google/GTMAppAuth
But by using this service, i'm not able to get Contacts from my gmail account. Can anyone help me out to get rid on this issue?

A: For gmail contacts, I have been using python to access the people API.
Google provides an apiclient and oauth2client to manage the entire application flow.
https://developers.google.com/people/quickstart/python
Once you have retrieved credentials, you can call the people service
https://developers.google.com/people/api/rest/
In python, you could try method results =
service.people().connections().list(resourceName='people/me', pageSize=10).execute()
connections = results.get('connections', [])

A: Thanks for looking for this issue. After digging more with below services i got solution.

*

*https://github.com/google/gtm-oauth2

*https://github.com/google/GTMAppAuth

*https://developers.google.com/google-apps/contacts/v3/
It is giving everything just we need to read carefully. They also giving good sample project which serve everything what we need.


text:
Q: gem install bundler error I am newbie here. When I tried to install gem install bundler, it gave me
ERROR:  Could not find a valid gem 'bundler' (>= 0) in any repository
ERROR:  While executing gem ... (Gem::RemoteFetcher::FetchError)
    bad response Forbidden 403 (http://rubygems.global.ssl.fastly.net/latest_specs.4.8.gz)

So I need to install 'bundler'?

A: Doing some digging, I found that your issue is related to being behind a proxy or firewall or having a virus.
The fastest workaround is to change your gem source address from https://rubygems.org to http://rubygems.org with the following command:
gem sources -a http://rubygems.org

confirm withy and retry.


text:
Q: Doesn't the contract need to enforce that Oracle has signed the Fix command in IRS example? I observed that normally in a typical contract we have something similar to
"The signers should be the participants for the state" using
(command.signers.toSet() == state.participants.map { it.owningKey }.toSet())

where we enforce if this specific command is used, the required signers are equal to the participants (assuming participants of the deal are always mandatory to sign) so nodes don't maliciously change the flow to sidestep getting signatures from some parties.
In the IRS demo on Oracle (RateFixFlow/NodeInterestRate), the State has the participants and oracle parties involved. There's also a verifyFixCommand that verifies some rules are met whenever a Fix command was used to get the rates from the Oracle.
Why doesn't the command also enforce that participants must have signed - plus the oracle must sign as well to guarantee the Fix rates was validated by the Oracle? Else why have the flow get the oracle's signature at all. What's stopping the initiator from bypassing getting the oracle signature in the first place.
Was there any rationale behind not putting a similar rule from the below in? i.e
"The signers should be the participants and oracle for the state" using
    (command.signers.toSet() ==
(state.participants.map { it.owningKey } + state.oracle.owningKey).toSet())

A: This is an oversight. The contract's verify method should check the required signers.
It would be appreciated if you could create a PR to amend this. The contribution guides are here: https://docs.corda.net/contributing.html.


text:
Q: Spring MVC ExceptionHandler and the controller context This should be a common problem with a solution but I haven't managed to find it anywhere.
I am defining a global exception handler using @ControllerAdvice, I define a new ModelAndView and redirect to my error page.  Works great EXCEPT for the fact that now we want to add a link to go back to the original page which of course could vary depending on where the error originated.
What I want to do is to store some kind of context information about the controller that generated the error, for instance if it's MyController then I can access a value via MyController.EXCEPTION_REDIRECT_URL and generate the appropriate link.
I find a lack of context information in the Exception handler rather limiting.

A: Make a custom exception class and pass your context in the exeption.
class MyException extends Exception {
  private MyController c;
  MyException( String msg, MyController c ) {...}
  ...
}

I do feel like there's a better way, probably revolving around a request context object. But this would do exactly what you want.


text:
Q: Denying user permissions for C Drive where Windows is installed I have added another user profile to my PC and have removed their access to the D drive through properties > security > edit and removing other users permissions (picture below for context).
With instructions from this video: https://www.youtube.com/watch?v=zWxx9uz1bP8
However I'd like to know if doing this for the C drive (where Windows is installed) will this cause any potential issues?

A: You can't do that and still have the user be able to use the computer.
Every user needs a minimum of read access to large parts of Windows itself and Full Control to certain portions of his own profile-folder which is also located on C:.
Without those rights the user can't login at all. You might just as well delete that user-account altogether and that is actually much easier to do.
In addition to that the file-access permissions to the Windows folders in C: are extremely complicated and are not a single set of settings that you can apply from the top of the disk as shown in that video.
If you try to do that on C: you will mess up your Windows installation to the point that you have to re-install it from scratch.
The instructions given in that video work, but only for drives that are used for data only. Don't try it with disks containing the Operating System.
Disks that contain installed software (other than the software installed on C:) might also cause issues. Some of the programs will malfunction or not work at all.


text:
Q: Redundant escape character in Pattern I am trying out the following code and it's printing false.
I was expected that this would print true.
In addition , the Pattern.Compile() statemenet , gives a warning 'redundant escape character'.
Can someone please help me as to why this is not returning true and why do I see a warning.
public static void main(String[] args) {
    String s = "\\n";
    System.out.println(s);

    Pattern p = Pattern.compile("\\\n");
    Matcher mm = p.matcher(s);
    System.out.println(mm.matches());
}

A: The s="\\n" means you assign a backslash and n to the variable s, and it contains a sequence of two chars, \ and n.
The Pattern.compile("\\\n") means you define a regex pattern \<LF> (a backslash and a newline, line feed, char) that matches a newline (LF) char, because escaped non-word non-special chars match themselves. \, matches a ,, \; matches a ;.  Thus, this pattern won't match the string in variable s.
The redundant escape warning is thrown because \<LF> matches the same newline char that can be matched with mere <LF>.
More examples:

Regex
Regex string literal
Matching text
Matching string literal

<LF>
"\n"
<LF>
"\n"

\n
"\\n"
<LF>
"\n"

\\n
"\\\\n"
\n
"\\n"

A: Because "\\n" evaulates to backslash \\ and the letter n while "\\\n" evaluates to a backslash \\ and then a newline \n.

A: Backslashes within string literals in Java source code are interpreted as required by The Java™ Language Specification as either Unicode escapes (section 3.3) or other character escapes (section 3.10.6) It is therefore necessary to double backslashes in string literals that represent regular expressions to protect them from interpretation by the Java bytecode compiler. The string literal "\b", for example, matches a single backspace character when interpreted as a regular expression, while "\\b" matches a word boundary.
Refer : https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

A: Your source s has two characters, '\' and 'n', if you meant it would be \ followed by a line break then it should be "\\\n"
Pattern has two characters '\' and '\n' (line break) and \ the escape characher is not needed, hence warning. If you meant \ followed by line break it should be "\\\\\n" (twice \ to escape it for regex and then \n).
    String s = "\\\n";
    System.out.println(s);

    Pattern p = Pattern.compile("\\\\\n");

    Matcher mm = p.matcher(s);
    System.out.println(mm.matches());


text:
Q: How can I boot ubuntu 22 installed in dual with windows 11? I have installed ubuntu 22 on my HP laptop that is already running windows 11. I restarted the computer and selected ubuntu to make sure it was all okay, then I restarted again to run on windows, and all went also good. But since then, when I shutdown or restart the computer, it goes straight to windows without giving me the option to choose which OS I want to use.
What can I do to solve this?

A: You have to enter the BIOS and choose which OS you want to boot into every time you reboot. If you don't do this, your computer will boot into the OS that you last used.

A: Each operating system has something called a bootloader, which is a piece of software that among other things lets you choose which operating system to boot to. In your case you have the Windows bootloader and GRUB, which is the bootloader commonly used on Linux operating systems.
If your computer is booting straight to Windows, then it is probably using the Windows bootloader, which by default does not recognize your Linux operating system. You have two options here:

*

*Add Linux to your Windows bootloader, as shown here.

*Use GRUB as the bootloader instead. It should recognize both operating systems from the beginning.


text:
Q: Datagridview show date or time (VB.NET) I have a datagridview in which some columns where initially specified as String and they contain date or time, depending on some bussiness logic.
I am changing the type of the column (to datetime) to allow correct sorting. And I would like to know if it is possible to show date values or time values depending on the row. Or I will always have to show both.
Thank you.

A: You can handle the CellFormatting event. This event is fired everytime a cell is painted. You can change what value is being displayed without changing the underlying value and the format of the cell.
By doing this you can change the format depending on the row and column
Private Sub CellFormatting_EventHandler(sender As Object, e As DataGridViewCellFormattingEventArgs)
     If e.ColumnIndex = 2 AndAlso CType(sender, DataGridView)(5, e.RowIndex).Value.ToString = "Steve" Then 'Or whatever logic you like
         e.Value = CType(e.Value, Date).ToShortTimeString
     End If
 End Sub


text:
Q: Java- can't read input file I am trying to load a png image of a card to an object but I keep getting the following error:
"C:\Program Files\Java\jdk-9\bin\java" "-javaagent:C:\Users\trevo\Documents\JetBrains\IntelliJ IDEA Community Edition 2017.2.5\lib\idea_rt.jar=60524:C:\Users\trevo\Documents\JetBrains\IntelliJ IDEA Community Edition 2017.2.5\bin" -Dfile.encoding=UTF-8 -classpath C:\Users\trevo\Desktop\Deck\out\production\Deck com.company.Card_Class
Exception in thread "main" javax.imageio.IIOException: Can't read input file!
    at java.desktop/javax.imageio.ImageIO.read(ImageIO.java:1308)
    at com.company.Card_Class.main(Card_Class.java:21)

Process finished with exit code 1

Here is my code:
package com.company;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class Card_Class {
    private String suit, face;
    private int value;
    private BufferedImage cardimage;

    public Card_Class(String suit, String face, int value, BufferedImage cardimage) {
        this.suit = suit;
        this.face = face;
        this.value = value;
        this.cardimage = cardimage;
    }

    public static void main(String[] args) throws IOException {
        Card_Class KingOfAxes = new Card_Class("Diamonds", "King", 13, ImageIO.read(new File("KingOfAxes.png")));
        System.out.println("King");
    }
}

I have all my png card files in a folder labeled deck which is the project name.

A: Try to write the full file path to the console to see if your file path is correct.
Maybe print the absolute path of your file to stdout to see if your path is correct. You should also check if your image exists and is readible before you use it. Here is an example for both:
public static void main(String[] args) throws IOException {
    System.out.println(new File("KingOfAxes.png").getAbsolutePath()); // Try this to pinpoint your issue
    File king = new File("KingOfAxes.png");

    if(king.canRead()){ // Check if your file exists and is readable before you use it
        JavaAssignmentPanel KingOfAxes = new JavaAssignmentPanel("Diamonds", "King", 13, ImageIO.read(new File("KingOfAxes.png")));
    } else{
        throw new IOException(king.getName() + " is not readable!"); // Not readable -> Throw exception
    }
    System.out.println("King");
}


text:
Q: Air publishing game error I receive this error durring the publishing of my game.
    Error creating files. dx tool failed :
UNEXPECTED TOP-LEVEL EXCEPTON: java.lang.illegalArgumentException:
already added : android/support/v7/appcomapt/R$anim;
at com.android.dx.dex.file.ClassDefsSection.add(ClassDefsSection.java.123)....

(is long error)
I have included an ane for ads (AIRPUSH)
When I run that ane in new project it's working perfectlly.
What can be the problem?

A: I've faced this one before.
The exception tells you that the android-support-v7 library's R class (See R* mechanism with ANEs) is being packaged twice. Which explains why it works fine with a new ANE project.
Please check if you have them included inside your ANE's platform.xml as a <packagedResource> (If so remove it from here)
OR
Check if it is being added from inside one of your other ANEs.


text:
Q: Restrict access to directory based on protocol I know .htaccess can be used to restrict access to specific directories based on domain, IP address, etc. but is there a way I can restrict access based on protocol?
I have some scripts I want to be able to run remotely on an Apache server only from SSH.

A: Ssh and http(s) are completely different protocols and usually different server-side programs are responsible for them.
The Apache httpd serves http and if configured https requests. Restricting access can be done with .htaccess files. In a .htaccess https usage can be forced with the SSLRequireSSL directive. The Apache httpd has nothing to do with ssh.
For ssh connections generally the sshd is responsible and therefor if you want to access and execute your scripts only over ssh, move them out of httpd access.


text:
Q: ByteBuddy call constructor of generated class I am trying to generate a method like this in a generated class
static void setDefault(Supplier<?> arg0, String[] arg1, String[] arg2) {
    defaultInstance = new GeneratedClass(arg0, arg1, arg2);
}

I am struggling with the API, where I'm currently is
        .defineMethod("setDefault", Void.TYPE, Visibility.PACKAGE_PRIVATE, Ownership.STATIC, MethodArguments.PLAIN)
            .withParameters(Supplier.class, String[].class, String[].class)
        .intercept(....)

I believe I need FieldAccessor.ofField and MethodCall.construct however I'm struggling to come up with a MethodDescription for the constructor of the to be generated class.

A: If you cannot describe the generated class, you can create an instance of InstrumentedType.Default and provide it as a type description.
You should use MethodCall which allows you to access parameters from its DSL.


text:
Q: llvm - get label of br instruction My question is simple. Given an instruction of type branch, how do I extract the label out of it?
For example:
br label %while.cond

Should give me while.cond
br label %while.end

Should give me while.end
br i1 %cmp1, label %if.then, label %if.end

Should give me if, if.then, if.end respectively.

A: First check inst->isConditional(), then access inst->getOperand(1) and inst->getOperand(2) in case it is true and inst->getOperand(0) if it is false.
The whole BasicBlock is what BranchInst actually accepts. If you want %if.then line, then call getName() on it.

A: I use the following code segment to get all the above information that you have asked.
 if (inst->getNumSuccessors() == 1)
     return; //indicates not a branching instruction

 unsigned int i;

  for (i = 0; i <= inst->getNumSuccessors(); i++) {

      llvm::outs() << inst->getOperand(i)->getName();

  }


text:
Q: Graficar con Python, Pandas Tengo que graficar a partir de un archivo csv similar a este:
Cedula,Genero,Placa,Tipo,Multa,Fecha
0931921407,Femenino,GYS-9575,Automovil,Grave,2016-06-13
0910703362,Masculino,GSF-7654,Automovil,Leve,2016-02-18
0931921408,Femenino,GOI-3298,Automovil,Muy grave,2016-01-04
0987654321,Masculino,ETR-9873,Camioneta,Grave,2016-08-05
0931921407,Femenino,GYS-9575,Automovil,Grave,2016-06-13
0910703362,Masculino,GSF-7654,Automovil,Leve,2016-02-18
0931921408,Femenino,GOI-3298,Automovil,Muy grave,2016-01-04
0987654321,Masculino,ETR-9873,Camioneta,Grave,2016-08-05
0931921407,Femenino,GYS-9575,Automovil,Grave,2016-06-13
0910703362,Masculino,GSF-7654,Automovil,Leve,2016-02-18
0931921408,Femenino,GOI-3298,Automovil,Muy grave,2016-01-04
0987654321,Masculino,ETR-9873,Camioneta,Grave,2016-08-05
0931921407,Femenino,GYS-9575,Automovil,Grave,2016-06-13

Mi principal problema es que de todas las formas que intento tengo el error de
Traceback (most recent call last):
  File "C:/Users/User1/Downloads/x/xx/aaa.py", line 14, in <module>
    my_plot = grp.plot(kind='bar')
  File "C:\python\lib\site-packages\pandas\core\groupby.py", line 311, in __call__
    return self._groupby.apply(f)
  File "C:\python\lib\site-packages\pandas\core\groupby.py", line 651, in apply
    return self._python_apply_general(f)
  File "C:\python\lib\site-packages\pandas\core\groupby.py", line 655, in _python_apply_general
    self.axis)
  File "C:\python\lib\site-packages\pandas\core\groupby.py", line 1527, in apply
    res = f(group)
  File "C:\python\lib\site-packages\pandas\core\groupby.py", line 647, in f
    return func(g, *args, **kwargs)
  File "C:\python\lib\site-packages\pandas\core\groupby.py", line 309, in f
    return self.plot(*args, **kwargs)
  File "C:\python\lib\site-packages\pandas\tools\plotting.py", line 3740, in __call__
    sort_columns=sort_columns, **kwds)
  File "C:\python\lib\site-packages\pandas\tools\plotting.py", line 2614, in plot_frame
    **kwds)
  File "C:\python\lib\site-packages\pandas\tools\plotting.py", line 2441, in _plot
    plot_obj.generate()
  File "C:\python\lib\site-packages\pandas\tools\plotting.py", line 1026, in generate
    self._compute_plot_data()
  File "C:\python\lib\site-packages\pandas\tools\plotting.py", line 1135, in _compute_plot_data
    'plot'.format(numeric_data.__class__.__name__))
TypeError: Empty 'DataFrame': no numeric data to plot

siendo esto lo que escribo en el codigo:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

lectura=pd.read_csv("dataset.csv",",",parse_dates=['Fecha'])

equis=lectura[["Tipo","Multa"]]
equis.head()

grp=equis.groupby("Multa")
grp.size()
my_plot = grp.plot(kind='bar')`

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

lectura=pd.read_csv("dataset.csv",",",parse_dates=['Fecha'])

equis=lectura[["Tipo","Multa"]]
equis.head()

grp=equis.groupby("Multa")
grp.size()
my_plot = grp.plot(kind='bar')

En este enlace se encuentran los gráficos que tengo que realizar.

A: Cuando haces una operación de agrupación (groupby) se te crea un objeto especial.
>>> print(type(grp))
<class 'pandas.core.groupby.DataFrameGroupBy'>

Es una especie de diccionario con información de los grupos. Lo que parece que quieres graficar, y tienes métodos para ello, son objetos de estructuras de datos (e.g., Series, DataFrame,...). Cuando aplicas una operación sobre pandas.core.groupby.DataFrameGroupBy, como cuando aplicas el método size, te devuelve, por ejemplo en tu caso, una Series.
>>> print(type(grp.size()))
<class 'pandas.core.series.Series'>

Si lo que quieres graficar es el resultado de grp.size() deberías hacerlo así:
>>> grp.size().plot(kind='bar')

Y el resultado sería este:

Si no es eso lo que quieres, por favor, especifica un poco mejor la pregunta y rehago la respuesta.


text:
Q: Trigger buttons based on values socket.io How can i change this to get worked by using value not ID. The function should search for the button with the exact value and run the click function.I tried in several ways but was not successful. so can anyone please help me get through this. I want ti make buttons with same values get clicked
app.js
const io = require('socket.io')(3000);
io.on('connection', function (socket) {
    console.log('a client has connected');
    socket.on('clicked', function() {
        io.emit('clicked');
    });
    socket.on('clicked1', function() {
        io.emit('clicked1');
    });

});

console.log('socket.io server started at port 3000');

button.html
<!doctype html>

      <title>Testing socket.io</title>

    <form>
      <button type="button" id="sq1" NAME="sqrone" class="tictac"  onClick="onClickHandler(this)"></button>

      <button type="button" id="sq2" NAME="sqrtwo" class="tictac"  onClick="onClickHandler(this)">
      </button>

      </form>

 waiting...

index.html
<!DOCTYPE html>

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

<link href='http://fonts.googleapis.com/css?family=Oxygen:400,300,700' rel='stylesheet' type='text/css'>

<form method="get" action="button.html">

<input type="number" id="sq1" name="sqrone" value=""  placeholder="Value" class="tictac"  />
<input type="number" id="sq2" name="sqrtwo" value=""  placeholder="Value" class="tictac"  />

                <input type="submit"  value="Submit" onclick="saveVal()">

</form>

Here is what i have tried so far
var socket = io("http://localhost:3000");

var click = document.getElementById("sq1");
var clicka = document.getElementById("sq2");

var required = document.getElementById("sq1").value;
var requireda = document.getElementById("sq2").value;

socket.on('connect', function() {

  click.addEventListener("click", function () {

socket.emit("clicked");

  });

  }

  clicka.addEventListener("click", function () {

    socket.emit("clicked1");

  });

 });
 if (required===l || requireda===c) {
socket.on('clicked', function() {

  console.log('clicked');
  document.getElementById("alert").innerHTML = "1 clicked";

  onClickHandler(sq1);

});
}
else if(required===c || requireda===l) {

socket.on('clicked1', function() {
//if condition
  console.log('clicked1');
  document.getElementById("alert").innerHTML = "2 clicked";

  onClickHandler(sq2);

});
}


text:
Q: htaccess working mechanism I have the folowing htaccess file:

RewriteEngine on

RewriteRule ^(.*)-(.*)-(.*)$   index.php?page=$1&id=$2&im=$3

And inside the php page I have:
href="home-46-126" //Contact Us
href="home-38-129" //News
I want to know how the redirection done?
What is the function that did this redirection ?
How Does the website know where to go if the user clicks on "Contact Us" ?

A: It isn't htaccess function, htaccess just parse "home-46-126", and redirect to index.php with these values.
If you want to work later with these values, you have to type it in PHP script.
<?php
$_GET["page"]; // including "home"
$_GET["id"]; // including "46"
$_GET["im"]; // including "126"
?>

Then you have to put these values to database or somethink, where you find out, that this ID and IM is page with Contact Us