text:
Q: Is it possible to offer different shipping methods to customers in different locations We ship perishable goods and currently get exact price quotes from UPS and USPS and allow the customer to choose their shipping method  (ground, 2nd day, etc.).  During the summer months we have to restrict the available shipping methods to 2nd Day air or better to ensure our goods are in good shape when they arrive.
  We would like to be able to offer ground shipping to the people who live nearby, while still only offering 2nd day or better to people who live further away.  We still want to use the exact price quotes so I'm pretty sure table rates won't work, and I haven't been able to figure out another way.
Thanks

A: @Tyler have you check this free extension? http://webshopapps.com/ca/matrixrate-shipping-extension.html
In some of my project with the free module option was enough.
Best,
ALe.


text:
Q: How do I configure a Contour heatmap to display colors for small overall data? Is there any way to configure a heatmap to have lower thresholds for high-density colors?
Example: I don't have too many data points for each geographic location, so as a result they're not showing up at all or are showing up in a very light color.

A: I haven't found a cleaner way of doing this but:

*

*Create a new column where the value is always 100. This can be done by using the Column Editor to make a column of all 1s via 1[some numeric variable]/[some numeric variable]1, then another new column equal to that column * 100

*Heatmap on the sum of that column rather than on the count of
the rows.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I convert a 32-bit binary string to float in ruby I'm receiving a binary string which represents a group of 32-bit floats.  It is reported from series of pairs of 16-bit MODBUS registers whereby the first register represents the lower bits and the second register represents the higher bits.  I am able to, in a horrifically ugly manner, rearrange the registers then decode to a float.  I'd like this to be quite a bit more attractive, but I'm failing at the task.  Essentially, I'm unpacking the string to a hex string array, converting to string, slicing the high bits and putting them in front of the low bits, then converting it to integer base 16, packing it to a 32 bit integer, unpacking to a float, then selecting the first value in the array.  If you'll excuse me, that last sentence makes me need to weep.  Without further ado:
def read_dual_input_registers(addr, npairs)
  @values = Array.new
  result = <binary-string-returned-here>.unpack('H*').to_s

  npairs.to_i.times do
    register = result.slice!(4..7) + result.slice!(0..3)
    @values.push([register.to_i(16)].pack('L').unpack('F')[0])
  end
  @values
end

A: Does this work?
t = <binary-string-returned-here>
result = (t[2..3] + t[0..1]).unpack('F')[0]


text:
Q: Converting a cURL request to an Axios Post I am working with the prometheus pushgateway library and am having trouble sending information to it. The examples use cURL which work well, but when I try to do the equivalent with AXIOS in my node program it throws an error.
I tried setting up an express server to send the same request to. I wanted to analyze the (REQ) and see how it was displayed. It was mangled by body parser and I am kind of lost.
  cat <<EOF | curl --data-binary @- http://pushgateway.example.org:9091/metrics/job/some_job/instance/some_instance
  # TYPE some_metric counter
  some_metric{label="val1"} 42
  # TYPE another_metric gauge
  # HELP another_metric Just an example.
  another_metric 2398.283
  EOF

I have tried a few different things in axios, none of which have worked
- https://github.com/axios/axios#using-applicationx-www-form-urlencoded-format

A:        request({
            url: 'http://localhost:9091/metrics/job/interface_data',
            method: 'POST',
            body: 'datahere 10\n',
            encoding: null
        }, (error, response, body) => {
            if (error) {
                console.log(error)
            } else {
                console.log(response)
                console.log('response, ', response.body)
            }
        })

Worked for me. The trick was encoding: null


text:
Q: Read shapefiles from many folders I have shapefiles spread over many folders and I'd like to pull them out and run a script to process each one in the same way. All the .shp files have the same name and I need to folder name to come along as an id (haven't attempted that part yet). I am stuck on the first step, but I feel like I am close.
# Read folder names to get list of folders

    folders <- list.dirs(path = "./locs", full.names = TRUE, recursive = TRUE)

# Make function that reads inside a folder same way for all files

    all_files <- function(folder) {
    readOGR(dsn = folder, layer = "SAMENAME.shp", verbose = FALSE)
}

# Map the function to each folder listed in "folders".

    try <- map(folders, all_files)

Sorry I don't have a reprex for this, maybe I can build one tomorrow if I can get some traction here.

A: I think you are pretty close.  I think you just need three fixes 1) use a paste0() function to combine the folder name and the shapefile name in the "dsn" argument, 2) add a return() call in your all_files() function and 3) switch from map() to either do.call() or lapply().  Try tweaking your code like this:
# Read folder names to get list of folders

    folders <- list.dirs(path = "./locs", full.names = TRUE, recursive = TRUE)

# Make function that reads inside a folder same way for all files

    all_files <- function(folder) {
    out<-readOGR(dsn = paste0(folder, "SAMENAME.shp", sep+"/), layer = "SAMENAME.shp", verbose = FALSE)
    return(out)
}

# Map the function to each folder listed in "folders".

    try <- lapply(folders, all_files) #lapply() approach
    try2 <- do.call(all_files, folders) #do.call() approach

If that doesn't work, you could consider reading in the shapefiles using the sf::read_st() function


text:
Q: What is error In this Java Inventory Management System Code? private void cmbProductItemStateChanged(java.awt.event.ItemEvent evt) {
    if (cmbProduct.getSelectedIndex() > 0) {
        Connection con = null;
        CallableStatement cstmt = null;
        ResultSet rs = null;
        try {
            con = DatabaseHelper.getConnection();
            cstmt = con.prepareCall("{?=call getProductQty(?)}");
            cstmt.registerOutParameter(1, java.sql.Types.INTEGER);
            cstmt.setString(2, cmbProduct.getSelectedItem().toString());
            cstmt.execute();
            int output = cstmt.getInt(1);
            lblQty.setText(String.valueOf(output));
            cstmt = con.prepareCall("{call avg_price(getProductId(?)}");
            cstmt.setString(1, cmbProduct.getSelectedItem().toString());
            cstmt.execute();
            rs = cstmt.getResultSet();
            while (rs.next()) {
                lblPrice.setText(rs.getString(1));

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                con.close();
                cstmt.close();
                rs.close();
            } catch (SQLException ex) {
                ex.printStackTrace();

            }

        }
    }
}

I am making a Java Inventory Management System. Currently I am in the data fetching process from the database. I have written code in the cmbProductItemStateChanged event of ComboBox. There is no syntax error.
getProductQty and getProductId are a function. avg_price is a procedure.
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1053)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4120)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4052)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2503)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2664)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2794)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155)
at com.mysql.jdbc.PreparedStatement.execute(PreparedStatement.java:1379)
at com.mysql.jdbc.CallableStatement.execute(CallableStatement.java:920)
at IMS.Inventory.cmbProductItemStateChanged(Inventory.java:242)
at IMS.Inventory.access$000(Inventory.java:19)
at IMS.Inventory$1.itemStateChanged(Inventory.java:75)
at javax.swing.JComboBox.fireItemStateChanged(JComboBox.java:1223)
at javax.swing.JComboBox.selectedItemChanged(JComboBox.java:1271)
at javax.swing.JComboBox.contentsChanged(JComboBox.java:1330)
at javax.swing.AbstractListModel.fireContentsChanged(AbstractListModel.java:118)
at javax.swing.DefaultComboBoxModel.setSelectedItem(DefaultComboBoxModel.java:93)
at javax.swing.JComboBox.setSelectedItem(JComboBox.java:576)
at javax.swing.JComboBox.setSelectedIndex(JComboBox.java:622)
at javax.swing.plaf.basic.BasicComboPopup$Handler.mouseReleased(BasicComboPopup.java:852)
at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:290)
at java.awt.Component.processMouseEvent(Component.java:6533)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at javax.swing.plaf.basic.BasicComboPopup$1.processMouseEvent(BasicComboPopup.java:501)
at java.awt.Component.processEvent(Component.java:6298)
at java.awt.Container.processEvent(Container.java:2236)
at java.awt.Component.dispatchEventImpl(Component.java:4889)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
at java.awt.Container.dispatchEventImpl(Container.java:2280)
at java.awt.Window.dispatchEventImpl(Window.java:2746)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at IMS.Inventory.cmbProductItemStateChanged(Inventory.java:254)
at IMS.Inventory.access$000(Inventory.java:19)
at IMS.Inventory$1.itemStateChanged(Inventory.java:75)
at javax.swing.JComboBox.fireItemStateChanged(JComboBox.java:1223)
at javax.swing.JComboBox.selectedItemChanged(JComboBox.java:1271)
at javax.swing.JComboBox.contentsChanged(JComboBox.java:1330)
at javax.swing.AbstractListModel.fireContentsChanged(AbstractListModel.java:118)
at javax.swing.DefaultComboBoxModel.setSelectedItem(DefaultComboBoxModel.java:93)
at javax.swing.JComboBox.setSelectedItem(JComboBox.java:576)
at javax.swing.JComboBox.setSelectedIndex(JComboBox.java:622)
at javax.swing.plaf.basic.BasicComboPopup$Handler.mouseReleased(BasicComboPopup.java:852)
at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:290)
at java.awt.Component.processMouseEvent(Component.java:6533)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at javax.swing.plaf.basic.BasicComboPopup$1.processMouseEvent(BasicComboPopup.java:501)
at java.awt.Component.processEvent(Component.java:6298)
at java.awt.Container.processEvent(Container.java:2236)
at java.awt.Component.dispatchEventImpl(Component.java:4889)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
at java.awt.Container.dispatchEventImpl(Container.java:2280)
at java.awt.Window.dispatchEventImpl(Window.java:2746)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

A: There is a closing parenthesis missing:
cstmt = con.prepareCall("{call avg_price(getProductId(?))}");
                                                        ^ (added)


text:
Q: Handle database exceptions with php This exception(error) is displayed when i try to delete a user.
Error: the XML response that was returned from the server is invalid.
Received:
Cannot delete or update a parent row: a foreign key constraint fails
(`db_almacen`.`perfil_solicitud_material`, CONSTRAINT `perfil_solicitud_material_ibfk_1`
FOREIGN  KEY (`id_usuario`) REFERENCES `usuario` (`id_usuario`))

