text:
Q: Trigger a rerender of parent component when a child component is rendered I am using the following material-ui theme Paperbase and within the Header.js component, I have the following useEffect hook:
const [temperature, setTemperature] = useState([]);

  const getTemperature= async () => {
    try {

      const response = await fetch('/get-temperature')
      const tempData = await response.json();

      setTemperature(tempData);
    } catch (err) {
      console.error(err.message);
    }
  };

useEffect(() => {
    getTemperature();
}, []);

The main purpose of this, is to display the current temperature as info, within the header component, which gets displayed at first page load/render.
Now within my App.js below, I have the following return setup where the above Header component is called.
return (
    <Router>
      <UserProvider myinfo={myinfo}>
        <Switch>
          <Route path="/">
              <ThemeProvider theme={theme}>

                  <CssBaseline />

                    <Hidden xsDown implementation="css">
                      <Navigator />
                    </Hidden>

                      <Switch>
                        <Route exact path="/new-user"
                          render={(props) => <Content key={props.location.key} />}
                        />
                        <Route exact path="/view-results"
                          render={(props) => <ViewResults key={props.location.key} />}
                        />
                      </Switch>

              </ThemeProvider>
          </Route>
        </Switch>
      </UserProvider>
    </Router>
);

My question is, how can I trigger a rerender of Header (parent) whenever the user routes to either /new-user or /view-results which in turn calls either Content.js or ViewResults.js, inorder to make the useEffect in Header.js refresh the data, from the REST api fetch and display the latest temperature in the header again?
Ideally anytime Content.js or ViewResults.js is rendered, ensure that Header.js getTemperature() is called.
Any help would be much appreciated.

A: Your current code is pretty close to a multi layout system. As being a component child of Route, you can access the current location via useLocation() or even the native window.location.pathname.
This is my example of multi layout React app. You can try to use it to adapt to your code.
The MainLayout use a fallback route when no path is specified. It also contains a Header and include a page

const Dispatcher = () => {
    const history = useHistory();

    history.push('/home');

    return null;
};

const App = () => (
    <BrowserRouter>
        <Switch>
            <Route
                component={Dispatcher}
                exact
                path="/"
            />

            <Route
                exact
                path="/login/:path?"
            >
                <LoginLayout>
                    <Switch>
                        <Route
                            component={LoginPage}
                            path="/login"
                        />
                    </Switch>
                </LoginLayout>
            </Route>

            <Route>
                <MainLayout>
                    <Switch>
                        <Route
                            component={HomePage}
                            path="/home"
                        />
                    </Switch>
                </MainLayout>
            </Route>
        </Switch>
    </BrowserRouter>
);

And here is the code for MainLayout

const MainLayout = ({ children }) => (
    <Container
        disableGutters
        maxWidth={false}
    >

        <Container
            component="main"
            maxWidth={false}
            sx={styles.main}
        >
            {children}
        </Container>

    </Container>
);

Now that Header can be anything. You need to put a capture in this component

import { useLocation } from 'react-router-dom'

cont Header = (props) => {
  const { pathname } = useLocation();

  //alternatively you can access props.location

  useEffect(() => {
    if (pathname === '/new-user') {
      getTemperature();
    }
  }, [pathname]);
};

Note that Header is not a direct descendant of Route therefore it cannot access the location directly via props. You need to transfer in chain
Route -> MainLayout -> Header

Or better use useLocation


text:
Q: if first column of first row contains "Region" word then make that entire row as header.how can i code this in R? I have multiple columns like
Region  | Canal |   Fabricantes|    Marcas  |Aromas Tamanos |   Año

like above so if 1st column of 1st row contains Region then make that row header of Dataframe otherwise dont do anythin...how can i code this in R?

A: Usually you can achieve this while importing the data already. For example, if you are using the openxl package, you can make it read the first row as the column names like this:
library(openxl)

open_xlsx(path='your_filename.xlsx', col_names=TRUE)

If you do not want the first to be the column name, use col_names=FALSE.

redpajama_set_name: RedPajamaStackExchange


text:
Q: MongoDB find by date in Array Schema:
var Users = mongoose.Schema({name: String, usersearchcontractors: [UserSearchcontractors]}

var UserSearchcontractors = new mongoose.Schema({
    type:{ type:String,index:  true },
    area: { type:String,index:  true },
    createdate: { type: Date, default: Date.now() }
    });

Query:
db.users.find( { usersearchcontractors: { $elemMatch: { createdate: { "$lt": new Date()} } } } )

What i'm doing wrong to get users by usersearchcontractors.createdate ?
No results
Thank,
Ron

A: No need to use $elemMatch for this query.
db.users.find( { 'usersearchcontractors.createdate': { "$lt": new Date() } } )


text:
Q: Как сделать так, чтобы при повороте объект не залезал за текстуру? скрипт, поворачивающий объект:
float AngleRotate = RotateSpeed * Input.GetAxis("MoveTower");
rot.z = Mathf.Clamp( rot.z + AngleRotate, -yLimit, yLimit);
Tower.transform.eulerAngles = rot;

Сделал вот такой код. Пушка ставится вертикально не могу понять почему и как можно это исправить?

A: использовать поворот на основе физики: Rigidbody.MoveRotation
вместо поворота который по-факту является телепортированием обьекта в другое положение. (вот в текстуры и залазит, ты же телепортируешь его)


text:
Q: How to access property value in js? I have an object like this:
   let rates = {AUD: 1.5016, BGN: 1.9558, BRL: 3.741, CAD: 1.497, CHF: 1.1446}

How can I access each property? for example I tried :
let val ='EUR';
let test = rates[val];

Resulting in test = undefined?

A: What you attempted to do was find the EUR property/value, which is undefined in your object. What you CAN do, if you want to create another property (if I'm understanding you correctly) is
rates.EUR = // whatever you want the rate to be
If that's not what you're trying to do, provide more information as to what you need done.

A: This may help for You:
     let rates = {AUD: 1.5016, BGN: 1.9558, BRL: 3.741, CAD: 1.497, CHF: 1.1446}
    You can access in two ways:
     1.  rates.AUD --Result is=1.5016
     2. rates['AUD'] -- Result is=1.5016

in case of you, it was showing undefined because of there is no property('EUR') exist in the above object (rated).

A: Here is a sample of how to access each value in the object. It will report the key and value to console.log.
The example generates an array of the  keys that do exist in the object, and then uses a forEach() method to just report the keys and values.  If you have a separate list of keys that you are using, you can use the .hasOwnProperty() method to test that a key exists in the object before you try to access it.

let rates = {AUD: 1.5016, BGN: 1.9558, BRL: 3.741, CAD: 1.497, CHF: 1.1446}
// How can I access each property? for example I tried :

let keys = Object.keys(rates);

keys.forEach( key => console.log(`key = ${key}, value = ${rates[key]}`));


text:
Q: Uncaught SyntaxError: Unexpected token ? using Zepto I'm using Zurb Foundation and am getting the following error
Uncaught SyntaxError: Unexpected token ?

From this block of code:
<script>
    document.write('<script src=http://[mydomain]/js/vendor/'
    + ('__proto__' in  ? 'zepto' : 'jquery')
    + '.js><\/script>');
</script>

The code appears to be in accordance with Zurb's documentation. Is this error something to be concerned about? If so, what could I do to resolve the error?

A: You are missing a variable in the below line:
+ ('__proto__' in  ? 'zepto' : 'jquery')

Should have been something like below:
+ ('__proto__' in myObject ? 'zepto' : 'jquery')


text:
Q: PhpStorm won't start - flashes logo then goes away After restarting my PC and clicking the PhpStorm icon to launch it, the splash screen loads, then nothing does.  PhpStorm will not open.

A: Three Step Solution

*

*From this post (copied below in case the URL ever dies):

I had the same problem on the same day so perhaps it relates to a Windows update.  (Edit - ignore that, my problem happened on January 17th, 2017 not 2016).
I renamed C:\Users\USERNAME.PhpStorm2016.3 to something else and it then started and allowed me to import my settings, which seems to have worked.  I hope this helps others as this is much easier than rebuilding my Windows profile.

NOTE: On older versions of PhpStorm the path is C:\Users\USERNAME\.WebIde100

*Upon restarting Windows after renaming my PhpStorm directory I tried to import the settings from my renamed C:\Users\USERNAME\OLD.WebIde100\config but got an error that settings.jar could not be found.

*I closed PhpStorm and renamed my new .WebIde100 to NEW.WebIde100 and my OLD.WebIde100 back to .WebIde100.  I did not have to restart my computer; launching PhpStorm again brought back my old settings.

I'm not sure why all this was needed, but it worked for me so I thought I'd share.


text:
Q: How to make GWT find source in linked folders? I'd like to create a GWT (2.0.4) project but with my source in a common java directory that's not kept under the GWT project directory.
I did the following:
1) Created new project 'game' in package com.mycomp.project.game.  This worked fine, with its source under C:\java\Projects\game\src\com\mycomp\project\game.
2) Copied the code into C:\java\com\mycomp\project\game
3) Deleted the directories under C:\Projects\game\src\
4) File, New Folder, Advanced/Link to folder in filesystem to make a 'com' folder under src that links to C:\java\com.
This worked enough that I can see all the source under a com.mycomp.project.game folder in Eclipse, but when I try to run my project I now get errors of "Unable to find type 'com.mycomp.project.game.client.Game'".
Does GWT just not work with these links to filesystem folders?  Is there any way for me to keep my Java code somewhere outside of my project directory but still have it work in GWT?
Thanks.

