text:
Q: Actions must be plain objects. Use custom middleware for async actions error eventhough useing thunk as middleWare I got this error:

"Actions must be plain objects. Use custom middleware for async actions."
even though i use thunk as a middleWare.

import { createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import { allReducers } from './reducers';
import thunk  from 'redux-thunk';
import { getAllCourses } from './../../utils/courseServices';

export const store = createStore(allReducers, composeWithDevTools(
  applyMiddleware(thunk),
  // other store enhancers if any
));

//initiliaze
store.dispatch(getAllCourses())

//subscribe
store.subscribe(()=>console.log(store.getState()))

and also my action:
import { getAllCourses } from "../../utils/courseServices"

export const courseAction = () =>{
  return async dispatch =>{
    //fetching data from server
    const {data} = await getAllCourses()
    await dispatch({type:"INIT" , payload: data.courses})
  }
}

A: You are dispatching getAllCourses there, not courseAction. That's probably your problem.
Also, please be aware that in new code you should be using configureStore of @reduxjs/toolkit, not createStore. Modern Redux does not use switch..case reducers, ACTION_TYPES, immutable reducer update logic, hand-written action creators or connect/mapStateToProps. (And that is nothing new, but the recommendation since 2019).
You are probably following an outdated tutorial - please follow the official Redux tutorial


text:
Q: Extracting Extended Data from KML using Javascript I have a placemark in a KML that looks something like this
<Placemark>
 <id>test345</id>
<name>Images from KML file</name>
<ExtendedData>
<Data name="type">
    <value>images</value>
</Data>
</ExtendedData>
<Point>
  <coordinates>-122.448425,37.802907,0</coordinates>
</Point>

I'm attempting to extract the ExtendedData information out of this placemarker on a click event:
google.earth.addEventListener(kmlObject, 'click', function(event) {
    event.preventDefault();
    var kmlPlacemark = event.getTarget();
});

An alternative solution would be to get the kmlObject from the kmlPlacemarker, any ideas?

A: Given the placemark the Google Earth API provides two methods to access the ExtendedData element.

*

*getBalloonHtml()

*getBalloonHtmlUnsafe()

API Reference:
https://developers.google.com/earth/documentation/reference/interface_kml_feature
You can find a working example in the Google Code Playground here:
https://code.google.com/apis/ajax/playground/?exp=earth#extended_data_in_balloons
If you wanted to get the raw KML for extended data then you could fetch the KML representation and parse it as an XML document.
var output = placemark.getKml();

A: Just to say I posted about just this issue on the support forum for the plug-in: https://code.google.com/p/earth-api-samples/issues/detail?id=16
Here is a method I cobbled together to provide support for getExtendedData. It takes a string of Kml as the argument via 'feature.getKml();` It returns any extended data elements that have values in a key[value] object. It expects the extended data to be in the format:
<Data name="Foo">
  <value>bar</value>
</Data>

Tested in XP - FF3.0, IE7, Chrome
function getExtendedData(kmlString) {
  var xmlDoc = null;
  var keyValue = [];
  //Parse the kml
  try {
    //Internet Explorer
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async="false";
    xmlDoc.loadXML(kmlString);
  } catch(e) {
    try {
      //Firefox, etc.
      var parser = new DOMParser();
      xmlDoc = parser.parseFromString(kmlString,"text/xml");
    }
    catch(e) {
      //Failed to parse
      alert(e.message);
      return;
    }
  }
  // Get all the named elements
  var data = xmlDoc.getElementsByTagName("Data");
  // Iterate through the data elements
  for(var i=0; i<data.length; i++) {
    if(data[i].getAttribute("name") &&
      data[i].getElementsByTagName("value").length > 0) {
      // Get the name and value
      var name = data[i].getAttribute("name");
      var value = data[i].getElementsByTagName("value")[0].firstChild.data;
      // Assign them to the keyValue object
      keyValue[name] = value;
    }
  }
  return keyValue;
}

Usage
// where 'feature' is the object with the extended data
var data = getExtendedData(feature.getKml());

for (var name in data) {
  var value = data[name];
  alert(name + '=' + value); // e.g. type=images
}

A: It is actually possible to access the ExtendedData elements via the DOM APIs, although they're not particularly well-documented anywhere.
I found them while grepping around inside some of the resource (.rcc) files packaged with the Plugin.
Assuming a simple Placemark sample similar to yours:
  <Placemark id="testmark">
    <!-- other stuff... -->
    <ExtendedData>
      <Data name="someDataUrl">
        <displayName>URL Representing some Data</displayName>
        <value>http://example.com/#hello</value>
      </Data>
    </ExtendedData>
  </Placemark>

Then (once it's fetched/parsed/loaded into Earth, you can access it something like:
var mark = ge.getElementById('testmark');
var extDataObj = mark.getExtendedData();
var extDataOut = Array(extDataObj.getDataCount());

for (var i = 0; i < extDataObj.getDataCount(); i++) {
    var item = extDataObj.getData(i);
    var details = { name: item.getName(),
                    displayName: item.getDisplayName(),
                    value: item.getValue()
                   };
    extDataOut[i] = details;
}
console.dir(extDataOut);

Haven't tested it for performance vs the .getKml() and feed to an external parser approach, and the lack of official documentation might mean it's not fully functional or supported, but in all testing so far it seems to do ok.  I haven't yet found a way to access any of the more complicated SchemaData type structures, only the simple <data name=''><value>... form.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a way to prevent ma req.params from chaning when calling res.redirect or res.writeHead methods I am trying to redirect user to a specific URL after I do the check with the received parameter from req.params.url.
However, i have that async method for checking if some url exists in redis storage, and my res.redirect is executed before the check is finished, so my req.params.url has been changed and wrong data is sent for checking.
I've tried to create an immutable object but didn't work.
My check method should stay async
async function keyExists(key) {
  let client = redis.createClient();
  client.on('error', (err) => {
    console.log('Error ' + err);
  });
  const res = await client.get(key.toString());
  return res;
}

async get(req, res) {
        try {
            let url = req.params.url;
            let urlCheck = req.params.url;
            console.log(req);
            if (url === '' || isNullOrUndefined(url)) {
                throw new Error('There was something wrong w with reading the data');
            }
            const exists = await redisService.keyExists(urlCheck);
            if (exists) {
                // res.status(302).send('Redirecting');
                console.log('Redirect');
                res.status(302).redirect(exists);
                res.end();
            } else {
                res.status(404).send('URL does not exists');
            }
        } catch (error) {
            res.status(400).send(error.message);
        }
    }


text:
Q: Надо разобраться,что происходит в куске кода Есть кусок кода нейронной сети, которую писал по инструкциям одного человека. Однако, я никак не могу понять, по какому принципу сравниваются два массива. Объясните на максимально понятном языке, а то мне крайне сложно понимать, что я делаю, если не представляю, основываясь на чем машина принимает решения.
trn_inp=np.array([[0,0,1,1],[1,1,1,1],[1,0,1,1],[0,1,1,1]])  #Массив 4 на 1. 4 списка по 1 значению

trn_out=np.array([[0,1,1,0]]).T   #Ожидаемые выходные данные    ЧТО ЭТО ЗНАЧИТ С ТОЧКИ ЗРЕНИЯ ЛОГИКИ?

np.random.seed(mt.ceil(dt_time.second/5)) #"зарождение семени" для генерации ранд. чисел
syn_wei=2*np.random.random((4,1))-1   #Создается массив размером x на y, который заполняется рандомными значениями от -1 до 1

A: .T - это транспонирование матрицы, можно было бы тоже самое написать и другим способом (таким как ниже в выводе), но так часто короче и понятнее.
import numpy as np
print(np.array([[0,1,1,0]]).T)

Вывод:
[[0],
 [1],
 [1],
 [0]]

То есть на входе нейросети у вас матрица размером 4x4, а на выходе - вертикальный столбец из 4-х элементов.
0 0 1 1     0
1 1 1 1 --> 1
1 0 1 1     1
0 1 1 1     0


text:
Q: PYTHON3: indentation of return values This is working fine but I just don't get it why this works in this way. I think the return of True value should be inside the for loop but when I run this program it works in the opposite way.
Can someone point out what i am misunderstanding about the indentation of return values?
Even though the solution was even shorter I wanted to know exactly about my way of coding. Please help!
# My attempt
def palindrome(s):
    mylist = list(s)
    j = -1
    for i in range(0,len(mylist)-1):
        if mylist[i] == mylist[j]:
            i+=1
            j-=1
            continue
        return False
    return True

# Solution answer:
def palindrome(s):
    return s == s[::-1]

A: When a function is called, the function can return only once.
This kind of return pattern is very frequently found across various programming languages. It is intuitive and efficient.
Let's say you have to check if a list of 1000 values contain only even numbers. You loop through the list and check if each element is even. Once you find an odd number, you do not need to go further. So you efficiently and immediately return and exit from the loop.
Here is hopefully a little bit more intuitive version of your code:
def palindrome(s):
    l, r = -1, 0  # left, right
    for _ in range(0, len(s) // 2 + 1):  # more efficient
        l += 1
        r -= 1
        if s[l] != s[r]:
            return False
    return True

Once you know the input is not palindrome, you do not need to go further.
If you did not need to stop, it is palindrome.

A: They follow the exact same rules as any other statement. What you have written means
def palindrome(s) {
    mylist = list(s)
    j = -1
    for i in range(0,len(mylist)-1) {
        if mylist[i] == mylist[j] {
            i+=1
            j-=1
            continue
        }
        return False
    }
    return True

}

A: # My attempt
def palindrome(s):
    mylist = list(s)
    j = -1
    for i in range(0,len(mylist)-1):
        if mylist[i] == mylist[j]:
            i+=1
            j-=1
            continue
        return False
    return True

In the above code what happens is inside the for loop each time it checks if there is a mismatch in the values by comparing values by iterating over the list forwards using  variable "i" and backwards using variable "j". and returns false immediately if any one letter mismatches and so exits from the loop. And true is returned only once the for loop is completed which means no  mismatch was found in the loop
Note: i=0 gives first index, i+=1 iterates forward and j=-1 gives last index, j-=1 iterates backward

A: Basically, when you index an array in numpy, you do it the way:
a[start:end:step]

,for every dimension. If step is negative, you return the values in inverse order. So, if step is -1, the array a[::-1] is the inverted array of a[::].
a[::-1] = a[::]

Then, if a sequence is the same as its inverse, by definition, it is a palindrome.
See:
https://www.geeksforgeeks.org/numpy-indexing/


text:
Q: How can i replace dot with comma in iReport? At first this question is needed for iReport.
I have to replace the dot sign with comma. My problem is the type of the field out of our database is BigDecimal und therefore does not exist any replace method.
So I changed the type to String, but then I got this message:
it.businesslogic.ireport.gui.logpane.ProblemItem@820dc5 The type java.lang.CharSequence cannot be resolved. It is indirectly referenced from required .class files

My code looks like:
new String($F{gewicht}.toString()).replace(".",",")

What can I do?

A: Try entering the following as a text expression:
$F{gewicht}.toString().replace(".",",")

If this doesn't work, one alternative would be to handle the formatting in your Java layer, e.g.
BigDecimal bd = new BigDecimal(1.2345);
NumberFormat nf = NumberFormat.getNumberInstance(Locale.GERMAN);
DecimalFormat df = (DecimalFormat)nf;
String gewicht = df.format(bd);

Here I have used the European German locale, where decimal points and commas reverse roles from what they are in the US and some other places.  You probably want to handle both commas and decimal points.

A: You can use a textfield pattern:
<textField pattern="#,##0.00 €">

This will give you the german format. In this case this is for € values but you can skip the € and add more descimals if wanted:
<textField pattern="#,####0.0000">

Another approach whould be:
new DecimalFormat("#,##0.00 €",
   new DecimalFormatSymbols(Locale.GERMANY)).
     format(Double.parseDouble($F{gewicht}))

A: To bypass the problem: The type java.lang.CharSequence cannot be resolved. It is indirectly referenced from required .class files
You can set a new DecimalFormat like:
new DecimalFormat("#,##0.00 €", new DecimalFormatSymbols(Locale.GERMANY)).format(Double.parseDouble($F{gewicht}))
Thanks @hering


text:
Q: ElectronJS: logging method fires multiple times when don't wanted when using invoke/handle As the title states. I have this problem with my ElectronJS project. When I try to log an output from an invoked handler, the logging happens multiple times, even though the function is run only once. What could be the cause of this?
The function is run only once, for each class object created. See GIF at the bottom to see the problem "in action".
I have tried removing the handler and listeners, but that just makes it so that the next object won't be able invoke downloadPoster..
Thanks in advance for any help.
Here is how the objects are instanciated and "processed".
// On drop
window.ondrop = async function(e) {
    e.preventDefault();
    body.classList.remove('file-hover');
    for (var [i, file] of Object.entries(e.dataTransfer.files)) {
        var x = new Movie(file.path);
        await x.process();
    }
    return false;
};

Here is the function from the class in renderer.js
/**
* Download poster file for movie
*/
async downloadPoster() {

    // This is the url used to search for the poster we want
    var searchUrl = new URL(Config.api.searchUrl);
    searchUrl.search = new URLSearchParams({
        page: 1,
        api_key: Config.api.key,
        query: this.#movie.tags.title,
        year: this.#movie.tags.year
    });

    // Search for poster in the main thread
    await axios.get(searchUrl.href)
    .then(async (resp) => {

        // No results
        if (resp.data.total_results <= 0) {
            this.log('No poster found', 'error');
            return;
        }

        // Invoke poster download
        const result = await ipcRenderer.invoke('downloadPoster', {
            src: Config.api.posterUrl + resp.data.results[0].poster_path,
            dest: path.join(this.#movie.new.absolutePath, Config.api.posterFilename)
        })

        // This shows "undefined"
        this.log(result);

    })
    .catch(async (err) => {
            this.log('Could not search for poster: ' + err, 'error');
    });

}

Here is the handler function from the main.js
// Download poster
ipcMain.handle('downloadPoster', async (event, args) => {

    await axios.get(args.src, { responseType: 'stream' })
    .then(async (resp) => {

        const writeStream = fs.createWriteStream(args.dest);

        // Write data to file
        await resp.data.pipe(writeStream);

        // When finished, send reply back
        writeStream.on('finish', async () => {
            return {
                success: true,
                message: 'Poster downloaded'
            }
        });

        // On error writing, send reply back
        writeStream.on('error', async (err) => {
            return {
                success: false,
                message: 'Could not write poster to file: ' + err
            }
        });

    })
    .catch(async (err) => {
        return {
            success: false,
            message: 'Could not download poster: ' + err
        }
    });

});

A: You may be misunderstanding invoke/handle. The whole point of using that feature is that the return value from the handler in the main process is returned by the invoke method in the renderer. So you can do this:
// main.js
ipcMain.handle('some-command', async (evt, data) => {
// do something with data, the handler can also be async
 const value = await getSomeValue();
 return doSomething(data, value);
}

// renderer.js
(async () => {
 const invokeReturn = await ipcRenderer.invoke('some-command', data);
 // invokeReturn will contain the result of doSomething(data, value) from main
})

I would need to do some debugging on your code to be sure but my instinct is that the behavior is caused by this bit of code:
// Poster download reply from the invoke above
ipcRenderer.on('downloadPosterReply', async (event, args) => {

You're setting a listener and never removing it, so with each function call there's a new handler added, causing more and more logs to appear. Thanks to invoke/handle, you don't need to use an on handler here at all.


text:
Q: Slide content in from the left, overlay existing content and push across sidebar I'm currently building a responsive site and i need to have a hidden div which will slide in from the left after clicking a button in the the left side bar. Once this button has been pressed the side bar will be pushed across from the sliding content (Sliding from the left) and overlay the existing content or push across the content in the right hand side.
This is where the problem lies as it's a responsive site. I would like the sidebar in the 'siteInnerLeft' div to be pushed to the right hand side of the page when the new div slides in. So after the content has sliden in the previous content is no longer visible until the sliding content has slid back out.
Here is a my JSFiddle - http://jsfiddle.net/76xvB/2/
Hopefuly you can see what i'm trying to acheive. I've manaed to get it working until a point but the issue I have is the content sliding in is fixed and I don't want it to be fixed as there is more content to view and this removes the users ability to scroll.
I understand that 'position fixed' takes the element out of the document flow. So is this going to stop me acheiving what I want? If so, is there another way of doing it.
NOTE: The real site will have percentages not pixels because of it being responsive, this is a broken down version.
My current code:
HTML

Click me

Current page content

Content to slide in from the left

This is my footer and this content always needs to be showing and can't be hidden behind the fixed div

CSS
#siteWrapper{
    max-width:500px;
    margin:0 auto;
    width:100%;
}

#siteInnerLeft{
    background-color:green;
    width:100px;
    float:left;
    position:fixed; /* Sidebar that needs to be fixed*/
}

#siteInnerRight{
    width: 400px;
    background-color:yellow;
    float:left;
    margin-left: 100px; /*Compensates for fixed header width */
}

.pushmenu {
    background: #e9e8e0;
    font-family: georgia,times news roman, times, serif;
    position: fixed;
    width:400px;
    height: 100%;
    top: 0;
    z-index: 1000;
}

.pushmenu-push{
    left: 0;
    overflow-x: hidden;
    position: relative;
    width: 100%;

}

.pushmenu-left{
    left:-400px;
}

.pushmenu-left.pushmenu-open {
        left: 0px;
       /* box-shadow: 5px 5px 5px #d9d8d0;*/
}

.pushmenu, .pushmenu-push {
    transition: all 0.3s ease 0s;
}

#footer{
    width:100%;
    clear:both;
    background-color:red;
}

jQuery
$menuLeft = $('.pushmenu-left');
$nav_list = $('#homeNavLink');

$nav_list.click(function() {
    $(this).toggleClass('active');
    $('.pushmenu-push').toggleClass('pushmenu-push-toright');
    $menuLeft.toggleClass('pushmenu-open');
});

Any suggestions would be most appreciated.
Thanks.

A: On completion of the transition, change the position of the sidebar so that it is not longer fixed. The answer on the following link breaks it down pretty well and has quality references:
Callback when CSS3 transition finishes

A: If the side-bar is fixed, you could create a scroll-bar inside for the content, so the text can be viewable; you could do this by adding overflow-y: auto;  in the .pushmenucss class.
Another way would be to set the sidebar as position: absolute; and then dynamically change the top property from javascript when the user hits the sidebar's bottom.


text:
Q: Get result.insertId from callback function in node.js Check my updated answer below the other answers. The question turned out to be quite simple, I just didn't understand how async worked or should be handled at the time of posting it
I have the following code:
function qcallb(err,result){
  console.log("result.insertID:"+result.insertId);
  return result.insertId;
}

var createRecord= function (tableName,record){
  try{
    queryStatment="INSERT INTO " + tableName + " SET ?";
    var result='';
    var query = connection.query(queryStatment, record, qcallb,false);
  }
  catch(err){
    return 0;
  }
  return iid;
}

I want to return the variable result.insertId from the callback function, to the function that calls create record, but I have not found a way to do this.
I tried to set a global variable in the callback function, but when I try to access it, its value is still unchanged.
Is there a way for me to either access the value directly in the callback function, or to have callback function notify me when it's called then return the value?

EDIT:
After testing every proposed solution here, and those that I found by searching elsewhere, the only thing that worked for me (without using external modules to make a piece of code run in 'sync' rather than 'async'), was to implement the logic I wanted inside the callback itself, which is what I wanted to avoid in the first place, but I couldn't work around it no matter what I did.

A: 2 years later:
After getting much more experience with node.js and async code, I see how naive this question was, although it was beyond me at the time, which is also obvious in my using a try/catch block around an async call which is useless with async code, where handling errors is done by checking for err in the callback and acting upon it if it exists.
Since it seems to have quite a number of views, this seems to be a recurring issue for those newly introduced to async development.
This can't be done in the sense that was asked in the question, for an operation to occur after an async operation and use a value that is a result of the async operation, it has to be called from the callback of the async operation with that value.
To resolve the issue, the code can be modified to:
function doSomethingWithResult(result) {
  // query is done, and this would only be called if no error occurred
  console.log('Result is: ', result)
  // do whatever you want
}

function queryCallback(err,result) {
  if (err) {
    throw err
  }

  doSomethingWithResult(result)
}

function createRecord(tableName, record) {
  queryStatment='INSERT INTO `' + tableName + '` SET ?'

  connection.query(queryStatment, record, queryCallback)
}

---
Old Answer: After testing every proposed solution here, and those that I found by searching elsewhere, the only thing that worked for me (without using external modules to make a piece of code run in 'sync' rather than 'async'), was to implement the logic I wanted inside the callback itself, which is what I wanted to avoid in the first place, but I couldn't work around it no matter what I did.

A: Yes, 'notify me' is the way to go:
var createRecord= function (tableName,record, cb){
  var query = "INSERT INTO " + connection.escape(tableName) + " SET ?";
  connection.query(query, record, function(err, res) {
    if (err) return cb(err);
    cb(null, res.insertId); // this is "notify me" part
  });
}

// now use it

createRecord('blah', { foo: "bar" }, function(err, id) {
  console.log(id);
});

Also, try/catch won't help much here as callback function is not executed down stack frame but called outside from event loop. You need to use domains/zones or some similar sort of async error handling

A: i think there is a way with waiting for the response with an endless loop, maybe you can also use the context to assign the variable like so :
var sleep = require('sleep');

var createRecord= function (tableName,record){
  try{
    queryStatment="INSERT INTO " + tableName + " SET ?";
    var insertId=0;
    var query = connection.query(queryStatment, record, function(err,result){
      console.log("result.insertID:"+result.insertId);
      insertId = result.insertId;
    },false);
  }
  catch(err){
    return 0;
  }
  while(insertId==0){
    sleep.sleep(0.1); # sleep for 0.1 second
  }
  return insertId;
}

i haven't tested this code on my machine, please test it and let me know if there is any error.


text:
Q: How do I install mods for Kerbal Space Program 1.1? How do I install mods into the latest 1.1 version of KSP? I tried to put the .zip file into the gamedata folder but when I launched I didn't see the parts.
Can anybody help me?

A: You need to put the unzipped contents of the mod in the right location which is more often than not GameData.
Here is a screenshot of my install with the base Squad game data, along with 2 mods


text:
Q: Is this a legitimate modification of the Cantor Set construction process? I'm new to topology (baby rudin) and playing around with ways to construct subsets of $R^k$ that have finite numbers of limit points, and I'm wondering if this works:
Let $E_{_0}=[0,1]$.
Remove the half open interval $(\frac{1}{2},1]$, and let $E_{_1}=[0,\frac{1}{2}]$.
Remove the half open interval $(\frac{1}{4},\frac{1}{2}]$, and let $E_{_2}=[0,\frac{1}{4}]$
Continue in this way to construct a sequence of compact sets {$E_{_n}$} such that $E_{_0}\supset E_{_1}\supset E_{_2}\supset ...$ and let $S$ be the intersection of every set in {$E_{_n}$}.
Is $0$ a limit point of $S$?
I see that I could remove segments instead of half open intervals and end up with an infinite set with a limit point only at $0$, I'm just wondering if the above process leads to the logical conclusion that $0$ is an isolated point or if it's still a limit point.

A: The set $S$ only contains the point $0$. A finite set of reals has no limit point.


text:
Q: Extjs4 -how to generate the grid from the returned json? I have a form and a grid to submit a query,like this:
items:[
{
     fieldLabel: 'query the month',
     xtype     : 'textfield',
     name      : 'query_year_month',
     id:   'query_year_month'
} ],

buttons:  {
    text: 'submit',
    formBind: true, //only enabled once the form is valid
    disabled: false,
    handler: function() {
        //some code
        }

var store = Ext.create('Ext.data.Store', {
        model: //uncertain,
        region : 'south',
        pageSize: 15,

        proxy: {
            type: 'ajax',
            url : 'brokee/brokagequery/',
            reader: {
            type: 'json',
            root: 'users'
            }
        },

        autoLoad: false
});

I'd like to load data to a grid  after submiting the form.The return data is a json
structure,I don't want to define the static model bind to the store and neither the grid columns,because the data returned is uncertained.  The  store model and grid columns should be generated from the json data,
for example:  json: {'field1':data1, 'field2':data2}
the model should be generated like this:
Ext.define('somemodel', {
    extend: 'Ext.data.Model',
    fields: [
        {name: 'field1', type: 'string'},
        {name: 'field2', type: 'string'}
               ]
});

In the official demo, the store and model are predefined, then call the store.load method to refresh the grid throuth the proxy.But how can I do that when the store and model need to be generated?

A: When you have your json loaded, you can create store store/model like this.... use record .raw to extract values and :
Ext.create("Ext.data.JsonStore",{
    id:record.raw.storeID,
    model: Ext.define('App.dataGridModel', {
        extend: 'Ext.data.Model',
        fields: [record.raw.id, record.raw.first]...
    })
...

});

the same with the grid etc..


text:
Q: Syntax error in UPDATE statement Visual Studio C#.net I've been trying to figure out the right syntax for the UPDATE statement when coding in C#.net and using OleDbCommand.  I feel like what I have is correct, but it definitely isn't because I still am getting the error: "Syntax error in UPDATE statement".  My code is posted below for my Update button.  I have checked many sites (including Stackoverflow) to see what the correct syntax and standard is for creating SQL statements, but still haven't found the one that doesn't give me a syntax error.  Any suggestions would be helpful. Thanks!
private void update_button_Click(object sender, EventArgs e)
    {
        String ssize = "";
        foreach (Control control in Controls)
        {
            if (control != null && control is RadioButton)
            {
                RadioButton radio = control as RadioButton;
                if (radio.Checked == true)
                {
                    ssize = control.Text;
                }
            }
        }
        OleDbConnection myCon = new OleDbConnection(connString);
        OleDbCommand cmd = new OleDbCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "UPDATE Youth SET FName = ?, MI = ?, LName = ?, Street = ?, CityStateZip = ?, PG = ?, HomePN = ?, WorkPN = ?, CellPN = ?, YEmail = ?, PGEmail = ?, Age = ?, DOB = ?, HS = ?, Grade = ?, PrevExp = ?, SSize = ?, Allergies = ?, MedConditions = ?, Avail = ?, FirstDep = ?, SecDep = ?, ThirdDep = ?, Fundraiser_1 = ?, Fundraiser_2 = ?, Fundraiser_3 = ?, Fundraiser_4 = ?, WHERE ID = ?";
        cmd.Parameters.Add("@FName", OleDbType.VarChar).Value = fname_tb.Text;
        cmd.Parameters.Add("@MI", OleDbType.VarChar).Value = mi_tb.Text;
        cmd.Parameters.Add("@LName", OleDbType.VarChar).Value = lname_tb.Text;
        cmd.Parameters.Add("@Street", OleDbType.VarChar).Value = address1_tb.Text;
        cmd.Parameters.Add("@CityStateZip", OleDbType.VarChar).Value = address2_tb.Text;
        cmd.Parameters.Add("@PG", OleDbType.VarChar).Value = pg_tb.Text;
        cmd.Parameters.Add("@HomePN", OleDbType.VarChar).Value = homePN_tb.Text;
        cmd.Parameters.Add("@WorkPN", OleDbType.VarChar).Value = workPN_tb.Text;
        cmd.Parameters.Add("@CellPN", OleDbType.VarChar).Value = cellPN_tb.Text;
        cmd.Parameters.Add("@YEmail", OleDbType.VarChar).Value = yemail_tb.Text;
        cmd.Parameters.Add("@PGEmail", OleDbType.VarChar).Value = pgemail_tb.Text;
        cmd.Parameters.Add("@Age", OleDbType.VarChar).Value = age_tb.Text;
        cmd.Parameters.Add("@DOB", OleDbType.Date).Value = bd_picker.Text;
        cmd.Parameters.Add("@HS", OleDbType.VarChar).Value = hs_tb.Text;
        cmd.Parameters.Add("@Grade", OleDbType.Integer).Value = grade_tb.Text;
        cmd.Parameters.Add("@PrevExp", OleDbType.Integer).Value = prevexp_tb.Text;
        cmd.Parameters.Add("@SSize", OleDbType.VarChar).Value = ssize;
        cmd.Parameters.Add("@Allergies", OleDbType.VarChar).Value = food_tb.Text;
        cmd.Parameters.Add("@MedConditions", OleDbType.VarChar).Value = special_tb.Text;
        cmd.Parameters.Add("@Avail", OleDbType.VarChar).Value = week1_tb.Text + "," + week2_tb.Text;
        cmd.Parameters.Add("@FirstDep", OleDbType.Date).Value = deposit_picker.Text;
        cmd.Parameters.Add("@SecDep", OleDbType.Date).Value = second_picker.Text;
        cmd.Parameters.Add("@ThirdDep", OleDbType.Date).Value = third_picker.Text;
        cmd.Parameters.Add("@Fundraiser_1", OleDbType.Date).Value = fund1Picker.Text;
        cmd.Parameters.Add("@Fundraiser_2", OleDbType.Date).Value = fund2Picker.Text;
        cmd.Parameters.Add("@Fundraiser_3", OleDbType.Date).Value = fund3Picker.Text;
        cmd.Parameters.Add("@Fundraiser_4", OleDbType.Date).Value = fund4Picker.Text;
        cmd.Parameters.Add("@ID", OleDbType.Integer).Value = idTB.Text;

        cmd.Connection = myCon;
        try
        {
            myCon.Open();
            cmd.ExecuteNonQuery();
            myCon.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Problem opening connection!\n" + ex.Message, "Exception");
        }
    }

A: You've got a comma before the WHERE clause in your sql.
cmd.CommandText = "UPDATE Youth SET FName = ?, MI = ?, LName = ?, Street = ?,
    CityStateZip = ?, PG = ?, HomePN = ?, WorkPN = ?, CellPN = ?, YEmail = ?,
    PGEmail = ?, Age = ?, DOB = ?, HS = ?, Grade = ?, PrevExp = ?, SSize = ?,
    Allergies = ?, MedConditions = ?, Avail = ?, FirstDep = ?, SecDep = ?,
    ThirdDep = ?, Fundraiser_1 = ?, Fundraiser_2 = ?, Fundraiser_3 = ?,
    Fundraiser_4 = ?,  <<--- extra comma
    WHERE ID = ?";

A: Your error (or at least one of them) is right here:
Fundraiser_4 = ?, Where ...
remove the , after the ?


text:
Q: Expressjs one function to handle GET and POST Is it is better to have a separate function to handle GET and POST requests for the same API endpoint or combine them into one function that discriminates based on the existence of req.body or req.params?
ie.
app.get('/api/profilepic',  api.get_profilepic);
app.post('/api/profilepic',  api.change_profilepic);

or:
app.get('/api/profilepic',  api.profilepic);
app.post('/api/profilepic',  api.profilepic);

If the latter, does expressjs provide a helper function to determine the request type? My approach so far to determine if req is POST requires underscore:
if (_.size(req.body) == 0)

A: Best practice is to separate concerns; therefore, you should have separate functions to handle each HTTP verb. This makes the code easier to maintain.

A: There is no general rule, the best approach depends on the case you are working on. I think if you want an api endpoint that accept POST and GET requests combined, you should use express function all() like this:
app.all('/api/profilepic',  api.get_profilepic);

You should use seperate endpoints for POST and GET when the handler function is not the same.
For more details see:
http://expressjs.com/en/guide/routing.html


text:
Q: How to warm up Azure App Service in staging slot and then swap with production when using virtual directories I have an Azure app service with a staging slot. I have setup both to use virtual directories to include a number of websites. The folders are client, server and legacy. I have setup custom domains on both production and the staging slot.
The custom domains for the production slot are

*

*client.sitename.com

*server.sitename.com

*legacy.sitename.com

The custom domains for the staging slot are

*

*clientstaging.sitename.com

*serverstaging.sitename.com

*legacystaging.sitename.com

I've updated the app service to include a web.config file to handle navigating requests to the correct directory and also run some code to warm up the applications. When the warm up code completes emails are sent which contain environment variables so I can tell which environment has been warmed up. The variables are in the projects themselves so are not connected to the variables on the app service.
The web.config of the current production slot contains the following
<applicationInitialization doAppInitAfterRestart="true" skipManagedModules="false">
    <add initializationPage="/primes/warmup" hostName="client.sitename.com" />
    <add initializationPage="/api/v1/primes/warmup?token=tokenId" hostName="server.sitename.com"/>
    <add initializationPage="/?initialise" hostName="legacy.sitename.com"/>
</applicationInitialization>

The web.config of the current staging slot contains the following
<applicationInitialization doAppInitAfterRestart="true" skipManagedModules="false">
    <add initializationPage="/primes/warmup" hostName="clientstaging.sitename.com" />
    <add initializationPage="/api/v1/primes/warmup?token=tokenId" hostName="serverstaging.sitename.com"/>
    <add initializationPage="/?initialise" hostName="legacystaging.sitename.com"/>
</applicationInitialization>

This works until the slots are swapped. If I restart the production slot after the slot I am receiving emails with the variables coming from the staging slot. The web.config on production now has hostNames with 'staging' and the staging slot looks to be warmed up rather than the production slot.
The production slot of the app service recycles sometimes so the applicationInitialization should be triggered and warm up that slot when it happens.
Is there a way of setting up the applicationInitialization so that it can work for both slots?


text:
Q: Why does using a variable cause the query to never complete? I have a table of ~10 million bigints offset that are larger than a known constant.
I'd like to know how many numbers are within a range of the constant. (The actual query doesn't really matter). When I use the constant converted to a bigint the performance is acceptable (1 second). When I store the constant in a variable or a parameter the query never finishes.
Here is the script to generate a sample table:
IF OBJECT_ID('bigints', 'u') IS NOT NULL
  DROP TABLE bigints;

WITH t
     AS (SELECT *
         FROM  (VALUES(1),(1),(1),
                      (1),(1),(1),
                      (1),(1),(1),
                      (1))f(n))
SELECT num = CONVERT(BIGINT, 123456789012)
             + ABS(BINARY_CHECKSUM(NEWID()))
INTO   bigints
FROM   t a,
       t b,
       t c,
       t d,
       t e,
       t f,
       t g

And here is an example of the failing query:
DECLARE @const BIGINT = CONVERT(BIGINT, 123456789012);

WITH t
     AS (SELECT *
         FROM  (VALUES(1),(1),(1),
                      (1),(1),(1),
                      (1),(1),(1),
                      (1))f(n)),
     tally(n)
     AS (SELECT @const
                + row_number() OVER (ORDER BY (SELECT NULL))
         FROM   t a,
                t b,
                t c,
                t d)
SELECT COUNT(*)
FROM   Tally t
       JOIN bigints b
         ON t.n = b.num

If you replace @const + row_number() with the expression CONVERT(BIGINT, 123456789012) + row_number() the query will complete. Why does the introduction of the variable cause the query to run forever?
This was done on Sql Server 2012 and Sql Server 2014 both cause the same issue.

A: The Fast plan gets 10,000 rows going into the hash join on bigints with a bitmap filter.
The slow plan gets 10,000 rows going into a nested loops join onto a 10,000,000 table with an intermediate table spool.
10,000 executions against that spool are going to be slow.
It looks like the query optimiser doesn't give itself any choice but to use nested loops though.
Attempting to force the issue with an INNER HASH JOIN hint produces

Query processor could not produce a query plan because of the hints
  defined in this query. Resubmit the query without specifying any hints
  and without using SET FORCEPLAN.

Indeed this issue can be seen in much simpler queries by adding a reference to a variable as below (also fails)
DECLARE @S VARCHAR(1) = '';

SELECT *
FROM   master..spt_values T1
       INNER HASH JOIN master..spt_values T2
                    ON T1.name = (T2.name + @S);

This additional reference to a variable certainly shouldn't prevent a hash (or merge) join on a query with an equality predicate and this is a fixed bug (Relevant KB article - Performance issues occur when the join predicate in your query has outer reference columns in SQL Server 2005 or in SQL Server 2008)

SYMPTOMS
You run a query in Microsoft SQL Server 2005 or in Microsoft
  SQL Server 2008, and the join predicate in the query has outer
  reference columns. In this case, you may experience performance
  issues, and the query cannot be completed.
Note This issue does not occur in Microsoft SQL Server 2000.
CAUSE
The problem that is described in the "Symptoms" section occurs
  because the database engine cannot generate a merge join or a hash
  join. Therefore, a loop join is used instead. Using a loop join causes
  the performance problem.

however you must be running on one of the builds (or later) described in the hotfix link (SQL Server 2005 SP3 CU7, 2008 RTM CU9, 2008 SP1 CU6) and must be running with trace flag 4199 enabled to take advantage of the fix (even up to and including SQL Server 2014).
Other less satisfactory work arounds are on 2008 CU5+ the parameter embedding optimization solves things with OPTION (RECOMPILE).
The following will get recompiled on each invocation treating the variable as though it was a constant and compilation succeeds with the desired faster plan.
DECLARE @const BIGINT = CONVERT(BIGINT, 123456789012);

WITH t
     AS (SELECT *
         FROM  (VALUES(1),(1),(1),
                      (1),(1),(1),
                      (1),(1),(1),
                      (1))f(n)),
 tally(n)
     AS (SELECT @const
                + row_number() OVER (ORDER BY (SELECT NULL))
         FROM   t a,
                t b,
                t c,
                t d)
SELECT COUNT(*)
FROM   Tally t
       INNER HASH JOIN bigints b
                    ON t.n = b.num
OPTION (RECOMPILE);

Or even the following defeats the issue and allows the main join to use hash or merge at the cost of some extra plan complexity.
DECLARE @S VARCHAR(1) = '';

SELECT *
FROM   master..spt_values T1
       INNER JOIN master..spt_values T2
                    ON T1.name = (T2.name + (SELECT MAX(@S)));


text:
Q: Fastest way to traverse DOM (Breadth First) Sorry if this will sound like a strange need.
Users can create a HTML page with any number of  elements in any order, Div's will be assigned a class. I have no control over which order or where they are placed.
I need to traverse the DOM and call an init function on each div with the class names specific to my framework. So I do not know the order they will be placed.
Here are my challenges:
- I am using a recursive .children() Jquery call then iterating through each child of the current element... I think I need to find a faster way of doing this, it is a performance hit.
- When iterating, $.each() is faster than a standard for loop. I have no idea why. Does $.each() perform faster for smaller sets? (i.e. size < 20 )
My other alternative is to do a selector on each class but I need to do several iterations as this can't guarantee the ordering so the iterations cancel out any performance advantage.
So My needs:
- A better performing way to traverse the DOM breadth first. Plain ol' Javascript is fine if I can find better performance than JQuery functions.
Sorry, I know this sounds a bit of a strange need. Any advice is greatly welcome.

A: First of all, you shouldn't be having a huge performance hit. The issue could somewhere else in your code, but you haven't shown us what you currently have, so I have no way of saying. That said, here's an idea that should be pretty speedy:
var classes = ["class1", "class2", "class3"];
i = classes.length, divs, j, curDiv;

while(i--) {
    divs = document.getElementsByClassName(classes[i]);
    j = divs.length;

    while(j--) {
        var curDiv = divs[j];
        // call some init function on the current div
    }
}

If this isn't fast, you must have an issue somewhere else (also, don't forget to make sure this is called after the document has loaded).

As for whether $.each() is faster than a standard for loop, this is pretty much a rule of thumb: native code is faster than library code (but library code is usually more convenient). That holds true in this case; your average for loop will be much faster than $.each().

A: Here's something a little bit more concise, with some current syntax.

    function bfs(root) {
      const queue = [];
      while (root) {
        console.log(root);
        [...root.children].forEach(child => queue.push(child));
        root = queue.shift();
      }
    }

    bfs(document.body);

        <title>Breadth First</title>

A: For breadth first tree traversal...
const html = `

    </div

`;

const parser = new DOMParser();
const doc = parser.parseFromString(html, "text/html");

function BFT_dom(root) {

    const queue = [];
    let currentEl = root;

    while(currentEl) {
      console.log(currentEl) // Do something to element here

      for(let i = 0; i < currentEl.children.length; i++) {
          queue.push(currentEl.children[i]);
      }
      currentEl = queue.shift();
  }

}

BFT_dom(doc)


text:
Q: Redefining cardinality of an element of a complex type. Is it possible? I want to use a predefined complex type with a modified cardinality on one of its element. How can i do that without using override/redefine (I don't want to split the xsd file). Is it even possible ?
Example : in the case of an event, I want the birth date of the organizer (person_type) to be mandatory. But for each guests (person_type as well), it has to be optional.
I've tried to use restriction/extension but it doesn't fit my needs.
It obviously works using 2 complex type (i.e person_type1/birth_date 1..1, person_type2/birth_date 0..1) but it is king of ugly.
How can I use the complex type "person_type" in the guest element with cardinality change on birth_date ?
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema elementFormDefault="qualified" attributeFormDefault="unqualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
   <xs:complexType name="event_type">
      <xs:sequence>
         <xs:element name="event_name" type="xs:string"/>
         <xs:element name="organizer" type="person_type"/>
         <xs:element name="guests_list">
            <xs:complexType>
               <xs:sequence>
                  <xs:element name="guest" type="person_type" maxOccurs="99"/>
               </xs:sequence>
            </xs:complexType>
         </xs:element>
      </xs:sequence>
   </xs:complexType>
   <xs:complexType name="person_type">
      <xs:sequence>
         <xs:element name="first_name" type="xs:string"/>
         <xs:element name="last_name" type="xs:string"/>
         <xs:element name="birth_date" type="xs:string"/>
      </xs:sequence>
   </xs:complexType>
   <xs:element name="event" type="event_type"/>
</xs:schema>

In order for this file to be valid :
<?xml version="1.0" encoding="UTF-8"?>
<event>
   <event_name>Party !!</event_name>
   <organizer>
      <first_name>John</first_name>
      <last_name>Doe</last_name>
      <birth_date>01/01/1970</birth_date>
   </organizer>
   <guests_list>
      <guest>
         <first_name>Jane</first_name>
         <last_name>Doe</last_name>
      </guest>
      <guest>
         <first_name>Foo</first_name>
         <last_name>Bar</last_name>
      </guest>
   </guests_list>
</event>

Thanks for your answers.

A: I'm increasingly inclined to use XSD 1.1 assertions for this kind of thing. It's much more convenient than using restrictions and extensions.
Specifically, define the complexType to be liberal, and then define context-dependent constraints in an xs:assert on the relevant element declaration.


text:
Q: SQL query improved performance needed (1 table) So, i've got a query (which i use as a Stored Procedure) in SQL Server 2008 R2.
It works, but i cannot believe there isn't a more efficient way.
The data is in a table 'ServiceInstance'. This is one, completely flat table containing 16 'instances' per IPAddress, each of them having a unique TCPPort for that IPAddress.
The columns 'isRestarting' and 'isInuse' are not really important to this system;
both when 'isRestarting' or 'isInUse' are True, the 'IsAvailable' is False
The column 'CPUId' is; each server has 4 CPUs - and the Delhpi application i'm running can only have 1 application on a CPU at the same time. So, when CPU #1 on Server with IP '192.168.4.151' is in use, that CPUId on that IP is not allowed to be returned from the query. (There are 16 instances on one server with 4 cores)
)
So, the SP must do the following:
Get an available instance, which must comply to:

*

*The SP should always return 1 row.

*

*This is a low prio for me atm - i can rerun the SP if needed

*The ServerInstance' IsEnabled must be true

*When the ServerInstance is returned, it must be set to 'IsAvailable' = False so it won't be picked again until work is done (reset is done by my application logic)

*None of the same CPUId on that IP must be 'IsAvailable = False'

*

*This makes sure the CPU # on that server is free

*The ServerInstance which hasn't been used the longest is preferred.

*

*Because I have a large pool and want to load balance traffic

*The 'found' ServerInstance is to be updated immediately.

*

*The 'LastRequestDate' should be stamped

*The 'IsInuse' set to True

*The 'IsAvailable' set to False
So. With this information I've created this monster:
 UPDATE top(1) ServiceInstance
    SET
        LastRequestDate=GETDATE()
        ,IsInUse=1
        ,IsAvailable=0
    OUTPUT
        inserted.ServiceInstanceId,
        inserted.IpAddress,
        inserted.TcpPort,
        inserted.LastRequestDate,
        inserted.IsInUse
    WHERE
    ServiceInstanceId IN
    (
    SELECT Top (1) ServiceInstanceId FROM ServiceInstance
    WHERE
    (ServiceInstance.IsAvailable = 1 AND ServiceInstance.IsEnabled = 1)
    AND ServiceInstanceId NOT IN
        (
        SELECT NGI1.ServiceInstanceId
        FROM
            (SELECT CpuId,IpAddress
            FROM [ServiceInstance] NGI
            WHERE IsInUse=1) a
            INNER JOIN ServiceInstance AS NGI1 ON a.IpAddress = NGI1.IpAddress AND a.CpuId = NGI1.CpuId
        )
    ORDER BY LastRequestDate ASC
    )

However, I feel this cannot be the most efficient way to go about things.
This Query is supposed to be running ~10 times per second on peek hours and thus currently putting some heavy CPU pressure on my SQL Server.
Any tips welcome! I feel i should be able to use PARTITION OVER or join to my own table, but I cannot seem to create it successfully...!
Ok, so, the table structure is as following:

*

* ServiceInstanceId INT NOT NULL

*IPAddres varchar(20) NOT NULL

*TCPPort varchar(5) NOT NULL

*LastRequestDate DateTime NOT NULL

*IsEnabled BIT NOT NULL

*IsAvailable BIT NOT NULL

*IsRestarting BIT NOT NULL

*IsInuse BIT NOT NULL

*CPU INT NOT NULL

On this moment, I have no indexes. This because the table is mutated a lot (every time a ServerInstance is 'used' the table mutates 3 or 4 times
(1= use, 2 = restart after use, 3= set IsAvailable, 4= restart on failure)
My guess was that, if i made Indexes, these would have to be updated every mutation. Not sure but i felt like it would decrease performance :)
Exec plan:

IMPORTANT ADDITION after some loadtests:
I really needed to use Exec @RC =sp_getapplock @Resource='MyLock', @LockMode='Exclusive', @LockOwner='Transaction', @LockTimeout = 1000 For this StoredProcedure. Doesn't work well without it!

A: WITH UnAvailableCpus AS (
    SELECT IpAddress
          ,CpuId
    FROM ServiceInstance
    WHERE IsAvailable = 0
    GROUP BY IpAddress
            ,CpuId
)
,AvailableInstances AS (
    SELECT ServiceInstanceId
          ,LastRequestDate
    FROM ServiceInstance
         LEFT JOIN UnavailableCpus
             ON UnavailableCpus.IpAddress = ServiceInstance.IpAddress
                AND UnavailableCpus.CpuId = ServiceInstance.CpuId
    WHERE ServiceInstance.IsAvailable = 1
          AND ServiceInstance.IsEnabled = 1
          AND UnavailableCpus.IpAddress IS NULL
)
,PreferredInstance AS (
    SELECT TOP 1 ServiceInstanceId
    FROM AvailableInstances
    ORDER BY LastRequestDate
)
UPDATE ServiceInstance
SET
    LastRequestDate=GETDATE()
   ,IsInUse=1
   ,IsAvailable=0
OUTPUT
   inserted.ServiceInstanceId
  ,inserted.IpAddress
  ,inserted.TcpPort
  ,inserted.LastRequestDate
  ,inserted.IsInUse
WHERE ServiceInstanceId IN (SELECT ServiceInstanceId FROM PreferredInstance)

A: It may be related with the structure of the table (if you post it we can further elaborate).
Best guess is to create indexes for any column used for joins, if not already done:

*

*CpuId

*IpAddress

*IsInUse

Also not bad to create indexes for columns used for where conditions:

*

*IsAvailable

*IsEnabled

Anyway, this that you present is a "planning" algorithm for process execution of something like a distributed operating system. This kind of algorithms are always programmed to have all information presistent in memory, and the execution of the planning (selecting which executes what and where) to be compiled to native code. In the case of the Linux kernel, for example, in C++. If you delegate the info to a database engine, and the planning to a three level nested SQL, performance is going to be bad. Databases are better suited for processing large quantities of information for a result, or serving a lot of clients quering information at the same time, or logging and storing a lot of data quickly.
Maybe you should try to program everything in Delphi, with an object oriented approach, without database and SQL.

A: Try this query to replace your retrieval query:
select top 1 tbl.serviceinstanceid from
(select
 ipaddress,
 cpuid,
 sum(case when isavailable = 1 then 1 else 0 end)
 over (partition by ipaddress, cpuid order by ipaddress, cpuid) s
 from tbl
 where isenabled = 1
) t
inner join serviceinstance tbl on tbl.ipaddress = t.ipaddress and tbl.cpuid = t.cpuid
where t.s = 4
and tbl.isinuse = 0
order by lastrequestdate

Assumptions: The 4 fields with 1 and 0 values are of type bit.
Breakdown:

*

*Sum is used to check how many of the 4 CPUIDs per IP Address are available. We are only interested in those where sum = 4.

*All must be enabled.

*Must not be in use when selecting.

*Must be the one with minimum value for last request date.


text:
Q: jQuery custom function with multiple selectors I am trying to create a custom jquery function which has two parameters, the one a single string defining the method in which to update the second parameter; an object of selectors.
Here is an example of the usage of the function:
$.select_content("update", {
    "object_1",
    "object_2"
});

And the function:
(function ( $ ) {
    var methods             = {
        "update"            : function ( objects ) {
            $.each(objects, function (object){
                // Do stuff...
            });
        },
        "reset"             : function ( objects ) {
            $.each(objects, function (object){
                // Do stuff...
            });
        }
    };
    $.fn.select_content     = function ( method ) {

    };
})( jQuery );

However I get a return error in my console which exclaims a unexpected token , on the this line: "object_1",",.
Is there a better way to approach this? Thank you.

A: Because the json syntax require key value pair. You can try an array:
$.select_content("update", [
    "object_1",
    "object_2"
]);

But you can also use the selector syntax:
$.select_content("update", "object_1, object_2");

Then:
$(objects).each(function (object){
    // Do stuff...
});

A: While I don't understand exactly what you're trying to do, your syntax error comes from this code sample:
$.select_content("update", {
    "object_1",
    "object_2"
});

In your second param, you are using object literal notation ({}, what some might mistakenly call JSON) without naming key/value pairs. That particular syntax error will go away if you use array literal notation instead:
$.select_content("update", [
    "object_1",
    "object_2"
]);

Or if you add key names:
$.select_content("update", {
    one: "object_1",
    two: "object_2"
});

Whichever of those changes you choose will fix the syntax error you're concerned about, as I said, but may not make the thing work. There are other issues in what you're showing us. A few are:

*

*You show your function being defined on the jQuery prototype ($.fn), making it an instance object. However, you are calling it as if it were "static" via $.yourFunc()

*You are defining your method on the jQuery prototype but you are not returning the collection against which it was run--which kills chaining.

Based on those two items, I suspect you meant to define you method under $ as opposed to $.fn. But I cannot be sure of your intent.


text:
Q: How do I set up a stand-alone Gunicorn App server if I already have an Nginx proxy set up? I'm trying to set up multiple servers that look like:
Client Request ----> Nginx (Reverse-Proxy / Load-Balancer)
                        |
                       /|\
                      | | `-> App. Server I.   10.128.xxx.yy1:8080 # Our example
                      |  `--> App. Server II.  10.128.xxx.yy2:8080
                       `----> ..

I understand that I need to put the App servers (Gunicorn in this case) behind an Nginx Proxy, but how do I set up the App servers by themselves?
I'm trying to set up the App server with systemd, and my configuration looks like:
[Unit]
Description=gunicorn daemon
After=network.target

[Service]
User=kyle
Group=www-data
WorkingDirectory=/home/kyle/do_app_one
ExecStart=/home/kyle/do_app_one/venv/bin/gunicorn --workers 3 --bind unix:/home/kyle/do_app_one/do_app_one.sock do_app_one.wsgi:application

[Install]
WantedBy=multi-user.target

I know the socket is being created because I can see it:

but I can't access the Gunicorn server by itself when I hit the IP address, with or without the :8000 port attached to it. Without the systemd configuration, I can access the site if I do:
gunicorn --bind 0.0.0.0:8000 myproject.wsgi:application

but I want to do this the right way with an init system like systemd, and I don't think I'm supposed to be binding it directly to a port because I've read it's less efficient/secure than using a socket. Unless binding to a port is the only way, then I guess that's what I have to do.
Every tutorial I see says I need an Nginx server in front of my Gunicorn server, but I already have an Nginx server in front of them. Do I need another one in front of each server such that it looks like:
Client Request ----> Nginx (Reverse-Proxy / Load-Balancer)
                        |
                       /|\
                      | | `-> Nginx + App. Server I.   10.128.xxx.yy1:8080 # Our example
                      |  `--> Nginx + App. Server II.  10.128.xxx.yy2:8080
                       `----> ..

If Nginx is an HTTP server, and Gunicorn is an HTTP server, why would I need another Nginx server in front of each App Server? It seems redundant.
And if I don't need another Nginx server in front of each Gunicorn server, how do I set up the Gunicorn server with systemd such that it can stand alone?
Edit:
I was curious as to why the binding to a physical port was working, but the socket wasn't, so I ran gunicorn status and got errors:
kyle@ubuntu-512mb-tor1-01-app:~/do_app_one$ . venv/bin/activate
(venv) kyle@ubuntu-512mb-tor1-01-app:~/do_app_one$ gunicorn status
[2016-12-03 20:19:49 +0000] [11050] [INFO] Starting gunicorn 19.6.0
[2016-12-03 20:19:49 +0000] [11050] [INFO] Listening at: http://127.0.0.1:8000 (11050)
[2016-12-03 20:19:49 +0000] [11050] [INFO] Using worker: sync
[2016-12-03 20:19:49 +0000] [11053] [INFO] Booting worker with pid: 11053
[2016-12-03 20:19:49 +0000] [11053] [ERROR] Exception in worker process
Traceback (most recent call last):
  File "/home/kyle/do_app_one/venv/lib/python3.5/site-packages/gunicorn/arbiter.py", line 557, in spawn_worker
    worker.init_process()
  File "/home/kyle/do_app_one/venv/lib/python3.5/site-packages/gunicorn/workers/base.py", line 126, in init_process
    self.load_wsgi()
  File "/home/kyle/do_app_one/venv/lib/python3.5/site-packages/gunicorn/workers/base.py", line 136, in load_wsgi
    self.wsgi = self.app.wsgi()
  File "/home/kyle/do_app_one/venv/lib/python3.5/site-packages/gunicorn/app/base.py", line 67, in wsgi
    self.callable = self.load()
  File "/home/kyle/do_app_one/venv/lib/python3.5/site-packages/gunicorn/app/wsgiapp.py", line 65, in load
    return self.load_wsgiapp()
  File "/home/kyle/do_app_one/venv/lib/python3.5/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp
    return util.import_app(self.app_uri)
  File "/home/kyle/do_app_one/venv/lib/python3.5/site-packages/gunicorn/util.py", line 357, in import_app
    __import__(module)
ImportError: No module named 'status'
[2016-12-03 20:19:49 +0000] [11053] [INFO] Worker exiting (pid: 11053)
[2016-12-03 20:19:49 +0000] [11050] [INFO] Shutting down: Master
[2016-12-03 20:19:49 +0000] [11050] [INFO] Reason: Worker failed to boot.

Still not sure how to fix the problem though.

A: The right answer is to just bind Gunicorn to a port instead of a unix socket. I'm not too sure about the details, but unix sockets can only be used within a local network according to:
https://unix.stackexchange.com/questions/91774/performance-of-unix-sockets-vs-tcp-ports
So when I changed the gunicorn.service file ExecStart line to:
ExecStart=/home/kyle/do_app_one/venv/bin/gunicorn --workers 3 --bind 0.0.0.0:8000 do_app_one.wsgi:application

I was able to access the server by itself, and connect it to my Nginx server that was on a different IP.


text:
Q: How to set env variables in Makefile to run tests? I'm trying to create a Makefile to run my tests. I have to set DATABASE_URL variable before running the tests but it looks like it doesn't work.
Here's my Makefile
IP := $(docker-machine ip default)
DATABASE_URL := "postgres://postgres@$(IP)/postgres"
test:
    @echo ${DATABASE_URL}
    py.test tests

I get error something like this
E   psycopg2.OperationalError: could not connect to server: No such file or directory
E       Is the server running locally and accepting
E       connections on Unix domain socket "/tmp/.s.PGSQL.5432"?

If I set DATABASE_URL directly from bash I can run the tests.

A: You should export DATABASE_URL as described here.
export DATABASE_URL := "postgres://postgres@$(IP)/postgres"

The echo ${DATABASE_URL} is resolved by make and not by shell. Just try env | grep DATABASE_URL and you will get and error as long as DATABASE_URL is not exported.
The behaviour you expected (exporting all variables) can be achieved by the export command without parameters.


text:
Q: C# Custom TrackBar Buffer Area I'm making a User Control to act as a TrackBar. I have a ToolboxCustomTrackbar1 which has a Min and Max as well as a SelectedMin which can be changed by the user dragging around a MinPanel in the area.
The MinPanel is drawn based on SelectedMin, which is changed with the following code:
    protected override void OnMouseMove(MouseEventArgs e)
    {
        base.OnMouseMove(e);

        if(e.Button == MouseButtons.Left)
        {
            UpdateSelectedMinFromMouse(e.X);
        }
    }

    private void UpdateSelectedMinFromMouse(float x)
    {
        var percentage = x * 100 / Width;
        var range = Max - Min;
        var rawValue = percentage * range / 100;
        var value = rawValue + Min;

        SelectedMin = (int)Math.Round(value);
    }

MinPanel is then drawn with the following code:
protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);

        e.Graphics.DrawRectangle(Pens.Black, 0, 0, Width - 1, Height - 1);

        minPanel.Location = new Point((int)GetPosition(ref selectedMin), 0);
        minPanel.Size = new Size(PanelWidth, Height/2);
        minPanel.BackColor = Color.Red;

        trackbarArea = new Rectangle(Buffer, 0, Width - Buffer * 2, Height);
        e.Graphics.FillRectangle(Brushes.LightBlue, trackbarArea);

    }

    private float GetPosition(ref int input)
    {
        var range = Max - Min;
        var value = input - Min;
        var percentage = (float)value * 100 / range;
        var position = percentage * Width / 100;

        Console.WriteLine(position);

        return position - (float)minPanel.Width / 2;
    }

