text:
Q: What's the practical value of all those newtype wrappers in `Data.Monoid`? When looking at Data.Monoid, I see there are various newtype wrappers, such as All, Sum, or Product, which encode various kinds of monoids. However, when trying to use those wrappers, I can't help but wonder what's the benefit over using their non-Data.Monoid counterparts. For instance, compare the rather cumbersome summation
print $ getSum $ mconcat [ Sum 33, Sum 2, Sum 55 ]

vs. the more succinct idiomatic variant
print $ sum [ 33, 2, 55 ]

But what's the point? Is there any practical value having all those newtype wrappers? Are there more convincing examples of Monoid newtype wrapper usage than the one above?

A: How about in an instance like this:
myData :: [(Sum Integer, Product Double)]
myData = zip (map Sum [1..100]) (map Product [0.01,0.02..])

main = print $ mconcat myData

Or without the newtype wrapper and the Monoid instance:
myData :: [(Integer, Double)]
myData = zip [1..100] [0.01,0.02..]

main = print $ foldr (\(i, d) (accI, accD) -> (i + accI, d * accD)) (0, 1) myData

This is due to the fact that (Monoid a, Monoid b) => Monoid (a, b).  Now, what if you had custom data types and you wanted to fold over a tuple of these values applying a binary operation?  You could simply write a newtype wrapper and make it an instance of Monoid with that operation, construct your list of tuples, then just use mconcat to fold across them.  There are many other functions that work on Monoids as well, not just mconcat, so there are certainly a myriad of applications.

You could also look at the First and Last newtype wrappers for Maybe a, I can think of many uses for those.  The Endo wrapper is nice if you need to compose a lot of functions, the Any and All wrappers are good for working with booleans.

A: Suppose you are working in the Writer monad and you want to store the sum of everything you tell. In that case you would need the newtype wrapper.
You would also need the newtype to use functions like foldMap that have a Monoid constraint.
The ala and alaf combinators from Control.Lens.Wrapped in the lens package can make working with these newtypes more pleasant. From the documentation:
>>> alaf Sum foldMap length ["hello","world"]
10

>>> ala Sum foldMap [1,2,3,4]
10

A: Sometimes you just end up needing a particular Monoid to fill a type constraint. One place that shows up sometimes is that Const has an Applicative instance iff it stores a Monoid.
instance Monoid m => Applicative (Const m) where
  pure _ = Const mempty
  Const a <*> Const b = Const (a <> b)

That's obviously a bit bizarre, but sometimes it's what you need. The best example I know is in lens where you end up with types like
type Traversal s a = forall f . Applicative f => (a -> f a) -> (s -> f s)

If you specialize f to something like Const First using the Monoid newtype First
newtype First a = First { getFirst :: Maybe a }

-- Retains the first, leftmost 'Just'
instance Monoid (First a) where
  mempty = First Nothing
  mappend (First Nothing)  (First Nothing) = First Nothing
  mappend (First (Just x)) _               = First (Just x)

then we can interpret that type
(a -> Const (First a) a) -> (s -> Const (First a) s)

as scanning through s and picking up the first a inside of it.

So, while that's a really specific answer the broad response is that it's sometimes useful to be able to talk about a bunch of different default Monoid behaviors. Somebody had to write all the obvious Monoid behaviors, anyway, and they might as well be put in Data.Monoid.

A: Monoid newtypes: A zero space no-op to tell the compiler what to do
Monoids are great to wrap an existing data type in a new type to tell the compiler what operation you want to do.
Since they're newtypes, they don't take any additional space and applying Sum or getSum is a no-op.
Example: Monoids in Foldable
There's more than one way to generalise foldr (see this very good question for the most general fold, and this question if you like the tree examples below but want to see a most general fold for trees).
One useful way (not the most general way, but definitely useful) is to say something's foldable if you can combine its elements into one with a binary operation and a start/identity element. That's the point of the Foldable typeclass.
Instead of explicitly passing in a binary operation and start element, Foldable just asks that the element data type is an instance of Monoid.
At first sight this seems frustrating because we can only use one binary operation per data type - but should we use (+) and 0 for Int and take sums but never products, or the other way round? Perhaps should we use ((+),0) for Int and (*),1 for Integer and convert when we want the other operation? Wouldn't that waste a lot of precious processor cycles?
Monoids to the rescue
All we need to do is tag with Sum if we want to add, tag with Product if we want to multiply, or even tag with a hand-rolled newtype if we want to do something different.
Let's fold some trees! We'll need
fold :: (Foldable t, Monoid m) => t m -> m
   -- if the element type is already a monoid
foldMap :: (Foldable t, Monoid m) => (a -> m) -> t a -> m
   -- if you need to map a function onto the elements first