A: You have two options.

*

*Move the source code into a directory under your GWT module (.gwt.xml file) location and change the <source path="" /> to point to the shared directory and the client code.

*Create a JAR file with the source you want to reuse. The JAR will also have to have a GWT module. In your existing project you'll have to <inherit ... /> that reusable JAR.


text:
Q: Why parsing this JSON string using JSONObject give me an error? I have this code
String resultStr = result.getString("result");
String testStr = "{\"movielens\":{\"searchMovie\":{\"code\":400,\"data\":\"Access Denied\"}}}";
Log.e("result", resultStr);
Log.e("teststr", testStr);
JSONObject testJson = new JSONObject(testStr);
JSONObject resultJson = new JSONObject(resultStr);

which normally parsing json from the web.
The testStr here is the string that i copy in the logcat by hand and try to put it to test if it is error or not.
and this is the result :
02-13 12:16:44.570: E/json result(23439): {"statusCode":200,"result":"{\"movielens\":{\"searchMovie\":{\"code\":400,\"data\":\"Access Denied\"}}}","success":true}
02-13 12:16:44.575: E/result(23439): {"movielens":{"searchMovie":{"code":400,"data":"Access Denied"}}}
02-13 12:16:44.575: E/teststr(23439): {"movielens":{"searchMovie":{"code":400,"data":"Access Denied"}}}
02-13 12:16:44.575: W/System.err(23439): org.json.JSONException: Value  of type java.lang.String cannot be converted to JSONObject
02-13 12:16:44.580: W/System.err(23439):    at org.json.JSON.typeMismatch(JSON.java:107)
02-13 12:16:44.580: W/System.err(23439):    at org.json.JSONObject.<init>(JSONObject.java:158)
02-13 12:16:44.585: W/System.err(23439):    at org.json.JSONObject.<init>(JSONObject.java:171)
02-13 12:16:44.585: W/System.err(23439):    at com.abac.recommender.movielensdemo.BaseActivity$MakeRequest.onPostExecute(BaseActivity.java:176)
02-13 12:16:44.585: W/System.err(23439):    at com.abac.recommender.movielensdemo.BaseActivity$MakeRequest.onPostExecute(BaseActivity.java:1)

It always error at this line JSONObject resultJson = new JSONObject(resultStr);
which is the json i get from the web but why testStr is not error when convert it to json? Both string look identical?
So i test equality for them like this
Log.e("compare", "" + resultStr.equals(testStr));

and i get
02-13 12:25:20.940: E/compare(23912): false

So, what are the difference and how can i get this to work?
Thanks.

A: Some times what happen when you are fetching data from the server at that time some un-wanted characters was added when you compose the String. So try this it will help you.
Instead of return only json object change from
return urJsonObject;

to
return new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1)


text:
Q: What are the best practices for versioning XML schemas? I often have to design XML schemas for different XML-bases import routines. It is clear that XML schemas will evolve over time or they could contain bugs to be fixed, so it is important to capture the schema's version and to have some mechanism to bind against a specific version.
Currently I have two scenarios:

*

*The bug is found within the schema and all schema instances must comply with the fixed version.

*The schema upgraded and should be considered as preferable but an old one should be also supported.
Finally I came up with storing version information within the namespace of schema:
targetNamespace="http://schemas.company.com/Geodesy/2010/River.xsd"

When fixing a bug I fix it in the same namespace but if I'm about to upgrade a schema then I need to create a new namespace but with upgrade month added:
targetNamespace="http://schemas.company.com/Geodesy/2010/01/River.xsd"

And if I have more than one upgrade in a month then just append a day too:
targetNamespace="http://schemas.company.com/Geodesy/2010/01/17/River.xsd"

Do you know any better approach?

A: This is such a difficult subject that it's not even funny, and one that I have spent years providing consultancy support for.
There are many best practices out there, but a most of them do not work in all situations. For example, many advocate the use of "xsd:any" to allow extensions, and that is just a recipe for disaster if developers are in charge of maintaining the schema, turning it into a dump.
Here are some tips for you if you're getting started:

*

*Do not put a minor version number, micro version number, date, or anything else of the sort, into your namespace. Every time you change the namespace, you will break all processing applications.

*Do put a "version" attribute in the XML instance document. That will enable a processing application or a version adapter service to figure out what it is processing.

*Do specify a policy of what constitutes a backwards compatible change, for example: adding optional elements will not break senders, and will not break receivers either if they use a policy of ignoring elements they do not know (JAXB and XMLBeans can be configured this way)