This all works fine and draws the MinPanel wherever I click and drag on the control. However, I want to allow for a buffer area on the left and right of the control so as to draw the entire MinPanel even when it's at the left and right edges of the control.
I'm currently trying to do this with:
Rectangle trackbarArea = new Rectangle(Buffer, 0, Width - Buffer * 2, Height);
And this creates the area which I actually want to be considered the range for my TrackBar.
However, I can't seem to figure out how to have my control treat the Left edge of trackbarArea as the Min spot and the Right edge as the Max spot.
How can I allow my TrackBar to work with a Buffer on either side of it?

A: I created a ShiftOffset variable which I essentially use to offset both the Min and the Max:
private int ShiftOffset
{
    get { return shiftOffset; }
    set { shiftOffset = value; }
}
private int Min
{
    get { return min - ShiftOffset; }
    set { min = value; }
}
private int Max
{
    get { return max + ShiftOffset; }
    set { max = value; }
}

Then, everytime I set a value, I ValidateValue() using:
private void ValidateValue(ref int value)
{
    if (value < Min + ShiftOffset) value = Min + ShiftOffset;
    if (value > Max - ShiftOffset) value = Max - ShiftOffset;
}

In my User Control initialization, I set ShiftOffset = NormalizeSize(PanelWidth * 100); but I have yet to figure out what the appropriate value for ShiftOffset is in order to leave room to draw the last half of the Panels.
I'm trying to do some sort of PanelWidth * (Max - Min) / Width or some variation, but I can't quite get it.