The DeriveFunctor and DeriveFoldable extensions ({-# LANGUAGE DeriveFunctor, DeriveFoldable #-}) are great if you want to map over and fold up your own ADT without writing the tedious instances yourself.
import Data.Monoid
import Data.Foldable
import Data.Tree
import Data.Tree.Pretty -- from the pretty-tree package

see :: Show a => Tree a -> IO ()
see = putStrLn.drawVerticalTree.fmap show

numTree :: Num a => Tree a
numTree = Node 3 [Node 2 [],Node 5 [Node 2 [],Node 1 []],Node 10 []]

familyTree = Node " Grandmama " [Node " Uncle Fester " [Node " Cousin It " []],
                               Node " Gomez - Morticia " [Node " Wednesday " [],
                                                        Node " Pugsley " []]]

Example usage
Strings are already a monoid using (++) and [], so we can fold with them, but numbers aren't, so we'll tag them using foldMap.
ghci> see familyTree
               " Grandmama "
                     |
        ----------------------
       /                      \
" Uncle Fester "     " Gomez - Morticia "
       |                      |
 " Cousin It "           -------------
                        /             \
                  " Wednesday "  " Pugsley "
ghci> fold familyTree
" Grandmama  Uncle Fester  Cousin It  Gomez - Morticia  Wednesday  Pugsley "
ghci> see numTree
     3
     |
 --------
/   |    \
2   5    10
    |
    --
   /  \
   2  1

ghci> getSum $ foldMap Sum numTree
23
ghci> getProduct $ foldMap Product numTree
600
ghci> getAll $ foldMap (All.(<= 10)) numTree
True
ghci> getAny $ foldMap (Any.(> 50)) numTree
False

Roll your own Monoid
But what if we wanted to find the maximum element? We can define our own monoids. I'm not sure why Max (and Min) aren't in. Maybe it's because no-one likes thinking about Int being bounded or they just don't like an identity element that's based on an implementation detail. In any case here it is:
newtype Max a = Max {getMax :: a}

instance (Ord a,Bounded a) => Monoid (Max a) where
   mempty = Max minBound
   mappend (Max a) (Max b) = Max $ if a >= b then a else b

ghci> getMax $ foldMap Max numTree :: Int  -- Int to get Bounded instance
10

Conclusion
We can use newtype Monoid wrappers to tell the compiler which way to combine things in pairs.
The tags do nothing, but show what combining function to use.
It's like passing the functions in as an implicit parameter rather than an explicit one (because that's kind of what a type class does anyway).

A: The basic idea, I think, is that you can have something like
reduce = foldl (<>) mempty

and it'll work for any list of those wrapped things.


text:
Q: Choosing knockout or kendo I have requirement to use kendo controls for my application as well as mvvm bindings.
I went through this articles
article 1
article 2
and found that all articles are aligned to kendo. Could you please let me know why so and could you please share the advantages and disadvantages?

A: If you wish to use both together, Knockout and Kendo (with MVVM), You just need to use Knockout-Kendo.js.

*

*Knockout-Kendo.js is a project to create a complete and robust set of Knockout.js bindings for the Kendo UI widgets. Examples and Configurations available there itself.

Knockout.js is an open source library that supports declarative data binding, dependency tracking, and automatic UI updates.
Kendo UI, by Telerik, provides fast, clean, and configurable HTML5 UI widgets as part of a jQuery-based framework to support modern web development.
Note: #2 Article link has the Answer (Answered By Covo).
I would suggest you to use both together (Knockout (MVVM) and Kendo with Knockout-Kendo.js), Since Knockout-Kendo.js is very much matured to use.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make Intel wi-fi signal stronger in Ubuntu Gnome 16.04 or 18.04? For some reason I don't know, my wifi signal is very weak in Linux but is ok in Windows. The speed doesn't seem to be the issue, but something related with the strength of the wifi signal itself.
I am using ASUS N580VD-DM129T and I have iwlwifi driver for Intel(R) Dual Band Wireless AC 8265 in Linux Ubuntu 16.04 with Gnome. (I checked the name of the network card using dmesg | grep iwlwifi and looked for the output line "Detected Intel(R) Dual Band Wireless AC 8265, REV=0x230"). I also tried running Ubuntu 18.04 and still had the same problem.
The output when I run dmesg | grep iwlwifi is the following:
[    3.347436] iwlwifi 0000:03:00.0: enabling device (0000 -> 0002)
[    3.386096] iwlwifi 0000:03:00.0: Direct firmware load for iwlwifi-8265-33.ucode failed with error -2
[    3.388185] iwlwifi 0000:03:00.0: Direct firmware load for iwlwifi-8265-32.ucode failed with error -2
[    3.397339] iwlwifi 0000:03:00.0: loaded firmware version 31.560484.0 op_mode iwlmvm
[    3.412232] iwlwifi 0000:03:00.0: Detected Intel(R) Dual Band Wireless AC 8265, REV=0x230
[    3.472665] iwlwifi 0000:03:00.0: base HW address: 88:b1:11:5e:93:f4
[    3.550283] iwlwifi 0000:03:00.0 wlp3s0: renamed from wlan0

I thought it was weird that the loading fails twice before succeeding and wondered if that was the problem but it is not because of this. I installed iwlwifi-8265-ucode-22.361476.0.tgz available at https://wireless.wiki.kernel.org/en/users/Drivers/iwlwifi and it fails many times (33, 32, 31, until 23, and then work with version 22). So it is just searching for the available version.
I have also tried changing some options in the iwlwifi module as suggested here. But it didn't work. More precisely, I added options iwlwifi 11n_disable=1 swcrypto=1 to the end of the file /etc/modprobe.d/iwlwifi.conf. Leaving me with the following content in it:
remove iwlwifi \
(/sbin/lsmod | grep -o -e ^iwlmvm -e ^iwldvm -e ^iwlwifi | xargs /sbin/rmmod) \
&& /sbin/modprobe -r mac80211
options iwlwifi 11n_disable=1 swcrypto=1

This didn't work even when I ran $sudo modprobe -rv iwlwifi to remove the module and then $sudo modprobe -v iwlwifi to add it again.
EDIT 2: I also tried with Linux 17.10 and 18.04 and still had the same problem (weak signal compared to Windows).
EDIT 3: Trying what was suggested for realtek did not work either:
sudo modprobe -v iwlwifi ant_sel=2
https://connectwww.com/how-to-solve-realtek-rtl8723be-weak-wifi-signal-problem-in-ubuntu/4625/
EDIT 5: Trying to alter power management running
 sudo sed -i 's/wifi.powersave = 3/wifi.powersave = 2/'  /etc/NetworkManager/conf.d/default-wifi-powersave-on.conf

and then systemctl restart network-manager.service didn't work either.
This was suggested here and here. This link explains how to do it.
EDIT 4: When I run $ nmcli dev wifi list I get the following results:
*  SSID           MODE   CHAN  RATE       SIGNAL  BARS  SECURITY
   neuromancer    Infra  11    54 Mbit/s  59      ▂▄▆_  WPA2
*  waffles        Infra  11    54 Mbit/s  48      ▂▄__  WPA2
   Stephens_iMac  Infra  11    54 Mbit/s  47      ▂▄__  WPA2
   eduroam        Infra  11    54 Mbit/s  45      ▂▄__  WPA2 802.1X
   mac-sfg003     Infra  11    54 Mbit/s  42      ▂▄__
   Crumpet        Infra  11    54 Mbit/s  37      ▂▄__

Neuromancer is actually 2.5 meters from me and still is not full strength.
(Note that EDIT 4 and EDIT 1 were run in different days, hence the different networks found)
EDIT 1:
Running $ sudo iwlist scan gives me the following output
 lo        Interface doesn't support scanning.

 enp4s0    Interface doesn't support scanning.

 wlp3s0    Scan completed :
           Cell 01 - Address: 58:97:1E:72:D0:A1
                     Channel:1
                     Frequency:2.412 GHz (Channel 1)
                     Quality=46/70  Signal level=-64 dBm
                     Encryption key:on
                     ESSID:"eduroam"
                     Bit Rates:12 Mb/s; 18 Mb/s; 24 Mb/s; 36 Mb/s; 48 Mb/s
                               54 Mb/s
                     Mode:Master
                     Extra:tsf=00000078646f81d9
                     Extra: Last beacon: 4328ms ago
                     IE: Unknown: 0007656475726F616D
                     IE: Unknown: 01061824B048606C
                     IE: Unknown: 030101
                     IE: Unknown: 050700010900200000
                     IE: Unknown: 0706474220010D14
                     IE: Unknown: 0B051B006F093D
                     IE: Unknown: 200100
                     IE: Unknown: 2A0100
                     IE: Unknown: 2D1A2C181BFFFF000000000000000000000000000000000000000000
                     IE: IEEE 802.11i/WPA2 Version 1
                         Group Cipher : CCMP
                         Pairwise Ciphers (1) : CCMP
                         Authentication Suites (1) : 802.1x
                     IE: Unknown: 3603E21600
                     IE: Unknown: 3D1601000700000000000000000000000000000000000000
                     IE: Unknown: 460573C0000000
                     IE: Unknown: 7F06001000000140
                     IE: Unknown: 851E27008F000F00FF035900636E63622D6C61625F617265615F6C001B000036
                     IE: Unknown: 9606004096001100
                     IE: Unknown: DD180050F2020101800003A44F0027A44F004243800072324100
                     IE: Unknown: DD06004096010104
                     IE: Unknown: DD050040960305
                     IE: Unknown: DD050040960B69
                     IE: Unknown: DD050040961409
                     IE: Unknown: DD16000B85F800015AA6AA0DD0F287C653371F84DC6C1608
           Cell 02 - Address: 58:97:1E:72:D0:A0
                     Channel:1
                     Frequency:2.412 GHz (Channel 1)
                     Quality=47/70  Signal level=-63 dBm
                     Encryption key:off
                     ESSID:"OWL"
                     Bit Rates:12 Mb/s; 18 Mb/s; 24 Mb/s; 36 Mb/s; 48 Mb/s
                               54 Mb/s
                     Mode:Master
                     Extra:tsf=0000007864711990
                     Extra: Last beacon: 4272ms ago
                     IE: Unknown: 00034F574C
                     IE: Unknown: 01061824B048606C
                     IE: Unknown: 030101
                     IE: Unknown: 050F000108002000000000000000010000
                     IE: Unknown: 0706474220010D14
                     IE: Unknown: 0B051B006F093D
                     IE: Unknown: 2A0100
                     IE: Unknown: 2D1A2C181BFFFF000000000000000000000000000000000000000000
                     IE: Unknown: 3D1601000700000000000000000000000000000000000000
                     IE: Unknown: 7F06001000000140
                     IE: Unknown: 851E27008F000F00FF035900636E63622D6C61625F617265615F6C001B000036
                     IE: Unknown: 9606004096001100
                     IE: Unknown: DD180050F2020101800003A44F0027A44F004243800072324100
                     IE: Unknown: DD06004096010104
                     IE: Unknown: DD050040960305
                     IE: Unknown: DD050040960B09
                     IE: Unknown: DD050040961408
                     IE: Unknown: DD16000B85F800015AA6AA0D68445B38B7430C870C13ED10
           Cell 03 - Address: 28:F0:76:49:02:32
                     Channel:11
                     Frequency:2.462 GHz (Channel 11)
                     Quality=40/70  Signal level=-70 dBm
                     Encryption key:on
                     ESSID:"Stephens_iMac"
                     Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 18 Mb/s
                               24 Mb/s; 36 Mb/s; 54 Mb/s
                     Bit Rates:6 Mb/s; 9 Mb/s; 12 Mb/s; 48 Mb/s
                     Mode:Master
                     Extra:tsf=0000073adbc53791
                     Extra: Last beacon: 3732ms ago
                     IE: Unknown: 000D5374657068656E735F694D6163
                     IE: Unknown: 010882848B962430486C
                     IE: Unknown: 03010B
                     IE: Unknown: 2A0100
                     IE: Unknown: 32040C121860
                     IE: IEEE 802.11i/WPA2 Version 1
                         Group Cipher : CCMP
                         Pairwise Ciphers (1) : CCMP
                         Authentication Suites (1) : PSK
                     IE: Unknown: 2D1AAD4917FFFFFF0000000000000000000000000000000000000000
                     IE: Unknown: 3D160B000400000000000000000000000000000000000000
                     IE: Unknown: 7F080400000000000040
                     IE: Unknown: DD150017F209000108694D616331372C31010103010000
                     IE: Unknown: DD180050F2020101800003A4000027A4000042435E0062322F00
           Cell 04 - Address: 58:97:1E:72:D0:AE
                     Channel:100
                     Frequency:5.5 GHz (Channel 100)
                     Quality=32/70  Signal level=-78 dBm
                     Encryption key:on
                     ESSID:"eduroam"
                     Bit Rates:24 Mb/s; 36 Mb/s; 48 Mb/s; 54 Mb/s
                     Mode:Master
                     Extra:tsf=00000352afa2581c
                     Extra: Last beacon: 2160ms ago
                     IE: Unknown: 0007656475726F616D
                     IE: Unknown: 0104B048606C
                     IE: Unknown: 050400010100
                     IE: Unknown: 070C47422024081764051784031E
                     IE: Unknown: 0B05010006093D
                     IE: Unknown: 200100
                     IE: Unknown: 2D1A6E181BFFFF000000000000000000000000000000000000000000
                     IE: IEEE 802.11i/WPA2 Version 1
                         Group Cipher : CCMP
                         Pairwise Ciphers (1) : CCMP
                         Authentication Suites (1) : 802.1x
                     IE: Unknown: 3603E21600
                     IE: Unknown: 3D1664050400000000000000000000000000000000000000
                     IE: Unknown: 460573C0000000
                     IE: Unknown: 7F06001000000140
                     IE: Unknown: 851E03008F000F00FF035900636E63622D6C61625F617265615F6C0001000035
                     IE: Unknown: 9606004096001100
                     IE: Unknown: DD180050F2020101800003A44F0027A44F004243800072324100
                     IE: Unknown: DD06004096010104
                     IE: Unknown: DD050040960305
                     IE: Unknown: DD050040960B69
                     IE: Unknown: DD050040961409
                     IE: Unknown: DD16000B85F800015AA6AA0F1A1ABC93574E004A621EB445


text:
Q: is it feasible to have a reference in a namespace? So this is what I have:
//graphics.hpp
#include guard

extern camera_c default_camera;

namespace graphics {
    camera_c &camera = default_camera;
};

#endif

//graphics.cpp

camera_c default_camera(ctor stuff);

//main.cpp

#include <graphics.hpp>

int main() {
    do stuff with graphics::camera;
}

and this gives me
main.o: multiple definition of graphics::camera
graphics.o: first defined here

I've also tried doing
camera_c &&camera = camera_c(ctor stuff);

And that gives me the same error, but from main.cpp and graphics.cpp
So my question is
Is there some feasible way to have a reference to a class in that namespace? Or should I just use a pointer? Ideally it should be a reference, but that might not be possible.

A: You're misunderstanding the error.
The error is telling you that main.cpp and graphics.cpp both included graphics.hpp, which violates the One Definition Rule.
Make that variable extern as well:
namespace graphics {
    extern camera_c &camera;
};

And define it in one source file only.
namespace graphics {
    camera_c &camera = default_camera;
};

A: What about...
// graphics.hpp
namespace graphics {
    extern camera_c camera;
}

// graphics.cpp
#include <graphics.hpp>

namespace graphics {
    camera_c camera(...);
}

I must add that globally defined variables is bad style; unless you are dealing with legacy APIs, they cause more problems than it's worth!


text:
Q: Reading files from loops I have the following part of the code that contains two loops. I have some txt files, which I want to be read and analyzed in R separately, one by one. Currently, I face a problem of importing them to R. For example, the name of the first file is "C:/Users/User 1/Documents/Folder 1/1 1986.txt". To read it in R I have made the following loop:
## company
for(i in 1)
{
  ## year
  for(j in 1986)
  {
    df=read.delim(paste("C:/Users/User 1/Documents/Folder 1/", i, j, ".txt"), stringsAsFactors=FALSE, header=FALSE)
    df<-data.frame(rename(df, c("V3"="weight")))
  }
}

When I run the loop, I get the following error:
Error in file(file, "rt") : cannot open the connection
In addition: Warning message:
In file(file, "rt") :
  cannot open file 'C:/Users/User 1/Documents/Folder 1/ 13 1986 .txt': No such file or directory

How do I avoid those additional gaps that R assumes to exist in the name of the original file?

A: You should replace paste with paste0.
By default, paste use spaces as a separator, thus yielding the obtained result. And paste0 use nothing as a separator.

A: Because I don't know how your files look like exactly, maybe this won't help you... But this is how I read in files with a loop:
First: setting the working directory
setwd("/Users/User 1/Documents/Folder 1")
Then I always save my data as one excel file with different sheets. For this example I have 15 different sheets in my excel file named 2000-2014, the first sheet is called "2000", the second "2001" and so on.
sheets <- list() # creating empty list named sheets
for(i in 1:15){
 sheets[[i]] <- read_excel("2000-2014.xlsx", sheet = i) # every sheet will be one layer of the list sheets
 k <- c(2000:2014)
 sheet[[i]]$Year <- k[i] # to every listlayer I add a column "Year", matching the actual year my data is from
}

No I want my data from 2000 to 2014 merged in one big data frame. I can still analyse them one by one!
data <- do.call(rbind.data.frame, sheets)

To tidy my data all in one and to get it into the form Hadley Wickham and ggplot2 like it (http://vita.had.co.nz/papers/tidy-data.pdf) I restructure it:
data_restructed <- data %>%
  as.data.frame() %>%
  tidyr::gather(key = "categories", value = "values", 2:12)

2:12 because in my case columns 2:12 contain all the values while column 1 contains countrienames. Now you have all your data in one big dataframe and can analyse them seperated to specific variables like the year or the category or year AND category and so on.

A: I would avoid the loop in this case and go with lapply.
Files <- list.files('C:/Users/User 1/Documents/Folder 1/', pattern = "*.txt")

fileList <- lapply(Files, FUN =- function(x){
  df <- read.delim(x, stringsAsFactors=FALSE, header=FALSE)
  df <- data.frame(rename(df, c("V3"="weight")))
  return(df)
})

do.call('rbind', fileList)


text:
Q: XPath expression doesn't work I have an XML file like this :
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT family (person)+>
<!ELEMENT person (name) >
<!ATTLIST person idnum ID #REQUIRED
gender (male | female) #REQUIRED
father IDREF #IMPLIED
mother IDREF #IMPLIED
children IDREFS #IMPLIED >
<!ELEMENT name (#PCDATA)>

<?xml version="1.0"?>
<!DOCTYPE family SYSTEM "family.dtd">
<family>
<person idnum = "T11" gender = "male" children ="T13 T14 T15"><name>11</name></person>
<person idnum = "T12" gender = "female" children ="T13 T14 T15"><name>12</name></person>
<person idnum = "T13" gender = "male" father="T11" mother="T12"><name>13</name></person>
<person idnum = "T14" gender = "male" father="T11" mother="T12"><name>14</name></person>
<person idnum = "T15" gender = "female" father="T11" mother="T12" children="T33"><name>15</name></person>
<person idnum = "T21" gender = "male" children="T23"><name>21</name></person>
<person idnum = "T22" gender = "female" children="T23"><name>22</name></person>
<person idnum = "T23" gender = "male" father="T21" mother="T22" children="T33"><name>23</name></person>
<person idnum = "T33" gender = "female" father="T23" mother="T15"><name>33</name></person>
</family>

I want to check the queries :

*

*All the people with no children (both male & female)

*All the people with no male children (ie. SONS)
I've tried :

*

*/family/person[count(children)==0]

*/family/person[count(children)==0 and children!=male]
But it doesn't work .
Can you please explain ? thanks .

A: The equals operator in XPath is "=", not "==".
Writing children!=male was presumably wishful thinking, you didn't really imagine that would work, I hope.
Presumably someone with no children might be represented either by having no @children attribute or by having the attribute present but blank. You can cover both cases for your first query by testing /family/person[normalize-space(@children)='']
The second query is more difficult, because it involves a join. XPath 1.0 cannot handle every join query; XPath 2.0 can. You don't say which you are using. Another complication is that the id() function can be a little bit erratic: the processing pipeline doesn't always retain information about which attributes are IDs. But assuming id() works in your environment, you can do the second query (in either XPath 1.0 or 2.0) as
/family/person[not(id(@children)[@gender='male'])]

A: These xpath are not correct. You are tryiing to find children-elements, but they are attributes.
It should be something like this:
//person[not(@children)]

A: *

*You use "person" like a xml-tag, but its an tag-attribute. So you better use @children.

*The use of count(@children) wont work because there is only one attribute named children

*You can not splice and count strings from attribute-values


text:
Q: How to decode backslashed special symbols to UTF-8 I have text in a database which stored as: \xE2\x82\xAC 50
Important note: symbols stored in a database not as UTF bytes, but as symbols: "slash", "letter x", "letter E" etc.. so Ruby representation will be "\\xE2\\x82\\xAC 50" (double slashes, not single).
How do I convert this string to € 50:
> xx = "\\xE2\\x82\\xAC"
"\\xE2\\x82\\xAC"
> xx.bytes
[92, 120, 69, 50, 92, 120, 56, 50, 92, 120, 65, 67]

This does not work:
xx.force_encoding('utf-8')
xx.encode('utf-8')
xx.force_encoding('binary').force_encoding('utf-8')
xx.encode('ASCII-8BIT').encode('utf-8')

A: It's not a "in Ruby" thing, it's about understanding what you're seeing and how strings and escaped characters work.
Meditate on this:
"\\xE2\\x82\\xAC" # => "\\xE2\\x82\\xAC"
'\xE2\x82\xAC' # => "\\xE2\\x82\\xAC"

"\xE2\x82\xAC" # => "€"

The third way is how to define the bytes that create the Euro symbol character. The first two are two different ways of writing the string with literal backslashes.
If you've stored the data correctly in the database it'll be retrieved correctly. The DB driver you're using is responsible for converting to the string used by the language, so it should be transparent to you once you've retrieved the fields.
Current Rubies use UTF-8 by default, so it's not necessary to try to force the string to UTF-8, simply define it correctly.
Dealing with character escaping in strings will be confusing until you learn the special cases and how single-quoted strings behave differently than double-quoted. You can find more information about escaping by reading Wikipedia's  "Escape character" article. The information applies to almost every language out there, not just Ruby.

A: For now came only with an ugly "converter"
  def fix_utf_symbols(str)
    match = str.scan /(\\x[0-9A-F]{2})/
    match.flatten.each do |ascii_code|
      utf_char = ascii_code[2..3].hex.chr
      str.gsub! ascii_code, utf_char
    end
    str
  end

More elegant solutions are welcomed


text:
Q: Need to join on slight similarity between two long text strings using SQL I need to write a sql query that operates somewhat like a fuzzy lookup where it will complete a join if a sentence within a paragraph matches a sentence in another paragraph in a different table. I'm trying to identify similarities between two datasets that aren't written exactly the same. What's the best plan of attack here?
I want to be able to join based on one sentence matching somewhere within the text and then analyze the results.
I tried parsing to just compare the unique identifiers and this works in some cases. However a lot of the data is messy and not written in a consistent structure.
SELECT *
FROM table1 t1
JOIN table2 t2 ON t2.para LIKE CONCAT('%', t1.para, '%')

I tried this code and didn't get the result I wanted.


text:
Q: For Loop Max JavaScript I have just created a prime number finder with a for loop that runs over time.  Right now its at 167899 and growing every second.
What is the max number of loops a for loop can go through???    If its an ungodly big number I don't want to be waiting all night to see what is the max prime number I can generate.
Is it infinite?
Here is my code:
        var isNotPrime = false;
        var currentNumber = 3;
        var primeArray = [2];

        function prime(){
            isNotPrime = false;
            for(a=0; a<primeArray.length; a++){
                if(currentNumber%primeArray[a] === 0){
                    isNotPrime = true;
                }
                if(a===(primeArray.length-1) && isNotPrime ===false){
                        document.write(currentNumber+"<BR>");
                        primeArray.push(currentNumber);
                }
                if(a===(primeArray.length-1)){
                    currentNumber++;
                }
            }
        }

        var main = setInterval(prime, 1);

        window.alert("Starting search for Prime Numbers!");

A: There's no maximum number of times a loop can execute since you can have an infinite loop:
for (var i = 0; i < 1;) { console.log('this will keep running forever' }

(Note that the increment step after i < 1; of the for loop is empty, instead of being i++)
However, there is a max integer in Javascript, which is probably what you were after.

A: As long as the length is an integer, it can and will continue the loop.
The max number is believe for an int is 9 007 199 254 740 992.
So loop has the potential to run that many times.

A: You will probably need to use a web worker to prevent the browser from interrupting the process. With a web worker, it is possible for the loop to run indefinitely (well, until the computer ceases to function).
As noted by others, you will run into issues dealing with the large numbers. There may be ways to work around the integer precision limitation in JavaScript: http://www.2ality.com/2012/07/large-integers.html
So, the answer to your first question is no, JavaScript doesn't have a well-defined maximum number of loops.
The answer to your second question depends on where the process is running. The number of loops cannot be infinite if the process is running on a real machine which will eventually suffer failure due to entropy. If the process is running in a virtual machine, you can keep the process running indefinitely (until the heat death of the universe).

A: Maximum safe integer in JavaScript is 9007199254740991 , you can check it in console of your browser

console.log('Max safe integer' , Number.MAX_SAFE_INTEGER); // 9007199254740991
console.log('Min safe integer' , Number.MIN_SAFE_INTEGER); // -9007199254740991
console.log('Max value' , Number.MAX_VALUE); // 1.7976931348623157e+308
console.log('Min value' , Number.MIN_VALUE); // 5e-324

So you can run

for (let i = 1; i <= Number.MAX_SAFE_INTEGER; i ++) {
  // console.log('Number ', i); <-- Uncomment this line and wait, but why? I don't recommend, because your browser will crash probably
}


text:
Q: Expand List jQuery I have some questions:
A) How can I switch between '+' and '-' when the list is expand (+) or not expand (-), and the correct expand symbol when I load my page.
B) How can I have the correct checkbox value on my principal lists when I load my page. For the first list '-', the second Checked box symbol, and the third no checked).
Here is my jsFiddle

        <input type="checkbox" />
   ....

Thank you so much.

A: Try,
//Expand list.
$('.list > li b').click(function() {
    var span = $(this).find('span');
    var text = span.text();
    span.text(text === "+"?"-":"+")
    $(this).parent().find('ul').toggle();
});

DEMO


text:
Q: How we converted NSAttributed String Backed to NSString I am changing the font of textview, after I get attributed string then I use to pass it to another controller which also shows me attributed string. I would like to convert attributed string to NSString (with specific font which I have changed).
I am using
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:text.attributedText];
NSAttributedString *nas = [[NSAttributedString alloc] initWithData:data
                                                           options:nil
                                                documentAttributes:NULL
                                                             error:NULL];