It is displayed on that way because i have a FOREIGN KEY related to my user's id.
I would like to display a different message instead of that. How can i do this i checked php exceptions manual but i didn't find an example please help me.
I am using Mysql and PHP
My php code
$query = "DELETE FROM unidad_solicitante where id_unid_sol ='$cod';";
$result = mysql_query($query) or die(mysql_error());

Thank You

A: Do not use mysql_ functions: http://pl1.php.net/mysql_query
See the red box? They are deprecated, not safe, and in general it is a bad idea to use them.
If you want PHP code to throw actual Exception, then use PDO; If you want to produce safe code, then use PDO; If you don't want dark demons (also applies to script kiddies) of SQL injection to get your site down, use... you know what :) mysql_ functions are wrong, mysql_ functions are evil, mysql_ functions are waking up dark forces , mysql_ functions will steal the ice cream from your child, mysql_ functions are voting in senate, mysql_ functions aren't feeding their dog; mysql_ functions will haunt you at night; mysql_ functions are selling drugs on the streets;
This fragment of your query code: ='$cod'; seems vulnerable, so please read this:
How can I prevent SQL injection in PHP?
With PDO, you can handle any exception with the usual try{} catch(...){} block;
If you cannot use PDO or really really do not want to, you should check if mysql_query() returned true, if not, then your error message will be returned by mysql_error(), so it will be something like this:
$result = mysql_query(...);
if(!$result) {
    $error = mysql_error();
    // .. handle
}

A: Any mysql error is going to trigger the or die(...), because mysql_query() will return a plain boolean FALSE to signal the failure. If you want to exempt certain error conditions from the die(), you'll have to test for them explicitly:
$result = mysql_query(...);
if ($result === FALSE) {
    switch(mysql_errno()) {
      case 1216: ... foreign key error ...
      case xxx: ...
      default:
            die(mysql_error());
    }
}

The error codes are defined here: http://dev.mysql.com/doc/refman/5.6/en/error-messages-server.html

A: The code responsible for displaying database error is here:
die(mysql_error())

*

*die() function terminates the script and displays a message

*mysql_error() outputs last error connected with executing MySQL query

If you want to display your own message use the following code:
if(mysql_query($query)) {
    echo 'success';
}
else {
    echo 'error';
}


text:
Q: Keep Element In Middle Of Excess Space With CSS calc() Function I have a  HTML element that takes up 80% of the  element on a page and it has a max-width value of max-width: 1220px.
Outside of this  element I have a small SVG arrow - is it possible with the CSS calc() function to have this so it is always in the middle of the area outside the main element on the left hand side?
If I didn't have a max-width property I could just do left: 10% but this only works up until the main element hits it max-width.
The full code is below and I've managed to get it so it aligns with the left hand side of the main element, but I can't get it so it is halfway across the white space on the left hand side. I'm thinking it may not be possible in CSS.
Codepen: https://codepen.io/emilychews/pen/bGEJjwX
Note 1: When viewing the snippet below you'll need to view it full-page because of the max-width value.
Note 2: What I am trying to do is illustrated in the below image.

main {
  position: relative;
  margin: 0 auto;
  width: 80%;
  padding: 6rem 0;
  background: red;
  height: 100vh;
  max-width: 1220px;
}

.down-arrow {
  position: absolute;
  width: 1rem;
  height: 1rem;
  bottom: 25vh;

  /* THIS IS THE BIT I NEED HELP WITH */
  left: calc((100% - 1220px) / 2);
}

<svg class="down-arrow" aria-hidden="true" viewBox="0 0 410.95 355.89">
  <polygon fill="#000" points="205.47 354.89 410.08 0.5 0.87 0.5 205.47 354.89" /></svg>

A: Because the arrow is absolutely positioned, it makes it a lot more complicated to position it relative to the main element. Instead, you can achieve the same effect (if i'm understand what you're looking for correctly!) using a wrapping container and Flexbox (or default CSS to vertically and horizontally center the child elements, I just prefer flex).
What I did was wrap the main element and the arrow in a div, labeled with a class of container. This way, we can position the main and svg relative to each other while still maintaining the flow of the application.
Display flex automatically aligns child elements in a row, which puts the svg and main elements next to each other. Adding align-items and justify-content center ensures that everything remains vertically and horizontally centered. I removed the margin: 0 auto; from main and the absolute positioning from the svg since it's no longer necessary.
Pen with changes, or see below: https://codepen.io/xenvi/pen/OJMGweV

body {
  margin: 0;
  height: 100vh;
}

 .container {
   display: flex;
 }

main {
  position: relative;
  width: 80%;
  padding: 6rem 0;
  background: red;
  height: 100vh;
  max-width: 1220px;
}

.down-arrow {
  width: 1rem;
  height: 1rem;
  bottom: 25vh;
}

.arrow-container, .end-container {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-grow: 1;
}

    <svg class="down-arrow" aria-hidden="true" viewBox="0 0 410.95 355.89">
    <polygon fill="#000" points="205.47 354.89 410.08 0.5 0.87 0.5 205.47 354.89" /></svg>

A: You need to use left: calc((100% - 1220px)/4);. From 100% we remove the width to get the white space. Then we divide by 2 to get only the left part and we divide again by 2 to get half of it.
You can also use min() to make it working for small screen too:

main {
  position: relative;
  margin: 0 auto;
  width: 80%;
  padding: 6rem 0;
  background: red;
  height: 100vh;
  max-width: 1220px;
}

.down-arrow {
  position: absolute;
  width: 1rem;
  height: 1rem;
  top: 25vh;
  left: calc((100% - min(1220px,80%))/4);
  transform:translate(-50%); /* don't forget this to get a perfect centring */
}

<svg class="down-arrow" aria-hidden="true" viewBox="0 0 410.95 355.89">
  <polygon fill="#000" points="205.47 354.89 410.08 0.5 0.87 0.5 205.47 354.89" /></svg>


text:
Q: Allowing users to edit and store HTML Ideally I want to allow users to edit HTML like tumblr does where you can edit your themes HTML in the browser. You get given also full control.
Ive heard of tools such html-purifier.
Other than ''purifying'' the HTML what other steps should br taken.

A: Some days ago I asked a similar question which might help you.
I would store all user-generated HTML on another domain/subdomain to avoid cookie stealing and make your cookies HttpOnly, so that they cannot be accessed with JavaScript. You could set your cookies (for authentication etc.) on the main domain only without subdomains. Additionally you could use CSRF tokens to avoid automated abuse.
If you want to disallow harmful code/JavaScript you have to filter your HTML, if you do so, you should just whitelist all allowed tags, not blacklisting forbidden tags (because new ones have come with HTML5 and there are even browser-specific ones).
Another challenge is the filtering of attributes (event attributes like onclick allowing to execute JavaScript).
Another user also called my attention to the Content Security Policy which is a header (but is unfortunately only supported by a few browsers).
But it depends on how much freedom you want to give to your users.