text:
Q: CSS layout with 2 columns, taking up all width of browser, where left column can collapse I want to have a 2 column layout, and have the left column able to be 200 px at first, and have a "shrink" button to shrink it down to 10px, and have the right column expand to fill all the rest of the available space.  Then if they click on the "show" button (which will be all they see in the now 10px wide left column) have the left grow back to 200px and have the right column shrink by that amount.
I can't figure out how to make the right column grown and shrink without knowing the exact width of the window.
I hope this makes sense, and I really hope someone can point me in the right direction.
Browser requirements are IE8, FF3.6, Safari, and Chrome, so in theory I can use some advanced CSS techniques.  At least I don't have to support IE6.

A: If you float your left column (float: left;) with variably a width of either 10 or 200px, and simply add overflow: hidden; to the styles of the right column, the right column will expand and contract to fill the space, whatever the site of the left column is.

A: it would help if you put your sample on http://jsbin.com/, but try the following:
html, body, form
    {
        height:   100%;
        margin:   0px;
        padding:  0px;
    }
and then make the right column width 100%.
Is this what your are looking for?:  http://jsbin.com/uweqe3

A: Something like this should do the trick:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

        <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
        <title>Demo</title>

                Sub content
                Toggle

                Main content


text:
Q: Autocompletion doesn't autocomplete Here is a page with:
<form action="action.php" method="get" autocomplete="on">
  First name:<input type="text" name="fname">

  E-mail: <input type="email" name="email">

  <input type="submit">
