text:
Q: How to align Input element text in middle in mac I developed a website using Slate Pro Regular and Slate Pro Bold fonts. It's working fine in windows but in Mac, input element text pushed up.  Please find screenshots for reference
Input element in Windows and
Alignment issue in Mac chrome
I tried below
How to vertically align text in input type="text"? and
https://css-tricks.com/forums/topic/vertical-align-on-text-input/
Please, anyone help me to fix the Input element alignment issues in Mac.

.container {
    max-width: 1040px;
    margin: 0 auto;
}
.row {
    display: -ms-flexbox;
    display: flex;
    -ms-flex-wrap: wrap;
    flex-wrap: wrap;
    margin-right: -15px;
    margin-left: -15px;
}

.form-input {
    margin-bottom: 10px;
    font-size: 16px;
    font-family: 'SlatePro Bold';
    color: #565656;
}

.form-control {
    display: block;
    width: 100%;
    height: calc(1.5em + .75rem + 2px);
    padding: .375rem .75rem;
    font-size: 1rem;
    font-weight: 400;
    line-height: 1.5;
    color: #495057;
    background-color: #fff;
    background-clip: padding-box;
    border: 1px solid #ced4da;
    border-radius: .25rem;
    transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out;
}

.enroll-form-input.form-input input:not([type='radio']) {
    border: 1px solid #2b5795;
    font-family: 'SlatePro Regular';
    width: 100%;
}

                            License first name
                            <input type="text" class="form-control" name="License_First_Name__c" id="licensefname" placeholder="*John" value="" maxlength="100" data-parsley-required="true" data-parsley-required-message="*License first name required" data-parsley-pattern="/^[a-zA-Z]+(([',. -][a-zA-Z ])?[a-zA-Z]*)*$/g" data-parsley-pattern-message="*Invalid License first name">

                            License last name
                            <input type="text" class="form-control" name="License_Last_Name__c" id="licenselname" placeholder="*Smith" value="" maxlength="100" data-parsley-required="true" data-parsley-required-message="*License last name required" data-parsley-pattern="/^[a-zA-Z]+(([',. -][a-zA-Z ])?[a-zA-Z]*)*$/g" data-parsley-pattern-message="*Valid license last name required">


text:
Q: How to bring back IIS Express for Debugging in Visual Studio 2019? I recently had to unload a project and reload it to fix a bug but now I dont have the option to start my code via IIS express anymore - instead it just says "Any CPU".

It used to say IIS Express (Google Chrome) and I can launch my web app through that but now it is gone and even going through the Web settings for debugging didn't fix it:

How can I bring back IIS Express so I can run my code properly again?

A: I research the issue and found a couple of ways to bring the IIS Express option back.
You could try the approaches below one by one.
Approach-1
In Visual studio 2019, select the solution(.sln)-> Properties. Select the drop-down Single Start-up project. select your project from the dropdown. Click OK.
It should bring back the IIS Express option.
Approach-2
In Visual studio 2019, Go to Tools-> Customize-> Commands tab, then click on the toolbar radio button and choose the standard option from the drop-down and delete one of the existing toolbar inside the standard toolbar and then choose the option reset all.

Helpful references:

*

*Can't debug asp.net core api in visual studio 2019 (No button IIS Express)

*Visual studio 2019 debugging option IISExpress is gone from drop down

*IIS Express hidden issue

A: Sounds like you need to exit, and then re-load VS.
If not, then I would repair it.
I would also consider (yes, I know!!!) a reboot of your computer to flush out any running copy of IIS express.
The setting (choice) of what browser should be to the right in your menu like this:

So, clicking on that down arrow (chevron) in your start button should drop a list of options to choose which browser.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Trying to make the smallest possible nested circles with css Im working on a Vue component, where the user can add circles in to other circles, with support for unlimited levels of nesting, but im having some problems with the CSS.
Here is a simplified version of the problem:
Im trying to achieve something like this.
I thought flexbox would be a great choice for that job, but cant make it work how i want it to, it always ends up way too big and not breaking up into separate lines or breaking out of the circles.
I have tried this approach, im open for a new structure if there is an easer way to do this. As long as the circle have a title and content, thought about using before and after for the title and content to simplify the structure, but haven't explored that option yet.

document.querySelectorAll(".circle").forEach( el => el.style.height = window.getComputedStyle(el).width);
* {
  margin: 0;
  padding: 0;
}
.flex {
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;

  flex-flow: row wrap;
  justify-content: space-around;
}
.circle {
  border-radius: 50%;
  padding: 40px;
  box-shadow: 7px 7px 5px 0px rgba(50, 50, 50, 0.75);
}
.head {
  color: #fff;
  text-align: center;
  margin-bottom: 10px;
  height: 20px;
}
.body {
  align-items: center;
}
.red {
  background-color: rgba(255, 17, 0, 0.76);
}
.blue {
  background-color: rgba(8, 0, 255, 0.76);
}
.green {
  background-color: rgba(0, 157, 11, 0.76);
}

            Parent

                    child-0

sub-child-0

content here

sub-child-1

content here

sub-child-2

content here

                    child-1

sub-child-0

content here

or as a jsfiddle.net link
Any inputs are appreciated, thanks :)

A: I think you could achieve something visually similar with d3.js:

var svg = d3.select("svg"),
  diameter = +svg.attr("width"),
  g = svg.append("g").attr("transform", "translate(2,2)"),
  format = d3.format(",d");

  var pack = d3.pack()
  .size([diameter - 4, diameter - 4]);

  var circles = '{ "name": "Parent", "children": [ { "name": "child-0", "children": [ {"name": "sub-child-0", "size": 100}, {"name": "sub-child-1", "size": 100}, {"name": "sub-child-2", "size": 100} ] }, { "name": "child-1", "children": [ {"name": "sub-child-0", "size": 100} ] } ]}';

  var circlesParse = JSON.parse(circles);

  circlesParse = d3.hierarchy(circlesParse)
  .sum(function(d) { return d.size; })
  .sort(function(a, b) { return b.value - a.value; });

  var node = g.selectAll(".node")
  .data(pack(circlesParse).descendants())
  .enter().append("g")
  .attr("class", function(d) { return d.children ? "node" : "leaf node"; })
  .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });

  node.append("title")
  .text(function(d) { return d.data.name + "\n" + format(d.value); });

  node.append("circle")
  .attr("r", function(d) { return d.r; });

  node.filter(function(d) { return !d.children; }).append("text")
  .attr("dy", "0.3em")
  .text(function(d) { return d.data.name.substring(0, d.r / 3); });
circle {
    fill: rgb(31, 119, 180);
    fill-opacity: .25;
    stroke: rgb(31, 119, 180);
    stroke-width: 1px;
  }

  .leaf circle {
    fill: #ff7f0e;
    fill-opacity: 1;
  }

  text {
    font: 10px sans-serif;
    text-anchor: middle;
  }

<svg width="250" height="250"></svg>

Inspired by https://bl.ocks.org/mbostock/4063530


text:
Q: Can't figure out GitHub repo name when I use `travis encrypt-file` when I use travis encrypt-file command,throw error:
Can't figure out GitHub repo name. Ensure you're in the repo directory, or specify the repo name via the -r option (e.g. travis <command> -r <owner>/<repo>)
How do I use travis command to specify the repo name? I don't find on travis's docs

A: A similar but more complete message can be seen in lib/travis/cli/repo_command.rb
Can't figure out GitHub repo name.
Ensure you're in the repo directory, or specify the repo name via the -r option (e.g. `travis <command> -r <owner>/<repo>`)"
GitHub repo name is invalid, it should be on the form 'owner/repo'

So in your case:
travis encrypt-file -r <owner>/<repo>

Or:
cd /path/to/GitHub/cloned/repo/locally
travis encrypt-file

(because in the last case, git remote -v shows the github remote repo url)
Speaking of remote, J0hnG4lt mentions in the comments:

Caused for me by having a non standard remote name.
Travis expects the remote to be called "origin".


text:
Q: restclient with ruby Here i am trying to pass one ID with the url, but that ID didn't append with URL...
def retrieve
    url =  "http://localhost:3000/branches/"
    resource = RestClient::Resource.new url+$param["id"]
    puts resource
end

giving ID via commend line that is
ruby newrest.rb  id="22"