NSString *str = [nas string];

Which shows below log:
2014-11-17 14:23:17.094 format[2785:98416] bplist00'°¢T$topX$objectsX$versionY$archiver—TrootÄØ"
%&'().6EFJRSTU[`glt}~ÅâäãåíñúU$null'
XNSString\NSAttributesV$class_NSAttributeInfoÄÄÄ!ÄYThud high"
ZNS.objectsÄ¢ÄÄ"
 !WNS.keys£ÄÄ   ÄÄ£"#$ÄÄÄ[NSUnderline_NSParagraphStyleVNSFont"
*+,-(ZNSTabStops_NSWritingDirectionÄ
Ä

A: Actually NSAttributedString has string property:
NSString *result = myAttributedString.string;

A: Just write
[attributedString string];

A: You can covert attributed string to string using following line of code :
self.txtView.text = [attributedstring string];

but I suggest its better use as attribute text like below :
self.txtView.attributedText = attributedstring;


text:
Q: Routed traffic away from VPN has no internet (Fedora) I'm very new to linux routing and such as a preface.  I have a plex server set up on Fedora 22. I've recently started using a VPN service connected via OpenVPN.  Everything works great via VPN on my internal network but of course externally my Plex server has stopped publishing.  I read somewhere about adding routing entries for plex.tv's services via IP to be routed through my router rather than my VPN tunnel.  So I added all of the IP's plex uses (found here: http://www.dnswatch.info/dns/dnslookup?la=en&host=plex.tv&type=A&submit=Resolve) via the following command
route add -net 184.169.156.178 netmask 255.255.255.255 gw 192.168.1.1

It appears as though traffic to plex.tv is trying to route through my router but it just drops off right after there.
traceroute plex.tv
traceroute to plex.tv (50.18.115.47), 30 hops max, 60 byte packets
1  gateway (192.168.1.1)  0.238 ms  0.212 ms  0.245 ms
2  * * *
3  * * *

As opposed to traffic going to google.com
traceroute to google.com (216.58.219.238), 30 hops max, 60 byte packets
1  10.174.1.1 (10.174.1.1)  47.522 ms  47.446 ms  47.448 ms
2  108.61.68.129 (108.61.68.129)  47.568 ms  47.687 ms  47.991 ms

I'm not sure why this is? My router has it's own OpenVPN server which assigns ip's on a different subnet 10.8.0.0 as opposed to 192.168.1.0, I added an entry for that subnet so I could VPN from work to home and SSH into my server and such and that works fine, not sure where to go from here to get just plex.tv traffic to not travel across the VPN

A: The information you have provided is insufficient to say something concrete. But If you want to bypass vpn, you have to see that you can reach internet at all through gateway 192.168.1.1. At the moment it doesn't seems so.
From the given information, the traceroute to google is clearly passing through another gateway (see the first hop is 10.174.1.1, where is it set?). To test further, if you can reach some other external ip, you may set static route for google dns (8.8.8.8 or 8.8.4.4) and see if it woks. If it doesn't then you have little chance.


text:
Q: Get Flux size when Flux is complete I'm kinda stuck with a trivial task: whenever I query an external API with reactive spring WebClient or query reactive MongoDBRepository, I'd like to log how many entities got through my flux, eg. to log message like "Found n records in the database.". Eg:
return repository.findAll()
                 .doOnComplete { log.info("Found total n records!") } // how to get the n?
                 .filter { it.age > 10 }
                 .distinct { it.name }

TLDR: How to get a flux size (and perhaps it's contents) when it completes?

A: You can use ConnectableFlux. In your example:
var all = repository.findAll()
             .filter { it.age > 10 }
             .distinct { it.name }
             .publish()
             .autoConnect(2)

all.count()
   .subscribe {c -> log.info("Found total {} records!", c)}

return all;

A: By calling the count(). It should emit a Mono when onComplete is observed.

A: Here was what I did,
AtomicInteger i = new AtomicInteger();
Flux<UserDetails> stringFlux =
                Flux.using(() -> stringStream, Flux::fromStream,
                Stream::close)
                        .doOnNext(s -> i.getAndIncrement())
                        .log()
                        .map(UserDetails::createUserDetails);

stringFlux
                .subscribe(updateUserDetailsService::updateUserDetails);

log.info("number of records: {}", i);


text:
Q: ES6: share data between modules To share data between modules, a usual pattern is to capsulate the data into a common module and import it in other modules.
In my case the data to be shared is a logger, which need to be initialized before used. I call init() at the entry point of my application.
// main.js

let logger = require('@my/logger');
logger.init({...});

let xxx = require('./moduleX');
let yyy = require('./moduleY');

In other modules, the initialized logger can be used:
// moduleX.js

let logger = require('@my/logger');
const log = logger('moduleX');

function x() {
  log.debug('some msg');
}

Above code works well in node.js. But if I change to ES6 module syntax, it doesn't work because ES6 module import is hoisted.
// main.js

import {logger} from '@my/logger';
logger.init({...});          // this line is run after import moduleX
import {x} from './moduleX';

// moduleX.js

import {logger} from '@my/logger';
const log = logger('moduleX');        // logger is not initialized !

export function x() {
  log.debug('some msg');
}

With ES6 module, how can I initialize some data and share them to other modules?
There was a similar question but the answer doesn't fit my case.
Update:
Some answers suggest to put the code which access shared data into function so that the code isn't invoked immediately at module load. But what if I really need to access it during module loading? I updated my code to demonstrate the use case -- it would be too trivial to call logger(name) in every function if not make log as module scope const.

A: Finally I solve it in the way that @PaoloMoretti mentioned in his comment.
Write a module in my app to init the logger for my app:
// logger_init.js
import {logger} from '@my/logger';
logger.init({...});

Import the initialization module once at the entry point of application, prior to imports of any other modules that use logger as well. It guarantees that the initialization is done before loading other modules.
// main.js
import './logger_init';
import {x} from '@my/other_module';
import {y} from './module_in_myapp';

Other modules can use initialized logger directly:
// @my/other_module

import {logger} from '@my/logger';
const log = logger('moduleX');       // logger has been initialized

export function x() {
  log.debug('some msg');
}

The dependency tree is:
                           <init>
myapp --+--> logger_init ------------> @my/logger
        |                       <use>   ↑
        +--> module_in_myapp -----------+
        |                       <use>   |
        +--> @my/other_module ----------+

Why I don't adopt the way that add a wrapper module which init and return a logger (as Bergi's answer) is because the modules uses logger could be reusable modules not in my application.

A: Try to provide some entry points to your xxx.js and yyy.js modules or even make them as functions.
// main.js
import {logger} from '@my/logger';
import * as xxx from './xxx';

logger.init({...});

xxx.run();

// xxx.js
import {logger} from '@my/logger';
export function run () {
   logger.debug('In xxx');
}

A: You could have each module that has a dependency on some initialisation routine return a function that can be executed manually to invoke its functionality, rather than expose that functionality as an immediate side-effect of importing it. For example, in xxx.js:
// xxx.js
export default function (log) {
    log('xxx');
}

Then place all initialisation operations within an entry file and invoke the modules defined in the above way after these operations are complete:
// main.js
import xxx from './xxx';
import {logger} from '@my/logger';
logger.init({...});
xxx(logger);

But what if I really need to access it during module loading?

Please see the amended code examples above. Pass the instance of logger to the function exported by each module.

A:
A logger, which need to be initialized before used. What if I need to access it during module loading?

Make an extra module with an initialised logger:
// main.js
import {x as xxx} from './moduleX';
import {y as yyy} from './moduleY';

// logger_ready.js
import {logger} from '@my/logger';
logger.init({…});
export default logger;

// moduleX.js
import logger from 'logger_ready';
const log = logger('moduleX');        // logger is initialized here!

export function x() {
  log.debug('some msg');
}

A: After experiments, found that the BroadcastChannel api is perfect to share data or events easily between different es6 modules, tabs, workers, frames...
We can pass objects or arrays by using json stringify there too:
To send datas:
new BroadcastChannel('myapp_section8').postMessage('Hello world!')

Example receiving, from another module:
new BroadcastChannel('myapp_section8').addEventListener('message', function(e){
  console.log(e.data)
})

It avoid to use any DOM elements to dispatchEvent, it simplify stuffs a lot!


text:
Q: Automating IE8 download window using WinApi My current task is the automated testing of an enterprise web-based software suite using Selenium on Java.
I've more or less successfully done the trick using JNA and WinApi, unfortunately, I've hit a nasty snag.
While changing the path to the download location via the WM_SETTEXT message, only the visual content of the file path changes, and after clicking the save button it still saves to the originally suggested location. What gives?
Is there any way I can make IE8 think I actually entered the path manually, or, perhaps send some other message that would trigger processing of the changed address?

A little background:
Unfortunately, Selenium cannot handle file downloads, and I need to verify the validity of the to-be-downloaded file so a simple HTTP 200 code check will not suffice.
Automatic file downloading is out, as I'm stuck with IE8, which does not support it. Direct HTTP requests are also out - SSO authentication and HTTPS have caused too many problems down this research vector.
P.S.: Unfortunately, I cannot provide a direct code snippet due to NDA, proprietary limits and other dull limitations...


text:
Q: determine whether group is additive I am taking a stab at group theory and in some of the questions I am working on they don't explicitly state whether a group is additive or multiplicative. $\mathbb{Z}_4$ is additive (and that makes sense because integers) but how do I for example determine the operation to use on $\mathbb{R}$? It seems like it could be either one (it satisfies the axioms for both) and it's not clear as to what the question wants. Is there a rule as to what I should do when?
Thanks a lot!

A: A group $G$ is a group, and as such is endowed with a single binary operation $$\star: \quad G\times G\to G, \qquad(x,y)\mapsto x\star y$$
satisfying certain axioms. If no optional properties of $\star$ are assumed the operation $\star$ is called multiplication in $G$. If in the case at hand  the operation $\star$ is commutative, as is the addition of integers, we are inclined to call the operation $\star$  addition, and write $+$ instead of $\star$. This notational move becomes a necessity if on $G$ additional binary operations, like $*$,  are installed which interact in a particular way with $+$.


text:
Q: Firebase HTTPS Cloud Function Returning 404 in Production I have pushed a very basic HTTP Cloud Function to Firebase and am getting a 404 when trying to access in browser or via Postman.  The function works locally, via both firebase serve and via various tests that I've written using the firebase-functions-test SDK.
// import function libraries and initialize admin app
var functions = require('firebase-functions');
var admin = require('firebase-admin')
admin.initializeApp(functions.config().firebase)

// push data to a specific database
var pushData = (path) => (payload) => {
  return new Promise((resolve, reject) => {
    admin.database().ref(path).push(payload).then(snapshot => {
      resolve(snapshot)
    }).catch((error) => {
      reject(error)
    })
  })
}

// github webhook endpoint
exports.postGitHubEvent = functions.https.onRequest((request, response) => {
  // handle invalid request method
  if (request.method !== 'POST') {
    return response.send(405, 'Only POST Requests Are Accepted')
  }
  // push request body to database
  var event = request.body
  var writeData = pushData('github')(event)

  // return write promise
  return writeData.then(
    result => response.send(200, `Successfully Pushed Github Event: ${result}`),
    error => response.send(500, `Error in Pushing GitHub Event: ${error}`)
  )
})

A: This has been answered.  My firebase project ID has two hiphens in it and was customized (edited) upon the creation of the project.  Kept one hiphen in the project name / project ID and now it functions correctly...


text:
Q: Нечетные числа из массива Подскажите как вернуть нечетные числа из массива?
И еще, как возвращать отрицательные значения, а также, если это 0, возвращать пустой массив.
Пример:
input: ([1, 2, 3, 4, 5, 6, 7, 7]) === [1, 3, 5, 7, 7];

input: ([0, 2, 4]) === [];

input: ([-10, 10, -11, 11, -12, 12]) === [-11, 11];

input: [] === [];

Написал:
function getNumbers(numbers) {

  let x = [];

  for (let i = 0; i < numbers.length; i++) {

    x = numbers[i];

    if (x % 2 == 1) {

      return [x];
    }
  }
}

Не понимаю где ошибся

A:

const filter = arr => arr.filter(item => item % 2 !== 0)

console.log(filter([1, 2, 3, 4, 5, 6, 7, 7]))
console.log(filter([-10, 10, -11, 11, -12, 12]))
console.log(filter([0, 2, 4]))
console.log(filter([]))
console.log(filter([-1, 0, 1]))

Ещё можно так)

A:
Не понимаю где ошибся

Везде.

function getNumbers(numbers) {
  let x = [];
  for (let i = 0; i < numbers.length; i++) {
    let n = numbers[i];
    if (n % 2)
      x.push(n);
  }
  return x;
}

console.log(JSON.stringify(getNumbers([1, 2, 3, 4, 5, 6, 7, 7])));
console.log(JSON.stringify(getNumbers([0, 2, 4])));
console.log(JSON.stringify(getNumbers([-10, 10, -11, 11, -12, 12])));
console.log(JSON.stringify(getNumbers([])));


text:
Q: ¿Como puedo devolver algo en el constructor para utilizarlo en mi clase? Tengo un filtro de acción para hacer un log en una clase llamada LogActionFilter el cual tiene sus respectivos metodos para realziar cada tarea especifica, y desde mi controlado llamo a este filtro de la siguiente forma [LogActionFilter] hasta ahí todo bien.
El problema es que necesito pasar un mensaje personalizado hacia la clase del filtro de acción estilo: [LogActionFilter("Mi mensaje de log")] para que lo reciba mi clase y poder utilizarlo en los demás métodos de ella.
Se que debo utilizar un constructor para ello, pero no se como recuperar el dato para utilizar en mis demás métodos que están fuera del constructor.
Mi Clase o Filtro de Acción:
public class LogActionFilter : ActionFilterAttribute{
    public LogActionFilter(string msg){

    }

    public override void OnActionExecuting(ActionExecutingContext filterContext){
        Log("OnActionExecuting Firxt", filterContext.RouteData);
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext){
        Log("OnActionExecuted", filterContext.RouteData);
    }

    public override void OnResultExecuting(ResultExecutingContext filterContext){
        Log("OnResultExecuting", filterContext.RouteData);
    }

    public override void OnResultExecuted(ResultExecutedContext filterContext){
        Log("OnResultExecuted", filterContext.RouteData);
    }

    private void Log(string v, RouteData routeData){
        var controllerName = routeData.Values["controller"];
        var actionName = routeData.Values["action"];
        var message = String.Format("{0} controller:{1} action:{2}", v, controllerName, actionName);
        Debug.WriteLine(message, "Action Filter Log");
    }
}

Mi Controller:
[LogActionFilter("SUCCES")]
public class HomeController : Controller{
    public ActionResult Index(){
        return View();
    }

    public ActionResult About(){
        ViewBag.Message = "Your application description page.";
        return View();
    }

    public ActionResult Contact(){
        ViewBag.Message = "Your contact page.";
        return View();
    }
}

A: Lo resolví de la siguiente forma, no se si sera "correcta".
Mi constructor:
private string message;

public LogActionFilter()
{
}

public LogActionFilter(string msg)
{
    this.message = msg;
}

public string Message
{
    get => message;
    set => message = value;
}

Pero al inspeccionar lo que contiene el parámetro msg me indica ERROR, eso no se por que sucede... pero funciona bien.


text:
Q: How to continue a try/except I'm currently learning about "try" and "except" concepts and I have a small question.
def sum_file():
    try:
        with open("text.txt") as entry:
            result = 0
            try:
                for line in entry:
                    result += int(line.strip())
                    print(result)
            except ValueError:
                print("Non-integer number entered")
    except:
        print("Non-existent file.")

Each line of the file is a number, some numbers are integers and others are floats. The code correctly sums the first integers but when the first float appears the program stops, when there are more lines further. How do I modify the code for it to continue the operation?

A: You need to put the second try block inside your loop:
def sum_file():

    try:
        with open("text.txt") as entry:
            result = 0
            for line in entry:
                try:
                    result += int(line.strip())
                    print(result)
                except ValueError:
                    print("Non-integer number entered")
    except:
        print("Non-existent file.")

A: or you can use re to help you.
re.match(r".*\D+.*", line) match any line which contains one or more not [0-9] character
from io import StringIO
import re

text_txt = """\
3.1
123
4 b 5 6
     7.2
c'] ? 9
  10
"""

def sum_file():
    with StringIO(text_txt) as f:
        result_list = []
        for line in [_.strip() for _ in f]:
            m = re.match(r".*\D+.*", line)
            print("Non-integer number entered") if m else (print(line), result_list.append(int(line)))
        print(f'result: {sum(result_list)}') if result_list else None

sum_file()

output
Non-integer number entered
123
Non-integer number entered
Non-integer number entered
Non-integer number entered
10
result: 133


text:
Q: Is it safe to ignore errors hg cloning from a write-protected source repo? I have a Mercurial repository on a write-protected USB thumb drive, from which I want to clone to a workstation.  I thought this would be a "one-way" operation, but it's not: after inserting the thumb drive into the workstation, and trying hg clone E:\my_repo, I get an error indicating that Mercurial is trying to write to the source repo.  (This is on Windows XP, with the following error details: "hg.exe - Write Protect Error / The disk cannot be written to because it is write protected.  Please remove the write protection from the volume in drive E:.")
Interestingly, selecting "Continue" among the error dialog options-- which effectively seems to mean, "ignore the error and continue what you were doing"-- seems to allow the clone to complete successfully.  Or at least I can't see anything wrong with the resulting cloned repo.
My questions are: (1) why does Mercurial need to write to the source when cloning?  And (2) is it indeed safe to simply continue and ignore whatever Mercurial fails to write to the source?

A: There are four ways Mercurial clones:

*

*hardlink: used for clones on the same volume where supported

*copy: used for clones from filesystem to filesystem

*pull: used for cloning from remote machines

*stream: used for cloning on a high-speed LAN (see --uncompressed)

All of these methods but pull try to lock the source repository to avoid any commits in the middle of the clone that might corrupt it. Since that's not a danger for you, it's safe to ignore the error (though it's not a given that Mercurial will be happy with the failure to lock).
Alternately, you can specify --pull to do a clone where locking isn't needed.


text:
Q: Child's height restricted to parent's remaining space How should I use CSS3 to set the scrollbox class to adjust its height to all remaining space of its parent. The scrollbox should not change its parent's height even if the scrollbox content is very long. In such a situation the scrollbox should show scrollbars. Is it possible?

div {
  margin: 0;
  border-radius: 12px;
  padding: 6px;
  background-color: white;
}
body {
  margin: 0px;
  width: auto;
  height: 100vh;
  display: grid;
  grid: 20vw 1fr / 20vh 1fr;
  grid-template-areas: "top-left main""bottom-left  main";
  grid-row-gap: 4px;
  grid-column-gap: 4px;
}
.top-left {
  grid-area: top-left;
  background-color: lightblue;
}
.bottom-left {
  grid-area: bottom-left;
  background-color: lightgreen;
}
.main {
  grid-area: main;
  background-color: lightpink;
}
.scrollbox {
  background-color: white;
}

    Top-Left

    Bottom-Left

      <svg viewBox="0 0 2000 2000">
        <circle cx="1000" cy="1000" r="1000" />
      </svg>

    Main

      <svg viewBox="0 0 2000 2000">
        <circle cx="1000" cy="1000" r="1000" />
      </svg>

A: If by "adjust its height to all remaining space of its parent" you are referring to the body's height of 100vh, the scrollbox classes are nor the real issue. What you may want is to restrict all the direct children of the body to a specific height, which when summed up, is less than the body's height.
I.e. if the body has 3 children, each children's height would be 100/3 units, so you'd only need something like this:
body>*{
  max-height: 33.33333333vh;
  overflow-y: auto;
}

The overflow property adds the vertical scrollbars you wanted.
In order to make sure that only the scrollbox classes are to have specific heights and those scrollbars then you can reference them in a similar way:
body>*>.scrollbox {
  max-height: 30vh;
  overflow-y: auto;
}

However, I wonder why you are giving the body that height? vh is a particular unit, and 100vh in the body tag is the same as writing 100%:

With vw/vh, we can size elements to be relative to the size of the viewport. The vw/vh units are interesting in that 1 unit reflects 1/100th the width of the viewport. To make an element the full width of the viewport, for example, you'd set it to width:100vw.

Here's your snippet though:

div {margin: 0;border-radius: 12px;padding: 6px;background-color: white;}
body {margin: 0px;width: auto;height: 100vh;display: grid;grid: 20vw 1fr / 20vh 1fr;grid-template-areas: "top-left main""bottom-left  main";grid-row-gap: 4px;grid-column-gap: 4px;}
.top-left {grid-area: top-left;background-color: lightblue;}
.bottom-left {grid-area: bottom-left;background-color: lightgreen;}
.main {grid-area: main;background-color: lightpink;}
.scrollbox {
  background-color: white;
}
body>*>.scrollbox {
  max-height: 30vh;
  overflow-y: auto;
}

    Top-Left

    Bottom-Left

      <svg viewBox="0 0 2000 2000">
        <circle cx="1000" cy="1000" r="1000" />
      </svg>

    Main

      <svg viewBox="0 0 2000 2000">
        <circle cx="1000" cy="1000" r="1000" />
      </svg>


text:
Q: Linear Transformations of Data (Econometrics) If $Z=XA$ and $A$ is a non-singular matrix, what is the dimension of $A$?

A: Typically, the term "non-singular" is only used to describe square matrices, so presumably we know that $A$ is square.  If $X$ is $n \times k$ and if the product $XA$ is conformable, then $A$ must have $k$ rows.
We conclude that $A$ must be $k \times k$.


text:
Q: Copy bower_components to Azure Web App using Visual Studio Team Services With an Azure Web App that is deployed to via Visual Studio Team Services.
The 'bower install' build step works perfectly, as the next build step executes tests using these files and these tests pass.
After this, I need a method to copy the bower_components folder into the Azure Web App wwwroot folder. How do I do this?

A: You can use FTP Deploy to copy files to your Azure Web App folder. Check this link for reference: Windows Azure Website: Uploading/Downloading files over FTP and collecting Diagnostics logs.
To use FTP in your build easily, you can install FTP Uploader extension and then add it in your build definition to copy the files into Azure Web App via FTP.


text:
Q: Add a default implementation of properties I got the following class:
public class Foo
{
    public string Property1
    {
        get { return (string)Properties["property1"]; }
        set { Properties.Add("property1", value); }
    }
    public string Property2
    {
        get { return (string)Properties["property2"]; }
        set { Properties.Add("property2", value); }
    }

    //A lot more here

    public string Property30
    {
        get { return (string)Properties["property30"]; }
        set { Properties.Add("property30", value); }
    }

    public string Property31
    {
        get { return (string)Properties["property31"]; }
        set { Properties.Add("property31", value); }
    }

    public Dictionary<string, object> Properties { get; set; }
}

I'm copying the getter and the setter a lot of times, which is kind of a hassle The class has about 20/30  properties. Is there a way to implement this automagically. I've done an implementation by making Foo dynamic and implementing the TryGetMember, but I don't like how the object isn't strongly typed anymore (especially the fact that there's no autocomplete in visual studio).
Cheers

A: If you are using Visual Studio, you can use snippets. For properties, these are available by default.

You can also create your own, or import snippets made by other developers or third parties using the Tools/Code Snippet Manager.
This is what your snippet would approximately look like:
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <CodeSnippet Format="1.0.0">
        <Header>
            <Title>myprop</Title>
            <Shortcut>myprop</Shortcut>
            <Description></Description>
            <Author>Me</Author>
            <SnippetTypes>
                <SnippetType>Expansion</SnippetType>
            </SnippetTypes>
        </Header>
        <Snippet>
            <Declarations>
                <Literal>
                    <ID>type</ID>
                    <ToolTip>Property type</ToolTip>
                    <Default>int</Default>
                </Literal>
                <Literal>
                    <ID>property</ID>
                    <ToolTip>Property name</ToolTip>
                    <Default>MyProperty</Default>
                </Literal>
                <Literal>
                    <ID>field</ID>
                    <ToolTip>The variable backing this property</ToolTip>
                    <Default>myVar</Default>
                </Literal>
            </Declarations>
            <Code Language="csharp"><![CDATA[private $type$ $field$;

    public $type$ $property$
    {
        get { return ($type$)Properties["$field$"];}
        set { Properties.Add("$field$",value);}
    }
    $end$]]>
            </Code>
        </Snippet>
    </CodeSnippet>
</CodeSnippets>

A: I'll post an alternative using PostSharp. Free version will work fine for this example. First install PostSharp from nuget, then create simple aspect:
[Serializable]
public class FooAspect : LocationInterceptionAspect {
    public override void OnGetValue(LocationInterceptionArgs args) {
        var foo = ((Foo)args.Instance);
        if (foo.Properties == null || !foo.Properties.ContainsKey(args.LocationName))
            args.Value = null;
        else
            args.Value = foo.Properties[args.LocationName];
    }

    public override void OnSetValue(LocationInterceptionArgs args) {
        var foo = ((Foo) args.Instance);
        if (foo.Properties == null)
            foo.Properties = new Dictionary<string, object>();
        foo.Properties[args.LocationName] = args.Value;
    }
}

Here we basically intercept getters and setters of a property and rewriting them to use Properties dictionary instead of what they did before. Then apply aspect to Foo class (remember to exclude Properties property itself to avoid stack overflow):
[FooAspect(AttributeTargetMembers = "Property*")]
public class Foo
{
    public string Property1 { get; set; }
    public string Property2 { get; set; }
    public string Property30 { get; set; }
    public string Property31 { get; set; }

    public Dictionary<string, object> Properties {get; set; }
}

Of course using PostSharp just for this is an overkill, but you might find it useful in many other cases too.


text:
Q: Are two function pointers to the same function always equal? Does the C++ standard guarantee that two pointers to a function always compare equal? I understand that this will normally be true for non-inline functions. But if there is an inline function and a pointer to the function is created in two separate compilation units, will the linker merge the two instantiations, or is it allowed to emit duplicate functions?
If the answer to the above is "they are equal": Does this still hold if there is a common header with an inline function, and both the main program and a dynamically loaded plugin (shared object/DLL) create a pointer to the function?

A:
Does the C++ standard guarantee that two pointers to a function always
  compare equal?

Yes, two pointers that point to the same function compare equal.

Does this still hold if there is a common header with an inline
  function, and both the main program and a dynamically loaded plugin
  (shared object/DLL) create a pointer to the function?

Yes, per 7.1.2.p4

An inline function with external linkage shall have the same address
  in all translation units.

A: Section §5.10/1 of the C++11 standard says:

Two pointers of the same type compare equal if and only if they are
  both null, both point to the same function, or both represent the same
  address

Two copies of the same inline function are still the same function. From an implementation point-of-view, the compiler will generate a copy of the function in each translation unit but the linker will then throw one of the copies away so only one is remaining.
By taking the address of a function you prevent it from being inlined (different from inline, which is more about avoiding violation of the One Definition Rule).
DLLs are outside the scope of the standard but only one copy of the function will remain in the binary image so getting the function address (e.g. GetProcAddress) from the DLL will get the same function pointer as code inside the DLL.


text:
Q: using Dbset.Add Versus using EntityState.Added I am working on an asp.net mvc 5 with EF 6. and is there any differences between writing the following code , when Adding new object:-
db.Students.Add(student);
db.SaveChanges();

OR
db.Entry(student).State = EntityState.Added;
db.SaveChanges();

and similarly when Deleting object:-
db.Entry(studentToDelete).State = EntityState.Deleted;
db.SaveChanges();

OR
db.Remove(StudentToDelete)
db.SaveChanges();

Thanks


text:
Q: AWK replace NULL column values with column values of previous row I have a sample file as following:
cat sample.txt

HOST dev@opulex.com
PORT 1066
DATABASE ORACLE_1
SCHEMA DEPT.*;
SCHEMA EMP.*;
DATABASE ORACLE_2
SCHEMA JOB.*;

For the content in the above sample file, I would like to print only the columns next to HOST/PORT/DATABASE/SCHEMA. So, I could achieve that as following:
cat sample.txt | awk 'tolower($0)~/^host|^port|^database|^schema/{printf "%s",$2 OFS;}' | awk -v RS=';' -v ORS=';\n' 'NF'

dev@opulex.com 1066 ORACLE_1 DEPT.*;
 EMP.*;
 ORACLE_2 JOB.*;

Assuming that last column in every record ends with semi-colon (;), How can I use AWK to replace NULL column values with the column values of previous row as following:
 dev@opulex.com 1066 ORACLE_1 DEPT.*;
 dev@opulex.com 1066 ORACLE_1 EMP.*;
 dev@opulex.com 1066 ORACLE_2 JOB.*;

Thanks in Advance.!

A: If you have this data:
cat file

dev@opulex.com 1066 ORACLE_1 DEPT.*;
 EMP.*;
 ORACLE_2 JOB.*;

Using awk you can do:
awk 'NF==1{print c1, c2, c3, $1; next}
     NF==2{print c1, c2, $1, $2; next}
     {c1=$1; c2=$2; c3=$3} 1' file

Output:
dev@opulex.com 1066 ORACLE_1 DEPT.*;
dev@opulex.com 1066 ORACLE_1 EMP.*;
dev@opulex.com 1066 ORACLE_2 JOB.*;

A: another awk alternative
$ rev file |
  awk 'NF>1{c2=$2?$2:c2; c3=$3?$3:c3; c4=$4?$4:c4}
           {print $1,c2,c3,c4}' |
  rev

dev@opulex.com 1066 ORACLE_1 DEPT.*;
dev@opulex.com 1066 ORACLE_1 EMP.*;
dev@opulex.com 1066 ORACLE_2 JOB.*;


text:
Q: Liferay Container fails to start with custom server.xml I was trying to run Liferay as a Docker Container. As soon as I create a custom tomcat/conf/server.xml and copy that into the image Elasticsearch fails to start.
Does someone have an idea what is going on?
My Dockerfile:
FROM liferay/portal:7.1.3-ga4

COPY --chown=liferay:liferay bundles/osgi/modules /opt/liferay/osgi/modules
COPY --chown=liferay:liferay docker/portal-setup-wizard.properties docker/portal-ext.properties \
        /opt/liferay/
COPY --chown=liferay:liferay docker/cors-filter-2.5.jar docker/java-property-utils-1.9.1.jar \
        /opt/liferay/tomcat-9.0.17/webapps/ROOT/WEB-INF/lib/
COPY --chown=liferay:liferay docker/web.xml /opt/liferay/tomcat-9.0.17/webapps/ROOT/WEB-INF
COPY --chown=liferay:liferay docker/user_default.png /opt/liferay/tomcat-9.0.17/webapps/ROOT/WEB-INF/classes/com/images/user_default.png
COPY --chown=liferay:liferay docker/server.xml /opt/liferay/tomcat-9.0.17/conf

The server.xml only has this modification:
<Connector port="8080" protocol="HTTP/1.1"
                   connectionTimeout="20000"
                   maxPostSize="20971520"
                   redirectPort="8443" URIEncoding="UTF-8" />

A: I tested the configuration you mentioned, and it seems you are blaming the wrong guys.
Using your sample as the only change with the tag you provided:
<Connector port="8080" protocol="HTTP/1.1"
                   connectionTimeout="20000"
                   maxPostSize="20971520"
                   redirectPort="8443" URIEncoding="UTF-8" />

I got:
Using CATALINA_BASE:   /opt/liferay/tomcat
Using CATALINA_HOME:   /opt/liferay/tomcat
Using CATALINA_TMPDIR: /opt/liferay/tomcat/temp
Using JRE_HOME:        /usr/lib/jvm/zulu-8
Using CLASSPATH:       /opt/liferay/tomcat/bin/bootstrap.jar:/opt/liferay/tomcat/bin/tomcat-juli.jar
22-Jul-2019 21:10:54.055 INFO [main] org.apache.catalina.startup.Catalina.load Server initialization in [942] milliseconds
Loading jar:file:/opt/liferay/tomcat-9.0.17/webapps/ROOT/WEB-INF/lib/portal-impl.jar!/system.properties
Loading jar:file:/opt/liferay/tomcat-9.0.17/webapps/ROOT/WEB-INF/lib/portal-impl.jar!/portal.properties
2019-07-22 21:10:55.654 INFO  [main][PortalContextLoaderListener:139] JVM arguments: -Djava.util.logging.config.file=/opt/liferay/tomcat/conf/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djdk.tls.ephemeralDHKeySize=2048 -Djava.protocol.handler.pkgs=org.apache.catalina.webresources -Dorg.apache.catalina.security.SecurityListener.UMASK=0027 -Dfile.encoding=UTF8 -Djava.net.preferIPv4Stack=true -Duser.timezone=GMT -Xms2560m -Xmx2560m -XX:MaxNewSize=1536m -XX:MaxMetaspaceSize=512m -XX:MetaspaceSize=512m -XX:NewSize=1536m -XX:SurvivorRatio=7 -Dignore.endorsed.dirs= -Dcatalina.base=/opt/liferay/tomcat -Dcatalina.home=/opt/liferay/tomcat -Djava.io.tmpdir=/opt/liferay/tomcat/temp
2019-07-22 21:10:58.689 WARN  [main][DialectDetector:100] Liferay is configured to use Hypersonic as its database. Do NOT use Hypersonic in production. Hypersonic is an embedded database useful for development and demonstration purposes. The database settings can be changed in portal-ext.properties.
2019-07-22 21:10:58.695 INFO  [main][DialectDetector:158] Using dialect com.liferay.portal.dao.orm.hibernate.HSQLDialect for HSQL Database Engine 2.3
2019-07-22 21:11:00.507 INFO  [main][ModuleFrameworkImpl:1334] Starting initial bundles
2019-07-22 21:11:01.586 INFO  [main][ModuleFrameworkImpl:1611] Started initial bundles
2019-07-22 21:11:01.587 INFO  [main][ModuleFrameworkImpl:1646] Starting dynamic bundles
2019-07-22 21:11:08.824 INFO  [main][ModuleFrameworkImpl:1743] Started dynamic bundles
2019-07-22 21:11:08.826 INFO  [main][ModuleFrameworkImpl:412] Navigate to Control Panel > Configuration > Gogo Shell and enter "lb" to see all bundles
2019-07-22 21:11:15.778 WARN  [Elasticsearch initialization thread][EmbeddedElasticsearchConnection:288] Liferay is configured to use embedded Elasticsearch as its search engine. Do NOT use embedded Elasticsearch in production. Embedded Elasticsearch is useful for development and demonstration purposes. Refer to the documentation for details on the limitations of embedded Elasticsearch. Remote Elasticsearch connections can be configured in the Control Panel.

    __    ____________________  _____  __
   / /   /  _/ ____/ ____/ __ \/   \ \/ /
  / /    / // /_  / __/ / /_/ / /| |\  /
 / /____/ // __/ / /___/ _, _/ ___ |/ /
/_____/___/_/   /_____/_/ |_/_/  |_/_/

Starting Liferay Community Edition Portal 7.1.3 CE GA4 (Judson / Build 7102 / May 14, 2019)

2019-07-22 21:11:22.651 INFO  [main][StartupHelper:72] There are no patches installed
Loading jar:file:/opt/liferay/tomcat-9.0.17/webapps/ROOT/WEB-INF/lib/portal-impl.jar!/portal.properties
2019-07-22 21:11:24.176 INFO  [main][AutoDeployDir:193] Auto deploy scanner started for /opt/liferay/deploy
2019-07-22 21:11:47.310 INFO  [main][ThemeHotDeployListener:108] 1 theme for admin-theme is available for use
2019-07-22 21:11:47.638 INFO  [main][ThemeHotDeployListener:108] 1 theme for classic-theme is available for use
2019-07-22 21:11:49.775 INFO  [main][SystemCheckOSGiCommands:54] System check is enabled. You can run a system check with the command "system:check" in Gogo shell.
22-Jul-2019 21:11:51.238 INFO [main] org.apache.catalina.startup.Catalina.start Server startup in [57,178] milliseconds


text:
Q: Get top value of rotated image in canvas So I create and image and place it in a canvas like this:
draw() {
    this.context = this.canvas.getContext("2d");

    var ox = this.x;
    var oy = this.y;

    this.x += (this.speed * this.mod) * Math.cos(Math.PI / 180 * this.angle);
    this.y += (this.speed * this.mod) * Math.sin(Math.PI / 180 * this.angle);

    this.detectCollision(ox, oy);

    this.context.save();
    this.context.translate(this.x, this.y);
    this.context.rotate(Math.PI / 180 * this.angle);
    this.context.drawImage(this.car, -(this.car.width / 2), -(this.car.height / 2));
    this.context.restore();
}

And now I'm trying to make collision detection, but because I rotate the image it is a bit harder in my opinion.
This is my collision detection:
detectCollision(ox, oy) {
    // top-left corner
    // OX/OY are old cords
    if (this.car.getBoundingClientRect().top < 0 || this.car.getBoundingClientRect().left < 0) {
        this.x = ox;
        this.y = oy;
    }
}

Then I found this function getBoundingClientRect() but it keeps returning 0.
Hope you understand my problem.


text:
Q: In Employee table how to update Experience column of All Employee based on Date Of joining column I have an Employee table and I want to update the Experience column of all employees based on their date of joining DOJ column.
+----+---------+------------+-------------+------------+
| Id |  name   |    DOJ     | Designation | Experience |
+----+---------+------------+-------------+------------+
|  1 | Krishna | 14/01/2012 | Developer   |            |
|  2 | Rahim   | 14/01/2013 | Developer   |            |
|  3 | Ram     | 14/01/2014 | Developer   |            |
|  4 | Shyam   | 14/01/2015 | Developer   |            |
|  5 | Ashok   | 14/01/2016 | Developer   |            |
+----+---------+------------+-------------+------------+

A: Experience calculated in years,
UPDATE test SET Experience = floor(datediff(curdate(),DOJ) / 365)

Experience calculated in months,
UPDATE test SET Experience = 12 * (YEAR(Curdate()) - YEAR(DOJ)) + (MONTH(curdate()) - MONTH(DOJ))


text:
Q: unable to require('aws-iot-device-sdk') using browserify. Hi we are unable to use require('aws-iot-device-sdk') using browserify in nodejs application, error as follows -
Uncaught SyntaxError: Unexpected identifier

from bundle.js

A: We were able to package aws-iot-device-sdk using browserify by doing the following:

*

*npm install -g browserify (only required once to install browserify)

*mkdir project

*cd project

*create main.js:
var awsiot = require('aws-iot-device-sdk'); console.log('success');

*npm install aws-iot-device-sdk

*browserify main.js -o bundle.js

One thing we did notice is that one of the files our package depends on has some characters in it which are not recognized by the browser; we were able to fix this by adding <meta charset="UTF-8"> in our html prior to referencing the bundle.


text:
Q: Code not validating, possible incorrect markup? I'm having trouble Validating this code with W3C with doctype <!doctype html> which as far as i'm aware is the HTML5 doc type.
     <?php
   echo "";
   echo "";
   echo "";
   echo "";
   echo "";
   echo "";
   echo "";
   echo "";

   ?>

The errors I am getting for each line are;

Generated Code,

NB. i've appended filetime to each image to stop browser caching of the images.

A: You are missing a closing ' after the image name:
<?php
   echo "";
   echo "";
   echo "";
   echo "";
   echo "";
   echo "";
   echo "";
   echo "";

   ?>

EDIT: Swapping around the double and single quotes
<?php
   echo '';
   echo '';
   echo '';
   echo '';
   echo '';
   echo '';
   echo '';
   echo '';

   ?>

A: The W3C Markup Validation Service checks if a document uses valid HTML.
You got the errors because you tried to validate a document that contains PHP: the validator tries to interpret it as HTML.
Solution: Validate the generated document (after PHP ran). You'll see that your snippet is valid HTML5.


text:
Q: How to insert value in word FormField as string from sql I've got a VBA script, but I get error "Compile error: Object required"
I added the following references in word VBA for application, but it didn't help
-Visual Basic For Applications
-Microsoft Word 12.0 Object library
-OLE Automation
-Microsoft office 12.0 Object Library
-Microsoft ActiveX data Objects 2.8 Library
-Microsoft ActiveX data Objects Recordset 2.8 Library
-Microsoft remote Data Services 2.7 Library

What's missing in this script?
===========================
Sub ftbox()
Dim spinr As String
Dim cnn As ADODB.Connection

Set cnn = New ADODB.Connection
    cnn.Open "lv", "xx", "xxxxxx"

Set spinr = cnn.Execute("select spinnr from cust where custid=" & ActiveDocument.FormField("custid").Result)

ActiveDocument.FormFields("reg").Result = spinr

End Sub

A: I think you are receiving the error because:
Set spinr = cnn.Execute("select spinnr from cust where custid=" & ActiveDocument.FormField("custid").Result)

should be:
Set spinr = cnn.Execute("select spinnr from cust where custid=" & ActiveDocument.FormFields("custid").Result)

That being said, there looks like lots of weirdness going on in your code.  This:
cnn.Open "lv", "xx", "xxxxxx"

looks very strange to me.  I'm not sure what data source you are trying to connect to (unless you just did it for posting).  Also:
Dim spinr As String

...

Set spinr = cnn.Execute("select spinnr from cust where custid=" & ActiveDocument.FormField("custid").Result)

The object returned by cnn.Execute is an ADODB.Recordset, not a string.  spinr should be an ADODB.Recordset type.
Finally:
ActiveDocument.FormFields("reg").Result = spinr

should be more like:
ActiveDocument.FormFields("reg").Result = spinr.Fields("spinnr")

because spinnr will be an Recordset object.  You don't close your connection or deallocate your objects.  May cause issues if you try to connect to your datasource, especially if the code breaks and you End the procedure. I don't know the Word objects that well, so you you may have even more issues.

A: I tried to use your code and got the same error. I think that the error is occurring because you are pre-fixing a string (assignment) with SET. If you remove the SET then you get a different error.
As already mentioned, you need to use a recordset:
Dim rst as ADODB.Recordset

Then run the following 2 lines after you have opened the connection:
Set rst = cnn.Execute("select spinnr from cust where custid=" & ActiveDocument.FormFields("custid").Result)
spinr = rst.GetString(adClipString, -1, vbTab)

I hope this helps.


text:
Q: how to have a deployed heroku build while maintaining separate development build I'm somewhat new to maintaining separate production vs development builds of an app.
I want to have my current build deployed to heroku so i can easily get it in front of people for critique but I'd also like to run a local version as well so i can make changes and see them quickly on the fly.
With my app on heroku, everytime i make a change, I have to push to github then hit the deploy button. This takes a relatively long amount of time compared to just launching the app on localhost and just refreshing the browser page to see how the changes came out. This is fine if you have made a ton of changes and you know they all work as expected, but its horrible for trying incremental changes, as you can imagine.
I know this is sort of a newbie question, but how can I have the best of both worlds?

A: The only way to achieve something like this is with review apps.
Instead of doing a git push, you will need to enable GitHub Sync. You will be able to deploy either through the heroku dashboard, or automatically when a push is made to master.
Review apps will automatically create a test app and configure it, for each pull request.
Then, when you wish to do QA with other people, you just have to give them the address to that review app where the new code is deployed instead of the main one.


text:
Q: Snowflake external auth0 with keycloak I hope someone can help me, I tried to create an external security integration in order to authenticate to snowflake over keycloak.
create or replace security integration external_oauth_keycloak
    type = external_oauth
    enabled = true
    external_oauth_type = custom
    external_oauth_issuer = '******'
    external_oauth_rsa_public_key = '+++++'
    external_oauth_scope_mapping_attribute = 'scp'
    external_oauth_token_user_mapping_claim='upn'
    external_oauth_snowflake_user_mapping_attribute= 'login_name'   ;

So when I validate the token, the following error comes throw
'{"Validation Result":"Failed","Failure Reason":"EXTERNAL_OAUTH_MISSING_AUDIENCE"}'

A: For Keycloak, do you see any values like API URL or client Id of the app etc. If yes, then that would be the value for the audience url

A: This article might help you with more details:
https://frost-stefan.medium.com/how-we-got-single-sign-on-to-work-with-snowflake-saml2-and-keycloak-53f047824296


text:
Q: Binding events based on ID with JSF and jQuery I'm having an issue with JQuery and JSF/Richfaces.
I have an inputText component inside a form component.
<h:form id="myForm">
<h:inputText id="myInputField" value="#{myBean.sampleName}" />

I have the following jQuery code:
MySite.supplier= function() {

  // Only attach event listener if the element exists on page
  if ( jQuery('#myInputField') ) {
    jQuery('#myInputField').bind('paste', MySite.common.handleMousePaste.bind(this));
  }

};

MySite.common.handleMousePaste = function(event) {

  // Need to put a tiny delay in so the element has time to get the pasted n content.
  setTimeout(function() { jQuery("#" + event.target.id).keyup(); }, 10);
};

The problem is the way my inputField is rendered. It gets the form name added to it and looks like this:
myForm:myInputField

So my current jQuery code will not find the ID to bind to.
The reason I do not reference it with full form name jQuery('#myForm\\:myInputField') is because I have a field called 'myInputField' in multiple locations throughout the site (Once on each page)
Has anyone any solutions to bind to the ID correctly in the 'MySite.supplier' method as well as in the 'MySite.supplier' method where I have event.target.id?
Thanks

A: Could you assign a class to the text box and then simply use the class selector to bind your paste event?
<h:form id="myForm">
<h:inputText id="myInputField" value="#{myBean.sampleName}" styleClass="bindPaste" />

if ( jQuery('.bindPaste') ) {
    jQuery('.bindPaste').bind('paste', MySite.common.handleMousePaste.bind(this));
}

Simple example on jsfiddle.

A: The awesomeness of the naming container in JSF.  When I was playing with this kind of thing, I used jQuery's endsWith selector ( the '$=' in the following code ).
jQuery('input[id$="myInputField"]')

http://api.jquery.com/attribute-ends-with-selector/

A: Have you tried settig prependId as false.
form id="myForm" prependId="false"


text:
Q: How to establish peer connection in web app using coturn (stun/turn) server I'm building a web app for cam broadcasting. I'm using Django for web app and coturn as (STUN/TURN) signalling server. My goal is to do it with WebRTC.
I don't know how to connect a peer to the signalling server in order to be reachable by other peer. So what I need to know is how to stablish "PeerConnection".
In web application, I have all I need (I think): user.id, shared secret, signalling server IP and port, ... But I don't know how to mix it in HTML JS scripts to connect with coturn server.
I've read coturn server docs and searched for some examples but can't find examples for this part.
Can anybody show me an a example?

A: I think you are bit confused, coturn is not a signalling server, it is a TURN/ STUN server.
Signalling server is something though which you exchange sdp, ice candidates and other data between the peers before they get a direct peer to peer connection, coturn does not do that.
I cannot explain all the bits, but gist is STUN is used for providing public IP of a peer, and TURN is used for a proxy point for transmitting and receving data from a peer when it cannot be directly accessed, and in most cases all you require is a STUN server. The only time they get involved in your WebRTC application is when you create the PeerConnection object, you pass the STUN/TURN server details in the config object, example:
let pc = new RTCPeerConnection({
  "iceServers": [
    {"urls": "stun:example.com"},  // STUN Server address
    {"urls": "turn:example.com", "credential": "test", "username": "test"}  // TURN Server address
  ]
});

A:
So as I understand I will not need to use coturn, just one signalling server like SignalMaster or any other like it. Am I wrong?

You still might need coTurn or any other STUN/TURN server to achieve peer-to-peer or relay connection when host-host connection is not possible. STUN/TURN is required for ICE to have server-reflexive and relayed candidates to perform ICE and guarantee the connectivity.
WebRTC works as offer-answer model, so you need some kind of signalling method like SIP/Jingle or another signalling mechanism to exchange the SDP between two party. You may use some third party solution above of WebRTC implementation or you can write your own simple signalling stack.


text:
Q: Is it possible to define abbreviations for coding? I am using the tikz-timing package to create a timeline since chronosys and chronology wouldn't cooperate and were too limited and archaic-looking to suit my purposes, and moderntimeline unfortunately was unable to display in a horizontal linear format. (The timeline I'm trying to create is rather complex, and the timeline package selection is extremely limited.)
Everything is working fairly nicely, considering that I have just recently taken up LaTeX (after some limited experience with Lilypond) to create this timeline, except for the fact that typing [white, timing/D/background/.style={fill=orange}] takes up a ridiculous amount of space (and time), which is very inconvenient and makes the code look super messy.
I've tried using \newcommand (I've heard \def is basically just an inferior version of it), but so far the compiler doesn't like me using it that way because I'm not defining an actual command, just a substitution.
What I had originally was
\newcommand{\efill}[1]{timing/D/background/.style={fill=#1}}

thinking this would allow me to type [\efill {blue}] to set the fill to blue. Since this was an abbreviation and not a command, it didn't work the way I had intended it to.
The ideal solution would allow the definition of character-to-color synonyms (so instead of typing the whole color name, I could just type the single-character name), and the definition of a custom enclosure notation (eg {{ob}} would expand during compilation to [orange, timing/D/background/.style={fill=blue}].
How can I achieve this?
Here is my newbie attempt at an MWE:

\documentclass{article}
\usepackage{tikz, tikz-timing}

\begin{document}
   \Huge
   \begin{tikztimingtable}
       {\LARGE{Benjy}}  & [blue, timing/D/background/.style={fill=none}]DDDD;[orange,timing/D/background/.style={fill=green}]DDDD  \\

       \begin{extracode}
        \tableheader
            {\begin{Large}Character\end{Large}}
                {\begin{LARGE}\textbf{Events}\end{LARGE}}
            \tablerules
            \fulltablegrid
        \end{extracode}
    \end{tikztimingtable}
\end{document}

I'm not sure if I tagged this correctly, so feel free to add/remove tags.

A: I hope, I got your question right.
I defined a new TikZ style efill, which takes two arguments.

*

*#1 is the draw color

*#2 is the fill color

Then one can use the style like
efill={draw color}{fill color}

To achieve the requested abbreviations b -> blue, etc. I used \colorlet like in
\colorlet{b}{blue}

Implementation
\documentclass{article}
\pagestyle{empty}% for cropping
\usepackage{tikz,tikz-timing}
\colorlet{b}{blue}
\colorlet{o}{orange}
\colorlet{g}{green}
\tikzset{
    efill/.style n args={2}{
        #1,timing/D/background/.style={fill=#2}
    }
}
\begin{document}
\Huge
\begin{tikztimingtable}
    {\LARGE Benjy}  & [efill={b}{none}]DDDD;[efill={o}{g}]DDDD  \\
    \begin{extracode}
        \tableheader
        {\Large Character}
        {\LARGE\textbf{Events}}
        \tablerules
        \fulltablegrid
    \end{extracode}
\end{tikztimingtable}
\end{document}

Output

With a little trickery from here (Arguments for TikZ style) you can also set draw and fill color independently and specify defaults for them. In this example the defaults are draw=black,fill=none.
\documentclass{article}
\pagestyle{empty}% for cropping
\usepackage{tikz,tikz-timing}
\colorlet{b}{blue}
\colorlet{o}{orange}
\colorlet{g}{green}
\tikzset{
    set efill/.code={\pgfqkeys{/tikz/efill}{#1}},
    set efill={draw/.initial=black, fill/.initial=none},
    efill/.style={
        set efill={#1},
        \pgfkeysvalueof{/tikz/efill/draw},timing/D/background/.style={fill=\pgfkeysvalueof{/tikz/efill/fill}}
    }
}
\begin{document}
\Huge
\begin{tikztimingtable}
    {\LARGE Benjy}  & [efill={fill=b}]DDDD;[efill={draw=o,fill=g}]DDDD  \\
    \begin{extracode}
        \tableheader
        {\Large Character}
        {\LARGE\textbf{Events}}
        \tablerules
        \fulltablegrid
    \end{extracode}
\end{tikztimingtable}
\end{document}


text:
Q: How to write a python program that read the input and convert it to pre-defined 14-segments characters with turtle graphics? I have written the turtle graphics functions that define the fourteen segments, and the functions that assemble these segments to form characters, e.g.
def MethodA (width) :
   top_stroke(width)
   middle_stroke(width)
   left_stroke
   right_stroke(width)

I have all the definitions ready, but how do I let python to read an input and convert the characters of the input into the fourteen segments forms, which I defined previously?
Idealy, if I enter "Pizza", the program should produce the output of the characters 'PIZZA' in the fourteen-segments form.
Any suggestions are welcomed and appreciated. Thanks,

A: You could define a dictionary with function references like this:
Characters = {
    'A': MethodA,
    'B': MethodB,
    # ...
}

Then, for a string s:
s = "Pizza"
for c in s:
    c = c.upper() # to fold lowercase into upper case
    if c in Characters:
        Characters[c](width)

This code works using Characters[c] to look up the function reference in the dictionary, then the (width) causes the function to be called (with a width parameter, as the function expects).


text:
Q: Don't want Images as an attachment but need it inline I have this code to include images in email using Java.
MimeBodyPart messageBodyPart = new MimeBodyPart();
DataSource imageSource = new ByteArrayDataSource(imageToByteArray(image, format), type);
messageBodyPart.setDataHandler(new DataHandler(imageSource));
messageBodyPart.setContentID(imageContentID);
multipart.addBodyPart(messageBodyPart);

But my images are shown as attachments as well as inline. What is wrong in it ?

A: Couple of things:

*

*I had not set filename in the body part.
messageBodyPart.setFileName(fileName);

*I was setting format and type as "jpg","image/jpg" respectively instead of "png","image/png"
DataSource imageSource = new ByteArrayDataSource(imageToByteArray(image, format), type);


text:
Q: How can I get my Django admin styles to load? I'm using Django 1.8 with static files and also using django-offsite-storage.
When I browse the Django admin in my browser on my local machine it's requesting the CSS file /admin/css/base.css from my S3 bucket but without the hashed version.  I want it to use the hashed file name version because that's what get's uploaded to the S3 bucket.
I've tried switching DEBUG = True or False, but neither do the trick.
How can I get it to do this on my local machine?

A: The reason my admin styles weren't loading was because I had DEBUG = True in a different settings file than my main settings file (which had DEBUG = False).


text:
Q: Hello. I'm building an app and I'm trying to avoid my onboarding screen showing at every startup. I want it to show only once per user This is my main.dart file:
void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    configOneSignal();
  }

  void configOneSignal() {
    OneSignal.shared.init(kAppID);
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<ThemeChanger>(
      create: (_) => ThemeChanger(),
      child: Builder(builder: (context) {
        final themeChanger = Provider.of<ThemeChanger>(context);
        return MaterialApp(
          debugShowCheckedModeBanner: false,
          title: TITLE,
          themeMode: themeChanger.getTheme,
          darkTheme: Style.get(true),
          theme: Style.get(false),
          home: Directionality(
            textDirection: textDirection,
            child: OnboardingScreenOne(),
          ),
        );
      }),
    );
  }
}

I need help making sure that my splash screen doesnt come up to every user on every startup. So I want to have it show only once per user per device.

A: You can use the shared_preferences package to store a isFirstTime boolean variable. Set it to true in the beginning. When the user finishes the onboarding for the first time, set it to false. And when loading the app, you can check if isFirstTime is true; if it is true, show onboarding, otherwise skip to home.

A: you need to use shared_preferences to record user behavior, once the user navigator after onboarding pages, record it locally, then determine by retrieving the value back when open app:
      home: Directionality(
        textDirection: textDirection,
        child: isRead? HomePage() : OnboardingScreenOne(),


text:
Q: Why does my left join in Access have fewer rows than the left table? I have two tables in an MS Access 2010 database: TBLIndividuals and TblIndividualsUpdates. They have a lot of the same data, but the primary key may not be the same for a given person's record in both tables. So I'm doing a join between the two tables on names and birthdates to see which records correspond. I'm using a left join so that I also get rows for the people who are in TblIndividualsUpdates but not in TBLIndividuals. That way I know which records need to be added to TBLIndividuals to get it up to date.
SELECT TblIndividuals.PersonID AS OldID,
TblIndividualsUpdates.PersonID AS UpdateID
FROM TblIndividualsUpdates LEFT JOIN TblIndividuals
ON ( (TblIndividuals.FirstName = TblIndividualsUpdates.FirstName)
and (TblIndividuals.LastName = TblIndividualsUpdates.LastName)
AND (TblIndividuals.DateBorn = TblIndividualsUpdates.DateBorn
    or (TblIndividuals.DateBorn is null
        and (TblIndividuals.MidName is null and TblIndividualsUpdates.MidName is null
            or TblIndividuals.MidName = TblIndividualsUpdates.MidName))));

TblIndividualsUpdates has 4149 rows, but the query returns only 4103 rows. There are about 50 new records in TblIndividualsUpdates, but only 4 rows in the query result where OldID is null.
If I export the data from Access to PostgreSQL and run the same query there, I get all 4149 rows.
Is this a bug in Access? Is there a difference between Access's left join semantics and PostgreSQL's? Is my database corrupted (Compact and Repair doesn't help)?

A: ON (

        TblIndividuals.FirstName = TblIndividualsUpdates.FirstName

        and

        TblIndividuals.LastName = TblIndividualsUpdates.LastName

        AND (
                 TblIndividuals.DateBorn = TblIndividualsUpdates.DateBorn
                 or
                 (
                     TblIndividuals.DateBorn is null
                     and
                     (
                     TblIndividuals.MidName is null
                     and TblIndividualsUpdates.MidName is null
                     or TblIndividuals.MidName = TblIndividualsUpdates.MidName
                     )
                 )
             )
    );

What I would do is systematically remove all the join conditions except the first two until you find the records drop off. Then you will know where your problem is.

A: This should never happen. Unless rows are being inserted/deleted in the meantime,
the query:
SELECT *
FROM a LEFT JOIN b
         ON whatever ;

should never return less rows than:
SELECT *
FROM a ;

If it happens, it's a bug. Are you sure the queries are exactly like this (and you have't omitted some detail, like a WHERE clause)? Are you sure that the first returns 4149 rows and the second one 4103 rows? You could make another check by changing the * above to COUNT(*).

A: Drop any indexes from both tables which include those JOIN fields (FirstName, LastName, and DateBorn).  Then see whether you get the expected
4,149 rows with this simplified query.
SELECT
    i.PersonID AS OldID,
    u.PersonID AS UpdateID
FROM
    TblIndividualsUpdates AS u
    LEFT JOIN TblIndividuals AS i
    ON
        (
            (i.FirstName = u.FirstName)
        AND (i.LastName = u.LastName)
        AND (i.DateBorn = u.DateBorn)
        );

A: For whatever it is worth, since this seems to be a deceitful bug and any additional information could help resolving it, I have had the same problem.
The query is too big to post here and I don't have the time to reduce it now to something suitable, but I can report what I found. In the below, all joins are left joins.
I was gradually refining and changing my query. It had a derived table in it (D). And the whole thing was made into a derived table (T) and then joined to a last table (L). In any case, at one point in its development, no field in T that originated in D participated in the join to L. It was then the problem occurred, the total number of rows mysteriously became less than the main table, which should be impossible. As soon as I again let a field from D participate (via T) in the join to L, the number increased to normal again.
It was as if the join condition to D was moved to a WHERE clause when no field in it was participating (via T) in the join to L. But I don't really know what the explanation is.