</form>

Let's enter the 2 fields, and submit. Then when reloading the page, the fields are not autocompleted, why?
Should I use local-storage? cookies? to be sure that a user that comes back a few days after will still have its fields autocompleted?
(I'm using Firefox with default options about autocompletion, i.e. not disabled).

A: Firstly you need to realise that an attribute on the element without any coding on your part is entirely browser implemented.
Browsers implement these things differently.
You should check the spec. There you will notice that, actually,

By default, the autocomplete attribute of form elements is in the on state.

The only solution to the problem you are having is to say that, if you want a more reliable and consistent, user experience; don't rely on browser implementation.
The short answer: Use Javascript
There are hundreds of plugins that will do this for you. I will point you to one that has been popular on github recently but will need you to actually need to tell this plugin what you expect it to do: https://leaverou.github.io/awesomplete/
Updated Answer:
I see that you just want to prefill the field. This can be accomplished with something like this (untested):
var form = document.forms["name_of_your_form"];
form.onsubmit = function(){
  localStorage.setItem("fname", form.elements["fname"].value);
  localStorage.setItem("email", form.elements["email"].value);
}
window.onload = function() {
  form.elements["fname"].value = localStorage.getItem("fname");
  form.elements["email"].value = localStorage.getItem("email");
}


text:
Q: Don't display html if function returns nothing This question is very similar to the one below however it requires a different solution.
Don't display html if custom field is empty
I'm using the plugin Related Posts Thumbnails but i'm using the template tag in my template file to display related products.
<?php get_related_posts_thumbnails(); ?>

Plugin Source
I've got this contained inside of a div with a title so the output looks a bit better. However if there isn't any related products i need it to hide the div otherwise it just displays an empty area.
This is the code i'm using.

Related Products

    <?php get_related_posts_thumbnails(); ?>

Is it possible to not show this div if the function returns no related products?
Thanks

A: <?php
global $related_posts_thumbnails;
if ($related_posts_thumbnails->get_html()) { ?>

Related Products

        <?php get_related_posts_thumbnails() ?>

<?php } ?>

A quick look at the get_related_posts_thumbnails() shows that it is simply echoing the HTML returned from the get_html() method of the $related_posts_thumbnails object. By checking the returned HTML first, you can make sure it is not an empty string (or any falsy value).
Note for the plugin author: picking the name get_related_posts_thumbnails() and making it echo the output is quite unintuitive. Other WordPress functions use the get_ prefix for functions that return data, and leave it out to echo it. For example: get_bloginfo('url') vs bloginfo('url').

A: Looks like the plugin's function echos the output and does not return it. But the plugin has a shortcode, which you can use to get what you want.
<?php
$thumbs = do_shortcode('[related-posts-thumbnails]');
if(strlen($thumbs) > 0)
{?

Related Products

        <?php echo $thumbs; ?>

<?php }
?>

Try this and let me know.


text:
Q: how to serialize objects with specific fields using serializers.serialize in django? I want to serialize django models for only some specific fields. How do I do that. I have a model as below:
class Person(models.Model):
    first_name = models.CharField(max_length=20)
    last_name = models.CharField(max_length=20)

    def __str__(self):
        return self.first_name

I am using serailizer as:
from django.core import serializers

serializers.serialize('json', Person.objects.all(), content_type='application/json')

My output is:
[
   {
       model: "myapp.Person",
       pk: 1,
       fields: {
           "first_name": "hello",
           "last_name": "world"
       }
   }
]

I want to serialize this model only for first_name and output must be as below:
[
   {
       model: "myapp.Person",
       pk: 1,
       fields: {
           "first_name": "hello"
       }
   }
]

A: Person.objects.all() also has the first_name value in it. You can access it via:
for p in Person.objects.all():
    p.first_name

Please read the documentation for more details.
Update:
For serialization, try like this:
serializers.serialize("json", Person.objects.all(), fields=["first_name", "last_name"])


text:
Q: How to make a project inside a submodule? I have recently found the neat submodules feature of git and I would like to use it. But as I have seen, a submodule goes inside a project... like this:
Project
   Submodule

but if I would like to develop a library or plugin, how do I work around? I would have a software and inside it I would develop my project ending with this structure:
Submodule
   Project

That way the software can get upgraded and I can upgrade the plugin on a new version.
I have read some tutorials and information but I'm not sure how to make the second approach.


text:
Q: WPF Datagrid: ListCollectionView sorting does not seem to work after Data is changed My DataGrid's ItemsSource is a ListCollectionView, which has a GroupDescription and two SortDescriptions. On the first run of the program, everything works as it should.
However, when the data the ListCollectionView is based on gets changed, the sorting of the ListCollectionView fails (whereas the Grouping does not). It behaves as if the two lines marked as "LINE A" and "LINE B" were not there at all.
public List<MyModel> Models { get; set; }
public ListCollectionView _collectionView;

public MyConstructor()
{
    InitializeComponent();
    GetData();
    Grouping();
}

public void GetData()
{
    // fill the list "Models"
}

public void Grouping()
{
    // _collectionView = null;
    _collectionView = new ListCollectionView(Models);
    _collectionView.GroupDescriptions.Add(new PropertyGroupDescription("MyModelSupplier"));
    _collectionView.SortDescriptions.Add(new SortDescription("MyModelSupplier", ListSortDirection.Ascending)); // LINE A
    _collectionView.SortDescriptions.Add(new SortDescription("MyModelName", ListSortDirection.Ascending)); // LINE B
    ModelControl.ItemsSource = _collectionView;
}

private void OnDataChanged (object sender, EventArgs e)
{
    // Save the Data to the Database
    //...

    // Retrieve the Data
    GetData();

    // Group it again
    Grouping();
}

To summarize:
On startup everything looks and behaves like it should. Changing data, saving it to the DataBase and retrieving it again does work also. Just the sorting of the retrieved, grouped data won't work (the list is sorted - like default - by the first property of the MyModel class, which is MyModelName ... and NOT by MyModelSupplier, as it does in the very beginning).
Edit:
This is a known bug/missing feature (up until .NET 4.6.2). Several suggestions can be found here (I went with the last solution):
Bug-Report: https://connect.microsoft.com/VisualStudio/feedback/details/2017716/wpf-live-shaping-groups-are-not-sorted-correctly-after-a-property-changes
Simple Fix: https://stackoverflow.com/a/10121983/8187945

A: Honestly, I wasted six hours of my lifetime.
SortDescriptions just worked for 1st time and I wasn't able to implement all offered solutions I found somewhere.
I decided to use CustomSort. After five minutes I was finished. So, if you read this, maybe you'll save time
The Solution 1 Part:
public class MyComparer : IComparer
{
    public int Compare(object x, object y)
    {
        var a = x as CustomViewEntityViewModel;
        var b = y as CustomViewEntityViewModel;

        if (a == null || b == null)
            throw new ArgumentException("Not My CustomViewEntityViewModel");

        if (a.SortOrder > b.SortOrder)  // I added property SortOrder to my viewmodel
            return 1;
        if (a.SortOrder == b.SortOrder)
            return 0;

        return -1;
    }
}

2nd Part: How to use
var myListCollectionView = (ListCollectionView)CollectionViewSource.GetDefaultView(Filters);
myListCollectionView.CustomSort = new MyComparer();
myListCollectionView.GroupDescriptions.Add(new PropertyGroupDescription("Category"));

MyListCollectionView = myListCollectionView; // Which is binded by DG.ItemsSource

A: I am unsure why you are making your ListCollectionView in your VM as this is a part of PresentationFramework.dll so no MvvM in here.
However if you use CollectionViewSource in your xaml then this would be much easier!
in your xaml you would do:
<CollectionViewSource Source="{Binding Items}" x:Key="items">
    <CollectionViewSource.GroupDescriptions>
        <PropertyGroupDescription PropertyName="yourPropertyHere"/>
    </CollectionViewSource.GroupDescriptions>
    <CollectionViewSource.SortDescriptions>
        <scm:SortDescription PropertyName="propertyHere" />
    </CollectionViewSource.SortDescriptions>
    <CollectionViewSource.LiveFilteringProperties>
        propertyNameHere
    </CollectionViewSource.LiveFilteringProperties>
</CollectionViewSource>

Where:
xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"

and then use it for your DataGrid like so:
<DataGrid ItemsSource="{Binding Source={StaticResource events}}"/>
This gives you the ability to have these options in xaml and away from your view model.
You can also do this in code behind:
XAML:
<CollectionViewSource x:Key="MyCVS"
                          Source="{Binding Items}"
                          Filter="My_Filter" />

and then in your code behind:
void My_Filter(object sender, FilterEventArgs e)
{
    var item = e.Item as yourModelObject;
    if (item == <your test here>)
    {
        e.Accepted = true;
    }
    else
    {
        e.Accepted = false;
    }
}

If you still have difficulties with the view not being refreshed then you could use this in your code behind to access the items being displayed and just refresh:
CollectionViewSource.GetDefaultView(lst.ItemsSource).Refresh();// where lst would be ListView or DataGrid


text:
Q: How much heap memory required for elasticsearch? I have 8 node cluster(3Master+3Data+2Coordinate) in each data node the heap size is 10gb and disk space is 441gb each total 1.2TB
in each day i have 32.73GB data in each day 26 shards created for 11 indices.So lets suppose the retention period is 30 days.In 30th day the data on cluster would be 982GB and total shards would be 780 each node gets 260 shards.So the average shard size would be 260mb(approx).i read  this documentation that a node of 30gb heap size can handle 600 shards.So the question is Can heap size of 10gb can handle 260 shards ?.

A: This article which you read can be considered a good general recommendations but there are various factors which can affect it, like size of indices, size of shards, size of documents, type of disk, current load on the system and so on, in the same document you can notice the shard size recommendation is between 10 to 50 GB, while you have very small shard size(260 MB as you mentioned), so based on this, I can say 10GB heap can easily handle 260 shards in your case, although you should benchmark your cluster and read more about how ES internally stores the data and searches them so that its easy for you to fine-tune it.


text:
Q: How to create numeric Textbox Custom Control with dependency Property in WPF? I want create a custom control for Numeric Text box  with dependency property in WPF , in my solution , I add one WPF application and custom control (WPF) ,then in public class , I create dependency property ....
Now I don't know how can i write my rule for text box and which event is true?
Another question : What is my rule for numeric text box , that this text box must be give number and . and Separating .this  custom Text box is for accounting system.
public static readonly DependencyProperty NumberTextbox;
static Numeric()
{
    DefaultStyleKeyProperty.OverrideMetadata(typeof(Numeric), new FrameworkPropertyMetadata(typeof(Numeric)));
    FrameworkPropertyMetadata metadata = new FrameworkPropertyMetadata("Enter Your Text", OnKeyDown);
    NumberTextbox =DependencyProperty.Register("Text", typeof(TextBox), typeof(FrameworkElement), metadata);
}

public string NumberTXT
{
    get { return (string)GetValue(NumberTextbox); }
    set { SetValue(NumberTextbox, value); }
}

A: I don't understand your question exactly and why you need dependency proerties to make a numeric text box custom control. What you can do is to inherit from textbox and handle the PreviewTextInput, like it is solved in this question by Ray:
then you get:
  public class NumericTextBox : TextBox
  {

    public NumericTextBox()
    {
      PreviewTextInput += NumericTextBox_PreviewTextInput;
    }

    void NumericTextBox_PreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
    {
      e.Handled = !isTextAllowed(e.Text);
    }

    private static bool isTextAllowed(string text)
    {
      var regex = new Regex("[^0-9]+");
      return !regex.IsMatch(text);
    }
  }

And you can use it like that:
 <myNameSpace:NumericTextBox />

And now you can add any other validation you want.
I would also implement a solution for the pasting issue, something like (see also in the link):
private void textBoxPasting(object sender, DataObjectPastingEventArgs e)
    {
      if (e.DataObject.GetDataPresent(typeof(String)))
      {
        var text = (String)e.DataObject.GetData(typeof(String));
        if (!isTextAllowed(text))
        {
          e.CancelCommand();
        }
      }
      else
      {
        e.CancelCommand();
      }
    }

A: I recommend to you add another Dependency Property in example code below I named it Value
Also format your number by comma or NumberFormatInfo.CurrentInfo.NumberDecimalSeparator
and control caret location changes by two property SelectionLength and SelectionStart.
Finally for more detail and complete code WPF Maskable Number Entry TextBox
region Value property
    public static readonly DependencyProperty ValueProperty =
        DependencyProperty.Register("Value", typeof(double), typeof(NumericTextBox), new PropertyMetadata(new Double(), OnValueChanged));

    private static void OnValueChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
    {
        //var numericBoxControl = (NumericTextBox)sender;
    }
    public double Value
    {
        get { return (double)GetValue(ValueProperty); }
        set { SetValue(ValueProperty, value); Text = value.ToString("###,###,###"); }
    }

endregion
    protected override void OnPreviewTextInput(TextCompositionEventArgs e)
    {
        base.OnPreviewTextInput(e);
        var txt = e.Text.Replace(",", "");
        e.Handled = !IsTextAllowed(txt);
        if (IsTextAllowed(txt))
        {
            if (Text.Length == 3)
            {
                Text = Text.Insert(1,",");
                SelectionLength = 1;
                SelectionStart += Text.Length;
            }
        }
    }

    protected override void OnPreviewKeyDown(KeyEventArgs e)
    {
        base.OnPreviewKeyDown(e);
        if (e.Key == Key.Back)
        {
            if (Text.Length == 5)
            {
                Text = Text.Replace(",", "");
                SelectionLength = 1;
                SelectionStart += Text.Length;
            }
        }
    }

    protected override void OnTextChanged(TextChangedEventArgs e)
    {
        var txt = Text.Replace(",", "");
        SetValue(ValueProperty, txt.Length==0?0:double.Parse(txt));
        base.OnTextChanged(e);
    }

    private static bool IsTextAllowed(string text)
    {
        try
        {
            double.Parse(text);
            return true;
        }
        catch (FormatException)
        {
            return false;
        }
    }

A: Good job, but let me do the following task with a UserControl in C #:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace NumericBox
{
    public partial class NumericBox : TextBox
    {
        public NumericBox
        {
            this.TextAlign = HorizontalAlignment.Right;
            this.Text = "0,00";
            this.KeyPress += NumericBox_KeyPress;
        }

        public double NumericResult
        {
            get{
                double d = Convert.ToDouble(this.Text.Replace('.', ','));
                return d;
            }
        }
        private void NumericBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.'))
                e.Handled = true;

            if ((e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1))
                e.Handled = true;

            if (e.KeyChar == 13)
            {
                e.Handled = true;
                SendKeys.Send("{TAB}");
            }
        }
    }
}