Dood luck!

A: http://www.xml.com/pub/a/2004/07/21/design.html provides good guidelines and XML Schema 1.1 enables 'versioning' through conditional inclusion (http://www.w3.org/TR/xmlschema11-1/#cip).


text:
Q: Javascript | Enter key first time should press a button, second time should press a label or url First time we press keyboard enter key should execute button(id="botonCorregir"). But the second time we press enter key should execute url().
I use cont, for the first time execute one part of the javascript code, and after when de cont value is 1, execute the second part of javascript code.
For some mistake, it doesn´t work.
thanks!
HTML:
<input id="respuestaUsuario"></input>

<button id="botonCorregir">Reply</button>
Next question

JAVASCRIPT:

A: I guess you were on the right track, but the problem is that your Javascript only gets executed once. So, the else case will never be triggered. I refactored your code to use the check in the event listener:
        var cont = 0;

        var input = document.getElementById("respuestaUsuario");
        input.addEventListener("keyup", function (event) {
          if (event.keyCode == 13) {
            event.preventDefault();
            if (cont == 0) {
              cont++;

              document.getElementById("botonCorregir").click();
            } else {
              document.getElementById("enlaceSiguiente").click();
            }
          }
        });

I also created a codepen for you to check out.

A: You have a few mistakes in the code.
You are assigning the event based on the value of cont so always will have that functionality. Javascript does not re-interpret the code once the value of cont is changed.
I mean, Javascript check only one time the condition:
if(cont==0){}

This is a solution that works:
var cont=0;
var input = document.getElementById('respuestaUsuario');

input.addEventListener('keyup', function (event) {
  event.preventDefault();
  if (event.keyCode == 13) {
    if(!cont){
      alert('uno');
      document.getElementById("botonCorregir").click();
      cont++;
    }else{
      document.getElementById("enlaceSiguiente").click();
    }
  }
});


text:
Q: start - end time in pandas column I have a following problem. I would like to compute time period when each id occurs in df.
data = {'id': [2, 2, 2, 4, 4], 'time': ['22:17:46', '22:19:02', '22:06:00', '22:18:06', '22:18:06']}
pd.DataFrame.from_dict(data)

In the example above the desired output would be 22:19:02 - 22:06:00 = 13.03 minutes for id 2. Similarly 0 for id 4. Finally, what I want is:
data = {'id': [2, 2, 4, 2, 4], 'time': ['22:17:46', '22:19:02', '22:18:06', '22:06:00', '22:18:06'], 'time_diff': [13.03, 13.03, 0, 13.03, 0]}

I tried this, but it is terribly slow on large data:
data["max_time"] = data.groupby(["ip_adresa"])["time"].transform("max").astype(str)
data["min_time"] = data.groupby(["ip_adresa"])["time"].transform("min").astype(str)

data["time_diff"] = ""

for i in range(0, len(data)):
    data["diff_time"][i] = (
        datetime.datetime.strptime(data["max_time"][i], format)
        - datetime.datetime.strptime(data["min_time"][i], format)
    ).total_seconds()

How can I do it please?

A: use the transform function.  it iterates over every row returned by the groupby for id and finds the min and max values.   cast the time as a datetime data type
data = {'id': [2, 2, 2, 4, 4], 'time': ['22:17:46', '22:19:02', '22:06:00', '22:18:06', '22:18:06']}
df=pd.DataFrame.from_dict(data)

df['time'] = pd.to_datetime(df['time'])
df['time_diff'] = df.groupby('id')['time'].transform(lambda x: x.max() - x.min())
print(df)

output
 id                time       time_diff
0   2 2021-11-16 22:17:46 0 days 00:13:02
1   2 2021-11-16 22:19:02 0 days 00:13:02
2   2 2021-11-16 22:06:00 0 days 00:13:02
3   4 2021-11-16 22:18:06 0 days 00:00:00
4   4 2021-11-16 22:18:06 0 days 00:00:00