I have got the error like this
`+': can't convert nil into String (TypeError)

But  all this working with mozilla rest client. How to rectify this problem?

A: Like this:
RestClient.get 'http://localhost:3000/branches', {:params => {:id => 50, 'name' => 'value'}}

A: Here are some examples from the documentation:
private_resource = RestClient::Resource.new 'https://example.com/private/resource', 'user', 'pass'

RestClient.post 'http://example.com/resource', :param1 => 'one', :nested => { :param2 => 'two' }

Just experiment with comma-separated parameters or with hashes so see what your URL gives you.

A: You can find the command line parameters in the global ARGV array.
If ruby newrest.rb 22 will do then just
id = ARGV[0]
response = RestClient.get "http://localhost:3000/branches/#{id}"
puts response.body

A: From my point of view line puts resource seems strange,
but when we leave it as it is
I'd suggest
def retrieve
    url =  "http://localhost:3000/branches/"
    resource = RestClient::Resource.new url
    res_with_param = resource[$param["id"]]
    puts res_with_param
end

I haven't tried so there may be a syntax mistakes.
I'm really newcomer in ruby.
But idea is good I hope.
Greetings,
KAcper


text:
Q: Issue with R Survey package with NA data when using svyby with covmat option I wanted to get differences between subgroup means from survey data (with survey weights, psu and strata), but due to a missing observation (NA), I could not do so. Would you mind helping me?
I used the package "Survey", created a survey design and grouped my observations which contained NA (income in the example below) by subgroup (city) using svyby. I also set covmat = True so I could use svycontrast later to compute standard errors. However, when I did so, I got NA.
library(survey)
data <- data.frame(psu = 1:8, city = rep(1:2, 4), income = c(2:8, NA), weights = 1)
svy <- svydesign(id=~psu, data = data, weights =~weights)
svyby(~income,~city, svy, svymean, covmat=TRUE)

  city income       se
1    1      5 1.195229
2    2     NA      NaN

I then tried to add all sorts of NA removals, but none of them seemed to work.
> svyby(~income,~city, svy, svymean, covmat=TRUE, na.rm.by=T, na.rm.all=T)
   city income       se
 1    1      5 1.195229
 2    2     NA      NaN
svyby(~income,~city, svy, svymean, covmat=TRUE, na.rm = T)
Error in inflmats[[i]][idxs[[i]], ] <- infs[[i]] :
  number of items to replace is not a multiple of replacement length

Any advice would be welcome.

A: Looks like a bug.
A work-around is to subset in advance:
> data <- data.frame(psu = factor(1:8), city = rep(1:2, 4), income = c(2:8, NA), weights = 1)
> svy <- svydesign(id=~psu, data = data, weights =~weights)
> svyby(~income,~city, subset(svy,!is.na(income)), svymean, covmat=TRUE)->a
> a
  city income       se
1    1      5 1.195229
2    2      5 1.007905
> vcov(a)
         1        2
1 1.428571 0.000000
2 0.000000 1.015873


text:
Q: DataTextFormatString DropDownList I am having an issue with using DataTextFormatString property where the values are not actually being formatted when they are being bound to the drop down list.
dvWaterLimits = this._lookupProvider.GetDataTable(version, form, package, state, DateTime.Today(), Zone);
this.ddlMyDropDown.DataSource = dvWaterLimits;
this.ddlMyDropDown.DataTextField = "LimitDescription";
this.ddlMyDropDown.DataValueField = "TotalLimit";
this.ddlMyDropDown.DataTextFormatString = " {0:$###,###,##0} ";
this.ddlMyDropDown.DataBind();

The data table I am getting back looks like the following:
Where the second column is the TotalLimit and the fifth column is LimitDescription
1133    5000    2   3   $5000
1133    10000   2   3   $10000
1133    15000   2   3   $15000
1133    20000   2   3   $20000
1133    25000   2   3   $25000

And the Drop down looks just like the fifth column when it should look like $5,000 $10,000... etc. with the commas.

A: use C in your format string.
{0:C}

C or c
Displays numeric values in currency format. You can specify the number of decimal places.
Note: a comma is not used in US for decimals!

A: One option can be override your CurrentCulture for this operation with cloned en-US culture which setted CurrencyDecimalDigits to 0 and use The "C" format specifier for DataTextFormatString property as "{0:C}".
It is unclear you want as $5,000 or $5000. If you don't want group separator, you need to assign CurrencyGroupSeparator to empty string as well.
As an example;
int i = 5000;
var clone = (CultureInfo)CultureInfo.GetCultureInfo("en-US").Clone();
clone.NumberFormat.CurrencyDecimalDigits = 0;
Console.WriteLine(i.ToString("C", clone)); // $5,000

or
int i = 5000;
var clone = (CultureInfo)CultureInfo.GetCultureInfo("en-US").Clone();
clone.NumberFormat.CurrencyDecimalDigits = 0;
clone.NumberFormat.CurrencyGroupSeparator = "";
Console.WriteLine(i.ToString("C", clone)); // $5000

Or much better without setting CurrencyDecimalDigits property;
int i = 5000;
Console.WriteLine(i.ToString("C0", CultureInfo.GetCultureInfo("en-US"))); // $5,000

I honestly don't know how to override a culture for just one element in asp.net (or possible or not) but you can check these topics;

*

*Is there a way of setting culture for a whole application? All current threads and new threads?

*How to: Set the Culture and UI Culture for ASP.NET Web Page Globalization

A: So not sure if it was the '$', or if the value was coming in as a string so it couldn't make the match between the # and the value coming in. But this started working after i made this ineffecient change.
foreach (DataRow dr in dtClone.Rows)
            {
                if (dr["LimitDescription"].ToString().Contains("$"))
                {
                    dr["LimitDescription"] = Convert.ToDouble(dr["LimitDescription"].ToString().Replace("$", "")).ToString("$###,###,##0");
                }
            }


text:
Q: How to load only one Worksheet using OpenXML? Using OpenXML,I need to read large excel file(50 to 100 mbs)  which contains multiple sheets each having heavy data. My input form having a textbox to enter specific sheetname to be read.
Now my question is how to load only specific sheet in memory & read cell values using openxmlreader, so I can get better performance.


text:
Q: Hamcrest - what version to use? 1.3 or 2 I am quite confused. Currently I am testing my spring application using
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
</dependency>

I was happy as long as I wanted to match RegularExpressions. In hamcrest 1.3 you need to write your own matcher, which I did not like that much.
I searched and found that hamcrest 2.0 has something build in, like:
assertThat(DateHelper.getActualDateForXML(), MatchesPattern.matchesPattern("\\d{4}+-\\d{2}-+\\d{2}+T\\d{2}+:\\d{2}+:\\d{2}+"));

I was happy, I added:
<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-junit</artifactId>
    <version>2.0.0.0</version>
    <scope>test</scope>
</dependency>

And kicked out the 1.3 hamcrest dependencies from spring-boot-starter-test:
<exclusions>
    <exclusion>
       <groupId>org.hamcrest</groupId>
       <artifactId>hamcrest-library</artifactId>
    </exclusion>
    <exclusion>
       <groupId>org.hamcrest</groupId>
       <artifactId>hamcrest-core</artifactId>
    </exclusion>
</exclusions>

Now everything is still working as I expect it to work, but I do not feel really comfortable. Because I can just find people writing about 1.3 and can not really find the use of hamcrest-junit 2.0.
Can somebody explain me the connection between them? Because it seems that hamcrest-junit 2.0 has everything build in from hamcrest 1.3...
Thanks Ben

A: EDIT: After several years the answer is to use the latest Hamcrest 2 version (2.2 from 17th October 2019). For additional details also refer to @dschulten's answer.
Following is my original answer which I leave as context to understand the problem and confusion around Hamcrest versions 1.3 and 2.0.0.0 back in the day.

Based on Hamcrest Github

*

*Hamcrest Github CHANGES.md

*Decouple the evolution of Hamcrest and JUnit

*Is this still being maintained?
and JUnit Lambda (Junit 5)

*

*Minimize dependencies (especially third-party)
My take on it

*

*hamcrest-junit 2.0 (should be) is a fresh start with also the goal to decouple hamcrest from junit

*in the meantime Junit 5 project kicked off which reduces/removes third party dependencies

=> In this situation, I expect it is prudent for the hamcrest guys to wait for / coordinate with the JUnit 5 project before moving forward substantially.
As @heenenee mentioned, the hamcrest guys became busy with other stuff and so not much is happening with the project at this point.
To answer

Can somebody explain me the connection between them? Because it seems that hamcrest-junit 2.0 has everything build in from hamcrest 1.3

*

*hamcrest-junit 2.0 started but the guys behind it got busy soon after (and still are) with other projects, so the development stopped

*there might also be some uncertainties regarding JUnit 5 which may be an incentive to defer further hamcrest-junit 2.0 development until the JUnit 5 release (speculation)

... but I do not feel really comfortable. Because I can just find people writing about 1.3 and can not really find the use of hamcrest-junit 2.0.

At the moment, other than for your case there is not much incentive to move to hamcrest-junit 2.0. Once Junit 5 releases I expect that there will be more incentive to move forward again.

A: Great answer by Ivo, which really should be getting more votes, but here's some added information. If you check Maven for information on the dependencies, Java Hamcrest 2.0.0.0 and Hamcrest JUnit 2.0.0.0, there are some usage links. At the time I write this, it's 74 and 68 respectively, and no major projects from a brief browsing.

A: The Hamcrest project has just released 2.1, and they reworked the package structure after thorough consideration. Make sure you follow the upgrade procedure.
The artifact java-hamcrest 2.0.0.0 is considered a failed attempt now.


text:
Q: Multi countdown I have a web page where I entered a countdown code and it works well. However, I can only call it 1 time with the id in html.
Second or third time, it no longer works. How can I always use it? I would need it 3 or 4 times on the page. Thank you.
This is the code:
  var counter = null;

  window.onload = function() {
    initCounter();
  };

  function initCounter() {
    // get count from localStorage, or set to initial value of 1000
    count = getLocalStorage('count') || 1000;
    counter = setInterval(timer, 1000); //1000 will  run it every 1 second
  }

  function setLocalStorage(key, val) {
    if (window.localStorage) {
      window.localStorage.setItem(key, val);
    }

    return val;
  }

  function getLocalStorage(key) {
    return window.localStorage ? window.localStorage.getItem(key) : '';
  }

  function timer() {
    count = setLocalStorage('count', count - 1);
    if (count == -1) {
      clearInterval(counter);
      return;
    }

    var seconds = count % 60;
    var minutes = Math.floor(count / 60);
    var hours = Math.floor(minutes / 60);
    minutes %= 60;
    hours %= 60;

    document.getElementById("timer").innerHTML = hours +  " ore "  + minutes +  " min "   + seconds +  "  sec"; // watch for spelling
  }

A: You need to encapsulate the functionality in a way that can be called many times. It usually helps to think about the question "As a programmer, how I'd like to use this?"
Usually, it's a single function that takes some parameters and does something and/or returns something.
As an example... wouldn't it be nice if we had a function startMyTimer(...) that takes a timerId, and an element and sets up a timer that will update that element? We already have the signature:
function startMyTimer(timerId, element) { ... }

And now you can build everything inside this function. JS allows declaring functions within functions, which helps with encapsulation, so copying from your code it would look like:
function startMyTimer(timerId, element) {
  var count = getLocalStorage(timerId) || 1000;
  var counter = setInterval(timer, 1000); //1000 will  run it every 1 second

  function timer() {
    count = setLocalStorage(timerId, count - 1);
    if (count == -1) {
      clearInterval(counter);
      return;
    }

    var seconds = count % 60;
    var minutes = Math.floor(count / 60);
    var hours = Math.floor(minutes / 60);
    minutes %= 60;
    hours %= 60;

    element.innerHTML = hours + " ore " + minutes + " min " + seconds + "  sec"; // watch for spelling
  }
}

Note that now count and counter are both private to the scope of startMyTimer, so only within this function (and any function inside this one, such as function timer()) will see these variables.
So if you want to do exactly what you did, you'd use this function as
window.onload = function() {
  startMyTimer('count', document.getElementById("timer"));
};

Again, this is just an example of a posible solution - Maybe you could pass in the element id instead of the element, or a timer duration, etc., and the best solution is the one that fits best your needs.


text:
Q: Text changeD (not changing) in a JTextPane or JTextField Ok, I had a very specific problem. I had a panel with a JTextField and a JTextPane (actually 2 JTextPane, but I had only one active) and needed an event to update the relative variables in the caller form when the user was done editing the text.
JTextPane is set with a StyledDocument, therefore, I can't afford to update its variable every single time I press a key, therefore using DocumentListener was not viable.
And using FocusListener was not a solution either, because the variable (couple) was selected using a JList component and it changed the reference before FocusLost was changed. In short, other components were interferring with the variable instance.
This is how I solved the problem.
First of all I created an InputVerifier:
InputVerifier myInputVerifier = new InputVerifier() {
    @Override
    public boolean verify(JComponent input) {
        if ((input instanceof JTextField source) && source == tfKeywords) {
            PropertyChangeEvent evt = new PropertyChangeEvent(source, "Keywords", source.getText(), null);
            for (PropertyChangeListener l: pnlEditorFull.this.getPropertyChangeListeners())
                l.propertyChange(evt);
        } else if (input instanceof JTextPane source && source == ActualEditor) {
            PropertyChangeEvent evt = new PropertyChangeEvent(source, "Description", source.getText(), null);
            for (PropertyChangeListener l: pnlEditorFull.this.getPropertyChangeListeners())
                l.propertyChange(evt);
        }
        return true;
    }
};

When the verifier is asked, it fires an event propertyChange as "Keywords" for the JTextField or "Description" for the JTextArea.
On the other side I have a PropertyListener
pnlEditor.addPropertyChangeListener((PropertyChangeEvent evt) - > {
    if ("Keywords".equals(evt.getPropertyName()))
        myKeywords = EditorPane.getKeywords(); // actually a little more complicated
    else if ("Description".equals(evt.getPropertyName()))
        myDescription = EditorPane.getText(); // actually a little more complicated
});

To retrieve the text I use a function on the panel called getText():
public String getText() {
    StringWriter sw = new StringWriter();
    try {
        ActualEditor.write(sw);
    } catch (IOException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
    }
    return sw.toString();
}

Using ActualEditor.write(sw); is needed because i need to retrieve the text and the formatting.
It worked. It fires before FocusLost and before the JList changes its selected item. Of course I could have just used the JList ListSelectionListener to setup the changes when the selection changed (I initially did it), but this would left an uncertainty window in which, if other components interferred, I could very well lose all the changes or change the wrong variables. It needs to be called when the changes are final (not while the changes were occurring), and that's the only solution I could thing of.
Here a simplified example of how it should work (it also includes the JList):
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
import javax.swing.DefaultListModel;
import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JList;
import javax.swing.JTextArea;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

/**
 *
 * @author luca.scarcia
 */
public class frmMain extends javax.swing.JFrame {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    static final Logger LOGGER  = System.getLogger(frmMain.class.getName());

    private JTextArea anEditor;
    private JList<String> aList;
    private DefaultListModel<String> Model;

    public frmMain() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new java.awt.GridLayout());

        aList = new JList<>();
        this.add(aList);
        Model = new DefaultListModel<>();
        Model.addElement("Element 1");
        Model.addElement("Element 2");
        Model.addElement("Element 3");
        Model.addElement("Element 4");

        aList.setModel(Model);

        anEditor = new JTextArea();
        this.add(anEditor);

        anEditor.setInputVerifier(new InputVerifier() {
            @Override
            public boolean verify(JComponent input) {
                if(input == anEditor) {
                    PropertyChangeEvent evt = new PropertyChangeEvent(anEditor, "Description", anEditor.getText(), null);
                    for(PropertyChangeListener l:anEditor.getPropertyChangeListeners()) {
                        l.propertyChange(evt);
                    }
                }
                return true;
            }
        });

        anEditor.addPropertyChangeListener(new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
            if(aList.getSelectedIndex()>=0)
                if("Description".equals(evt.getPropertyName()) && evt.getSource()==anEditor) {
                    StringWriter sw = new StringWriter();
                    try {
                        anEditor.write(sw);
                    } catch (IOException ex) {
                        LOGGER.log(Level.ERROR, ex);
                    }
                    Model.setElementAt(sw.toString(), aList.getSelectedIndex());
                    aList.validate();
                }
            }
        });

        aList.addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                if(e.getSource() == aList) {
                    StringReader sr = new StringReader((String)aList.getSelectedValue());
                    try {
                        anEditor.read(sr, null);
                    } catch (IOException ex) {
                        LOGGER.log(Level.ERROR, ex);
                    }
                }
            }
        });
        pack();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            LOGGER.log(Level.ERROR, ex);
        }

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(() -> {
            new frmMain().setVisible(true);
        });
    }
}

Question: Does anybody have a better solution?

A:
And using FocusListener was not a solution either, because the variable (couple) was selected using a JList component and it changed the reference before FocusLost was changed

You could save the selected index when focus is gained on the text area.
You then also need to make sure you don't reset the text until the selection listener is finished adjusting:
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

/**
 *
 * @author luca.scarcia
 */
public class frmMain2 extends javax.swing.JFrame {

    private JTextArea anEditor;
    private JList<String> aList;
    private DefaultListModel<String> Model;

    public frmMain2() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new java.awt.GridLayout());

        aList = new JList<>();
        this.add(aList);
        Model = new DefaultListModel<>();
        Model.addElement("Element 1");
        Model.addElement("Element 2");
        Model.addElement("Element 3");
        Model.addElement("Element 4");

        aList.setModel(Model);

        anEditor = new JTextArea(5, 30);
        this.add(anEditor);

        anEditor.addFocusListener( new FocusAdapter()
        {
            int selected;

            @Override
            public void focusGained(FocusEvent e)
            {
                selected = aList.getSelectedIndex();
            }

            @Override
            public void focusLost(FocusEvent e)
            {
                Model.setElementAt(anEditor.getText(), selected);
            }
        });

        aList.addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                if(!e.getValueIsAdjusting()) {
                    StringReader sr = new StringReader((String)aList.getSelectedValue());
                    try {
                        anEditor.read(sr, null);
                    } catch (IOException ex) {
                        System.out.println(ex);
                    }
                }
            }
        });

        pack();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
        }

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(() -> {
            new frmMain2().setVisible(true);
        });
    }
}


text:
Q: read() complete data on SPP using thread I have a third party Android application which connects to my target using Bluetooth SPP.
Application sends JSON data, but number of data bytes sent are not known, also data received at my target is inconsistent (sometimes in chunks), there are no line endings to detect the end of data sent.
I have a thread running in my code to read the data over serial port.
int fd = open(rfcommDevice, O_RDWR | O_NOCTTY | O_SYNC);

void readData(int fd)
{
   while (1)
   {
      nbytes = read(fd, buf, buflen);
      if (nbytes < 0)
      {
         break;
      }
      else if (nbytes > 0)
      {
            showCompleteData();
      }
      else
      {
         close(fd);
         break;
      }
   }
}

Now showCompleteData() first parses the data and if found incomplete it fails.
As data is received in chunks, so I am not able to understand how to accumulate the complete data and then call showCompleteData().
Also read() does not return 0, as its a blocking call.
Please suggest.


text:
Q: How to create Silverlight 3 Themes? The new Silverlight 3 features page says:
Developers can now theme applications by applying styles to their Silverlight 3 applications and changing them at runtime.
But I can't find any information about this.  I would like to create a theme for may app to define button styles/etc...
Can someone let me know how to do this or point me to a web tutorial?

A: Did you see Karen Corby's talk at Mix09 online?
Around the 43-44 minute mark of her talk she shows off dynamic styling with Silverlight 3 and she has some example code on her blog.
Karen's talk on the Mix video site.
Karen's blog which had sample code and slides


text:
Q: Producto.ID IN Error.MULTIDELETE Quiero borrar el registro de porductoId donde la cantidad es null, pero me sale un error.
delete productoId
from producto p
left join ventas v on p.ProductoId=v.ProductoId
WHERE v.cantidad is null

Lo que quiero borrar es el productoId:
select p.productoId, v.cantidad
from producto p
left join ventas v on p.ProductoId=v.ProductoId
WHERE v.cantidad is null

A: El error es que no estas indicando de que tabla quieres borrar.
Solución:
Si lo que quieres es borrar los productos entonces debes indicar el alias de la tabla. En tu caso es p
Ejemplo:
DELETE p
FROM producto p
LEFT JOIN ventas v ON p.ProductoId = v.ProductoId
WHERE v.cantidad IS NULL

Demo

Actualización:

Me sale este error cuando lo hago asi: Error Code: 1175. You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column.

Aparentemente tu MySQL tiene activo actualizaciones seguras.
Para desactivarlo, antes de realizar la consulta, tienes que ejecutar:
SET SQL_SAFE_UPDATES = 0;

A: Fijate como tenes configurada la relación en cuanto a las restricciones (que comportamiento toma al borrar o modificar una tabla relacionada con otra)
Alter table .... ....  ON DELETE X ON UPDATE X;

Donde x es: RESTRICT no te deja borrar registros si esta asociada a otra tabla.
SET NUll borra el registro de la tabla y setea a null la tabla asociada.
CASCADE borra el registro de la tabla y todos los asociados.
NO ACTION borra el registro de la tabla y la otra tabla ni se entera.


text:
Q: python3 JSON parse         [
        {
            "Match":"solo",
            "Region":"eu",
            "Season":"2017-pre1",
            "Stats":[
                {
                    "ValueDec":0.9,
                    "ValueInt":null,
                    "category":"Performance",
                    "displayValue":"0.90",
                    "field":"KillDeathRatio",
                    "label":"K/D Ratio",
                    "partition":null,
                    "percentile":65.0,
                    "rank":null,
                    "subLabel":null,
                    "value":"0.9"
                },
                {
                    "ValueDec":1328.12,
                    "ValueInt":null,
                    "category":"Skill Rating",
                    "displayValue":"1,328.12",
                    "field":"Rating",
                    "label":"Rating",
                    "partition":null,
                    "percentile":22.0,
                    "rank":29346,
                    "subLabel":null,
                    "value":"1328.12"
                }
            ]
        }
        ]

Скажите пожалуйста, как достать значение "rank" там где "category" == "Skill Rating"?

A: Можно так:
import json

In [25]: lst = json.loads(s)

In [26]: lst
Out[26]:
[{'Match': 'solo',
  'Region': 'eu',
  'Season': '2017-pre1',
  'Stats': [{'ValueDec': 0.9,
    'ValueInt': None,
    'category': 'Performance',
    'displayValue': '0.90',
    'field': 'KillDeathRatio',
    'label': 'K/D Ratio',
    'partition': None,
    'percentile': 65.0,
    'rank': None,
    'subLabel': None,
    'value': '0.9'},
   {'ValueDec': 1328.12,
    'ValueInt': None,
    'category': 'Skill Rating',
    'displayValue': '1,328.12',
    'field': 'Rating',
    'label': 'Rating',
    'partition': None,
    'percentile': 22.0,
    'rank': 29346,
    'subLabel': None,
    'value': '1328.12'}]}]

In [27]: [x['rank'] for x in lst[0]['Stats'] if 'category' in x and x['category'] == 'Skill Rating' and 'rank' in x]
Out[27]: [29346]

In [28]: [x['rank'] for x in lst[0]['Stats'] if 'category' in x and x['category'] == 'Skill Rating' and 'rank' in x][0]
Out[28]: 29346


text:
Q: Скопировать 22Гб файлов Мне нужно с помощью php скрипта перекопировать 22Гб файлов из одной папки на сайте в другую.
Скрипт я написал, но боюсь его запускать))
max_execution_time поставил в -1
Копируется с помощью функции copy()
Посоветуйте пожалуйста стоит ли это делать с помощью php?
Или может посмотреть на другие языки, если да то посоветуйте какие?
Сервер под Debian


text:
Q: @StreamListener to inbound a list of messages I'm currently using @StreamListener to inbound messages one-by-one and then process it in our service class to save it in db.
Instead, I want to inbound a list of messages (say 100) at a time and then process it to save all these 100 messages at once to avoid repetitive calls to DB.
How can we achieve this using @StreamListener.


text:
Q: Get eclipse run configuration arguments from script or environment variable (Pydev) I am developing with openerp using PyDev on a Linux box.
So far I have to use 6 different run configurations, with an argument whose value is the same for all these configurations, and an other argument which is specific to each one.
Example: openerp -d <common_value> -u <specific_value>
I want to be able to do this : openerp -d $COMMON_VALUE -u <specific_value>, so that everytime I have to change the value of db, I don't have to go and change its value manually in all the six run configurations.
I tried to use environment variables, but these do not get reloaded even after I restart Eclipse. Would there be a way to read it from a bash script or other ?
Thank you for your help

A: Well, I think the best way in this case would be creating a launcher script (which in turn would fix sys.argv and call execfile with the openerp module) and create a launch for that module instead.
If you want, you can load that value from an environment variable (then set the environment variable in preferences > PyDev > Interpreters > Python Interpreter > Environment) -- and that's also the place you have to use to change it later on, as the process will by default inherit the environment variables that were used when Eclipse was started up.
Or load it from a file -- or leave it hardcoded and change on that module -- which may be the most straightforward way :)

Another option:
You can 'connect' your launch configurations to a file (run > run configurations > select the configuration > common > save as > shared file), that way you can do a search/replace to fix the run configurations (which should be faster than doing it in the UI).


text:
Q: Change Tomcat Port on CentOS 5.3 I installed Tomcat5 on CentOS 5.3, by default tomcat runs on port 8080 but i already have ISPConfig running on that port.
Port 80 is taken up by Apache
How do I know which port tomcat is listening on ? and if required change the port.

A: In server.xml (usually in /etc/tomcat), there's a block starting
<Server port="xxxx">

or similar, where xxxx is the port your server is listening on, this will tell you where the server is listening.
Changing the port is easy, just change this setting and restart tomcat.
Alternatively run netstat -anp and it will tell you which program is using which port.


text:
Q: Hikari cp with spring boot.. Active connections always at 1.. Not increasing but not comig down to 0 I am connecting to a db2 database using springBoot application.
I am using SpringBoot 2.1.2 Release.
db2jcc4 version is 4.26.14
At the server startup the database connection is established.
@ConfigurationProperties(prefix="data.app")
@Bean
public DataSource dataSourceApp(){

return new HikariDataSource(new HikariConfig())
}

@Bean
EntityManagerFactory appEntityManagerFactory(){
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean ();
emf.setDataSource(dataSourceApp);
emf.setJPAVendorAdaptor(jpaVendorAdaptor);
emf.afterPropertiesSet();
return emf.getObject();

}

@Bean
publc EntityManager appEntityManager()
{
return appEntityManagerFactory.createEntityManager();
}

Then this entityManager is used for executing queries for each request.
Following are the connection pool properties
data.app.minimumIdle=0
data.app.idleTimeout=120000
data.app.driverClassName=com.ibm.db2.jcc.DB2Driver
data.app.jdbcURL=
data.app.username=
data.app.password=
data.app.maximumPoolSize=10
data.app.connectionTimeout=300000
data.app.poolName=
data.app.maxLifetime=130000
data.app.validationTimeout=300000

When the request comes
@Autowired
Entitymanager entityManager;

Query query= entitymanager. CreateNativeQuery(queryString) ;

ExecuteQueries(query, queryString)

When the application  is first started the active Connections are shown as 0(have enabled Hikari monitoring)
On execution of 1stquery the active connections grow to 1 and remain at 1 even if multiple queries are fired. And even after the idleTimeout and maxlifetime have reached. How do I return back this connection to pool. I have tried using entitymanager.
Close() in the finally block.. But this is also not returning the connection to pool.
Any help is appreciated. Thanks.
Thanks in advance .

A: Try removing the minimumIdle property.
From the Hikari docs

minimumIdle
This property controls the minimum number of idle connections that HikariCP tries to maintain in the pool. If the idle connections dip below this value and total connections in the pool are less than maximumPoolSize, HikariCP will make a best effort to add additional connections quickly and efficiently. However, for maximum performance and responsiveness to spike demands, we recommend not setting this value and instead allowing HikariCP to act as a fixed size connection pool. Default: same as maximumPoolSize

Ideally for the best performance, you want the min and the max to be the same so connections are created at startup and not created on the fly.


text:
Q: How to verify the email links in the selenium without login to mail? How to verify the email links in the selenium without login to mail?
I need to click the email link after my first test is completed and i should not login to gmail as i need to verify for dynamic mails. So is that possible to use any other option please help me on this. and we are using sql DB.

A: Instead of using a real mail server use a fake one (e.g. JTalks Pochta):

*

*Configure your app to point to such a server

*In your tests access fake server via REST to get the contents of the emails

*Parse out links from the body

*Profit

A: You can use restmail.net, it has very clear REST API.


text:
Q: problema con rows en bootstrap 5 Hola tengo esta pagina web, y el problema es que queria mostrar las dos rows en dos filas separadas y no como dos columnas que es como se muestra. Es decir quiero que aparezca una fila con color danger y que ponga "i'm vertically centered" y debajo otra fila con color warning y que ponga tambien "i'm vertically centered". Y que por supuesto ambas filas esten centradas verticalmente.

        <meta charset="UTF-8">
        <title></title>

        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

                    I'm vertically centered

                    I'm vertically centered

Si en lugar de d-flex pongo d-block en el contanier me aparece en dos filas distintas pero no aparece alineado al centro verticalmente.
Por cierto en el navegador (tanto en firefox como en chrome) las dos filas (la danger y la warning) ocupan todo el alto de la pantalla cosa que no sucede en el snippet.

A: Puedes hacer algo así:

                I'm vertically centered

                I'm vertically centered

El container no debe ser display: flex, y los row siempre son display: flex por defecto, por lo que funciona agregando solo a los rows un align-items center, luego a cada row le puse un h-50 que es equivalente a height: 50%;
De esta forma quedan 2 Rows una encima de la otra, con sus cols adentro alineadas verticalmente.
Espero te sirva.
Por último vi que tienes cols de 6, entonces estás usando el mx-auto para centrarlas, eso funciona, quizás podrías usar también ya que estás utilizando flexbox aplicar justify-content-center.. Quedaría así:

                I'm vertically centered

                I'm vertically centered

La primer row está hecha con justify-content-center y la segunda con mx-auto. En estos casos ya estaría centrada horizontal y verticalmente..


text:
Q: Hidden div appear on table option select I have a page with a form and questions of these forms are asked on two separate tables. I want to make the second table appear only if One, Two or Three is selected from the first table, and be invisible by default. If Zero is selected again, table 2 disappears again.
I got it to partially work with the code below, however I think my script is cancelling each other out. I can get it to work with One, Two or Three, but not all three selections. In this case, table 2 only appears when I select "Three", and nothing happens when Zero, One and Two is selected.
How would I go about changing the script to let it appear when One, Two or Three are selected and disappear when Zero is selected once again.

    Numbers

      <select id="numbers" name="numbers">
         <option value="Zero" selected>0</option>
         <option value="One">1</option>
         <option value="Two">2</option>
         <option value="Three">3</option>
       </select>

           Animal

              <select id="animal" input name="animal">
                  <option value="Dog">Dog</option>
                  <option value="Cat">Cat</option>
                  <option value="Rabbit">Rabbit</option>
              </select>

A: You do not need to write three event listeners. Just one can do this.
 document.getElementById('numbers').addEventListener('change', function () {
var style = (this.value == 'One' || this.value == 'Two' || this.value =='Three')  && (this.value != 'Zero') ? 'inline' : 'none';
document.getElementById('animals').style.display = style;
 });

A: using Array include, check code snippet.

    Numbers

      <select id="numbers" name="numbers">
         <option value="Zero" selected>0</option>
         <option value="One">1</option>
         <option value="Two">2</option>
         <option value="Three">3</option>
       </select>

           Animal

              <select id="animal" input name="animal">
                  <option value="Dog">Dog</option>
                  <option value="Cat">Cat</option>
                  <option value="Rabbit">Rabbit</option>
              </select>


text:
Q: Telegram BotFather API Is there a way to "communicate" with Telegram BotFather via API to create and configure new bots without actually "chat" with it?
It could be useful to create a bot programmatically.


text:
Q: filter pandas data on specific index I'd like to filter a dataframe based on specifics index.
I've read things about query but I don't succeed.
Here is the code which create my pivot table. I'd like to filter on specific members
    df = pd.DataFrame(my_dataframe)
    table = pd.pivot_table(df,index=["Date","member","Card"], columns=["Type"],values=["Heure"],aggfunc=[len]) #,fill_value=0)
    table.to_excel(writer, sheet_name='TcD')

What should I do ?
Thanks

A: You can use query or select by level of MultiIndex by slicers:
df = pd.DataFrame({'Card':list('baaaaa'),
                   'Date':['2017-10-01'] * 6,
                   'Heure':[1,3,5,7,1,0],
                   'Type':[5,5,5,9,5,9],
                   'member':list('aaabbb')})

print (df)
  Card        Date  Heure  Type member
0    b  2017-10-01      1     5      a
1    a  2017-10-01      3     5      a
2    a  2017-10-01      5     5      a
3    a  2017-10-01      7     9      b
4    a  2017-10-01      1     5      b
5    a  2017-10-01      0     9      b

table = pd.pivot_table(df,index=["Date","member","Card"],
                       columns="Type",
                       values="Heure",
                       aggfunc='size')
print (table)
Type                      5    9
Date       member Card
2017-10-01 a      a     2.0  NaN
                  b     1.0  NaN
           b      a     1.0  2.0

table1 = table.query('member == "a"')
print (table1)
Type                      5   9
Date       member Card
2017-10-01 a      a     2.0 NaN
                  b     1.0 NaN

idx = pd.IndexSlice
table1 = table.loc[idx[:,'a',:],:]
print (table1)
Type                      5   9
Date       member Card
2017-10-01 a      a     2.0 NaN
                  b     1.0 NaN

EDIT:
For filter by multiple values use:
table1 = table.query('member in ["a", "b"]')
print (table1)
Type                      5    9
Date       member Card
2017-10-01 a      a     2.0  NaN
                  b     1.0  NaN
           b      a     1.0  2.0

idx = pd.IndexSlice
table1 = table.loc[idx[:,['a', 'b'],:],:]
print (table1)
Type                      5    9
Date       member Card
2017-10-01 a      a     2.0  NaN
                  b     1.0  NaN
           b      a     1.0  2.0


text:
Q: Valgrind blocks are definitely lost in loss record I am trying to figure out what is wrong with my valgrind debugging. I am learning this valgrind slowly.
debug:
==1701== HEAP SUMMARY:
==1701==     in use at exit: 390 bytes in 12 blocks
==1701==   total heap usage: 59 allocs, 47 frees, 1,097 bytes allocated
==1701==
==1701== 39 bytes in 1 blocks are definitely lost in loss record 6 of 12
==1701==    at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==1701==    by 0x401246: songToString (song.c:147)
==1701==    by 0x40083C: main (songtest.c:52)
==1701==

Code (songToString function):
char *songToString(const song *s)
{
    char *sstr = NULL ;
    char *st = NULL ;
    char *sa = NULL ;
    char *tt = NULL ;
    int len = 0 ;

    st = songGetTitle(s) ;
    sa = songGetArtist(s) ;

    // calculate the total string length needed.
    len = strlen("Title: ") + strlen(st) +
                  strlen("  Artist: ") + strlen(sa) + 1 ;

    if (NULL != s->lastPlayed)
    {
        tt = mtimeToString(s->lastPlayed) ;
        len += strlen(" at ") + strlen(tt) ;
    }

    // allocate enough space for the song
    sstr = malloc( len ) ;

    sprintf(sstr, "Title: %s  Artist: %s", st, sa) ;

    if (NULL != s->lastPlayed)
    {
        sstr = strcat(sstr, " at ") ;
        sstr = strcat(sstr, tt) ;
    }

    free(sa) ;
    free(st) ;
    free(tt) ;
    return sstr ;
}

In songToString, line 147 is sstr = malloc( len ) ;
in songTest (line 52):
char * sstr = songToString( song1 ) ;

Any help would be great. Thank you.

A: valgrind is showing you where the leaked memory was allocated, but the actual bug has to be tracked to where that memory ends up.
Obviously after you assign to sstr in main, you never free that.

A: @o11c
You gave wrong advice.
See link:
http://c-faq.com/ptrs/passptrinit.html
Another solution is to have the function return the pointer:
int *f()
{
    static int dummy = 5;
    return &dummy;
}

...

int *ip = f();


text:
Q: Api returns 403 error when calling through webrequest, but works when calling in postman I can successfully run the following OpenStreetMap api from Postman:
https://nominatim.openstreetmap.org/reverse?format=json&lat=30.32736&lon=56.91912
Postman request:
GET /reverse?format=json& lat=30.32736& lon=56.91912 HTTP/1.1
Host: nominatim.openstreetmap.org
cache-control: no-cache
Postman-Token: 92646056-107c-4011-b35f-85858ec715bd

But when trying to call it in c# using this code:
            HttpWebRequest objRequest = (HttpWebRequest)WebRequest
            .Create("https://nominatim.openstreetmap.org/reverse?format=json&lat=30.32736&lon=56.91912");
            objRequest.Method = "GET";
            objRequest.Headers.Add("User-Agent: Other");

            WebResponse response = (WebResponse)objRequest.GetResponse();
            HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
            string result = "";
            using (StreamReader responseStream = new StreamReader(objResponse.GetResponseStream()))
            {
                result = responseStream.ReadToEnd();
                responseStream.Close();
            }

I get the following error:

System.Net.WebException: 'The remote server returned an error: (403)
  Forbidden.'

On line:
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();

After I did a search, I found the following header suggested to be added to the request:
objRequest.Headers.Add("User-Agent: SomeName");

But still not working.

A: Actually, when I run your code, I get an ArgumentException "The 'User-Agent' header must be modified using the appropriate property or method."
Removing the line also yields the 403 error. But, you are already on the right track: Replace your objRequest.Headers.Add("User-Agent: SomeName"); line with:
objRequest.UserAgent = "SomeName";

Then, it works fine for me.


text:
Q: Generating custom data in FsCheck I've got an FsCheck question:
I have the following record type (and I say upfront, I have been told that my Single-Case DUs are maybe an overkill, but I find them descriptive of the domain, and therefore necessary, and I will not remove them unless must):
type Name = Name of string
type Quality = Quality of int
type ShelfLife = Days of int
type Style = Plain | Aged | Legendary

type Item = {
    Name: Name
    Quality: Quality
    ShelfLife: ShelfLife
    Style: Style
}

Assuming I already have defined the functions repeat: Int -> ('a -> 'a) -> 'a and decreaseQuality: Item -> Item, I want to code an FsCheck test that checks the invariant: Any item with style OTHER THAN Legendary, after 100 days have passed, has quality of 0.
My problem is I don't know the following things about FsCheck:
1. How do I define a custom generator that generates items whose style is not Legendary? And in contrast, how do I define items only of type Legendary (to test both types)?
I've looked into:
 let itemGenerator = Arb.generate<Item>
 Gen.sample 80 5 itemGenerator

but that creates Items that are plain weird, as the size controller, in the example, 80, controls also the length of the Name of string (due to the of string) and also produces Quality and ShelfLife values that are unacceptable to my domain (i.e. negative) as they are both defined as ... of int which the size also controls.
(I've also looked into Gen.oneof..., but that turned out to also be a dud).

*How do I even define a test that only tests the Quality property of the record, even assuming I found out a way to generate custom data?.

Thanks!

A: Most of what you want becomes easy once you know how to use the gen { } computation expression to maximum effect.
First, I'll tackle how to generate a Style that isn't Legendary. You could use Gen.oneOf, but in this case I think it's simpler to use Gen.elements, since oneOf takes a sequence of generators to use, but elements just takes a list of items and generates one item from that list. So to generate a Style that isn't Legendary, I'd use Gen.elements [Plain; Aged]. (And to generate a Style that is Legendary, I'd just not use a generator and simply assign Legendary to the appropriate record field, but more on that later.)
As for names being too long, to limit the size of the strings produced to, say, a maximum of 15 characters, I'd use:
let genString15 = Gen.sized (fun s -> Gen.resize (min s 15) Arb.generate<string>)
// Note: "min" is not a typo. We want either s or 15, whichever is SMALLER
Gen.sample 80 5 genString15
// Never produces any strings longer than 15 characters

But this can still generate null strings, so I'd probably use this for my final version:
let genString15 =
    Gen.sized (fun s -> Gen.resize (min s 15) Arb.generate<NonNull<string>>)
    |> Gen.map (fun (NonNull x) -> x)  // Unwrap
Gen.sample 80 5 genString15
// Never produces any strings longer than 15 characters, AND never produces null

Now, since Quality and ShelfLife both can't be negative, I'd use either PositiveInt (where 0 isn't allowed either) or NonNegativeInt (which allows 0). Neither one is well documented in the FsCheck documentation, but they work like this:
let x = Arb.generate<NonNegativeInt>
Gen.sample 80 5 x
// Produces [NonNegativeInt 79; NonNegativeInt 75; NonNegativeInt 0;
//           NonNegativeInt 69; NonNegativeInt 16] which is hard to deal with
let y = Arb.generate<NonNegativeInt> |> Gen.map (fun (NonNegativeInt n) -> n)
Gen.sample 80 5 y
// Much better: [79; 75; 0; 69; 16]

To avoid duplicating code between generators for Quality and Days, I'd write something like the following:
let genNonNegativeOf (f : int -> 'a) = gen {
    let! (NonNegativeInt n) = Arb.generate<NonNegativeInt>
    return (f n)
}
Gen.sample 80 5 (genNonNegativeOf Quality)
// Produces: [Quality 79; Quality 35; Quality 2; Quality 42; Quality 73]
Gen.sample 80 5 (genNonNegativeOf Days)
// Produces: [Days 60; Days 27; Days 50; Days 22; Days 23]

And finally, let's tie that all together in a nice, elegant fashion with a gen { } CE:
let genNonLegendaryItem = gen {
    let! name = genString15 |> Gen.map Name
    let! quality = genNonNegativeOf Quality
    let! shelfLife = genNonNegativeOf Days
    let! style = Gen.elements [Plain; Aged]
    return {
        Name = name
        Quality = quality
        ShelfLife = shelfLife
        Style = style
    }
}
let genLegendaryItem =
    // This is the simplest way to avoid code duplication
    genNonLegendaryItem
    |> Gen.map (fun item -> { item with Style = Legendary })

Then once you've done that, to actually use this in your tests, you'll need to register the generators, as Tarmil mentioned in his answer. I'd probably use single-case DUs here so that the tests are easy to write, like this:
type LegendaryItem = LegendaryItem of Item
type NonLegendaryItem = NonLegendaryItem of Item

Then you'd register the genLegendaryItem and genNonLegendaryItem generators as producing (Non)LegendaryItem types by passing them through a Gen.map. And then your test cases would look like this (I'll use Expecto for my example here):
[<Tests>]
let tests =
    testList "Item expiration" [
        testProperty "Non-legendary items expire after 100 days" <| fun (NonLegendaryItem item) ->
            let itemAfter100Days = item |> repeat 100 decreaseQuality
            itemAfter100Days.Quality = Quality 0
        testProperty "Legendary items never expire" <| fun (LegendaryItem item) ->
            let itemAfter100Days = item |> repeat 100 decreaseQuality
            itemAfter100Days.Quality > Quality 0
    ]

Note that with this approach, you'd basically have to write the shrinkers yourself, whereas using Arb.convert as Tarmil suggested would get you shrinkers "for free". Don't underestimate the value of shrinkers, but if you find you can live without them, I like the nice, clean nature of the gen { } computation expression, and how easy it is to read the resulting code.

A: To always generate valid Quality and ShelfLife, you need to register Arbitrary instances:
type Arbs =
    static member Quality() =
        Arb.Default.NonNegativeInt()
        |> Arb.convert (fun (NonNegativeInt x) -> Quality x) (fun (Quality x) -> NonNegativeInt x)

    static member ShelfLife() =
        Arb.Default.NonNegativeInt()
        |> Arb.convert (fun (NonNegativeInt x) -> ShelfLife x) (fun (ShelfLife x) -> NonNegativeInt x)

Arb.register<Arbs>()

For the actual property you want to check, here's a rewording that will help translate it to FsCheck: IF Style is not Legendary, THEN after 100 days the quality is 0. In code:
let ``Non-legendary item breaks after 100 days`` (item: Item) =
    (item.Style <> Legendary) ==>
        let agedItem = item |> repeat 100 decreaseQuality
        agedItem.Quality = Quality 0

A: After resolving all the issues I had with understanding FsCheck usage (for the moment, I'm sure I'll have more issues in the future), this is the repo with my entire solution.
Obviously, the tests code is in the (I think aptly named) GildedRoseTests folder.
I have used the gen computation expression method, suggested by rmunn above, but a different experiment I did, using Tarmil's Arb method works just as well (and you get shrinking "for free").


text:
Q: How to create number limitations with JOptionPane.showInputDialog(null, ""); So I'm making a game as you can see but i need to make it so that the player cannot use more than 28 stat points.
Can anyone help?
Here is my code.
package fallout.pkg4.game;
import javax.swing.JOptionPane;
public class Fallout4Game
{
public static void main(String[] args)
{
  int pointsint2;

  int pointsint;
  String points;
  String points2;

  int resultint;
  String perc;
  int resultPerc;

  int result3;
  String end;
  int endParsed;

  int result4;
  String chari;
  int chariParsed;

  int result5;
  String inte;
  int inteParsed;

  int result6;
  String agi;
  int agiParsed;

  int result7;
  String luck;
  int luckParsed;

  Boolean error;

  points = JOptionPane.showInputDialog(null, "Welcome to Brandons first game. Please enter 28 to start.");

  JOptionPane.showMessageDialog(null,"You have " + points + " stats points. Choose wisley.....");

  JOptionPane.showMessageDialog(null,"You will be choosing your S.P.E.C.I.A.L. attributes");

  points2 = JOptionPane.showInputDialog(null, "STRENGTH You have " + points + " points.");

  if(JOptionInput <= then )

  pointsint = Integer.parseInt(points);
  pointsint2 = Integer.parseInt(points2);
  resultint = pointsint - pointsint2;

  perc = JOptionPane.showInputDialog(null,"PERCEPTION You have " + resultint + " points left");

  resultPerc = Integer.parseInt(perc);
  result3 = resultint - resultPerc;

  end = JOptionPane.showInputDialog(null,"ENDURENCE You have " + result3 + " points left.");

  endParsed = Integer.parseInt(end);
  result4 = result3 - endParsed;

  chari = JOptionPane.showInputDialog(null,"CHARISMA You have " + result4 + " points left.");

  chariParsed = Integer.parseInt(chari);
  result5 = result4 - chariParsed;

  inte = JOptionPane.showInputDialog(null,"INTELIGENCE You have " + result5 + " points left.");

  inteParsed = Integer.parseInt(inte);
  result6 = result5 - inteParsed;

  agi = JOptionPane.showInputDialog(null,"AGILITY You have " + result6 + " points left");

  agiParsed = Integer.parseInt(agi);
  result7 = agiParsed - result6;

  luck = JOptionPane.showInputDialog(null,"LUCK You have " + result7 + " points left");

  luckParsed = Integer.parseInt(luck);

}

}


text:
Q: Proper Way to Auto Mount NFS/Samba Shares Before Apache Startup at Boot? I'm using an Ubuntu 12.04 (Server) VM as a development web server.  I keep the served files on the VM host, therefore Apache uses NFS mounted directories for DocumentRoot  To keep things as automated, I have Apache set to start on boot.

*

*I have no problem with automounting NFS at boot.

*I have no problem with starting Apache at boot.

The problem: mountall starts after upstart fires up Apache.
After fiddle-farting around with upstart and initctl I came up with a hack that works -- but is certainly not ideal -- nor portable.
/etc/fstab
nfs_server:/    /mnt/nfs_server  nfs4   _netdev,noauto  0   0

/etc/init.d/apache2
The following was inserted at the top beneath the INIT INFO section:
if [ ! -s "/var/www/default/index.php" ]; then
    echo -n "  Mounting NFS and Samba shares...."
    mount nfs_server:/
    result=$?
    if [ 0 -ne $result ]; then
        echo "  ERROR. mount returned $result";
    else
        echo "    [ OK ]";
    fi
fi
...

Otherwise, the script is what was installed originally ( see default file here ).
Notes

*

*I've tried using mountall instead of mounting the NFS share by name.

*

*This results in other error messages (notably, swapon didn't mount my swap partition)

*(however) upon final startup, everything seems fine.

*This VM will be zipped up and given to other developers.  Some may mount using NFS, some may use Samba.

A: One way to solve this is to change the order that these things load by modifying the order the init script calls them.  There may be other (easier) ways to do this, but the bare metal way would be to -

*

*Find the runlevel the server is running on by issuing the command (as root) "runlevel".

*Go to /etc/rcX.d  where X is the runlevel number you are in.

*You will see a whole lot of symlinks in that directory - they will typically be in the
form SxxNAME, where "S" means start, xx is the order - earlier scripts run first - and
name is the name of the script this links to in etc/rc.d.  Rename the apache script to
have a higher number then the nfs script.


text:
Q: Set of cylinder sets is closed under finite intersections Notation: In what follows, $T$ is an arbitrary parameter set and $(X, \mathbb{X})$ is a measurable space. Moreover, the $n$-fold cartesian products of $X$ (resp. $T$) with itself is denoted by $X^{n}$ (resp. $T^{n}$). When $X^{n}$ is considered, the associate $\sigma$-algebra $\mathbb{X}^{n}$ is just the usual product $\sigma$-algebra. Finally, the set of all functions $f: X \to T$ is denoted by $X^{T}$.
Definition: Let $t:=(t_{1},...,t_{n}) \in T^{n}$ and $B \in \mathbb{X}^{n}$. We define a cylinder set with coordinates $t_{1},...,t_{n}$ and basis $B$ by:
$$C_{n}(t, B) := \{f \in X^{T}: f(t) := (f(t_{1}),...,f(t_{n})) \in B\}$$
Moreover, the set of all such cylinder sets is denoted by $\mathcal{A}$. In other words:
$$\mathcal{A} := \{C_{n}(t, B): \hspace{0.1cm} t \in T^{n}, B\in \mathbb{X}^{n}, n \in \mathbb{N}\}$$
I would like to prove that $\mathcal{A}$ is an algebra of subsets of $E^{T}$. It is easy to see that $\emptyset, E^{T}\in \mathcal{A}$.
[$\mathcal{A}$ is closed under complementations] Given $B \in \mathbb{X}^{n}$ and $\tau = (t_{1},...,t_{n})\in T^{n}$, we can see that $C_{n}(\tau, B)^{c} = C_{n}(\tau, B^{c})$. In fact
\begin{align}
    C_{n}(\tau,B)^{c} &= \{f\in X^{T}: \hspace{0.1cm} f(\tau) := (f(t_{1}),...,f(t_{n}))\not\in B\} \\
    &= \{f\in X^{T}: \hspace{0.1cm} f(\tau) := (f(t_{1}),...,f(t_{n}))\in B^{c}\} \\
    &= C_{n}(\tau, B^{c}). \nonumber
\end{align}
Since $B^{c} \in \mathbb{X}^{n}$, it follows that $C_{n}(\tau, B)^{c} = C_{n}(\tau, B^{c}) \in \mathcal{A}$.
My problem is proving $\mathcal{A}$ is closed under finite intersections. Any help is appreciated! Thanks.

A: Observe that if  $\tau=\{t\}$ and $\tau'=\{t'\}$ and $B,B' \in \mathcal{B}(\mathbb{R})$ with $t<t'$,then we have :
$C(\tau,B)\cap C(\tau',B') = C(\{t,t'\},B\times B')\in \mathcal{A}$
and if $t=t'$ then :
$C(\tau,B)\cap C(\tau',B') = C(\tau,B\cap B')\in \mathcal{A}$
From those two observations you can build any intersection of set in $\mathcal{A}$ and observe that they still in $\mathcal{A}$.


text:
Q: $∀m, ∀n, ∃l | (nn)∧(lI have to show if the following proposition is true or false and prove my answer.
$l,m,n$ ∈ {whole numbers} = {$0,1,2,3...$}.
I'm thinking to do a contrapositive on each side. So by putting
the left side $(∀ m, ∀ n, ∃ l | (n < m)) = P$ and right side $((l > n)∧(l < m))$ = Q to show if P⇒Q = ¬Q⇒¬P  and if $¬Q⇒¬P$ is true then $P⇒Q$ is also true.
I'm new to Discrete Math; sorry for my lack of knowledge.
Thanks for your help.

A: This is not true, for if $m,n$ are consecutive numbers there does not exist some $l$ between $m$ and $n$ which is not equal to $m$ or $n$.


text:
Q: Javascript only recognizising inline style and not style set in head I have simple JS function that toggles the DISPLAY of a DIV. The DIV display is set to 'none' by default. If I use an inline style to set the display, it works fine, but if I set the style in the head it only works after I run the function the second time. So it only sees that the display is set to none after the display is set in the function. It doesn't recognize that it is set in the CSS in the head. If I use an inline style, it works fine.
Also, if I change my conditional statement from:
if (OBJ.style.display == 'none')

to
if (OBJ.style.display = 'none')

A: Use window.getCurrentStyle or element.currentStyle in order to obtain style from the head or body. They're supported by different browsers so here's a cross-browser example:
function getStyle( elem, style ) {
  var a = window.getComputedStyle,
      b = elem.currentStyle;

  if ( a ) return a( elem ).getPropertyValue( style );
  else if ( b ) return b[ style ];
}

getStyle( document.getElementById('OBJ'), 'display' )

A: The style property of an element only contains the inline style, not inherited styles or styles from a style sheet.
You can use the offsetHeight property to check if the element has any size, as it is zero when the element is not visible.
if (OBJ.offsetHeight == 0) ...

A: Another suggestion is to use css classes:
css:
.hide{
 display:none;
}

html:

hello world

<button onclick="toggle();">toggle</button>

js:
function toggle(){
    var obj = document.getElementById('mydiv');
    if(obj.className == 'hide')
        obj.className = '';
    else
        obj.className = 'hide'
}

http://jsfiddle.net/XBhMA/1/
Note this will only work if the element contains only one class. If it contains more, you will need to modify.


text:
Q: Ubuntu wont detect my second monitor anymore Is there a way to restart it to its default settings? i've tried everything else

sudo dpkg-reconfigure xserver-xorg

does not work

A: If you are using the default opensource drivers or ati/nvidia drivers then one quick way to reset is simply to move to one-side xorg.conf and then reboot i.e.
sudo mv /etc/X11/xorg.conf /etc/X11/xorg.conf.backup

You rarely need to sudo dpkg-reconfigure xserver-xorg for the latest versions of Ubuntu.
ATI Graphics
If you have been playing with ATI graphics installs then deactivate the driver from the Additional Drivers window and then reactivate to reinstall.
Additionally run the aticonfig routine to generate a new xorg.conf
aticonfig --initial -f

NVIDIA
If you have been playing with NVIDIA graphics installs then deactivate the driver from the Additional Drivers window and then reactivate to reinstall.
You can also remove all references to nvidia kernels install via
sudo apt-get remove nvidia*

Then reinstall the driver from Additional Drivers window.
Additionally run the Nvidia routine to generate a new xorg.conf
gksudo nvidia-settings

A: Check your cables.
I know this is kind of a off-topic answer, but I spent hours blaming linux for the problem, upgrading and downgrading kernels, nvidia drivers, resetting X.
Turns out the years of linux being terrible with multi-monitor support has coloured my expectations, and once in awhile, a cable just stops working that reliably.


text:
Q: Pushing MailGun webhook onto AWS SQS I need to process MailGun webhooks. I did implement a solution directly on our web servers to process the webhooks, but MailGun generates so many calls from a large campaign that it effectively becomes a DOS attack.
One solution I've been looking at is using AWS API Gateway to a Lambda function to then push onto an SQS queue. We can then poll the queue at a rate we can manage. Unfortunately we can't get this to work as AWS API Gateway does not support multipart/form-data content types (which some of the webhooks are). This means that our SQS messages are not well formatted / structured. The best we can do is use the $util.escapeJavaScript($input.body) function in the mapping template to create an SQS message that contains the raw string of the webhook content (with escaped javascript chars) that is effectively unparsable i.e. we can't get data out of it.
I've had a go at using Zapier to process the webhook and push directly on the SQS queue. This can parse the various content types effectively and create a nicely structured message for us, but the cost of the service is not viable.
Has anybody managed this problem in another way? Are there solutions to API Gateway not parsing the content properly? I've deliberately stayed away from MailGuns event polling API as it involves significant delays before the polled data can be 'trusted' (according to MailGun).
Basically, is there another way of getting a nicely parsed message from content types multipart/form-data and application/x-www-form-urlencoded onto the queue?
Any ideas would be much appreciated!
To add, this link higlights issues with APS Gateway and multipart\form-data content:
API Gateway - Post multipart\form-data

A: As you've mentioned you can base64 encode in api gateway and call base64decode in the lambda function to retrieve the original payload (There are standard libraries in every language).
Also, note you can that you can use multipart form data for non file bodies.
Get non file body from multipart/form-data using AWS API Gateway and Lambda

A: I had the same challenge when building Suet. I ended up switching to Google Cloud functions which I really recommend. Don't waste time on Amazon API Gateway. Use Google Cloud Functions and use a middleware like multer. (You can see the source of Suet's webhook handler here).

A: Not sure if you ever came to a solution, but I have this working with the following settings.

*

*Setup your API Gateway method to use "Use Lambda Proxy integration"

*In your lambda (I use node.js) use busboy to work through the multi-part submission from the mailgun webhook. (use this post for help with busboy Busboy help)

*Make sure that any code you are going to execute after all busboy is complete is executed in the 'finish' portion of the busboy code.


text:
Q: In perforce, how to remove a symlink to a directory and add files in the same directory? This can be done like this:
1. p4 delete dir,
   p4 submit;
2. p4 add dir/file,
   p4 submit;
Is there a way to do this in one go?
I don't want to do p4 submit in step 1 because not having that directory will break things at my end.

A: There does not seem to be anything preventing this:
C:\Perforce\test\dir>p4 opened
//stream/main/dir#1 - delete default change (symlink)
//stream/main/dir/bar#1 - add default change (text)
//stream/main/dir/foo#1 - add default change (text)

C:\Perforce\test\dir>p4 submit -d "presto"
Submitting change 106.
Locking 3 files ...
delete //stream/main/dir#2
add //stream/main/dir/bar#1
add //stream/main/dir/foo#1
Change 106 submitted.


text:
Q: Python access to Parent Directory I have a file in the directory
app
   a
     Ulil.py
   b
     main.py

I want to import Ulil.py (at app\a) into main.py (at app\b).
How do i go about doing this. I need to move the file around as well so I don't want to put the entire path. I just to be in app\b and access only app\a. Folder name stays the same.

A: First, create an empty file called __init__.py in a
Second,  in main.py in b import it using
import sys
sys.path.insert( 0, '../' )
from a.Util import *

A: You can add the directory to sys.path:
import sys
sys.path.insert( 0, '../a' )
import Util


text:
Q: How to configure ssl in mongodb? I have followed document to configure ssl in mongodb. But no luck.The mongod service doesnot start after configuring ssl in mongo.conf.
I have gone through and looks like i need to use Scon first to support SSL/TLS.
Can anyone please share steps or document, I need to follow first .
I am using mongo version 2.6

A: This wiki should cover everything you need to build from source using scons.  Ensure you have the correct ssl package installed as mentioned in the System Specific Requirements.  Your scons command will look
scons mongod --ssl

If you are able to upgrade to mongodb 3.0+ from 2.6 most distributions include ssl support.


text:
Q: Find $\int\frac{(1+x^2)dx}{1-2x^2\cos\alpha+x^4}$ ,where $\alpha\in(0,\pi)$ $\int\frac{(1+x^2)dx}{1-2x^2\cos\alpha+x^4}$ ,where $\alpha\in(0,\pi)$

Let $I=\int\frac{(1+x^2)dx}{1-2x^2\cos\alpha+x^4}$
$I=\int\frac{(1+x^2)dx}{\sin^2\alpha+(x^2-\cos\alpha)^2}$
But there seems no way to solve it further.So tried another method.
 $I=\int\frac{(1+x^2)dx}{1-2x^2\cos\alpha+x^4}$
Put $\cos\alpha=1-2\sin^2(\frac{\alpha}{2})$
$I=\int\frac{(1+x^2)dx}{1-2x^2(1-2\sin^2(\frac{\alpha}{2}))+x^4}$
$I=\int\frac{(1+x^2)dx}{1-2x^2+4\sin^2(\frac{\alpha}{2})x^2+x^4}$
$I=\int\frac{(1+x^2)dx}{(1-x^2)^2+4x^2\sin^2(\frac{\alpha}{2})}$
But i could not solve it further.

A: HINT:
$$I=\int\dfrac{1+x^2}{1-2x^2\cos\alpha+x^4}dx=\int\dfrac{1/x^2+1}{1/x^2-2\cos\alpha+x^2}$$
As $\displaystyle\int\left(\dfrac1{x^2}+1\right)dx=x-\dfrac1x,$ set $x-\dfrac1x=y$
$$I=\int\dfrac{1/x^2+1}{(x-1/x)^2+2-2\cos\alpha}$$
$$=\int\dfrac{dy}{y^2+\left(2\sin\dfrac\alpha2\right)^2}$$
Now as $\alpha\in(0,\pi), \sin\dfrac\alpha2>0$


text:
Q: Lost minionpro font after migrating from latex 2014 to latex 2017 I have osx el capitan 10.11.6, and I recently updated from latex 2014 to latex 2017. I found that my  minionpro font in stalled under 2014 do not compile anymore. I remember that getting this font was pretty tough to do the last time. If there an easy way to migrate the installed font so that it can work with 2017 now, or do I need to reinstall it from scratch by downloading the font and installing it? Otherwise, it is possible to point my TexShop (that is what I use to compile) to the 2014 release of latex with the idea that it will be able to compile the minionpro font successfully from there?

A: I can tell you how they're organised on my MiKTeX system:

*

*.enc files are in texmf-local/fonts/enc/dvips/MinionPro/,

*MinionPro.map is in texmf-local/fonts/map/dvips/MinionPro/,

*.otf files are in texmf-local/fonts/adobe/MinionPro/,

*.tfm files are in texmf-local/fonts/adobe/MinionPro/,

*.pfb files are in texmf-local/fonts/type1/adobe/MinionPro/,

*.vf files are in texmf-local/fonts/vf/adobe/MinionPro/,

*.fd and .sty files are in texmf-local/tex/latex/MinionPro/.

I hope this helps.


text:
Q: jQuery - Event that captures creation of dynamically created text boxes Does jQuery have an event that will capture the creation of dynamically created DOM content? Or is there some way of doing this in jQuery?
The web page in which I am injecting jQuery into creates text boxes dynamically. I have no control over that. I would however like to check every 3 seconds whether a new text box has been created and then populate it with a value.
The text boxes look like the following:
<input id="AplEducationTbl:EstName:0" type="text" onchange="return false">
<input id="AplEducationTbl:EstName:1" type="text" onchange="return false">

So there are a couple of problems. The id uses a colon, which I don't know how to escape in jQuery. The onchange returns false, which prevents me from hooking on my events.
Using:
 setTimeout(function(){
      /* What do I put here? */
  }, 3000);

A: Can you use event delegation and search for IDs starting with AplEducationTbl:EstName?
$(document).on("change", "input[id^=AplEducationTbl\\:EstName]", function() {
    console.log("Change");
});

jsFiddle

A: I would however like to check every 3 seconds whether a new text box has been created
To this you have to use setInterval() method instead:
var len = $('input[id^="AplEducationTbl:EstName"]').length;
setInterval(function () {
   if ($('input[id^="AplEducationTbl:EstName"]').length > len) {
      console.log('changed.');
      len = $('input[id^="AplEducationTbl:EstName"]').length;
   }  //^^^^----------------------------------------update the value of len
}, 3000);

The id uses a colon, which I don't know how to escape in jQuery.
For this either you can use two forward slashes \\ as suggested by other answer and other way to use a string representation put that id value in quotes like this:
$('input[id^="AplEducationTbl:EstName"]')
//-----------^-----------------------^------put the value in quotes like this
//------------------------------------------and you are good to go.


text:
Q: Select and Update Using the select statement result in temp table stored procedure ALTER PROCEDURE sp_updateInward
    (@bl_num VARCHAR(30),
     @cg_type VARCHAR(10))
AS
    CREATE TABLE #temp_select
    (
        qty int,
        wght decimal(8,2),
        vol decimal(8,2)
    )

    INSERT INTO #temp_select
        SELECT
            CASE
               WHEN @cg_type = 'BB'
                  THEN SUM(ISNULL(CAST(t1.qty AS FLOAT), 0))
               ELSE 1
            END AS qty,
            SUM(ISNULL(CAST(t1.wght AS FLOAT), 0)) AS wght,
            SUM(ISNULL(CAST (t1.vol AS FLOAT), 0)) AS vol
        FROM
            godown_storage t1
        INNER JOIN
            ccosbl t2 ON t2.id = t1.blso_id
        WHERE
            t2.bl_num = @bl_num

    UPDATE ccosblitem
    SET qty = #temp_select.quantity,
        wght = #temp_select.weight,
        vol = #temp_select.volume
    FROM ccosblitem t3
    INNER JOIN ccosbl t4 ON t4.id = t3.master_id
    WHERE t4.bl_num = @bl_num

    SELECT * FROM ccosblitem

I need to update the ccosblitem from the select statement. I do it in stored procedure and create a temp table. I tried using the declare variable but it prompt error saying that 'AS' is incorrect.

A: Replace
from:
  ALTER PROCEDURE sp_updateInward
(
    @bl_num VARCHAR(30),
    @cg_type VARCHAR(10)
)
AS

To:
ALTER PROCEDURE sp_updateInward @bl_num VARCHAR(30),@cg_type VARCHAR(10)
AS

begin
//your action here
end

A: Your update statement need changes. You are using temp table columns in SET clause without using the temp table in FROM clause. Also for joining purpose you need to have ID column in temp table and need to populate the same column in insert statement. Below are the changes to your code.
CREATE TABLE #temp_select
    (
        id int,
        qty int,
        wght decimal(8,2),
        vol decimal(8,2)
    )

SELECT T1.ID, case....

UPDATE ccosblitem
    SET qty = #temp_select.quantity,
        wght = #temp_select.weight,
        vol = #temp_select.volume
    FROM ccosblitem t3
    INNER JOIN #temp_select t4 ON t4.id = t3.master_id


text:
Q: Does $\frac{1}{2}\prod_{n=1}^\infty\frac{\operatorname{prime}(n)-1}{\operatorname{prime}(n)}$ converges? I have this series, and I would like to know if it converges and, if so, for what value.
$$\frac{1}{2}\prod_{n=1}^\infty\frac{\operatorname{prime}(n)-1}{\operatorname{prime}(n)}$$
Looking at the plot, it seems to converge:
WolframAlpha result

Also, considering the values for big n goes close to 1, the series value would converge. What makes sense, considering the small difference that removing 1 should do proportionally in a big number.
$$\frac{\operatorname{prime}(4100000000)-1}{\operatorname{prime}(4100000000)} \approxeq 1 $$
I try to calculate by hand using this recursive function:
$$f(0) = \frac{1}{2}; \qquad f(n) = f(n-1) \cdot \frac{\operatorname{prime}(n)-1}{\operatorname{prime}(n)} $$
I am getting a stable partial result: $f(50000000) \approxeq 0.02711 4$
A similar series, $\frac{1}{2}\prod_{n=2}^\infty\frac{n!-1}{n!} \approxeq 0.1976695 $.

A: This is the same as
$$ \prod_n \Big( 1 - \frac{1}{p_n} \Big),$$
where $p_n$ is the $n$th prime. This would typically be written as
$$ \prod_p \Big(1 - \frac{1}{p} \Big).$$
This actually has a name! If you recall the Riemann zeta function, we have
$$ \zeta(s) = \sum_{n \geq 1} \frac{1}{n^s} = \prod_p \Big( 1 - \frac{1}{p^s} \Big)^{-1},$$
and so your product is $1/\zeta(1) = 0$.
More generally, the convergence of infinite products is closely related to the convergence of infinite sums. See Proving a result in infinite products: $\prod (1+a_n)$ converges (to a non zero element) iff the series $\sum a_n$ converges. Since it is known that
$$ \sum_{p \leq X} \frac{1}{p} \approx \log \log X, $$
the infinite sum diverges very very slowly to $\infty$, and so the product goes to $0$ very very slowly also. (See also Why do we say some infinite products "diverge" when the limit is zero, a finite value? for a confusing terminology).


text:
Q: using SSL on Nginx or Jenkins? I have Jenkins running on Nginx on a virtual machine. I need to secure trafic, should I apply SSL on Nginx or Jenkins.
(Jenkins is the only service running on that machine).

A: i prefer u apply SSL on Nginx to secure the server


text: Q: get final price for different configurable product to be sent in GA I have a 3 different configurable products on the page. example p1 = $100, p2 = $100 p3 = $100 also but since it is discounted it became but when I get $specialPrice = $product->getPriceInfo()->getPrice('special_price')->getValue(); the result will give me $90 for all of them, is there any way to get the respective amount in each product?


text:
Q: json.dumps serialized query set into unusable format in Django with WebSockets (Channels) I read everything I could found about serializing QuerySets in Django but still can not find any working solution for transferring the existing WSGI function into a ASGI WebSocket Consumer.
My view function looked like this:
    ...
    context = {
        "registered": user_is_player,
        "object": game,
        "player": player,
        "players": game.player_set.all(),
        "players_cards": players_cards,
        "card_deck": game.globalcarddeck_set.all(),
        "prio_deck": game.prioritydeck_set.all(),
        "table": game.table_set.all(),
        "cards": game.card_set.all(),
    }
    return render(request=request, template_name=template_name, context=context)

and was working fine, but the query results sadly seam not to be transferable via synchronous web socket.
Within my class GameConsumer(WebsocketConsumer) I figured that I can
transfer a single result with with model_to_dict (after sadly loosing a few fields) but same does not apply to QuerySets. Those can be only serialized with the serialize function like: serialize("json", game_instance.player_set.all()).
...
game_instance = Game.objects.get(slug=self.game_name)
game_json = model_to_dict(
game_instance, fields=["name", "slug", "round_number", "active", "started"]
)
context = {
    "registered": user_is_player,
    "game": game_json,
    "player": player,
    "message": message,
    "players": serialize("json", game_instance.player_set.all()),
    "players_cards": serialize("json", players_cards),
    "card_deck": serialize("json", game_instance.globalcarddeck_set.all()),
    "prio_deck": serialize("json", game_instance.prioritydeck_set.all()),
    "table": serialize("json", game_instance.table_set.all()),
    "cards": serialize("json", game_instance.card_set.all()),
}
self.send(text_data=json.dumps({"context": context}))

At the end everything needs to be dumped with json.dumps, otherwise one would end up with the exception:
self.sendMessage(content.encode("utf8"), binary)
AttributeError: 'dict' object has no attribute 'encode'

This seam to be the only way to get the context serialized over the socket, but the end result makes me cry:
{"context":{"registered":true,"game":{"name":"third","slug":"third","round_number":0,"active":true,"started":true},"player":{"id":17,"cardholder_ptr":17,"game":3,"name":"Maciek","dam":0,"idm":0,"round_score":0,"game_score":0},"message":null,"players":"{\"model\": \"suena1M.player\",\"pk\": 17,\"fields\": {\"game\": 3,\"name\": \"Maciek\",\"dam\": 0,\"idm\": 0,\"round_score\": 0,\"game_score\": 0}}\n{\"model\": \"suena1M.player\",\"pk\": 19,\"fields\": {\"game\": 3,\"name\": \"Peter\",\"dam\": 0,\"idm\": 0,\"round_score\": 0,\"game_score\": 0}}\n{\"model\": \"suena1M.player\",\"pk\": 21,\"fields\": {\"game\": 3,\"name\": \"Petra\",\"dam\": 0,\"idm\": 0,\"round_score\": 0,\"game_score\": 0}}\n","players_cards":"[]","card_deck":"[{\"model\": \"suena1M.globalcarddeck\", \"pk\": 23, \"fields\": {\"game\": 3}}, {\"model\": \"suena1M.globalcarddeck\", \"pk\": 26, \"fields\": {\"game\": 3}}, {\"model\": \"suena1M.globalcarddeck\", \"pk\": 29, \"fields\": {\"game\": 3}}, {\"model\": \"suena1M.globalcarddeck\", \"pk\": 32, \"fields\": {\"game\": 3}}, {\"model\": \"suena1M.globalcarddeck\", \"pk\": 35, \"fields\": {\"game\": 3}}, {\"model\": \"suena1M.globalcarddeck\", \"pk\": 38, \"fields\": {\"game\": 3}}, {\"model\": \"suena1M.globalcarddeck\", \"pk\": 41, \"fields\": {\"game\": 3}}, {\"model\": \"suena1M.globalcarddeck\", \"pk\": 44, \"fields\": {\"game\": 3}},

Basically everything, what has been serialized with serialized is not usable from within the template because of the escaping hell.
Please, I'm new to Django and Django Channels, maybe there is a batter way to pass ORM Results over the sockets - but for now, I'm out of ideas.
UPDATE
I am using the following serializers:
from django.forms.models import model_to_dict
from django.core.serializers import serialize

and the build in json.dumps method

A: WebsocketConsumer.send() accepts either text_data or bytes_data. You cannot pass QuerySet into .send() as it only accepts strings. so you need to serialize your data into json and parse it on the client side.
Also, the escaping is because your are double encoding some of your data; once with .serialize() method, then with json.dumps().
I suggest using Django Rest Framework's Serializers. This way you choose which fields you want to serialize. Please refer to this link: https://www.django-rest-framework.org/api-guide/serializers/

A: Yeay - once I have adopted @Smil23 solution as following:
declared a ModelSerializer like this:
class PlayerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Player
        fields = "__all__"

and replaced calls like
"players": serialize("json", game_instance.player_set.all()),

by
"players": PlayerSerializer(game_instance.player_set.all(), many=True).data,

I finally got correctly looking data transferred to the page via the socket :)
Thx!


text:
Q: Data type for storing hour interval Is there a specific data type that allows you to store data for which hour interval an event has occurred (for example "15.00-15.59", "16.00-16.59" etc)?
If there isn't, what is the best way to store this data?

A: Yes there is:
https://dev.mysql.com/doc/refman/5.7/en/time.html
So you would need two fields.. time_start and time_end to reflect your case.

A: Postgre SQL Range Types (Link) fits better in your problem, because it uses a single field to save the time interval.
It has many operators to check overlapping and etc. In addition, using Canonicalization Functions you can convert -discrete data- from interval (range) to its Canonical Form.


text:
Q: Why button click event is not triggering? I am adding a button with every list item here.
$(".show").click(function(){
    var list="";

    for(var i=0;i<contacts.length;i++)
    {
       list=list+"
"
       +"Name: "+contacts[i][0].value+" "+contacts[i][1].value+"
"
       +"Phn: "+contacts[i][2].value+"
"
       +"Address: "+contacts[i][3].value+"
"
       +"<button>Delete</button>"
       +"
";

    }
    $(".contactsList").append(list);

});

triggering this button here,
$("button").click(function(){

        console.log(78);
        $(this).parent().remove();

    }
);

But the click function is not calling?


text:
Q: What is devmode for snaps? I have heard about the ability to use snaps in developer mode.
What is this mode and what can I use it for?

A: Developer mode, or devmode in short, enables developers and users to install snaps without enforcing security policies. E.g.
sudo snap install notes --devmode

When installed this way, snaps behave in a similar way to traditional .deb packages in terms of accessing system resources. That is, snaps have access to the system without being restricted by app isolation and interfaces.
Developer mode is useful when:

*

*Testing a snap in the first stages of development to ensure it runs as expected

*Temporarily bypassing security enforcement if there is not yet an interface available that controls a particular system access required by the snap

As a developer, you can also relax security requirements at the snapcraft.yaml level by declaring devmode confinement instead of strict
confinement: devmode

You'll be then flagging users that this app specifically needs to be installed with --devmode to work. Not specifying the switch will result in failure to install.
That is, users will have to specifically acknowledge that they will install your snap in developer mode.


text:
Q: Is there a Rack middleware for using sessions without cookies? The provided session management middleware that comes with Rack are all based on cookies for identifying the user. Since I'm developing an api, I would rather pass the session-id explicitly as a query string parameter. Looking at the code base, it doesn't seem that this use case was taken into consideration, as all the session middlewares extend from a common class, that reads/writes to cookies.
So my question is - Is there a project that maintains an alternative Rack middleware or a monkey patch for racks built-in middleware's, that will allow me to maintain the session-id over the query string, rather than a cookie store?

A: Rack can use custom session ID items instead of cookies:
require 'rack/session/abstract/id'

The Rack documentation may be a helpful place to start your search. I believe you're looking for the "skip" option (or "defer" option).
Docs:
ID sets up a basic framework for implementing an id based sessioning
service. Cookies sent to the client for maintaining sessions will only
contain an id reference. Only #get_session and #set_session are
required to be overwritten.
All parameters are optional.

*

*:key determines the name of the cookie, by default it is
'rack.session'

*:path, :domain, :expire_after, :secure, and :httponly set the related
cookie options as by Rack::Response#add_cookie

*:skip will not a set a cookie in the response nor update the session state

*:defer will not set a cookie in the response but still update the session
state if it is used with a backend

*:renew (implementation dependent) will prompt the generation of a new
session id, and migration of data to be referenced at the new id. If
:defer is set, it will be overridden and the cookie will be set.

*:sidbits sets the number of bits in length that a generated session
id will be.

These options can be set on a per request basis, at the location of
env['rack.session.options']. Additionally the id of the session can be
found within the options hash at the key :id. It is highly not
recommended to change its value.
Is Rack::Utils::Context compatible.
Not included by default; you must require 'rack/session/abstract/id' to use.
Source:
  class ID
    DEFAULT_OPTIONS = {
      :key =>           'rack.session',
      :path =>          '/',
      :domain =>        nil,
      :expire_after =>  nil,
      :secure =>        false,
      :httponly =>      true,
      :defer =>         false,
      :renew =>         false,
      :sidbits =>       128,
      :cookie_only =>   true,
      :secure_random => (::SecureRandom rescue false)
    }

I hope this gives you a lead... when you learn more, can you share your results here?
Edit:
The magic trick is to combine options :cookie_only => false with :defer => true. Of course, the standard Rack::Session::Cookie doesn't make much sense here, so you could do:
use Rack::Session::Pool, :cookie_only => false, :defer => true

Interestingly you can alter the options in run time. In my use case, I actually need to support a traditional cookie-based mechanism alongside the explicit parameter-passing style, so I have done the following:
class WebApp < Sinatra::Base

  configure do
    use Rack::Session::Pool, :key => 'session_id'
  end

  before do
    # Switch to parameter based session management if the client is an ios device
    if env['HTTP_USER_AGENT'] =~ /iOS/
      session.options[:cookie_only] = false
      session.options[:defer] = true
    end
  end

  get '/' do
    session[:user_id] ||= nil # This triggers a session-write, giving us a valid session-id
    body "session_id=#{session.id}"
  end
end

A: If you want to eliminate usage of cookies in your API application, but still want to manage sessions. For instance, in my case session identifier came from token.
You need to redefine method extract_session_id to extract you session identifier from received token. This method have to be redefined on your session store class, because Rack::Session::Abstract::ID provides default implementation, based on cookies.
It is called from Rack::Session::Abstract::ID#current_session_id method which calls #id method on session object, usually represented by Rack::Session::Abstract::SessionHash instance. And inside this SessionHash#id method #extract_session_id from your session store finally called.
I suppose it would be simpler to have session identifier extractor configured independently, but desire to store session identifiers in cookies along with session data lead to that tricked design.
As well it is a bit weird to see cookie interaction in Rack::Session::Abstract::ID class in method #commit_session and #set_cookie.
So to be completely sure that no cookie will be set you could redefine #set_cookie method on your store as well. The same goal probably can be achived by setting cookie_only: false, defer: true for your session storage middleware, as mentioned in one of the answer here, but I have not checked this.
Definitely you need to modify your middleware stack to exclude all middlewares which interact with cookies and likely browser specific. On default middleware stack of rails it can be look like this:
# config/application.rb
[
  Rack::MethodOverride, # browser specific
  ActionDispatch::Cookies,
  ActionDispatch::Flash
].each do |middleware|
  config.middleware.delete(middleware)
end

As well you definitely need to replace session store to something which store information on server side, like redis, for example:
# config/initializers/session_store.rb
Rails.application.config.session_store ::Custom::Session::TokenRedisStore

In my case, ::Custom::Session::TokenRedisStore inherits ::RedisSessionStore and redefined all methods mentioned above.
::RedisSessionStore contained in redis-session-store gem. So, obviously you need to add it to you Gemfile if you going to use it.
I do that for Rails 4.2.x, but same approach can be adopbed to any framework as Rack everywhere the same.