text:
Q: Existence of adjoint operator in Euclidean space If we define the adjoint operator of linear operator $A:E\to E$, where $E$ is a complex or real Euclidean, $n$- or $\infty$-dimensional, space, as operator $A^\ast:E\to E$ such that $\forall x,y\in E\quad \langle Ax,y\rangle=\langle x,A^\ast y\rangle$, I wonder whether for any $A$ the adjoint exists. If it does, how can we prove it?
In the case that it exists, I think -please correct me if I am wrong- it is unique as in the case of the adjoint operator of linear operator $A:E\to E_1$, with $E$ a Banach space, defined as $A^\star: E_1^\star\to E^\star$, $f\mapsto f\circ A$.
Thank you very much for any answer!

A: From comments, it sounds like by "Euclidean space" you mean "Hilbert space".  Let's call it $H$.
It is certainly true that for any bounded linear operator $A : H \to H$, the adjoint map exists.  It's really the same as for Banach spaces: define the linear operator $A^*$ on $H^*$ via $A^* f = f \circ A$, and then use the Riesz representation theorem to identify $H^*$ with $H$.
More explicitly: for each $y \in H$, the map $x \mapsto \langle Ax, y \rangle$ is a continuous linear functional on $H$.  By the Riesz representation theorem, there exists a unique $z_y \in H$ such that $\langle Ax, y \rangle = \langle x, z_y \rangle$.  Define $A^*$ as the map taking $y$ to this uniquely determined $z_y$.  Then it is an easy verification that $A^*$ is linear and bounded, and $\langle Ax, y \rangle = \langle x, A^* y \rangle$ holds by construction.
If $A$ is an unbounded linear operator on $H$ having dense domain $D(A)$, we can also define an adjoint $A^*$ as an unbounded operator.  We let $D(A^*)$ be the set of all $y$ such that the map $x \mapsto \langle Ax, y \rangle$ is a continuous linear functional on $D(A) \subset H$, which by (uniform) continuity extends uniquely to a continuous linear functional on $H$.  Then for such $y$ we may define $A^* y$ just as before.  It is an exercise to show that $A^*$ is a closed operator, and is densely defined iff $(A, D(A))$ is closable.