text:
Q: scp copy directory to another server with private key auth is there something wrong with this scp command ?
scp -C -i ./remoteServerKey.ppk -r /var/www/* root@192.168.0.15:/var/www

I use the same .ppk as in putty and enter the same passphrase, but it asks me 3 times and than says connection denied. I thought I used it before and it worked, but it isn´t atm.
If it is wrong, how should I do it ?

A: or you can also do ( for pem file )
 scp -r -i file.pem user@192.10.10.10:/home/backup /home/user/Desktop/

A: Covert .ppk to id_rsa using tool PuttyGen, (http://mydailyfindingsit.blogspot.in/2015/08/create-keys-for-your-linux-machine.html) and
scp -C -i ./id_rsa -r /var/www/* root@192.168.0.15:/var/www

it should work !

A: The command looks quite fine. Could you try to run -v (verbose mode) and then we can figure out what it is wrong on the authentication?
Also as mention in the other answer, maybe could be this issue - that you need to convert the keys (answered already here): How to convert SSH keypairs generated using PuttyGen(Windows) into key-pairs used by ssh-agent and KeyChain(Linux) OR http://winscp.net/eng/docs/ui_puttygen (depending what you need)

A: Putty doesn't use openssh key files - there is a utility in putty suite to convert them.
edit: it is called puttygen


text:
Q: Как проверить поддержку es 2015, 2016? Хочу генерировать на сайте несколько вариантов js (es5, es2015, es2016), и отдавать клиенту нужный файл с js, в зависимости от того, какой стандарт поддерживает его браузер.
Подскажите, пожалуйста, как лучше проверить что поддерживает браузер клиента?
Я сначала хотел прямо в браузере проверять, что он поддерживает, а потом соответственно подключать нужный файл js. Но меня, беспокоит, не приведёт ли это к тому, что js начнёт выполнятся позже?
Просто изначально браузер сразу начал бы загружать файл с js, а так он сначала должен дойти до кода с проверкой, выполнить его и только после этого добавить тег с подключением скрипта и браузер начнет грузить нужный js.
Я подумал, может такую проверку можно делать на сервере, по заголовку который приходит от клиента? Т.е. например смотреть версию юзер агента, и по ней понимать поддерживает этот браузер es2015, или нет, может есть какая нибудь php библиотека для этого?

A: В вашем случае просто делайте две сборки: под IE и под все остальные браузеры. Есть пакет babel-env, там можно указывать список браузеров, под которые компилится бандл. Если вы указываете новые браузеры, то babel не будет компилить все в es5, а только те вещи, которые в новых браузерах еще не поддерживаются.
Поэтому, отдельно собираете для новых браузеров, отдельно для IE и отдаете с сервера по условию
Как вариант еще, использовать полифилы, подгружая их только для IE, для этого условные комментарии подойдут:
// если IE9
<!--[if lt IE 9]>
    <script src='ссылка на полифил' >
<![endif]-->


text:
Q: Ethernet does not work with a specific cable (Ubuntu 15.10) I have to use a static IP configuration. I just got a new ethernet cable, and it worked fine for a while. Then it stopped detecting the ethernet connnection. I mean, it would tell me that I'm connected, then as soon as I tried accessing any website it would stop detecting the connection.
I followed the advice I found in several answers on this forum, and set managed=true in my NetworkManager.conf file. This worked for a while, but now it refuses to detect the ethernet connection altogether.
It works with two other ethernet cables I've tried (borrowed from friends) but not with mine. All the cables work fine with Windows 10 though.
Are there some compatibility issues with my particular cable? Do ethernet cables come in different types?
UPDATE: One of the cables Ubuntu is fine with is a category 6 cable, while mine is a category 5e.

A: it sounds similar to the problem that I have at the moment. Unfortunately I have not been able to find a solution yet but I will let you know if I figure it out.
edit
In the meantime please could you post the output of the following commands
lspci | grep Ethernet
ifconfig eth0
sudo lshw -class bridge
sudo lshw -class network

edit 2
For reference
https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1003297
https://bbs.archlinux.org/viewtopic.php?pid=1551149#p1551149

A: It seems to me to be a problem with the r8169 driver I had. I downloaded the r8168 driver from the Realtek website and now my ethernet connection works perfectly.


text:
Q: Python 'tarfile' module unable to handle non utf-8 filenames in tar file I am using Python 2.7 with 'tarfile' module, the tar file I am processing has filenames that are not unicode, and 'tarfile' module is erroring out. How do I tell the 'tarfile' model to ignore the errors? The code below gives me the error:
UnicodeDecodeError: 'utf8' codec can't decode byte 0xa2 in position 5: invalid start byte

if tar_flag:
    tar_obj = tarfile.open(infile, 'r', encoding='utf-8', errors='surrogateescape')
    try:
        member_list = tar_obj.getmembers()
        for member in member_list:
            if member.isfile():
                if member.name.lower().endswith('.exe'):
                    tar_obj.extract(member.name, path='/home/tar/')
                    print 'extracting {}'.format(member.name)
    except Exception as err:
        print err

A: Python 2.x does not support UTF, so I switched to Python 3 and this worked.


text:
Q: How can I create two borders or box shadows around an image? I'm trying create this background/border using only CSS but I have some difficulties:

My code:
.profile-userpic img {
    width: 80%;
    background-color: transparent;
    box-shadow: -10px -10px 0 0px #291026, 10px 10px 0 0px #f00;
}

Actually I got this:

I need just transform the red background in a transparent object with border, just like the original design
The picture needs to be responsive and I need to use this 'border/background' in others elements like a button or div.

A: This should get you started, not responsive, but shows one way it can be accomplished.

.profile-userpic img {
  transform:translateY(20px) translateX(30px);
}
.profile-userpic:before {
  content:'';
  display:block;
  width:250px;
  height:280px;
  background:black;
  position:absolute;
  z-index:-1;
}
.profile-userpic:after {
  content:'';
  display:block;
  width:250px;
  height:280px;
  border:1px solid black;
  position:absolute;
  z-index:-1;
  top:22px;
  left:60px;
}

A:

.ctn {
  width: 400px;
  height: 400px;
  display: flex;
  justify-content: center;
  align-items: center;

}

.picture {
  width: 200px;
  height: 200px;
  background-color: purple;
  position: relative;
}

.picture:before {
  position: absolute;
  background: red;
  content:'';
  width: 100%;
  height: 108%;
  top:-12px;
  left:-12px;
  z-index: -1;
}

.picture:after {
  position: absolute;
  background: transparent;
  border: 2px solid red;
  content:'';
  width: 105%;
  height: 107%;
  top:-6px;
  left:10px;
  z-index: -1;
}

Have you considered using :before and :after elements instead:
have a look at this sample I made:
https://jsfiddle.net/bo2nn6kk/
All you need to do is position it appropriately and adjust width and height.

A: Here is a fiddle that should help. :before, :after, and z-index are valuable for something like this.
CSS
.profile-userpic {
  position: relative;
  display: inline-block;
}

.profile-userpic:before,
.profile-userpic:after {
  z-index: 1;
  content: "";
  position: absolute;
  display: block;
  width: 100%;
  height: 100%;
}

.profile-userpic:before {
  background-color: red;
  top: -8px;
  left: -12px;
}

.profile-userpic:after {
  background-color: #fff;
  border: 1px solid red;
  bottom: -25px;
  right: -25px;
}

.profile-userpic img {
  z-index: 2;
  position: relative;
}

https://jsfiddle.net/d6tv5jp3/3/


text:
Q: Using  on a List doesn't update model values I've the below data table:
<h:dataTable var="row" value="#{myBean.listOfStrings}">
    <h:column>
         <h:inputText value="#{row}" />
    </h:column>
</h:dataTable>

Which is tied to a List<String>:
private List<String> listOfStrings = new ArrayList<String>();

public List<String> getListOfStrings() {
    return listOfStrings;
}

public void setListOfStrings(List<String> listOfStrings) {
    this.listOfStrings = listOfStrings;
}

When I enter a value in the field and save the form it is not passing the value to the field in the list, it is setting null, what am I doing wrong here?

A: The String class is immutable. It doesn't have a setter for the instance value. The getter is in this construct basically the Object#toString() method as implicitly called by EL, which coincidentally returns the string value itself.
You need to set the changed value as a new list item instead. You can do this via the brace notation on the list whereby you pass the list index: #{myBean.listOfStrings[index]}.
So, this should do, making use of UIData#getRowIndex() as list index:
<h:dataTable binding="#{table}" value="#{myBean.listOfStrings}" var="row">
    <h:column>
         <h:inputText value="#{myBean.listOfStrings[table.rowIndex]}" />
    </h:column>
</h:dataTable>

(note: the value expression of binding is as-is! don't bind it to a bean property)
See also:

*

*Using <ui:repeat><h:inputText> on a List<String> doesn't update model values

*What is component binding in JSF? When it is preferred to be used?


text:
Q: Modelling a backspin pool shot I'm trying to derive equations for $\theta(t)$ and $r(t)$ when modelling a backspin shot in pool.
I am of the understanding that the rotational deceleration is $\ddot \theta(t)=\dfrac{m\mu_sgR}{I}$ where $\mu_s$ is the coefficient of sliding friction.
However, the values that I have for the real world gives me a crazy deceleration.

*

*mass of whiteball $96$g = $0.096$kg

*radius of whiteball $\frac{15}{16}$in = $2.38$cm = $0.0238$m

*coefficient of sliding resistance = $0.3$

*$g = 9.8$m/s²

*Moment of inertia $I$ = $\frac{2}{5}mR^2$ = $0.0000218$ kg m²

Subbing all of this in gives $\ddot \theta(t)=\dfrac{0.096 \times 0.3 \times 9.8 \times 0.0238}{0.0000218}\approx 300$
Why am I getting an angular acceleration of $300$ rad / second?

A: I think the critical part is to understand the way the rotation of the ball is connected to its translation, which isn't trivial (at least not for me).
Of course there might be a strange result at the end since your model assumes constant frictional force and rotational parameters can be hard to estimate.
From what you worked out (seems to be plausible regarding $L=I\cdot \dot{\theta}, ~ \dot{L}=M, ~ M=F \cdot r$ ) you can try to find the above mentioned connection between translation and rotation to estimate how this result affects the outcome, i.e. how long it takes the ball to reach the turning point.
A simple approach is to think of the ball as a point mass for a moment and to use $$m\cdot a = F = m\cdot g\cdot \mu_s.$$
However, i don't think that this calculation is accurate, because the force acts on the ball by slowing down his forward motion and affecting his rotation. The latter seems to be somehow unregarded because this actually assumes the force to act on the center of mass, which implies no effect on it's rotation. Nevertheless you get
$$ v(t) = v_0 - a \cdot t = v_0 - m  g \mu_s \cdot t $$
$$ \dot{\theta}(t) = \omega_0 - \ddot{\theta}\cdot t = \omega_0 - \frac{m \mu_s g R}{I}\cdot t$$
By muliplying the last equation with $R$  and using $I = \frac25 m R^2$ you  obtain the rotational speed: $$v_r (t) =\omega_0 R - \frac{5 \mu_s g}{2} \cdot t$$
Maybe you can use these equations to estimate if your result is possible.
Good luck!
Paul


text:
Q: Корректное отображение содержимого WPF при масштабировании Windows (100% - 175%) При разработке WPF приложения столкнулись со следующей проблемой.
Обнаружили, что если скомпилировать приложение при установленном пользователем масштабе операционной системе Windows(100%), содержимое WPF отображается корректно. Но стоит во время работы программы поменять масштабирование системы на любое другое(125-200%), содержимое WPF окна начинается размываться. Но если при выбранном масштабе заново собрать приложение, размытие пропадает.
Как с этим бороться ?


text:
Q: Convert Query Cursor Data to URL's and Run it in AsyncTask Hi I am using a function that looks like this. It converts a string to URL's
protected URL stringToURL(String urlString) {
    try {
        URL url = new URL(urlString);
        return url;
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    return null;
}

and sample use of that is this.
final URL url1  = stringToURL("www.link_to_my_page/sample_image1.jpg");

and if i want to use more i will just use it like this.
final URL url1  = stringToURL("www.link_to_my_page/sample_image1.jpg");
final URL url2  = stringToURL("www.link_to_my_page/sample_image2.jpg");
final URL url3  = stringToURL("www.link_to_my_page/sample_image3.jpg");
final URL url4  = stringToURL("www.link_to_my_page/sample_image4.jpg");
final URL url5  = stringToURL("www.link_to_my_page/sample_image5.jpg");
final URL url6  = stringToURL("www.link_to_my_page/sample_image6.jpg");
final URL url7  = stringToURL("www.link_to_my_page/sample_image7.jpg");
final URL url8  = stringToURL("www.link_to_my_page/sample_image8.jpg");
final URL url9  = stringToURL("www.link_to_my_page/sample_image9.jpg");

and then i have an AsyncTask that will process all of that and here it is
private class DownloadTask extends AsyncTask<URL, Integer, ArrayList<image_class>> {
    protected void onPreExecute() {

    }

    protected ArrayList<image_class> doInBackground(URL... urls) {

    }

    protected void onProgressUpdate(Integer... progress) {

    }

    protected void onCancelled() {

    }

    protected void onPostExecute(ArrayList<image_class> result) {

    }
}

and if i want to run my AsyncTask i will call it like this
mMyTask = new DownloadTask().execute(url1);

or for multiple
mMyTask = new DownloadTask().execute(url1,url2,url3,url4,url5,url6,url7,url8,url9);

and now here is my concern. all my links where inside my SQLite Database and what I did so far is create a Cursor Loop them while using stringToURL inside an array then call it like this mMyTask = new DownloadTask().execute(Array_of_Urls.ToString()); but no luck and it gave an errors.
My question is how can call that task using my urls in database?
Here is my current code
on Create Method
load_sync = findViewById(R.id.load_sync);
mProgressAnimation = new ProgressBarAnimation(load_sync, 100);

startMyAsyncTaskWithURList();

and here is the whole code
private ArrayList<URL> getMyURLFromDB() {
    ArrayList<URL> listURL = new ArrayList<>();

    Cursor cursor = Sync.get_image(current_email);
    while (cursor.moveToNext()) {
        String folder = cursor.getString(cursor.getColumnIndex("folder"));
        String urlString = cursor.getString(cursor.getColumnIndex("myimage"));
        String gen_link = "Custom URL" + folder + "/" + urlString;
        Log.e("Link ", "" + gen_link);
        URL url = null;
        try {
            url = new URL(gen_link);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        listURL.add(url);
    }
    return listURL;
}

private class DownloadTask extends AsyncTask<String, Integer, ArrayList<image_class>> {
    protected void onPreExecute() {

    }

    ArrayList<URL> listURL = null;
    public DownloadTask(ArrayList<URL> urls){
        this.listURL = urls;
    }

    protected ArrayList<image_class> doInBackground(String... params) {
        int count = listURL.size();
        HttpURLConnection connection = null;
        ArrayList<image_class> bitmaps = new ArrayList<>();

        for (int i = 0; i < count; i++) {
            URL currentURL = listURL.get(i);
            String fileName = currentURL.toString().substring(currentURL.toString().lastIndexOf('/') + 1);

            try {
                connection = (HttpURLConnection) currentURL.openConnection();
                connection.connect();

                InputStream inputStream = connection.getInputStream();
                BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);

                Bitmap bmp = BitmapFactory.decodeStream(bufferedInputStream);
                bitmaps.add(new image_class(bmp,fileName));

                publishProgress((int) (((i + 1) / (float) count) * 100));
                if (isCancelled()) {
                    break;
                }

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                connection.disconnect();
            }

            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        return bitmaps;

    }

    protected void onProgressUpdate(Integer... progress) {
        mProgressAnimation.setProgress(progress[0]);
    }

    protected void onPostExecute(ArrayList<image_class> result) {
        Iterator itr = result.iterator();
        while(itr.hasNext()){
            image_class st = (image_class) itr.next();
            Bitmap bitmap = st.image;
            saveImageToInternalStorage(bitmap, st.filename);
        }
    }
}

protected Uri saveImageToInternalStorage(Bitmap bitmap, String filename) {
    File file = sdCardDirectory;
    file = new File(file, filename);

    try {
        OutputStream stream = null;
        stream = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        stream.flush();
        stream.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

    Uri savedImageURI = Uri.parse(file.getAbsolutePath());
    return savedImageURI;
}

the image doesnt download or the AsyncTask is not working

A: This is just a basic outline:
private ArrayList<> getMyURLFromDB(){
    ArrayList<> listURL = new ArrayList<>();

    // You will need to fill in some blanks here...
    //... This is just a basic outline!
    SQLiteDatabase db = dbModel.getReadableDatabase();
    Cursor cursor = db....
    while (cursor.moveToNext()) {
        String urlString = cursor.getString(cursor.getColumnIndex(MY_URL_STRING));
        URL url = new URL(urlString);
        listURL.add(url);
    }
    return listURL;
}

Get the List from the database and pass the ArrayList as a parameter of the AsyncTask:
private void startMyAsyncTaskWithURList(){
    ArrayList<URL> listURL = getMyURLFromDB();
    // Just pass the ArrayList as a parameter
    new DownloadTask(listURL).execute();
}

You need to add a constructor of the AsyncTask that will accept the ArrayListas a parameter:
private class DownloadTask extends AsyncTask<String, Integer, ArrayList<image_class>> {

    ArrayList<URL> listURL = null;
    public DownloadTask(ArrayList<URL> urls){
        this.listURL = urls;
    }

    protected ArrayList<image_class> doInBackground(String... params) {
        // Now you have access to the list
        if(listURL != null){
        }

    }

    protected void onPostExecute(ArrayList<image_class> result) {

    }
}


text:
Q: Displaying html tags as simple string I'd like to make html no interpreted. so when i do an "ECHO" within my php page
the html balise will not be interpreted
for example :
"‹b    ›chat  ‹/b›" will be "   ‹b ›chat  ‹/b›" : true
"‹b    ›chat  ‹/b›" will be chat : false

A: Use htmlentities()
Try this,
echo htmlentities("<b>chat</b>");


text:
Q: How to get around a 'by design' issue with Windows dir? dir /b produces a nice file-only list
dir /x produces a detailed listing (date, time, size, longname, shortname)
However, if you combine the two (i. e. dir /b /x) the /x switch gets ignored. this behavior as per this page is by design.
So if you ask for a simple list containing only of shortnames of files, Redmond (Microsoft) says it is against the rules of heaven to give it to you.
How could one get around this 'by design' issue?
many thanks in advance
p.s. this is to help me achieve something explained in this question. five kind friends have posted answers to whom i am very grateful, but non of the answers helped me get what i want.

A: Try this:
for /f "usebackq delims=" %X in (`dir /b`) do @echo %~nsxX

Or, if you want fully-qualified path names:
for /f "usebackq delims=" %X in (`dir /b`) do @echo %~fsX

For more information, see the for help:
for /?

Note that if you use these commands in a batch file, you'll need to double up the % signs. For example:
for /f "usebackq delims=" %%X in (`dir /b`) do @echo %%~nsxX

A: Short of dumping dir /x to a text file and parsing it, I'm not sure what to suggest.  Do you have the ability to run whatever it is you're doing in code?
It's a more complicated solution, but writing something using perl or another scripting language; or go whole hog and write some code in C#.
I suspect that you're going to get much the same kind of answers that you got on the previous question...

A: You could write your own directory listing executable.  It wouldn't take much to whip up something in C#.  Use Directory.GetFiles() to retrieve the directory listing, and pass each one into the "GetShortPathName()" Win32 function.
This page has a decent example of how to call GetShortPathName() from C#:
http://csharparticles.blogspot.com/2005/07/long-and-short-file-name-conversion-in.html


text:
Q: Is there a way of dynamically attributing the description annotation in testNG?
    private String GIVEN = "";
    private String WHEN = "";
    private String THEN = "";

    @Test(description = GIVEN + WHEN + THEN)
    public void test() {

            GIVEN += "blah blah blah";
            WHEN += "blah blah blah";
            THEN += "blah blah blah";

    }

I want to do it this way b/c I want to add the descriptions in the methods used within tests. This way I avoid comments and can keep details up to date as tests change.
For instance, I will call this method within a test and update the given at the same time:
public void method(){
     code;
     GIVEN += "this code is doing this blah blah";
}

Values can only be a constants so I'm stumped at this point.

A: Define the parameters on TestNG.xml
<parameter name="blah blah blah" />
<parameter name="when" value="blah blah blah" />
<parameter name="then" value="blah blah blah" />

And then can use in your test case like below
  private String GIVEN = "";
   private String WHEN = "";
   private String THEN = "";

    @Test
         @Parameters({"given","when","then"})
            public void test() {

                    GIVEN += given;
                    WHEN += when;
                    THEN += then;

            }

A: ITestResult report = Reporter.getCurrentTestResult();
report.getMethod().setDescription("Whatever you would like to say");


text:
Q: I keep getting this Line : 5 -- syntax error, unexpected ')', expecting ';' Here is line 5 for($i=2005,$i<2016,$i++){
here is the rest of the code just in case anybody asks.
<?php
echo $today = date("m/d/Y")."<br/>";
$myString = "The quick brown fox jumps over the lazy dog";
$year = $i+4;
for($i=2005,$i<2016,$i++){
if($i+date("L"))
echo $year()is a leap year;
$myString = strtoupper($myString);
}else{
echo $year() is not a leap year;
$myString = strtolower($myString);}
if($i=2015)
echo "The quick brown fox jumps over the lazy dog";
str_replace(fox,cat);
?>


text:
Q: Streams :Collect with supplier and accumulator I have been trying to work with collect method of Stream, to convert list into HashMap.
I am using below code as reference :
String result = list.parallelStream().collect(StringBuilder::new,
            (response, element) -> response.append(" ").append(element),
            (response1, response2) -> response1.append(",").append(response2.toString()))
            .toString();

while I write the below incomplete statement in eclipse and do a ctrl+space at ?
Map<String,Choice> map1=  list1.stream().collect(()-> new HashMap<String,Choice>(),
        (r,s) -> r.?,(r,s) -> r.putAll(s));

considering the code snippet that uses StringBuilder, my expectation was that, the first argument of accumulator function should be a HashMap as I have used HashMap::new as supplier function. As per this understanding, eclipse should suggest me methods of HashMap, but that's not the case.
However, this seems to work fine
list1.stream().collect(ArrayList::new, ArrayList::add, ArrayList::addAll);

Already referred Java 8 Int Stream collect with StringBuilder but, not much luck with this.

A: If you wanted to explore more the supplier, accumulator, combiner you should have written that a bit more clear to begin with.
Suppose you have a class like this:
static class Foo {
    private final int id;

    private final String s;

    public Foo(int id, String s) {
        super();
        this.id = id;
        this.s = s;
    }

    public int getId() {
        return id;
    }

    public String getS() {
        return s;
    }

    @Override
    public String toString() {
        return "" + id;
    }
}

If you know that s in this case will be unique you can simply do this:
HashMap<String, Foo> result = Arrays.asList(new Foo(1, "a"), new Foo(2, "b"))
            .stream()
            .collect(HashMap::new,
                    (map, foo) -> map.put(foo.getS(), foo),
                    HashMap::putAll);

    System.out.println(result); // {a=1, b=2}

But if s is not unique you would probably need to collect to a List and that makes things a bit more complicated:
 HashMap<String, List<Foo>> result = Arrays.asList(
            new Foo(1, "a"),
            new Foo(2, "b"),
            new Foo(3, "a"))
            .stream()
            .parallel()
            .collect(HashMap::new,
                    (map, foo) -> {
                        map.computeIfAbsent(foo.getS(), s -> new ArrayList<>()).add(foo);
                    },
                    (left, right) -> {
                        for (HashMap.Entry<String, List<Foo>> e : right.entrySet()) {
                            left.merge(
                                    e.getKey(),
                                    e.getValue(),
                                    (l1, l2) -> {
                                        l1.addAll(l2);
                                        return l1;
                                    });
                        }
                    });

    System.out.println(result); // {a=[1, 3], b=[2]}

A: Convertting a list into a map?
Collectors.toMap(..) might be what you need.
the javadocs have a couple good examples: https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#toMap-java.util.function.Function-java.util.function.Function-

A: Accoring to your comment, I guess you can do it as simple as that.
List<Choice> choices = new ArrayList<>();

Map<String, Integer> map = choices.stream().collect(Collectors.toMap(Choice::getString, Choice::getID);

Rather than writing you own suppliers and accumulators, I recommend using Collectors and its static methods, whose are used to transfer stream to any type of Collection.
EDIT:
If value of the map is required to be Choice. Function interface has static method called identity() (type of last stream transformation before collect was called, Choice in this example).
Map<String, Choice> map = choices.stream().collect(Collectors.toMap(Choice::getString, Function.identity());

A: Map<String,Choice> map= list1.stream().collect(()-> new HashMap<String,Choice>(), (r,s) -> r.put(s.getString(),s),(r,s) -> r.putAll(s));


text:
Q: How to derive geometric mean Suppose that $(1+r_g)^n = (1+r_1)(1+r_2)$, how should I derive the formula such that $r_g = (r_1r_2)^{1/n}$. I am trying to prove that $r_g = (r_1r_2)^{1/n}$.

A: If 1+$r_1, $(1+r_g) and 1+$r_2 are in geometric progression, as your first equation indicates, then $r_1, $r_g and $r_2 also being in G.P is not possible (for all such numbers), AFAIK. There might be numbers satisfying that condition, but it cannot be a general truth that can be proved.


text:
Q: Reachability takes too long to fail when connected to WIFI without internet Hi there
I have been using reachability class and everything works fine; except for ...
When the device is connected to wifi, and for whatever reason, the wifi router does not have internet connectivity the reachability class takes too long to say that there is no internet.
It works well(fast!) when there is no network/internet connectivity at all, for instance, if the wifi is off and the device does not have a 3G connection, reachability class returns success/failure almost instantly.
To re-iterate, connected to a wifi router, where there is no internet connectivity almost takes a full minute for reachability class to return a status.
Reachability *reachability=[Reachability reachabilityWithHostName:@"www.google.com"];
    NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];
    if(remoteHostStatus == NotReachable) {
 ............

My Code
Any suggestions?
Thanks

A: i just tried this
Reachability *reachability=[Reachability reachabilityForInternetConnection];

Looks like it works!  Since i just wanted to see if the internet is available or not
Thanks


text: Q: solve differential equation $x y'=y+\sqrt{x^2-y^2}$ I used $y=vx$ and I got $x^2v'=\sqrt{x^2-v^2x^2}$, normally we write absolute value of $x$ when we extract $x^2$ from the square root, but I do not see anyone doing this at all, why?


text:
Q: How to check the user's link to an account with two domain names? How to validate user profile URL with two domain names. For example, there are sites that are available from some domains. The same site opens with many domain names. For example I can visit to https://website.com with https://wb.com too. In this case URL's to user profiles can be with two domains:

*

*https://website.com/username

*https://wb.com/username
I can individually check these domains with two different patterns:
For: https://website.com/username
(?:(?:http|https):\/\/)?(?:www.)?website.com\/(?:(?:\w)*#!\/)?([\w\-]*)?

For: https://wb.com/username
(?:(?:http|https):\/\/)?(?:www.)?wb.com\/(?:(?:\w)*#!\/)?([\w\-]*)?

How to create a single template to check the link to the user profile?

A: Using alternation to match website or wb, and refactoring the regex to remove unnecessary groups and such, you can use:
(?:https?:\/\/)?(?:www\.)?(?:wb|website)\.com\/(?:\w*#!\/)?([\w-]*)?

Note that because . matches any character, you need to escape it with a \ in front.
https://regex101.com/r/BCbmEw/1
Separated out:
(?:https?:\/\/)?
(?:www\.)?
(?:wb|website)\.com\/
(?:\w*#!\/)?
([\w-]*)?

A: Your regex would probably have to be programmatic if it were to include any username (I'm using Bash to check my work here, so, for name sakes, I'm going with {username} where that is the desired username of the person I want. I'm also going to safely assume all URLs you desire are in that format.
My methodology of testing sites is also to use a text file named sites.txt and my methodology of testing the regex is to run cat sites.txt | grep '{expression}'.
My expression is, where, again, {username} is our desired username:
.*\/{username}$

For example, for the username username, my expression would be:
.*\/username$

Or, for your name of Andreas Hunter, yours might be ahunter1, and the resulting expression would be:
.*\/ahunter1$

The reason why I mention programmatic regex is; say you're doing this from within a program, and your language has a method/plugin/library or something that checks every item in an array or every line in a file, and on an exact match, it returns true, otherwise false.
If you were doing this in Java and your method was running on a string str, and the method was a method of String that was called isRegexMatch(String), and your username that you're checking against is another String called username, your method call would look like:
str.isRegexMatch(".*\\/" + username + "$");


text:
Q: Issues with GAN and VAE models I'm reading this amazing paper on Normalizing Flows https://arxiv.org/pdf/1908.09257.pdf but one sentence kind of bothers me:

GANs and VAEs have demonstrated impressive performance results on
challenging tasks such as learning distributions of natural images.
However, several issues limit their application in practice. Neither
allows for exact evaluation of the probability density of new points.

Maybe I misinterpret it somehow... But can someone explain to me why VAE (or GAN to this matter) cannot evaluate probability density of new points? Isn't it the whole idea of estimating PDF's parameters, so we can evaluate it at any point we want, i.e. new points?
Or do you think the author was making emphasis on "exact evaluation" part?

A: They're some sort of generative models, learning the PDF so that they can sample from it. This is achieved by having random latent representations and mapping them to the relevant domain. So, you can easily generate new samples, but, this is not the same thing as calculating the probability of that sample. The learnt parameters belong to the neural network, not the PDF itself directly. There is no explicit calculation of the probability. To do that, you may need to resort to Monte Carlo methods.


text:
Q: Octave-gui had crashed in macOS, how to fix it? After I installed octave by homebrew command:
brew install octave

, I start octave with gui by command:
octave --force-gui

But it had no response after I entered command
help sign

So I kill the process and tried to restart it. But octave-gui crashed immediately.
the error is : octave exited with signal 6
and I have the crash report:
Process:               octave-gui [12398]
Path:                  /Applications/Octave-4.4.1.app/Contents/Resources/usr/Cellar/octave-octave-app_4.4.1_0/4.4.1/libexec/octave/4.4.1/exec/x86_64-apple-darwin15.6.0/octave-gui
Identifier:            octave-gui
Version:               0
Code Type:             X86-64 (Native)
Parent Process:        ??? [12396]
Responsible:           octave-gui [12398]
User ID:               501

Date/Time:             2019-07-07 12:01:12.543 +0800
OS Version:            Mac OS X 10.14.5 (18F203)
Report Version:        12
Bridge OS Version:     3.5 (16P5200)
Anonymous UUID:        BFDE7534-3B4F-4F39-0D15-117761865994
...

I have tried restart my computer and reinstall the octave but the octave-gui still crashed.
please give me some help.


text:
Q: Nunjucks throws error in template loop I have the following code:
var items = [{'name': 'item1'}, {'name': 'item2'}]
var items = nunjucks.render('items.html', items);

And template:
{% for item in items %}
    {{ item.name }}
{% endfor %}

I get the following error:
TypeError: s.fromIterator is not a function
at Object.e.prettifyError (nunjucks-slim.min.js:2)
at nunjucks-slim.min.js:2

When I try render a single item, ie not in an array and no loop in the template, it renders fine and there is no issue.  The error isn't really much to go on and nothing turns up in a google - any idea what might be wrong or how to troubleshoot further?

A: Try change var items = nunju... to nunju....
// example
var nunjucks  = require('nunjucks');
var env = nunjucks.configure();
var items = [{'name': 'item1'}, {'name': 'item2'}];

var res = nunjucks.renderString(`
    {% for item in items %}
    {{item.name}}
    {% endfor %}`,
    {items}
);

console.log(res);


text:
Q: Formatting Windows timestamp using Logstash I have successfully integrated Windows Event logs to Logstash.
the timestamp on windows event logs looks like this: 20131007071942.087375-000
To convert this timestamp into a readable one i have used the date filter on logstash.
date{
  match => [ "TimeGenerated", "yyyyMMddHHmmss.ssssss-sss" ]
}

This gives me this error :
 ←[33mFailed parsing date from field {:field=>"TimeGenerated", :value=>"20131007080720.040037-
000", :exception=>java.lang.IllegalArgumentException: Invalid format: "20131007080720.040037-
000" is too short, :level=>:warn}←[0m

It would be great if someone could help me to fix this. Thanks

A: Try using the grok debugger:
http://grokdebug.herokuapp.com/
and looking at the existing regex patterns: https://github.com/logstash/logstash/tree/master/patterns
To get you started:
%{YEAR:YYYY}%{MONTHNUM:MM}%{MONTHDAY:dd}%{GREEDYDATA:remainder}


text:
Q: Select all second highest values only from temp table Using T-SQL (SQL Server 2008 R2), I'm trying to list only the rows with the second highest value in a particular column from a temp table and then place the results into a new temp table.  The PK is the ID, which can have increasing version numbers and then unique codes.
Example:
 ID | Name| Version | Code
------------------------
 1  | A   | 1       | 10
 1  | A   | 2       | 20
 1  | A   | 3       | NULL
 2  | B   | 1       | 40
 2  | B   | 2       | 50
 2  | C   | 1       | 60

The desired outcome of the query is
ID |  Version | Code
------------------------
1  |  2       | 20
2  |  1       | 40

To achieve this I need the below query to be adapted to pull the second highest value as long as the result gives a version number greater than 1.  These results come from a temp table and will then be placed into a final results temp table.  EDIT: Please note this will be applied over 33000 rows of data so I would prefer something neater than INSERT VALUES. Thanks.
Current query:
SELECT
    ID
    ,Version
    ,Code
INTO
    #table2
FROM
    #table1

SELECT *
FROM #table2
WHERE Version > 1
ORDER BY ID asc

DROP TABLE #table1
DROP TABLE #table2

I have tried running the where clause WHERE Version < (SELECT MAX(VERSION) FROM #TABLE 2) but this has no effect, presumably due to the unique code values and in any case wouldn't work where I have more than 3 Versions.
Ideas would be gratefully received.
Thanks in advance.

A: If your primary key is only ID, you have duplicate rows. So I assume your primary key is something else, for example ID, Version, Name. You have two rows with the same ID and same Version, what kind of rule do you want to apply on this ? Lowest number ?
I made an example that does kind of what you want:
First declare the necessary tables:
declare @table1 table (
    Id int,
    Name nvarchar(20),
    [Version] int,
    Code int
)

insert into @table1 values (1,'A',1,10),(1,'A',2,20),(1,'A',3,30),(1,'A',4,NULL)
                          ,(2,'B',1,40),(2,'B',2,50),(2,'C',1,60);

And then the query to get the results:
with HighestVersions (Id, MaxVersion) As
(
    select Id, max(version) from @table1 group by Id
)
select
    t1.Id,
    t1.[Version],
    min(t1.Code) as Code
from
    @table1 t1
    inner join
        HighestVersions hv
        on
            hv.Id = t1.Id
            and (hv.MaxVersion-1) = t1.[Version]
group by
    t1.Id
    ,t1.[Version]

I had to do a little dirty trick with the outermost select, this is because of the duplicate 'Id' and 'Version'. Else you would have gotten two rows with ID = 2, Version = 1
If you want to remove the NULL value you can change the WITH part (according to your last edit):
with HighestVersions (Id, MaxVersion) As
(
    select Id, max(version) from @table1 where Code is not null group by Id
)

A: Try this:
DECLARE @List TABLE (ID int, Name char(1), Version int, Code int NULL)

INSERT INTO @List
VALUES
(1, 'A', 1, 10),
(1, 'A', 2, 20),
(1, 'A', 3, 30),
(1, 'A', 4, NULL),
(2, 'B', 1, 40),
(2, 'B', 2, 50),
(2, 'C', 1, 60)

SELECT
    ID, Name, Version, Code
FROM
   (
    SELECT
        *,
       ROW_NUMBER() OVER (PARTITION BY ID, Name ORDER BY Version DESC) Rn
    FROM @List
   ) a
WHERE
    a.Rn = 2

A: i HAVE TEST THE BELOW CODE AND IT IS GIVING OUTPUT AS PER The YOUR desired outcome of the query is
SELECT ID,Name,[Version],Code
FROM (
        SELECT ROW_NUMBER() OVER (PARTITION BY NAME ORDER BY [Version] DESC) AS RNK,*
        FROM
            (
                SELECT 1 ID, 'A' Name ,1 [Version] ,10 Code
                UNION ALL
                SELECT 1, 'A', 2 ,20
                UNION ALL
                SELECT 1, 'A', 3 ,30
                UNION ALL
                SELECT 1, 'A', 4 ,NULL
                UNION ALL
                SELECT 2, 'B', 1 ,40
                UNION ALL
                SELECT 2, 'B', 2 ,50
                UNION ALL
                SELECT 2, 'C', 1 ,60
            )B
        )BASE
WHERE RNK =2