text:
Q: Extending bundles from the outside in Symfony / Doctrine 2? As far as I know, if you want to extend a bundle from another bundle, without creating a dependency between them or using any OO concept of inheritance, it is not yet possible w/ Symfony & Doctrine2. This confirmed my first idea :
"Due to the way Doctrine works, it is not possible to override entity mapping of a bundle." (source: http://symfony.com/doc/current/bundles/override.html#entities-entity-mapping)
The only existing way did not give me satisfaction : using SuperMappedClasses...
What I want is, for instance:

*

*having Contacts in a standalone bundle in one hand (CRMBundle)

*having EmailMessages in an other standalone bundle in the other (EmailBundle)

*adding "magically" the Contact::$emailMessages property + getter/setter + twig template in the ShowMapper (if I'm using Sonata, which is not mandatory) + fields in the DatagridMapper/FormMapper... when the EmailBundle is present in the App at the same time than the Contact/CRMBundle.

*the same thing on the reverse side (Email)

For the moment, as the official Symfony doc says, it does not seem possible.
Anyone can confirm the "state of the art" on this point ?
In fact we are working on this here, and I think we are about to touch something new and interesting for everyone on that point... but I don't want us to work on this issue without the necessity for.
Thanks in advance,

A: Basically, you want to create some "dynamic" property. There is no way to do this.
IMO, either EmailMessages and Contact are separated entities, then they are in 2 different bundles and does not know each other (you can still use the e-mail address as a key to query from one to another), either they do and are part of the same "aggregate".


text:
Q: Match everything after the 8th comma I'm parsing a raw log file and have to resort to regex because the comma delimiter shows up in a field.
20200914 01:38:16,ip-XX-YY-1-202,user,10.0.0.0,978,108421,QUERY,db,'select some random query, that has, commas in it, sometimes and not always quotes either..'

This is a maria DB audit log - I need to select the Database query which is everything after the 8th comma.
The output for the above example would be
`'select some random query, that has, commas in it, sometimes and not always quotes either..'`

I'm processing using pandas and .str.extract. I have a hacky version that matches everything before the 8th comma, but not sure how to get what's after it.

A: One way without regex is to use str.split:
s.split(",", 8)[-1]

Output:
"'select some random query, that has, commas in it, sometimes and not always quotes either.'"

Benchmark:
%timeit s.split(",", 8)[-1]

# 511 ns ± 46.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit re.search("^(?:[^,]*,){8}(.*)$", s).group(1)
# @41686d6564's comment
# 1.52 µs ± 121 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)


text:
Q: How to extract features from image for classification and object recognition? I'm confused about the way I should make the "features extraction " method
I want to use SVMs to apply "Object recognition" in images ,
There's a sample in Emgu's examples that holds an XML file contains the features of a cat !
and I've been trying since a week to know how they did it and what methods they used
and I came across this page
http://experienceopencv.blogspot.com/2011/02/learning-deformable-models-with-latent.html
that displays the steps ! It's so complicated plus couldn't do it myself
I'm so lost !! can anyone tell me an appropriate method of  "features extraction "Compatible with SVMs learning ?
Accord has SVM example but it's on hand writing and doesn't deal with color images =(
any helping links ?
thanks

A: all feature extraction methods are compatible with svm... u just need to choose one... select one and get the features and then input these features into svm.... explanation of what is feature extraction is here http://en.wikipedia.org/wiki/Feature_extraction

A: You need to concentrate on the gabor filter, which is an advanced extractor for face recognition and object recognition.


text:
Q: React runtime errors - What happens if an expected prop is not given? ErrorBoundary and PropTypes I have a component Profile which might receive this a prop:
RootProfile.propTypes = {
  route: PropTypes.shape({
    params: PropTypes.shape({
      userData: PropTypes.oneOfType([
        PropTypes.shape({
          id: PropTypes.string.isRequired,
        }),
        PropTypes.shape({
          username: PropTypes.string.isRequired,
        }),
      ]),
    }),
  }).isRequired,
};

In the code of Profile, I do:
function RootProfile({route: { params }}){
   const currentUser = useCurrentUser();

   let { userData = currentUser.data } = params ?? {};

   // Consume the most up-to-date data from context
   userData = useUpdatedUserData(userData);

   if (userData.id) {
      return <Profile userData={userData} />
   }

   // We will need to fetch the user by username!
   return <ProfileFetcher username={userData.username} />
}

As you can see, if userData.id is not defined, I do not render the my lazy loading Profile component... Instead, I render my ProfileFetcher component, which just fetches the user data by username and stores it to my context (which I consume in RootProfile to re-render the screen when everything is ready).
My question is: what if, for an unexpected reason, Profile doesn't receive the "required" prop fields for its work? I mean, what if it doesn't receive neither userData.id nor userData.username?
Should I do something like
function RootProfile({route: { params }}){
   const currentUser = useCurrentUser();

   let { userData = currentUser.data } = params ?? {};

   // Consume the most up-to-date data from context
   userData = useUpdatedUserData(userData);

   if (userData.id) {
      return <Profile userData={userData} />
   } else if (userData.username) {
      // We will need to fetch the user by username!
      return <ProfileFetcher username={userData.username} />
   } else {
     throw new Error("id or username is required");
   }
}

?? I mean, is it considered "correct" to throw an error inside a React component?
Or, should all these situations be handled with ErrorBoundaries and PropTypes?

A: If you think that the prop may be undefined consider removing isRequired and making it optional. However, in answer to your question PropTypes library doesn't throw errors in production mode so you can't catch it with an ErrorBoundary you have to check it menually.


text:
Q: MacOS BASH, Get output from networkQuality command running in background I am trying to launch networkQuality command in the background and live fetch the first part of the output to the bash script launching it.
First part I want to fetch from the background command:
current download capacity: 49.342 Mbps - current upload capacity: 52.951 Mbps
Code:
networkQuality &

When the command have finished in the background I also want to fetch the result:
==== SUMMARY ====
Upload capacity: 68.877 Mbps
Download capacity: 67.388 Mbps
Upload flows: 16
Download flows: 20
Anyway of doing this?

A: Use the following call to get verbose data with all the raw data in JSON format...
networkquality -v -c


text:
Q: Iterate through file.txt and update map values Im trying to update my map as i iterate though my file.txt
I added some "test code" to output my values and im getting 125.00 (which is what i want) and 100 (which i dont want)
I dont think that im inserting it into the map the right way or retrieving it the right way. Because the value before i add it is right and when i retrieve it, its not the right way
if (accountFile.is_open())
    {
        while (!accountFile.eof())
        {
            (std::getline(accountFile, accounttemp.user, ',') &&
                std::getline(accountFile, accounttemp.trantype, ',') &&
                std::getline(accountFile, (accounttemp.bal)));

            (std::getline(loginFile, logintemp.user, ',') &&
             std::getline(loginFile, (logintemp.pass)));
            cout << logintemp.user << endl;

            //http://www.cplusplus.com/reference/map/map/find/
            // find value given key
            it = balances.find(accounttemp.user);
            if (it != balances.end())
            {
                double holder = 0;
                if (accounttemp.trantype == "D")
                {
                    holder = std::stod(accounttemp.bal) + std::stod(balances.find(accounttemp.user)->second);
                }
                if (accounttemp.trantype == "W")
                {
                    holder = std::stod(accounttemp.bal) - std::stod(balances.find(accounttemp.user)->second);
                }
                stringstream stream;
                stream << fixed << setprecision(2) << holder;
                string s = stream.str();
                accounttemp.bal = s;

                //this is were i added some test code to see my output
                cout << accounttemp.bal << endl;
                balances.insert(pair<string, string>(accounttemp.user, accounttemp.bal));
                cout << (balances.find(accounttemp.user)->second) << endl;
enter code here
                //out put is 125.00
                //out put is 100
            }
            else
            {
                balances.insert(std::pair<string, string>(accounttemp.user, (accounttemp.bal)));
            }

        }
    }
    cout << "\n";

A: You have:
        it = balances.find(accounttemp.user);
        if (it != balances.end())
        {

Which enters the block only if balances contains an accounttemp.user element. Then the code has:
            balances.insert(pair<string, string>(accounttemp.user, accounttemp.bal));

which does nothing, since the map already contains an element with that key. Note that insert does not replace an existing element. At most, for std::multimap a new element, with the same key, might be inserted. But with std::map nothing will happen at all. Look at the documentation of std::map::insert:

Returns a pair consisting of an iterator to the inserted element (or to the element that prevented the insertion) and a bool denoting whether the insertion took place.

I assume it returned false for you, since no insertion took place.
FIX: update the iterator instead:
            // instead of:
            // balances.insert(pair<string, string>(accounttemp.user, accounttemp.bal));
            it->second = accountemp.bal;


text:
Q: Automatically create a new Google Spreadsheet with Script Editor How to automatically create a new Google Spreadsheet with Script Editor?
I know it seems obvious but I couldn't find an answer to this as everyone has only been interested in creating a sheet, instead of an entirely new spreadsheet automatically.

A: To create anew spreadsheet refer to the create() method there : https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet-app#createname
Code is really simple
function createNewSpreadsheet(){
  var ssNew = SpreadsheetApp.create("My New Spreadsheet");
  Logger.log(ssNew.getUrl());
}

And if you want to get the first tab
  var firstTab = ssNew.getSheets()[0] ;

And if you want to get the cell C15
  var cell = firstTab.getRange("C15");

Stéphane


text:
Q: Получение GET переменной из URL'а в JS Как с помощью JS считать GET переменную которая находится в URL'е?
Например:

http://site.ru?data=value

A: // Выставим нужный URL для теста с помощью History API
history.replaceState({}, '', '/test?param=value&param2=42&keyonly');

// location.search === '?param=value&param2=42&keyonly'
var search = location.search.substr(1)
  .split('&') // разбиваем на параметры
  .reduce(function (res, a) { // разбираем пары ключ-значение
    var t = a.split('=');

    // нужно декодировать и ключ и значение, значения может не быть
    res[decodeURIComponent(t[0])] = t.length == 1 ? null : decodeURIComponent(t[1]);
    return res;
  }, {});

console.log(search); // {"param":"value","param2":"42","keyonly":null}

JSFiddle

A: Можно использовать URLSearchParams. Данный пример считывает все переменные.
urlParams = new URLSearchParams(window.location.search);
params = {};

urlParams.forEach((p, key) => {
  params[key] = p;
});

Затем параметр data будет доступен в params.data.

A: Можете использовать объект location и его поля для доступа к url
// www.example.com?data=value
console.log(location.href); // www.example.com?data=value
console.log(location.search) // ?data=value

A: function $_GET(key) {
    var s = window.location.search;
    s = s.match(new RegExp(key + '=([^&=]+)'));
    return s ? s[1] : false;
};

Затем можно получать нужную переменную из вашего примера через
$_GET('data')

Касаемо URLSearchParams в одном из ответов, приведу ссылку на caniuse.


text:
Q: Use XSL to transform an XML list into an XHTML tree I need to take this xml…
<root>
   <item id='1' parent_id='0'>ONE</item>
   <item id='2' parent_id='1'>TWO</item>
   <item id='3' parent_id='1'>THREE</item>
   <item id='4' parent_id='2'>FOUR</item>
   <item id='5' parent_id='0'>FIVE</item>
</root>

And produce this xhtml…

ONE

TWO

FOUR

THREE

FIVE

I get how to collect the child nodes and put them under their parent, but I can't grasp how to then skip over considering them as parents if I have already used them as children.

A: Tested the following, which appears to work
Apply all items at the root with parent_id = 0, then recursively iterate for any children..
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
  <xsl:apply-templates select="root/item[@parent_id='0']"/>
</xsl:template>

<xsl:template match="item">

<xsl:value-of select="."/>

  <xsl:if test="count(../item[@parent_id=current()/@id]) != 0">

      <xsl:apply-templates select="../item[@parent_id=current()/@id]"/>

  </xsl:if>
</xsl:template>

A: This stylesheet:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:key name="kItemById" match="item" use="@id"/>
    <xsl:key name="kItemByParentId" match="item" use="@parent_id"/>
    <xsl:template match="root">
        <xsl:apply-templates select="item[not(key('kItemById',@parent_id))]"/>
    </xsl:template>
    <xsl:template match="item">
        <xsl:variable name="vChild" select="key('kItemByParentId',@id)"/>

            <xsl:value-of select="."/>

        <xsl:if test="$vChild">

                <xsl:apply-templates select="$vChild"/>

        </xsl:if>
    </xsl:template>
</xsl:stylesheet>

Output:

ONE

TWO

FOUR

THREE

FIVE

Note: Keys for cross references.


text:
Q: Time dilation in L. Ron Hubbard's "To the Stars" So I just finished reading L. Ron Hubbard's novel To the Stars and noticed a rather glaring issue. The plot in the beginning speaks of a ship capable of near-light-speed travel which makes a return trip to Alpha Centauri and returns to Earth probably around 60 or even more years later. The exact number is never given, but 60 is a good guess, and it's certainly more than 40 which is still good enough for my argument.
The thing is that the ship constantly travels with a speed of at least 296000 km/s, which is a speed at which they will, for an outside observer, travel the 4.367 light years to Alpha Centauri in no more than 4.42 years. Even giving them 0.6 years extra, they should return at worst 10 years after leaving.
Note: there is no need to explain time dilation to me. I know how it works, but it does not apply here. The question is not how much time passed inside the super fast ship, and I agree that the answer is "much less than outside".
The point is that from the standpoint of Earth, people looking up would see a ship traveling at 296000km/s, and the ship would reach its destination after about 5 years (of course, we would only see the ship reach its destination after 9 years, but that makes no difference, the clock on earth would still show five years at the time the ship made it to AC)
Is there any in-story explanation why the time dilation was so much bigger in the story?

A: The numbers make no sense.
Using this, assuming an acceleration/deceleration of only 1g, and a maximum velocity of 0.987c, and a distance of roughly 4.4 light years, and ignoring time dilation so it's only the outside observer's measurement, it takes about 6 years to get to Alpha Centauri, with about 349 days of acceleration on each end, so about 4.1 years coasting, then the same coming back. So just a touch over 12 years.
Even dropping the acceleration down to 0.1g gives a round-trip time of only 27.6 years.
I think the problem simply comes down to one factor not in the text: Writers Can't Do Math.

A: As @ Richard and @ Hypnosifl suggested, the "extra" time comes from acceleration and deceleration on the way out and on the way back.
The OP says that "The story makes it clear that only the first couple of days are troublesome because the ship is accelerating, and that it gets easier later."  This is unclear to me.  If the ship took "only the first couple of days" to accelerate to the speed of light, the occupants would be squashed flat.  If the ship took 3.5 days to accelerate to a mere 0.1 speed of light, that would be an acceleration of 10g.  That is more than "troublesome."

A: First, let's note that there may be two or three somewhat different versions of that story. Quoting the ISFDB:

The story was serialized in February and March 1950 as To the Stars and first published in book form in 1954 as Return to Tomorrow and then reprinted in 2004 as To the Stars.

I suppose the 1954 book was an expanded version of the 1950 serial. I have no idea if the text of the 2004 book (the one you read, I presume) is from the 1950 serial or the 1954 book or contains further revisions. Unfortunately I don't have either of the books on hand. This answer is based on the 1950 serial, which is available at the Internet Archive, in the February 1950 and March 1950 issues of Astounding Science Fiction. Maybe some revisions in the book you read invalidate my answer, though I'm inclined to doubt that. [Never mind! See postscript below. I forgot there's a thing called "Google Books". It's the same trip in 2004 as it was in 1950.] All quotations below are from the February 1950 ASF, page references and links provided so you can view them in context.
By the way, I would also like to mention that, while L. Ron Hubbard was a good storyteller, a master of pulp fiction, and a spectacularly successful "artist" of a sort, his yarns were not especially noted for their scientific accuracy, so you should not take his math and physics too seriously. For instance, he seems to think that, if you're driving a spaceship at just under the speed of light, you'd better keep a close eye on the speedometer, or you might accidentally go over the speed limit with catastrophic results. The pilot has a gong to warn him if he gets too close.
p. 35, column 2 — p. 36, column 1:

The gong rang three times and then three times again.
Let her go. Let her edge on up to Constant. Let her flash on through zero time and explode to pure energy or let her hang as one ship had at the exact speed of light and hang there forever, impervious, unmoving, her people statues within her, locked, protected and condemned to eternity by zero time.

The answer to your question is that, at least in the original serial, Alan Corday's first voyage on the Hound of Heaven aka the Flea Circus was not a simple round trip to Alpha Centauri, and in fact the error seems to be in the other direction; with stops at Betelgeuse and "Other Ports of Call", he should have been gone for much longer than 60 years. Here the author states correctly that a round trip to Alpha Centauri would take less than 10 years Earth time:
page, 16, column 1:

Outward bound on the long passage, outward bound to the stars. He did not know the speed of this pariah nor how close it would come to light. If it was as slow as ninety-four percent it still meant that for every moment ticked by the clocks of the Hound of Heaven, hundreds passed on Earth. If the Hound spent six weeks in a round trip to Alpha Centauri, nine years would pass on Earth.
"As mass approaches the speed of light, time approaches zero." It was his sentence. A cold equation, a dispassionate mathematics, but it was Alan Corday's sentence to forever.
The run to Alpha Centauri would be the shortest trip they could make.
How old would be his people when he saw them next? How old?

Here's what it said on the paper that Alan Corday was tricked into signing.
page 11, column 1:

And he looked down and saw his name on the articles. "The Hound of Heaven. Outward Bound for Alpha Centauri, Betelguese [sic] and Other Ports of Call." He went white and lunged back. But Gow-eater and his friend still had him.

Only one landing is described in the story, on a planet called Johnny's Landing (star unnamed as far as I know), and this seems to be the last stop before the return to Earth.
P.S. The quotation

"The Hound of Heaven. Outward Bound for Alpha Centauri, Betelgeuse and Other Ports of Call."

also appears in a Google Books copy of the 2004 edition, with nothing changed from 1950 except for correcting the misspelling of Betelgeuse. So there's your in-story explanation: they did not just fly from Earth to Alpha Centauri and back.


text:
Q: All instances of a class have the same dict as an attribute in Python 3.2 I'm writing a space trading game in Python, and I've decided that the map needs to be split into smaller chunks to reduce the number of objects that need to be considered for drawing on the screen at any given time.
This is handled by having a Sector object, which is defined as such:
class Sector:
   x=0     #Position of the sector. The galactic (absolute) position of any object is its in-sector position
   y=0     #plus the galactic position offset times the size of a sector.
   stardict=dict()

Then, the generator code populates each sector (100 of them at the moment) with 75 stars, kept in stardict.
thesector=Sector()

size=size/2

#Generate stars
for t in range(stars):
    #name="Star "+str(t)
    name=generate_name().capitalize()
    thesector.stardict[name]=Star( name, (random.randint(-size,size), random.randint(-size,size)), (random.randint(0,255), random.randint(0,255), random.randint(0,255)), random.randint(3,7))

    if math.floor((t/stars)*100)==(t/stars)*100: print("Generating stars: "+str((t/stars)*100)+"% done.")

However, there's some strange bugs when trying to actually run the program, and opening it with the debugger shows why: the stardict attribute of each sector is identical, they each contain the exact same stars (not duplicates, they have the same memory address). As far as I can tell, each Sector.stardict is actually referencing the same dict object.
I have no idea why this is happening. Can anyone shed some light on this?

A: They are refering to the same object.  This is a very common gotcha.  If you want them to each have their own dict, you need to have it created in the __init__ method.
class Sector:
   x = 0     #Position of the sector. The galactic (absolute) position of any object is its in-sector position
   y = 0     #plus the galactic position offset times the size of a sector.
   def __init__(self):
       self.stardict = dict()

As your code currently stands, when you try to access stardict via self.stardict, python first looks for stardict on the instance, but when it doesn't find a stardict attribute there, it looks on the class.  It finds stardict on the class, so it uses that.  But, this implies that all instances find the same stardict (since they all instances of the same class) -- an update to one of their stardict and all of the others will know (faster than light speed!)*.
*Note that this doesn't voilate any laws of physics.  Since they are the same object, there is no distance for the information to travel ...


text:
Q: How to create a pop up menu in Android i tried the following code
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.ListAdapter;

public class Custom_dialogActivity extends Activity {
/** Called when the activity is first created. */
String test[] = {"Security","Data Backup","Missing Device"};
ListAdapter adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setCancelable(true);
    builder.setTitle("My Title");
    builder.setInverseBackgroundForced(true);
    builder.setIcon(R.drawable.ic_launcher);
    builder.setItems(test, new OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            System.out.println("onClick " + which);

        }
    });
    builder.setAdapter(adapter, new OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            System.out.println("DialogInterface : " + which);
        }
    });
    EditText ed = new EditText(this);
    builder.setView(ed);
    builder.setPositiveButton("Yes",
            new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which)
                            {
                                dialog.dismiss();
                             }
                       });
                builder.setNegativeButton("No",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,int which)
                            {
                                dialog.dismiss();
                            }
                        });

                AlertDialog alert = builder.create();
                alert.show();
          }
}