text:
Q: DIV com height:auto; não se reajusta de acordo com a altura da DIV interna Tenho uma DIV com height:auto; que não ajusta a altura de acordo com uma div interna com height:120px;
Veja o CSS
.conteudo-modelo-3-0 {
width:960px;
height:auto;
margin: 0 auto;
}

.conteudo-modelo-3-1{
position:relative;
width:840px;
height:120px;
float:right;
background-color:#666666;
}

A DIV conteudo-modelo-3-0 não se reajusta de acordo com a altura de conteudo-modelo-3-1.
O que faço para corrigir isso?

A: Em resumo, isso acontece porque a div interna (child) está utilizando o atributo float. Quando se utiliza o atributo float, o elemento fica "flutuando" e por isso a div pai (parent), não consegue identificar a altura do filho (child). OK, como resolver? A resposta está em utilizar o clear: both;.
A maneira mais utilizada hoje é através do pseudo elemento after. Cria-se uma classe geral chamada clearfix, com os seguintes atributos:
.clearfix:after{
    content: "";
    display: table;
    clear: both;
}

Então respondendo a sua pergunta, ficaria assim:

Criei um fiddle para dar um exemplo: Exemplo
Créditos: https://css-tricks.com/snippets/css/clear-fix

A: Utilize a propriedade overflow: auto.
Ficará assim.