**but it looks like but i tried to set color and icon but failed to setIcon and Color Green on Top of Dialog box solve my problem and i didint created any xml and didnt made any changes **

but i want like

A: You can achieve this by using AlertDialog.Builder, but instead of using standard dialog, you need to inflate your own xml to override the view.
update
or create an activity with dialog style:
your custom style:
<style name="styleActivityDialog" parent="@android:style/Theme.Light.NoTitleBar">
 <item name="android:windowNoTitle">true</item>
 <item name="android:windowFrame">@null</item>
 <item name="android:windowIsFloating">true</item>
 <item name="android:windowContentOverlay">@null</item>
 <item name="android:colorBackgroundCacheHint">@android:color/transparent</item>
 <item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
 <item name="android:windowSoftInputMode">stateUnspecified|adjustPan</item>

 <item name="android:windowBackground">@drawable/bg_activity_dialog</item>
</style>

drawable bg_activity_dialog:
    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android">

      <stroke android:width="1dp" android:color="#C0C0C0" />
      <solid android:color="#FFFFFF" />
      <corners android:radius="5dp" />
      <padding android:top="5dp" android:bottom="5dp" android:left="5dp"
         android:right="5dp"/>
    </shape>

your activity in AndroidManifest.xml:
<activity android:name=".ActivityDialog"
     android:theme="@style/styleActivityDialog">
</activity>

now create any layout for your activity ActivityDialog and it should appear as a dialog window

A: You could create an Activity with the layout you desire and add the following theme to the Activity's tag in the AndroidManifest.xml to simulate a dialog look.
android:theme="@android:style/Theme.Dialog"

If that is not enough, you can use inheritance and modify this specific theme to use a translucent, non-dim background.
<style name="MyTheme" parent="@android:style/Theme.Dialog">
     <item name="android:windowIsTranslucent">true</item>
     <item name="android:windowBackground">@android:color/transparent</item>
     <item name="android:backgroundDimEnabled">false</item>
</style>

A: You can use AlertDialog or custom dialog.
I've discussed about this in my personal blog.You can just visit my humble blog if you desire..
http://androiddesk.wordpress.com/tag/dialog-in-android/page/2/


text:
Q: My computer fails to start virtual machine in Android Staudio and Genymotion My virtual machine can boot up to this point, I can't open it up.
I fixed the error following the instructions on google but it didn't work. Everyone please help me fix this
Thanks!


text:
Q: Populate table with MVC on submit I am learning MVC by converting an old Web Form to MVC 5. The page is pretty simple, just a few text boxes, a submit button and a grid. I want similar functionality where there is no grid on page load, and after the submit takes place, the grid appears. The issue I am having is all the examples I have seen contain the data coming at page load.
Here is my View

Search Craigslist

@using (Html.BeginForm())
{

        Enter Search Criteria:

        @Html.TextBox("Criteria", null, new { @style = "width: 450" })

        @Html.DropDownList("DropDownValues")
        Days:
        @Html.TextBox("Days")

        <input type="submit" value="Submit" />

}
@Html.Partial("~/Views/Search/_Search.cshtml")

and the partial
@model IEnumerable<CraigsListSearch.MVC.Models.SearchModel>
@{
Layout = null;
}

        @Html.DisplayNameFor(model => model.Location)

        Link

        @Html.DisplayNameFor(model => model.DateSubmitted)

@foreach (var item in Model)
{

            @Html.DisplayFor(modelItem => item.Location)

            @Html.Hyperlink(Html.DisplayFor(modelItem => item.URL).ToString(), Html.DisplayFor(modelItem => item.Title).ToString())

            @Html.DisplayFor(modelItem => item.DateSubmitted)

}

and finally the controller
public class SearchController : Controller
{

    [HttpGet]
    //public ViewResult Index(string DropDownValues, string Criteria, string Days)
    public ViewResult Index()
    {
        Populate();

        Session["list"] = SearchModel.GetQuickList();
        return View(new List<SearchModel>());

    }

    [HttpPost]
    public ViewResult Index(string DropDownValues, string Criteria, string Days)
    {
        Populate();
        Criteria = Server.UrlPathEncode(Criteria).Replace(",", "%2c");

        List<Location> list = (List<Location>)(Session["list"]);
        List<SearchModel> results = SearchModel.Search(Criteria, Days, DropDownValues, list.Take(5).ToList());
        return View(results);
    }

    private void Populate()
    {
        List<DropDownModel> ddlList = DropDownModel.GetDropdowns();

        ViewBag.DropDownValues = (from a in ddlList
                                  select new SelectListItem
                                  {
                                      Text = a.Text,
                                      Value = a.Value
                                  }).ToList();
    }
}

What I am looking for is to have the partial only be "called" on POST. Is this something that can easily be done? Let me know if other info is needed.
Thanks!