.conteudo-modelo-3-0 {
  width:960px;
  height:auto;
  margin: 0 auto;
  overflow: auto;
}
.conteudo-modelo-3-1 {
  position:relative;
  width:840px;
  height:120px;
  float:right;
  background-color:#666666;
}

O overflow: auto irá servir apenas quando o height não estiver com uma altura definida.


text:
Q: selinux file context precendence, logrotate and httpd UPDATE:
figured out the issue, its with my fcontext path expression
I have to use
semanage fcontext -a -t logrotate_tmp_t "/etc/httpd/logs(./*)?"
instead of
semanage fcontext -a -t logrotate_tmp_t "/etc/httpd/logs/*"

and -t httpd_log_t also works

I think the questions that remain

*

*Where can I find the documentation reference to the expression? and will it be version specific?

*is there any man command to show these kind of selinux file context related help content on the server? I checked seinfo and sesearch was not installed on that server, do I simply have to install them?

ORIGINAL:
I have a server in AWS running SELinux, been trying to configure httpd log rotation.
sestatus
SELinux status: enabled
SELinuxfs mount: /selinux
Current mode: enforcing
Mode from conif files: enforcing
Policy version: 24
Policy from config file: targeted

logrotate can't seem to work properly on httpd logs
Manually running logrotate and logrotate -f as root works. I tried it with logrotate -d it does read the logrotate.status and retrieve last date correctly. But when its put to cron.daily/logrotate, the rotation does not happen and I receive mail in /var/mail/root that
/etc/cron.daily/logrotate:

error: unable to open /etc/httpd/logs/access_log-yyyymmdd for compression

or sometimes
error: error opening /etc/httpd/logs/access_log: Permission denied

ls -Z in the path yields below
~cd /etc/httpd
~ls -dZ logs
dxwxr-xr-x. root root unconfined_u:object_r:httpd_log_t:s0 logs
~ls -Z logs
-rw-r--r--. root unconfined_u:object_r:httpd_config_t:s0 access_log

I was having difficulty determining what file contexts to and how to put it to the folder and files
man logrotate does not mention what contexts it needs, and date of manual is 2022
man semanage date of manual is 2010
reading https://linux.die.net/man/8/logrotate_selinux, the only appropriate file context seems to be logrotate_tmp_t, so I tried to add it
semanage fcontext -a -t logrotate_tmp_t /etc/httpd/logs/*
restorecon -v /etc/httpd/logs/*

but restorecon did not produce any output, not even without * or /
checked semanage fcontext -l with grep -n
 685:/etc/httpd(/.*)? all files system_u:object_r:httpd_config_t:s0
2928:/etc/httpd/logs all files system_u:object_r:httpd_log_t:s0
4642:/etc/httpd/logs/* all files system_u:object_r:logrotate_tmp_t:s0

and I read that lines come later should take precendence, however that does not seems the case, as seen in the ls -Z output above. I also tried to give the logs folder var_log_t context as a workaround (same context as /var/log) but it also does not show in ls -Z.
I even tried semanage fcontext -C -l in the logs folder, and only the entry /etc/httpd/logs/* all files system_u:object_r:logrotate_tmp_t:s0 came up
I am confused whether if this is due to the selinux and logrotate version being too old? would want to know.

*

*If there is a correct way invoke the selinus related manual of logrotate on the machine? man logrotate_ tab does not show any available options

*Did I understand the selinux file context precedence correctly?

*Is this an old version issue?

*does the context type given by fcontext -l matter? choices are "all files, regular file, directory, symbolic link etc"

*and if the context type matters, how do I set it in the command? semanage -v showed that its in the Object-specific Opions, -f specifies file type of object, "" is all files, -- is regular file, -d is directory, but wherever I insert it in the semanage fcontext -a -t type files command, it always give me semange: bad option

*What is my actual issue


text:
Q: How to sort double objects? I have an array. The data in the array is in the following format.
var test = [
    {
    "a" : {
        "order" : 100,
    }
  },
  {
    "b" : {
        "order" : 10,
    }
  },
  {
    "c" : {
        "order" : 1,
    }
  },
];

I want to sort this data according to order value. Is there any way to do this?

A: You can use JS custom sort from Array.prototype.sort(), reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
Then you can sort by comparing the two element's order, but you still need to determine it's key/attribute (e.g.: a or b or c)
Here, you can use Object.keys() function and take the first key in the object, reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
Here's a working example:

var test = [
    {
    "a" : {
        "order" : 100,
    }
  },
  {
    "b" : {
        "order" : 10,
    }
  },
  {
    "c" : {
        "order" : 1,
    }
  },
];

//console.log(test);

test.sort((firstEl, secondEl) => {
    var key1 = Object.keys(firstEl)[0];
    var key2 = Object.keys(secondEl)[0];
    return firstEl[key1].order - secondEl[key2].order
} );
console.log(test);

Output:
[
  {
    "c": {
      "order": 1
    }
  },
  {
    "b": {
      "order": 10
    }
  },
  {
    "a": {
      "order": 100
    }
  }
]

A: You can use Object.values to get the first property value and access the order property on that to compare.

let test=[{a:{order:100}},{b:{order:10}},{c:{order:1}}];
test.sort((a, b)=>Object.values(a)[0].order - Object.values(b)[0].order);
console.log(test);

For a more generalized solution, you can create a key extractor function to get the value to compare by.

let test=[{a:{order:100}},{b:{order:10}},{c:{order:1}}];
const getOrder = x => Object.values(x)[0].order;
test.sort((a, b)=>getOrder(a) - getOrder(b));
console.log(test);


text:
Q: Optimizing function for search Hi i have a search filter in my application. I would like to optimize this code, because it has too much lines of code. How change it so,it will work the same but with less code?
function myFunction() {
        var input, filter, table, tr, th, i;
        input = document.getElementById("myInput");
        filter = input.value.toUpperCase();
        table = document.getElementById("myTable");
        tr = table.getElementsByTagName("tr");
        for (i = 0; i < tr.length; i++) {
            th = tr[i].getElementsByTagName("th")[0]; // for column one
            th1 = tr[i].getElementsByTagName("th")[1];
            th2 = tr[i].getElementsByTagName("th")[2];
            th3 = tr[i].getElementsByTagName("th")[3];
            th4 = tr[i].getElementsByTagName("th")[4];
            th5 = tr[i].getElementsByTagName("th")[5];
            th6 = tr[i].getElementsByTagName("th")[6];
            th7 = tr[i].getElementsByTagName("th")[7];
            th8 = tr[i].getElementsByTagName("th")[8];
            th9 = tr[i].getElementsByTagName("th")[9];// for column two
            /* columns for search*/
            if (th) {
                if ( (th.innerHTML.toUpperCase().indexOf(filter) > -1) || (th1.innerHTML.toUpperCase().indexOf(filter) > -1) || (th2.innerHTML.toUpperCase().indexOf(filter) > -1) || (th3.innerHTML.toUpperCase().indexOf(filter) > -1) || (th4.innerHTML.toUpperCase().indexOf(filter) > -1) || (th5.innerHTML.toUpperCase().indexOf(filter) > -1) || (th6.innerHTML.toUpperCase().indexOf(filter) > -1) || (th7.innerHTML.toUpperCase().indexOf(filter) > -1) || (th8.innerHTML.toUpperCase().indexOf(filter) > -1) || (th9.innerHTML.toUpperCase().indexOf(filter) > -1)  )  {
                    tr[i].style.display = "";
                } else {
                    tr[i].style.display = "none";
                }
            }
        }
    }

A: Using hidden and find  will be much shorter
I use find instead of some for semantic reasons.
document.getElementById("myInput").addEventListener("input", function() {
  const filter = this.value.toUpperCase();
  const trs = document.querySelectorAll("#MyTable tbody tr")
  trs.forEach(tr => {
    const hide = filter &&
      ![...tr.querySelectorAll("th")]                              // none of the cells
        .find(th => th.textContent.toUpperCase().includes(filter));// contains filter
    tr.hidden = hide;
  })
})

Example

document.getElementById("myInput").addEventListener("input", function() {
  const filter = this.value.toUpperCase();
  const trs = document.querySelectorAll("#myTable tbody tr")
  trs.forEach(tr => {
    const hide = filter && ![...tr.querySelectorAll("td")].find(td => td.textContent.toUpperCase().includes(filter))
    tr.hidden = hide;
  })
})
* {
  box-sizing: border-box;
}

#myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 10px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}

#myTable {
  border-collapse: collapse;
  width: 100%;
  border: 1px solid #ddd;
  font-size: 18px;
}

#myTable th,
#myTable td {
  text-align: left;
  padding: 12px;
}

#myTable tr {
  border-bottom: 1px solid #ddd;
}

#myTable tr.header,
#myTable tr:hover {
  background-color: #f1f1f1;
}
<input type="text" id="myInput" placeholder="Filter" title="Filter text" autocomplete="off" />

      Id
      A
      B
      C
      D

      1
      One
      Two
      Three
      Four

      2
      Five
      Six
      Seven
      Eight

      3
      Nine
      Ten
      Eleven
      Twelve

A: You can also search in table by this way:
//search input id
    $("#search").on("keyup", function() {
        var value = $(this).val().toLowerCase();
    //tableStudentbody table id
        $("#tableStudentbody tr").filter(function() {
          $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
        });
      });


text:
Q: Fundamental group of covering space given fundamental group of base Exercise 18.4 (f) of Kosniowski's "A first course in Algebraic Topology" reads
Let $p: (\tilde{X}, \tilde{x}_0) \rightarrow (X, x_0)$ be a covering. Suppose the fundamental group of $X$ at $x_0$ is $\pi_1(X, x_0) = \mathbb{Z}$ and $p^{-1}(x_0)$ is finite. Find the fundamental group of $\tilde{X}$ at $\tilde{x}_0$.
Now all I can say is that $\tilde{X}$ cannot be simply connected, else there would be a 1-to-1 correspondence between $\mathbb{Z}$ and $p^{-1}(x_0)$, which is not possible with the latter finite.
I think I should somehow use the homomorphism $p_{\ast}$ induced by the covering map, but I have no further idea how to procede from here. Any suggestion?

A: Hint: $p_*$ must be an injective group homomorphism from $\pi_1(\tilde X)$ to $\Bbb Z$.


text:
Q: How to connect to internet through Ubuntu VM I don't know if this is simple or possible (if this is solved by openvpn or something).
I have an Ubuntu VM, that is connected to a proxy, so I can access some webpages that I cannot outside the VM.
At my host machine (windows), I cannot install the proxy, so I cannot access the same webpages, but I want to use the ethernet interface from Ubuntu to do so.
Is this possible in anyway?
I'm using Hyper-V, Ubuntu 18.04 LTS, Windows 10.