A: There are a couple of ways you could approach solving this problem.
One option would be to use AJAX. When the user clicks the button make an AJAX call to the controller and have the controller render the partial and return the HTML which you then inject into the page DOM.
Another option is to add a "DisplayGrid" property to your model. When you first render the View set it to false and then set it to true after the post.
One point I want to make is that rendering a View from the Post action isn't a great idea. If the user hits Refresh in their browser it's going to post again, giving the user that annoyingly ugly dialog that tells them they're going to send data to the server. In general you should use a Post-Redirect-Get pattern, the user posts, you redirect, and then you use a get to re-render in the browser. If you use the AJAX approach this all becomes moot because you never post the whole form back to a controller action. If you continue to use a full post the HttpPost version of Index should return a RedirectToAction result sending the user back to the Get version of Index. You can communicate between the two actions by using TempData, for example:
[HttpGet]
public ActionResult Index()
{
    if( TempData.ContainsKey( "DisplayGrid" )
    {
        // Use the other values from TempData to populate the model with the grid data
        myModel.DisplayGrid = (bool)TempData["DisplayGrid"];
    }
}

[HttpPost]
public ActionResult Index( string dropDownValues, string criteria, string days )
{
    TempData["DisplayGrid"] = true;
    TempData["DropDownValues"] = dropDownValues;
    TempData["Criteria"] = criteria;
    TempData["Days"] = days;

    return RedirectToAction( "Index" );
}

A: You should pass whatever information you need to render view via model (or ViewBag).
Since you already have sample of how to use Model here is how you can use ViewBag
@if(ViewBag.RenderSearch)
{
  @Html.Partial("~/Views/Search/_Search.cshtml")
}

And set RenderSearch in particular action:
public ViewResult Index(string DropDownValues...
{
     ....
     ViewBag.RenderSearch = true;

With model just add property to your model (you'd need to make it custom class instead of just List) and check that flag instead.

A: Try This, the Ajax only replace the GridDiv only

Search Craigslist

using (Ajax.BeginForm("BindGridAction", "Contoller",new AjaxOptions { UpdateTargetId = "GridDiv" }))
{

        Enter Search Criteria:

        @Html.TextBox("Criteria", null, new { @style = "width: 450" })

        @Html.DropDownList("DropDownValues")
        Days:
        @Html.TextBox("Days")

        <input type="submit" value="Submit" />

    }

    @Html.Partial("~/Views/Search/_Search.cshtml")

Bind your partial view in controller
    public PartialViewResult BindGridAction()
    {
       // your model coding
        return PartialView("~/Views/Search/_Search.cshtml", model);
    }


text:
Q: Linq to build hierarchical list I have a method that retrieves a set of records from a database.
I map this data to a business object - let's call the business object ProcessModel.  One of the properties in ProcessModel is a list, called ProcessChildren.  The property is List.
So, the data is linked by various fields/properties.  There is one object at the top of the hierarchical list, then that object has multiple objects in it's ProcessChildren property, those objects have multiple objects in their ProcessChildren properties etc.
Anyway, I wrote quite a bit of code to iterate through the dataset returned, and build the hierarchical list, which I then bind to a TreeView in Silverlight.
I would be very appreciative if someone could provide me with a much cleaner, simpler way to do this, either using linq, or using linq or some other approach via means of an extension method.
I have included the code that I am currently using, to hopefully better illustrate what I am trying to achieve.
var processes = new List<Process>();

        var rootLevelProcesses = new List<Process>();

        var allProcesses = new List<Process>();

        foreach (Process process in e.Results)
        {
            process.ProcessChildren = new List<Process>();

            if (process.ParentId > 0 || (process.ParentId == 0 && process.EntityId == 1))
            {
                allProcesses.Add(process);
            }
        }

        var rootProcess =
                    (from parent in e.Results
                     where parent.EntityType == 1 && parent.ContainerLevel <= 1
                     select parent).FirstOrDefault();

        processes.Add(rootProcess);

        var level2Processes = (from parent in allProcesses
                               where parent.EntityType == 1 && parent.ContainerLevel == 2
                               select parent).ToList();

        foreach (Process process in level2Processes)
        {
            var level3Processes = (from parent in allProcesses
                                   where parent.EntityType == 1 && parent.ContainerLevel == 3
                                   select parent).ToList();

            process.ProcessChildren = level3Processes;
        }

        processes[0].ProcessChildren = level2Processes;

        foreach (Process process in processes)
        {
            if (process.ProcessChildren != null && process.ProcessChildren.Count > 0)
            {
                foreach (Process level1 in process.ProcessChildren)
                {
                    if (level1.EntityType == 1)
                    {
                        var children =
                        (from child in allProcesses
                         where child.ParentId == level1.EntityId
                         select child).ToList();

                        level1.ProcessChildren = children;

                        foreach (Process level2 in level1.ProcessChildren)
                        {
                            if (level2.EntityType == 1)
                            {
                                children =
                            (from child in allProcesses
                             where child.ParentId == level2.EntityId
                             select child).ToList();

                                level2.ProcessChildren = children;

                                foreach (Process level3 in level2.ProcessChildren)
                                {
                                    if (level3.EntityType == 1)
                                    {
                                        children =
                                    (from child in allProcesses
                                     where child.ParentId == level3.EntityId
                                     select child).ToList();

                                        level3.ProcessChildren = children;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

A: This related post might help....
Update:  here's code in support of comments below...  You will need to edit to support your own classes.
public class Proc
{
    public System.Diagnostics.Process RealProc;
    public List<Proc> SubProcs = null;
}

void Main()
{
    var Processes = from p in System.Diagnostics.Process.GetProcesses() select new Proc { RealProc = p, SubProcs = null };
    while (Processes.Any(pr => pr.SubProcs == null))
    {
        foreach(Proc pr in Processes)
        {
            pr.RealProc.Id.Dump();
            pr.SubProcs = Processes.Where(prx => prx.RealProc.ParentId == pr.Id).ToList();  // doesn't work because no ParentId
        }
    }
}

A: I imagine that this answer is a little late, but here goes.
Try using the .LookUp(...) extension method and a recursive lambda expression:
var lookup = e.Results.ToLookup(x => x.ParentId);

Action<IEnumerable<Process>> addChildren = null;
addChildren = ps =>
{
    foreach (var p in ps)
    {
        p.ProcessChildren = lookup[p.EntityId].ToList();
        addChildren(p.ProcessChildren);
    }
};

var rootProcesses = e.Results.Where(x => x.ParentId == 0);

addChildren(rootProcesses);

This worked fine with the test data I created. I didn't use the ContainerLevel property as the ParentId relation implicitly define the level.


text:
Q: Is my logic valid in this rates of change question?

A hemispherical bowl of radius $r$ is initially empty. Water is poured into it at a constant rate of $k$cm$^3$ per minute. When the depth of water in the bowl is $x$ c,, the volume of water in the
bowl is given by $v\ =\ \frac{\pi}{3}x^{2}\left(3r-x\right)$. Show that it takes 3.5 times as long to fill the bowl to the point where $x = \frac{2r}{3}$ as it does to fill the bowl to the point where $x = \frac{r}{3}$

For part (ii), I simply subbed the two $x$ values into $V$ and divided them to get the ratio of $3.5$ since water is poured in at a constant rate. The solutions go through a lengthy process of integrating to find $t$, then finding times are $t_1$ and $t_2$ to show that $t_1 = 3.5 t_2$. Is my way valid? My thinking is that since the rate is constant, you can measure the volume at $ x = t_1 = \frac{2r}{3}$ and divide that by the volume when $x = \frac{r}{3}$ to see the extent to which filling up to $x_1$ is compared to $x_2$. Then can I conclude that it is logically indeed $3.5$?


text:
Q: PhoneGap File Upload (other then images) using file transfer i have a a sequence of task to do with the phoneGap.
one is that i have to select the file from library/storage of the device and then upload to server.
With the reference from the documentation form the phoneGap site here i found somethings related to the image upload and i successfully able to run that as well, but

*

*the problem is that when i browse the device it only shows the image files, how can i select the other files??  here is the code
function getImage()
{
    // Retrieve image file location from specified source
    navigator.camera.getPicture(uploadPhoto, function(message)
                                {
                                alert('get picture failed');
                                },{
                                quality: 50,
                                destinationType: navigator.camera.DestinationType.FILE_URI,
                                sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY

                                });

}

*selection and uploading succesfull only in case if selection is made from photo library , the app crashes when selection using file manager ,, how to handle this ??
any help will be appreciated
thanks

A: You can use the file chooser plugin to pick a file (android only), and then upload it


text:
Q: EF Core 3.1 How to include nested property of a owned entity I have following relationships:
    public class Order : IAggregateRoot
    {
        public Guid OrderId { get; private set; }
        public string Title { get; private set; }

        private ICollection<OrderProduct> _orderProducts;

        private Order()
        {
            _orderProducts = new List<OrderProduct>();
        }
    }
    public class OrderProduct
    {
        public Guid OrderProductId { get; private set; }
        public int Quantity { get; private set; }
        public Order Order { get; private set; }
        public Product Product { get; private set; }
        public bool Purchased { get; private set; }

        private OrderProduct()
        {
        }
    }
    internal class OrderEntityTypeConfiguration : IEntityTypeConfiguration<Order>
    {
        private readonly string orderProducts = "_orderProducts";
        public void Configure(EntityTypeBuilder<Order> builder)
        {
            builder.ToTable("Orders");

            builder.HasKey(b => b.OrderId);

            builder.OwnsMany<OrderProduct>(orderProducts, x =>
            {
                x.ToTable("OrderProducts");
                x.HasKey(y => y.OrderProductId);
                x.WithOwner(y => y.Order);
                x.HasOne(x => x.Product)
                    .WithMany();
            });
        }
    }

Order is aggregate root, owns collection of OrderProduct entities. Based on https://learn.microsoft.com/en-us/ef/core/modeling/owned-entities owned types are included by default(without using the Include method).
My question is, how can I include Product for each OrderProduct when I load Order from db by following method:
public async Task<App.Domain.Orders.Order> GetOrder(Guid orderId)
{
    return await _appDbContext.Orders
        .SingleOrDefaultAsync(x => x.OrderId == orderId);
}

Is it possible in such a configuration of types and without exposing the collection of OrderProduct from Order?

A: My goal was to avoid using hard-coded strings for eager load, solution which I found is as follows:
internal class OrderEntityTypeConfiguration : IEntityTypeConfiguration<Order>
{
    public void Configure(EntityTypeBuilder<Order> builder)
    {
        builder.OwnsMany<OrderProduct>(x => x.OrderProducts, x =>
            {
                x.WithOwner(y => y.Order);
                x.HasOne(x => x.Product)
                    .WithMany();

                x.OwnedEntityType.FindNavigation(nameof(OrderProduct.Product)).SetIsEagerLoaded(true);
            }
        );
        builder.Metadata.FindNavigation(nameof(Order.OrderProducts))
            .SetPropertyAccessMode(PropertyAccessMode.Field);
    }
}

public class Order : IAggregateRoot
{
    public Guid Id { get; private set; }
    public string Title { get; private set; }

    private List<OrderProduct> _orderProducts;
    public IReadOnlyCollection<OrderProduct> OrderProducts => _orderProducts.AsReadOnly();

    private Order()
    {
        _orderProducts = new List<OrderProduct>();
    }
}
public class OrderRepository : IOrderRepository
{
    public async Task<Order> GetOrder(Guid orderId)
    {
        return await _shoppingAppContext.Orders
            .SingleOrDefaultAsync(x => x.OrderId == orderId);
    }
}

Thanks that Product is eager loaded by default. What do you think about it?

A: The reason why you can't get Product for each of the OrderProduct in the Order object is that you are making OrderProduct as an owned type of Order while Product is not an owned type of OrderProduct.
That's why you can get OrderProduct without .Include() method on Order object and can't get Product without .Include() method on OrderProduct.


text:
Q: Generate a Date and Time in JavaScript I have a counter embedded in a page and it works from the date and time specified as below;
$(document).ready(function (){
 $('#fade').county({endDateTime: new Date('**2016/10/05** 15:00:00'),reflection:false,animation:'fade',theme:'black'});
});

What I want to do is set the DATE to be today's DATE if before 15:00 on Monday, Tuesday, Wednesday, Thursday or Friday AND IF before 15:00 else I want the date to roll to the next day.
One other consideration is Bank Holidays.  Would it be possible to have some kind of array of days that are considered to be weekend days as well?


text:
Q: Can I bundle MSVCRT DLLs with my app without installing the distributable VC++ package I have a complex app which cannot be linked statically with the CRT, but on the other hand does not require admin privileges to be installed (since it isn't doing anything that requires it). The normal way for installing the CRT so it can be linked to dynamically is to install the MS distributable CRT, but it requires admin privileges.
I am contemplating simply placing the MSVCRT100 DLLs in the same directory as the executable in order to alleviate the problem, but I'm not sure whether this practice has any downsides since it's not condoned or condemned anywhere I seen. Is there any reason not to do it, other than following the usual practice of static linking vs. installing the distributables?

A: The short answer is yes you can. It's even one of the option descibe on microsoft website to deploy application http://msdn.microsoft.com/en-us/library/dd293565.aspx

Copy the appropriate MFC and C Run-Time (CRT) library files—for example, for an x86 platform and Unicode support, copy mfc100u.dll and msvcr100.dll from \Program Files\Microsoft Visual Studio 10.0\VC\redist\x86\—and then paste them in the \Release\ folder of your MFC project. For more information about other files that you might have to copy, see Determining Which DLLs to Redistribute.

The downside is that the redistributable package is updated by microsoft security fixes. So if a security fix is deployed your application would not use it and may remains unsafe. I'm not a big fan, but it's the idea of the winsxs directory, and manifest since visual 7.0 which 'helps' your application to always use the best version.


text:
Q: WP_Query не работает на простых страницах с пользовательскими таксономиями Перепробовал много функций wp и большинство не работает например в том же functions.php c произвольными таксаномиями, хотя на страницах записей все нормально работает
Пример запроса:
$mypost = array(
   'post_type' => 'post',
   'tax_query' => array(
      array(
        'taxonomy' => 'category_advert',
        'field'    => 'slug',
        'terms'    => 'avtorynok'
      ),
));

$loop = new WP_Query( $mypost );

Кто знает в чем может быть причина? А то надоело уже в ручною запросы к бд делать.
Таксономии через плагин tooset создавались


text:
Q: "Undefined method `concat'" on "devise_parameter_sanitizer.permit" I'm writing a custom sign-up devise controller, and I'm having trouble adding permitted params due to this error (this is the output from Rspec, but the same error happens manually):
Failure/Error: devise_parameter_sanitizer.permit(:sign_up, keys: [:nome, :password, :password_confirmation, :cnpj, :razao_social, :nome_fantasia, :email, :tipo_entidade_id])

 NoMethodError:
   undefined method `concat' for #<Proc:0x0055ca9fb2d850>
   Did you mean?  concern

The full controller:
class Users::RegistrationsController < Devise::RegistrationsController
 before_action :configure_sign_up_params, only: [:create]
# before_action :configure_account_update_params, only: [:update]

  # POST /resource
  def create
    user_params     = sign_up_params[:user_params]
    entidade_params = sign_up_params[:entidade_params]

    if !(User.exists?(email: user_params[:email]) || Entidade.exists?(cnpj: entidade_params[:cnpj]))
      @entidade = Entidade.new(entidade_params)
      @entidade.data_validade = 30.days.from_now

      if @entidade.save
        @user = User.new(user_params)
        @user.entidade_id = @entidade.id
        if @user.save
          flash[:notice] = 'Usuario criado com sucesso.'
          redirect_to root_path
        end
      end
    end
  end
  protected

  # If you have extra params to permit, append them to the sanitizer.
  def configure_sign_up_params
    devise_parameter_sanitizer.permit(:sign_up, keys: [:nome, :password, :password_confirmation, :cnpj, :razao_social, :nome_fantasia, :email, :tipo_entidade_id])
  end
end

At first glance it seems like a bug in the gem, but no one seems to have this issue - google returns nothing relevant. Is this an error in my code?

A: I'm not sure if it was the case, but this error can occur if you duplicate the parameters sanitizer, like using it in users controller but also in application controller.
You can see a more detailed explanation here:
GitHub issue closed


text:
Q: Not marked as serializable error when serializing a class I am serializing an structure by using BinaryFormatter using this code:
private void SerializeObject(string filename, SerializableStructure objectToSerialize)
{
    Stream stream = File.Open(filename, FileMode.Create);
    BinaryFormatter bFormatter = new BinaryFormatter();
    bFormatter.Serialize(stream, objectToSerialize);
    stream.Close();
}

Which objectToSerialize is my structure, I'm calling this function like this:
SerializableStructure s = new SerializableStructure();
s.NN = NN;
s.SubNNs = SubNNs;
s.inputs = inputs;
SerializeObject(Application.StartupPath + "\\Save\\" + txtSave.Text + ".bin", s);

Which SerializableStructure, and Type of NN, SubNNs and inputs are serializable. (inputs contains some Points, Rectangles and generic lists).
Now, When I run my code, I am given this error:

Type 'MainProject.Main' in Assembly 'MainProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.

Why I'm given this error? Main is my form, and these variables are located in my form.
I have successfully serialized Type of NN with MemoryStream and VB.NET , But I don't know why I'm getting this error?
Here is the definition of my structures:
SerializableStructure:
[Serializable()]
public class SerializableStructure
{
    public List<Inputs> inputs = new List<Inputs>();
    public NeuralNetwork NN;
    public NeuralNetwork[] SubNNs;
}

Inputs:
[Serializable()]
public class Inputs
{
    public string XPath { get; set; }
    public string YPath { get; set; }
    public string ImagePath { get; set; }
    public string CharName { get; set; }
    public string CharBaseName { get; set; }
    public List<double> x { get; set; }
    public List<double> y { get; set; }
    public List<double> DotsX { get; set; }
    public List<double> DotsY { get; set; }
    public List<Point> GravityCenters { get; set; }
    public List<Rectangle> Bounds { get; set; }

    public override string ToString()
    {
        return CharName;
    }

    public Inputs(string xPath, string yPath, string imagePath, string charName, string charBaseName)
    {
        XPath = xPath;
        YPath = yPath;
        ImagePath = imagePath;
        CharName = charName;
        CharBaseName = charBaseName;
        x = new List<double>();
        y = new List<double>();
        GravityCenters = new List<Point>();
        Bounds = new List<Rectangle>();
    }
}

Also NN is very big structure(!).

A: The problem is that you are trying to serialize a class derived from Form.  The Form class is fundamentally unserializable.  It has an enormous amount of internal state that is highly runtime dependent.  That starts with an obvious property like Handle, a value that's always different.  Less obvious are properties like Size, dependent on user preferences like the size of the font for the window caption.  Ends with all the text, location and sizes for the controls, they are subject to localization.  The odds that a serialized Form object can be properly deserialized anywhere at any time to create an exact clone of the form are zero.
Microsoft made no bones about it when they wrote the code, they simply omitted the [Serializable] attribute from the class declaration.  Which is why you get the exception.
You'll have to aim lower, write your own class to capture your form's state.  And give it the attribute.  You'll need to write a bunch of code that maps between the form and control properties to an object of that class, back and forth.

A: This almost alwas means you have an event (or other delegate - maybe a callback) somewhere in your object model, that is trying to be serialized. Add [NonSerialized] to any event-backing fields. If you are using a field-like event (the most likely kind), this is:
[field:NonSerialized]
public event SomeDelegateType SomeEventName;

Alternatively: most other serializers don't look at events/delegates, and provide better version-compatibility. Switching to XmlSerializer, JavaScriptSerializer, DataContractSerializer or protobuf-net (just 4 examples) would also solve this by the simple approach of not trying to do this (you almost never intend for events to be considered as part of a DTO).


text:
Q: Simplephp and arrays I'm simply iterating through nodes and adding the name of the node to an array but it is creating it as multidimensional array instead of one dimensional.
$arrayname[] = attribute['name'];

How do I get this to build as a one dimensional array? I need it this way as I'm checking to see if a value exists before adding it using in_array.
Right now I get
[0] SimpleXMLElement Object
(
  [0] => bob

)

A: SimpleXMLElements have to be cast to string type to use as a string. Change your code to this (assuming your attributes array is $attribute):
$arrayname[] = (string)$attribute['name'];


text:
Q: How to print TRUNC(SYSDATE) how can I get SQL to return me the value of TRUNC(SYSDATE) I know in unix it would be echo does SQL have an equivalent?
Cheers,

A: For Oracle:
select trunc(sysdate) from dual;

(like stated above Oracle requires a dummy table "dual")


text:
Q: Angular JS controller called twice (ng-controller) I'm developping an ionic application and when using angular for login my controller is called twice,
I've looked through all the others similar questions but didn't find a solution .
The problem is even when I remove the ng-controller="LoginCtrl as lgnCtrl"
I get my controller called once but without two-way databinding.
here is my route file :
$stateProvider
.state('login', {
  url: "/login",
  views: {
    'main': {
      templateUrl: "app/user/loginView.html",
      controller: "LoginCtrl",
      controllerAs: "lgnCtrl"
    }
  }
})

  $urlRouterProvider.otherwise('/login');

here is my controller
angular.module('starter.controllers')
.controller('LoginCtrl', LoginCtrl);

function LoginCtrl($state, $storage, $translate, $ionicPopup, LoginService, messageService) {
    var lgnCtrl = this;
    console.log("user dash 1zz");
    return lgnCtrl;
}

and here is my views:
loginView.html :
<ion-view view-title="loginView" id="signinBlk">
   <ion-content>
       <div class="list list col span_1_of_2 "  ng-controller="LoginCtrl as lgnCtrl">
   </div>
   </ion-content>
</ion-view>

index.html:
<body ng-app="starter">
  <ion-nav-view name="main"></ion-nav-view>
</body>

A: if you already define your controller in route you dont need to define controller in html template remove the ng-controller attribute with value form html template then run it will run just once

A: Instead of having this
ng-controller="LoginCtrl as lgnCtrl"
in html, we can have this in the controller when the route is defined with a controller, for example in the controller, it will go like this
$routeProvider
        .when("/", { templateUrl: "views/abc.html", controller: "LoginCtrl as lgnCtrl", caseInsensitiveMatch: true });

it worked like a charm
the functions in the controller are only called once.


text:
Q: Can a service worker built with Google's sw-precache really be networkFirst? I run the website https://www.igluonline.com running Hugo and I recently installed a service worker following Google's sw-precache.
This is the Config file:
module.exports = {
  staticFileGlobs: [
    'dist/css/**.css',
    'dist/**/*.html',
    'dist/images/**.*',
    'dist/js/**.js'
  ],
  skipWaiting: true,
  stripPrefix: 'dist',
  runtimeCaching: [{
    urlPattern: /\/*/,
    handler: 'networkFirst'
  }]
};

Considerations:
Although sometimes the automatic generated code runs into some erros, the service worker works properly and deliver the offline experience both on web and mobile.
Also it has cache-control set to max-age=0 and when I push a new code it makes the update.
Problem:
I set the runtimeCaching handler to networkFirst and according to Google's sw-toolbox API (which is present in sw-precache when using runtimeCaching) it should get the page preferably from the http call and if there is no connection it should fallback to the cache.
But when I refresh my code and open a new window to test (note that I do close all tabs and windows running the website prior to the update), it will show the cached page. It will naturally download the new service worker and on second reload update the page, but I don't expect my visitors to double refresh my homepage every time to get new content.
I try changing the runtimeCachingcode to the following hoping to get at least my homepage to load directly from the network, but I had no luck:
runtimeCaching: [{
    urlPattern: /\//,
    handler: 'networkOnly'
  },{
    urlPattern: /\/*/,
    handler: 'networkFirst'
  }]

Now I'm not sure if the desired PWA experience is like that - meaning that users have to reload twice or at least visit two pages to see the refreshed code - or if I'm making some mistake. I'd really appreciate a consideration.

A: When generating service-workers, the easiest way to get the policy you want, is by using sw-precache with sw-toolbox.
When generating a new service-worker withsw-precache, you can also get the sw-toolbox code at the end of the generated file by passing the correct configuration options.
According to the sw-precache Documentation:

The sw-precache module has the ability to include the sw-toolbox code and configuration alongside its own configuration. Using the runtimeCaching configuration option in sw-precache (see below) is a shortcut that accomplishes what you could do manually by importing sw-toolbox in your service worker and writing your own routing rules.

This is an example of the runtimeCaching option showed on the sw-precache documentation:
runtimeCaching: [{
  urlPattern: /^https:\/\/example\.com\/api/,
  handler: 'networkFirst'
}, {
  urlPattern: /\/articles\//,
  handler: 'fastest',
  options: {
    cache: {
      maxEntries: 10,
      name: 'articles-cache'
    }
  }
}]

You can use this option alongside your configuration of choice.
For example you can use a configuration file as stated in the documentation:

There's support for passing complex configurations using --config . Any of the options from the file can be overridden via a command-line flag. We strongly recommend passing it an external JavaScript file defining config via module.exports. For example, assume there's a path/to/sw-precache-config.js file that contains:
module.exports = {
  staticFileGlobs: [
    'app/css/**.css',
    'app/**.html',
    'app/images/**.*',
    'app/js/**.js'
  ],
  stripPrefix: 'app/',
  runtimeCaching: [{
    urlPattern: /this\\.is\\.a\\.regex/,
    handler: 'networkFirst'
  }]
};

That file could be passed to the command-line interface, while also
  setting the verbose option, via
$ sw-precache --config=path/to/sw-precache-config.js --verbose

This provides the most flexibility, such as providing a regular expression for the runtimeCaching.urlPattern option.

Or you can use a JSON file:

We also support passing in a JSON file for --config, though this provides less flexibility:
{
  "staticFileGlobs": [
    "app/css/**.css",
    "app/**.html",
    "app/images/**.*",
    "app/js/**.js"
  ],
  "stripPrefix": "app/",
  "runtimeCaching": [{
    "urlPattern": "/express/style/path/(.*)",
    "handler": "networkFirst"
  }]
}

This example uses the JS file for the configuration options:
$ sw-precache --config=path/to/sw-precache-config.js --verbose

After executing the command and generating the service-worker with this configurations, you can handle the precache and policies much easier than with just sw-precache.
You can configure your policies directly in the file or add them manually at the bottom of your service-worker code.
Here is the example of the bottom part of the generated code:
//sw-precache generated code...

// *** Start of auto-included sw-toolbox code. ***
/*
 Copyright 2016 Google Inc. All Rights Reserved.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*/
//(!function(e){if("object"==typeof exports&&"undefined"!=typeof module))...

// *** End of auto-included sw-toolbox code. ***

// Runtime cache configuration, using the sw-toolbox library.

toolbox.router.get(/this\\.is\\.a\\.regex/, toolbox.networkFirst, {});

toolbox.options.debug = true;

//Here you can configure your precache:

toolbox.precache([
    '/',
    '/assets/background.png',
    '/assets/logo.png',
    '/assets/application.css',
]);

//And here you can configure your policies for any route and asset:

toolbox.router.get('/', toolbox.fastest);
toolbox.router.get('/assets/background.png', toolbox.fastest);
toolbox.router.get('/assets/logo.png', toolbox.fastest);

//Here is the Network First example

toolbox.router.get('/myapp/index.html', toolbox.networkFirst);

I've found this much more effective and flexible than using just sw-precache.
Here you can find the sw-toolbox Usage Guide for more info on the configuration.


text:
Q: How to limit label string length in GridView with Read More link? Currently I used like this...
<asp:TemplateField HeaderText="Description">
 <ItemTemplate>
      <asp:Label ID="lblDescription" runat="server"
                Text='<%# Limit(Eval("Description"),40) %>' >
      </asp:Label>
 </ItemTemplate>

The helper function:
public static string Limit(object Desc, int length)
{
    StringBuilder strDesc = new StringBuilder();
    strDesc.Insert(0, Desc.ToString());

    if (strDesc.Length > length)
        return strDesc.ToString().Substring(0, length) + "..." + [Read More];
    else return strDesc.ToString();
}

But I have no idea how to put [Read More] link...

A: Do something like this.
Markup
<asp:TemplateField HeaderText="Description">
 <ItemTemplate>
      <asp:Label ID="lblDescription" runat="server"
                Text='<%# Limit(Eval("Description"),40) %>'
                Tooltip='<%# Eval("Description") %>'>
      </asp:Label>
      <asp:LinkButton ID="ReadMoreLinkButton" runat="server"
                Text="Read More"
                Visible='<%# SetVisibility(Eval("Description"), 40) %>'
                OnClick="ReadMoreLinkButton_Click">
      </asp:LinkButton>
 </ItemTemplate>
</asp:TemplateField>

And code-behind
protected bool SetVisibility(object desc, int maxLength)
{
    var description = (string)desc;
    if (string.IsNullOrEmpty(description)) { return false; }
    return description.Length > maxLength;
}

protected void ReadMoreLinkButton_Click(object sender, EventArgs e)
{
    LinkButton button = (LinkButton)sender;
    GridViewRow row = button.NamingContainer as GridViewRow;
    Label descLabel = row.FindControl("lblDescription") as Label;
    button.Text = (button.Text == "Read More") ? "Hide" : "Read More";
    string temp = descLabel.Text;
    descLabel.Text = descLabel.ToolTip;
    descLabel.ToolTip = temp;
}

protected string Limit(object desc, int maxLength)
{
    var description = (string)desc;
    if (string.IsNullOrEmpty(description)) { return description; }
    return description.Length <= maxLength ?
        description : description.Substring(0, maxLength)+ "...";
}

A: Add an invisible HtmlAnchor control after the Label.  Try something like,
<asp:TemplateField HeaderText="Description">
 <ItemTemplate>
      <asp:Label ID="lblDescription" runat="server"
                Text='<%# Limit(Eval("Description"),40) %>' >
      </asp:Label>
      [Read More]
 </ItemTemplate>

if(strDesc.Length > length)
{
    var anchor = ((Label)Desc).NamingContainer.FindControl("aReadMore");
    anchor.Visible = true;
    return strDesc.ToString().Substring(0, length) + "...";
}

A: You can use Modal Popup dialog box:
In ASP.Net page:


text:
Q: Animation doesnt work when onClick event occurs (react.js) I'm creating a simple hamburger menu and I want to add new className to  element when onClick event occurs. This new className should transform the  element, but when onClick occurs element  dissapears, animation doesn't work. I understand the problem is in classes.line[i] part, but what could be the problem maybe someone can help me here.
link to the example https://repl.it/@RokasSimkus/DelectableFrugalMuse
jsx:
   const menu = (props) =>{
  let lineArray= ['', '', ''];
  let lines= lineArray.map((lineArray, i) => {
  return
});
console.log(props.active);
  return(
  <>

{lines}

</>
)
};

css code:
 @media(min-width: 500px){
  .hamburger{
        display: none;
  }
}
.hamburger {
left: 0;
top: 0;
}
.hamburger .line {
  display: block;
  width: 30px;
  height: 2px;
  background-color: white;
  margin: 8px 0;
  transition: all 0.3s ease-in-out;
}

.hamburger:hover {
  cursor: pointer;
  .line:nth-of-type(1) {
    transform: translateX(15px);
    width: 40px;
  }
}

.hamburger .line1 {
  transform: translate(4px, 1px) rotate(45deg);
  width: 18px;
}

.hamburger .line2 {
  transform: rotate(-45deg);
  width: 51px;
}

.hamburger .line3 {
  transform: translate(14px, 4px) rotate(45deg);
  width: 28px;
  transform-origin: bottom right;
}

A: If I change the line you marked to the following, it works:
return <span key={"classes.line" + i} className={`${classes.line} ${props.active ? `${classes["line" + i]}` : ''}`}>

To show anything, your lines need the class .line. To be in the "active" state, they need to add their respective .lineX class to add the transform you want to see. As you need both classes at the same time, you need to put both into the className property, which I've done here by putting them together into a string.
I'd suggest to change your CSS and add an active class to your menu.
The underlying problem is that you need to add multiple classes to your elements at some point. You can do that with string interpolation like I showed above (same would be for adding an active class to .menu) or you could use a module like classnames which does a great job concatenating classes. Thus you could write
return

I'd still suggest to create an active modifier class on your "root" element of your component, to keep modifiers on the top level and your code a bit more understandable. Here is your modified example.


text:
Q: Picocli Parse Search String I would like to provide a search string for my program like:
cmd.execute("getDevices", "-h 1.2.3.4", "-p myPSW", "-u myUser", "-n red|blue&black,-nonprod");

I want to create predicates to search for hostNames that contain red OR blue AND Black, but NOT nonprod. It is unclear to me how to go about parsing this the logical operators along with the Strings in Picocli to create a Predicate. Is there a simple and Straight forward way to parse a String to a predicate?
My CLI is set up as follows:
@Command(name = "HostMagicCLI", mixinStandardHelpOptions = true,
        version = "1.0",
        description = "Do Stuff With Hosts"
        ,
        subcommands = {TufinDevices.class}
)

public class HostMagicCLI implements Runnable {

    public static void main(String[] args) {
        CommandLine cmd = new CommandLine(new InterfaceMagicCLI());
        cmd.setExecutionStrategy(new RunAll());
        cmd.getHelpSectionMap().put(SECTION_KEY_COMMAND_LIST, new MyCommandListRenderer());
        cmd.usage(System.out);
        cmd.execute("getDevices", "-h1.2.3.4", "-p myPSW", "-u myUser", "-n red|blue&black");

    }

    @Override
    public void run() {
        System.out.println("Running..");
    }
     }

@Command(name = "getDevices", aliases = {"l"}, description = "SpecifyTufin Credentials", subcommands = {InterfaceCommand.class})

class TufinDevices implements Runnable {
 .
 .//Options to collect user,psw, host etc.
 .
@CommandLine.Option(names = {"-n", "--n"}, split = ",", arity = "0..*", description = "Hostname Contains")
String[] hostNameContains;
private void filter(TufinDeviceCollection<TufinDevice> devices) {
    if (hostNameContains != null) {
        Predicate< ? super TufinDevice> deviceFilter = device -> Arrays.stream(hostNameContains)
                .allMatch(input -> device.getHostName().toLowerCase().contains(input.toLowerCase()));

        devices = devices.stream()
                .sequential()
                .filter(deviceFilter)
                .collect(Collectors.toCollection(TufinDeviceCollection<TufinDevice>::new));
    }
@Override
public void run() {
    try {
        TufinDeviceCollection<TufinDevice> FETCH_DEVICES = Tufin.FETCH_DEVICES(user.trim(), password.trim(), hostName.trim());
        this.filter(FETCH_DEVICES);
    } catch (IOException | NoSuchAlgorithmException | KeyManagementException | IPConverter.InvalidIPException ex) {
        Logger.getLogger(TufinDevices.class.getName()).log(Level.SEVERE, null, ex);
    }

}

}

A: I suspect you may want to use a library for parsing the string that the end user specifies as the filter expression (the -n parameter). It may be an idea to look at libraries like Spring Expression Language, OGNL, JXPath, there may be others. Alternatively, if it is easy to write such a filter in Groovy or BeanShell, these languages can be called from Java, so you can call that filter from the Java command.

CAUTION:
I notice the example passes parameter to the picocli parser like this:
cmd.execute("getDevices", "-h 1.2.3.4", "-p myPSW", "-u myUser", "-n red|blue&black,-nonprod");

This will probably give an error explaining that "there is no -p myPSW option defined".
In your testing, if you call the execute method directly, make sure to pass parameters separately like this:
cmd.execute("getDevices", "-h", "1.2.3.4", "-p", "myPSW", "-u", "myUser", "-n", "red|blue&black,-nonprod");


text:
Q: Update an entity with additional clause I'm currently working on a column-based multitenant app.
I added tenantId on each entity with a base class, and used query filters which fits perfectly my needs.
I also overrided savechanges method to populate tenantid property on added entities using the changetracker.
But now i'm stuck with update and delete.
As far as i know, ef generates a where clause with only primary key, which is very unsafe for me, because i work on an api environment with a lot of attach/detach stuff, and wrote a lot of entity.state = modified instead of querying first, in order to improve performance.
My question is : how to add a predicate to an ef core update/delete statement ?
I know that i can :
1. Query first (and i'm pretty sure you'll recommand me this)
2. Make tenantid as a part of a compositekey, but this would really be painfull to refactor all my code as the add/find/etc. Methods need full primary keys.
I would be really gratefull to anyone who knows how to trigger this !

A: Option 3:
Although not designed for that, you can use EF Core Optimistic concurrency control to perform that safety checks for you:

On relational databases EF Core includes a check for the value of the concurrency token in the WHERE clause of any UPDATE or DELETE statements. After executing the statements, EF Core reads the number of rows that were affected.
  If no rows are affected, a concurrency conflict is detected, and EF Core throws DbUpdateConcurrencyException.

The idea is (1) to mark the TenantId as concurrency token by either [ConcurrencyCheck] attribute or IsConcurrencyToken() fluent API, and (2) inside your SaveChanges override, set the TenantId property value with the current tenant Id not only for added, but also for modified and deleted entities.
By doing that, EF Core will add something like AND TenantId == @currentTenantId to UPDATE and DELETE commands, which will succeed only if the current tenant matches the one used for entity creation.
The drawback is the exception type/message, and mixing with the existing concurrency checks if used.
Update: The code for modified and deleted entities inside SaveChanges should set the OriginalValue of the TenantId property entry and reset the IsModified flag:
var tenantIdEntry = entityEntry.Property("TenantId");
tenantIdEntry.OriginalValue = CurrentTenantId;
tenantIdEntry.IsModified = false;

The last is not needed if the TenantId property is configured with AfterSaveBehavior = PropertySaveBehavior.Ignore as explained in What is the best way to perform partial updates in EF core and never update certain properties?.


text:
Q: No CMAKE_C_COMPILER could be found even after trying all generators I am using Visual Studio 2015 Basic. I tried all the 3 generators(Visual Studio 14 2015, Visual Studio 14 2015 Win64, and Visual Studio 14 2015 ARM ). still I am getting the this error.

No CMAKE_C_COMPILER could be found.
No CMAKE_CXX_COMPILER could be found.

Is there any thing else that I can do to troubleshoot the error.