text:
Q: AnalyticsHashTagWebPart Showing No Results I have inherited a problem on a SharePoint 2013 on a project I have just recently joined. In the My Sites area of the SharePoint is the AnalyticsHashTagWebPart which shows as "Trending #tags". This web part always shows "Tagging's been quiet lately. No trending tags right now".
I am aware that on page load the part will (should) initiate a search for tags. Using Firefox tools I can see the requests for the tags are not being sent. The results should come back as JSON.
A few gotchas found by others is messing around with the search crawls and breaking it, that does not seem to be the issue.
The page is customized, which makes this more difficult. The changes are not mine so I am still figuring out what could be the issue. Looking at the part markup I see nothing different from the OOTB webpart.

*

*I have Continuous crawls set up

*I have tested a tag search in the search service (Manage Query Rules)
and it came back highlighting the Tags in Sharepoint Search OOTB
rule. So it seems that works.

There are enough posts in the last few days, as I have had some created with tags, so there should be trending.
Any ideas on where else to look to find the issue?

A: This may help someone else in the future, and maybe save them days of searching. It turned out the Managed Property Tags was no longer mapping to the crawled property ows_taxId_MetadataAllTagsInfo


text:
Q: Ears and neck detection using ARKit I am trying to detect ears and neck to put jewelry using ARKit. Currently, I am using hardcode value to do this but this is very inaccurate for different - different face.
 SCNNode *contentNode = [SCNNode node];
    ARSCNFaceGeometry *faceGeometry = [ARSCNFaceGeometry   faceGeometryWithDevice:_sceneView.device];
    SCNNode *faceNode = [SCNNode nodeWithGeometry:faceGeometry];
    contentNode = [SCNNode nodeWithGeometry:faceGeometry];
    earringsPlane.firstMaterial.doubleSided = true;
    [earringsNode setPosition:SCNVector3Make(-0.09, -0.04 , -0.04)];
    earringsNode.geometry = earringsPlane;
    [earringsNode2 setPosition:SCNVector3Make(0.09, -0.04 , -0.04)];
    earringsNode2.geometry = earringsPlane2;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Format String every N characters depending on the length of the String everyone, I need to live update character by character a String/TextField depending on the length of the String.
Eg: If user inserts 43041058, it should change to 4.304.105-8,
else if user inserts one more number (12 total characters) 430410582, it should update to 43.041.058-2.
Real Time Execution eg:
Step | User Input
1 | 4.
2 | 4.3
3 | 4.30
4 | 4.304.
5 | 4.304.1
6 | 4.304.10
7 | 4.304.105
8 | 4.304.105-8
9 | 43.041.058-2

The important thing is that the textField updates itself for each Character pressed, the closet I've got its to make it work only for 12 positions not for 11.
override func viewDidLoad() {
        super.viewDidLoad()
    rutFormatter()
    }

    func rutFormatter() {
        textRut.addTarget(self, action: #selector(VCLogin.textFieldDidChange(_:)), for: UIControl.Event.editingChanged)
    }

    @objc func textFieldDidChange(_ textField: UITextField) {
var newRut = String()
        for (index, character) in (textField.text?.enumerated())! {
            if index % 2 == 0 {
                if index != 0 && index % 2 == 0 {
                    switch index {
                    case 2:
                        if character != "." {
                            newRut.append(".")
                        }
                    case 10:
                        if character != "-" {
                            newRut.append("-")
                        }
                    default:
                        print("Default")
                    }
                }

                if index != 0 && index % 3 == 0 {
                    switch index {
                    case 6:
                        if character != "." {
                            newRut.append(".")
                        }
                    default:
                        print("Default")
                    }
                }
            }

            newRut.append(String(character))
        }
        textField.text = newRut
}

A: The following code should work.
let mask = "X.XXX.XXX-X"
let mask2 = "XX.XXX.XXX-X"

@objc func textFieldDidChange(_ textField: UITextField) {
    let string = textField.text
    let number = formattedNumber(number: textField.text!)
    textField.text = number
    print(string)
}

private func formattedNumber(number: String) -> String {
    var cleanPhoneNumber = number.components(separatedBy: CharacterSet.decimalDigits.inverted).joined()

    var result = ""
    var index = cleanPhoneNumber.startIndex
    var fieldMask: String!
    if number.count < 12 {
        fieldMask = mask
    }else {
        fieldMask = mask2
    }
    for ch in fieldMask.characters {
        if index == cleanPhoneNumber.endIndex {
            break
        }
        if ch == "X" {
            result.append(cleanPhoneNumber[index])
            index = cleanPhoneNumber.index(after: index)
        } else {
            result.append(ch)
        }
    }
    return result
}


text:
Q: Some arrangements problems [1] The numbers of ways of selecting $3$ pairs from $8$ distinct objects.
[2] The no. of $6$ Digit no. in which exactly $2$ digits are even, must be
[3] The no. of $6$ Digit no. in which exactly $2$ digits are even, must be
$\bf{My\; Try}$ for $(1)$ one::Let we have $8$ distinct objects..
$\left(a_{1},a_{2},a_{3},a_{4},a_{5},a_{6},a_{7},a_{8}\right)$ and we have to select $3$ pairs
which can be done by $\displaystyle \underbrace{\binom{8}{2}}_{\bf{for\; first\;  pair} }\times \underbrace{\binom{6}{2}}_{\bf{for\; second\;  pair} }\times \underbrace{\binom{4}{2}}_{\bf{for\; third\;  pair} }$
But i did not understand why we divide the above quantity by $3$
Help Required
also for $(2)$ and $(3)$ one
Thanks

A: Suppose that the eight objects are the numbers $1,2,3,4,5,6,7$, and $8$. You might select $\{1,2\}$ as your first pair, $\{4,6\}$ as your second pair, and $\{3,7\}$ as your third pair. You might instead select $\{4,6\}$ as your first pair, $\{3,7\}$ as your second pair, and $\{1,2\}$ as your third pair. Your calculation counts these as two separate outcomes, but of course in both cases you get the same three pairs. In fact you can select these pairs in any of $3!=6$ (not $3$) different orders, so you're counting this set of $3$ pairs $6$ times. Thus, to get the actual number of different sets of $3$ pairs, you must divide your answer by $3!=6$ to get
$$\frac1{3!}\binom82\binom62\binom42\;.$$
The answer to the second problem depends on whether you're allowed to have leading zeroes, i.e., on whether $012345$ counts as a $6$-digit number. If it does not, you should split the problem into two cases: the number begins with an odd digit, and the number begins with an even digit.

*

*If the first digit is odd, it can be any of the $5$ odd digits ($1,3,5,7,9$). So can each of the other $3$ odd digits. Each of the $2$ even digits can be any of $0,2,4,6$, or $8$, so there are also $5$ choices for each even digit. Thus, there are $5$ choices for each of the $6$ digits. How many ways are there to choose which $2$ of the digits are even?

*If the first digit is even, it cannot be $0$, so there are only $4$ choices for it. Are there still $5$ choices for each of the other $5$ digits? How many ways are there to choose where the other even digit goes?
The third problem is identical to the second, so it may not be what you meant to ask.


text:
Q: refactoring stored procedure I have a stored procedure currently executing a complicated fetch that is frequently timing out when used. The proposed solution in my department has been to simply increase the timeout time length; which I don't really want to do. I'd like to refactor this sproc, but because it's so complicated and undocumented (yay legacy systems) I'm concerned my refactoring my not result in the same functionality executing more efficiently. Are there any strategies to use when refactoring a stored procedure to ensure the same functions are being performed in less time?
This is a Microsoft SQL Server 2005 stored procedure.

A: Generally, time outs occur on a single SQL statement.  Break up the proc into separate statements, possibly by making effective use of temp tables, so you are not trying to do too much in a single chunk.  By doing this you can also hone in on your performance bottleneck and possibly identify some useful indexes if needed.

A: The most common cause of inefficient stored procedures I've encountered is a prevalence of scalar-type operations as opposed to set-based operations. Most RDBMS systems (Oracle, SQL Server, MySQL, etc) are much more efficient at performing work on large sets of data, not single operations repeated multiple times. It is more efficient to perform one operation on a million rows of data, than perform an operation a million times on each row.
After trying to determine these types of bottlenecks (typically look at function calls first) then I would suggest taking a look at the indexing strategy on the table(s) you're referencing. Depending on your RDBMS of choice, you might have some wizard-type functionality that could help you discover a proper index structure based on a sample workload.
What database are you using? That might help to fine-tune some of my suggestions.

A: I have been faced with this situation in the past.  The best thing to do is create a simple C# or VB .Net application.  When you refactor the sp, give it a new name.  Use the application to call both the old and new sp's.  Then compare the output of the two sp's to ensure they return the exact same values in the same order.
You would want to test as wide a variety of input parameters as you can to ensure your refactoring hasn't modified the business logic.
Also, using NUnit can help simplify this task.
When I started my current position, I was given a database that had to be modified for a new schema.  It required changing over 100 sp's.  Using the application I've described, I was able to be reasonably sure that one of my modifications did not break the business rules.
You're right, just increasing the timeout is the wrong first answer.  Improve the sp as best you can, then increase the timeout if necessary.

A: Use the SQL Server Profiler to study how the current SP runs; it will highlight inefficiencies and allow you to target just those specific areas to begin with, whilst leaving the more performant bits alone. You can then use the profiler again on your revised SP to compare performance.
I would echo Gunny's recommendation to take a good look at function calls - in set based operations these can have a real impact on performance. I've achieved massive performance gains in the past just by stripping out a single UDF and replicating the logic inline.


text:
Q: Unable to send data from react to express server I am trying to send data from react to express server.
React code:
const imageRenderer = async () => {
  const res = await axios({
    method: "post",
    url: "http://localhost:8080/previewRender",
    data: selectedFile.filePaths,
  });
console.log(res.data);

};
Express code:
app.post("/previewRender", (req, res) => {
  var fileLocation = req.body;
  console.log(fileLocation);
});

However in console the filelocation is shown as undefined. selectedFile.filePaths is of type object. Can't I send object to express?

A: Add this in app.js (app.js) or your root file of the app to post req
app.use(express.json());

app.use(express.urlencoded({ extended: false }));

Put this middleware in app.js above your routes...

A: Did you use app.use(express.json()) in your app.js?


text:
Q: Having conditions inside python generator functions I have some txt file that I have to parse in some way. In the middle of the file there is a part formatted as XML data.
I've written some class, with the following methods inside of them.
def generate_lines(self):
    start_line = self.get_starting_line()
    for idx, line in enumerate(open(self.log_file, 'r', encoding='ANSI')):
        if idx >= start_line:
            yield line
            if f'</{self.xml_tag}>' in line:
                break

def get_starting_line(self):
    for idx, line in enumerate(open(self.log_file, 'r', encoding='ANSI')):
        if f'<{self.xml_tag}>' in line:
            return idx

def get_xml_data(self):
    xml_data = ''
    for li in self.generate_lines():
        xml_data += li
    return xml_data

My solution works fine but I was wondering if having multiple conditions inside a generator methods is correct, or should I just write a simple one
like lines = (line for line in open(self.log_file) and that have a method that iterates over this generated lines with multiple conditions.
What will be more clean, pythonic way.


text:
Q: How to improve search speed in elasticsearch (my main query: term query and phrase query)? I have about 165G data and I stored it into three elasticsearch servers(each server has 32G memory). The total size of the resulting index(named my_index) is 240.3GB (198030346 docs) with about 75GB used for indexes. The index my_index has three primary shards and no replica shards.
The index my_index has two fields(names field1 and field2) with a same analyzer. The analyzer split content of field1 and field2 by space. A document looks like
{
  "field1": "AW110 AW111 AW112 AW113 AW1104 AW1103 AW11023 AW11012 AW1101 AW1102 AW1102 AW1101 AW11032 AW110 AW11032 AW11032",
  "field2": "BP111 BP111 BP111 BP111 BP111 BP1110 BP111s BP111s BP111a BP111as BP1117 BP1119 BP11100 BP11100 BP11100 BP11111 BP111009 BP11122"
}

My main query is term query and phrase query. For example, I want to search for all documents containing the term AW111 or search for all documents containing the phrase AW110 AW111.
I have tried to improve search speed:

*

*I configured swapping.

*

*vm.swappiness is set to 1.

*make the user hjs who install elasticsearch can raise the locked memory size without limit.

hjs soft memlock unlimited
hjs hard memlock unlimited

- Enable `bootstrap.memory_lockedit` (set `bootstrap.memory_lock: true` in elasticsearch.yml)

Other configuration

*

*File Descriptors(/etc/security/limits.conf)

hjs soft nofile 65536
hjs hard nofile 65536

*

*JVM(config/jvm.options )

-Xms5g
-Xmx5g

*

*Virtual memoryedit(/etc/sysctl.conf)

vm.max_map_count=655360

This is a picture show the result of the command top when I running multiple term search. The process 31283 is elasticsearch.

The picture is used to show the cluster status:

My question:
When I execute term query to search for documents that contain a specific terms, probably a large number of documents match the term. So when I search for a lot of terms(usually 10,000-40,000 and I used multi search + term query), it needs to cost too much time
is there any respect to improve search speed?


text:
Q: Supporting dark mode for MFC dialog application (DwmSetWindowAttribute) I might be going about this all wrong, but I stumbled on this article:
Support Dark and Light themes in Win32 apps
I followed the steps:
1/
#include <dwmapi.h>

2/
#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE
#define DWMWA_USE_IMMERSIVE_DARK_MODE 20
#endif

3/
Call in InitInstance:
BOOL value = TRUE;
::DwmSetWindowAttribute(m_pMainWnd->GetSafeHwnd(),
                        DWMWA_USE_IMMERSIVE_DARK_MODE,
                        &value, sizeof(value));

As you can see, I am using a CDialog based application.
4/ I added Dwmapi.lib.
It compiles fine. But when I run my application the title bar is not dark. Why?
A related question is that in the article it states:

This article provides examples of ways to detect system theme changes, and request a light or dark title bar for your Win32 application's window. It does not cover specifics of how to repaint and render your app UI using a Dark mode color set.

So how do we go about this for an MFC Dialog application?
Note that my Windows 11 PC is running in Dark Mode.

A: In theory, it is achievable for common controls such as dialog boxes.
It will use the themes file.

[Visual Styles] Section shows a VisualStyles section for a High Contrast Black theme.
This thread has implemented it. It may help.


text:
Q: Sharing pre-release NuGet packages Given the following set-up:
SolutionA
 |_ LibA -> Creates LibA.*.nupkg

SolutionB:
 |_ LibB -> Creates LibB.*.nupkg. Depends on LibA.*.nupkg

What is the simplest way to share development versions between the projects i.e. I update LibA creating LibA.1.0.0-beta.nupkg and then consume it in LibB?

*

*Several devleopers should be able to make changes to LibA simultaneously and work with their modified copies.  They should not be picking up other changes.

A: A possible solution I'm considering is as follows:

*

*Add a local directory as a NuGet feed

*Add a post build step that packages the library and adds it to the local directory feed

Then it should just be a case of taking pre-release package dependencies and updating as required.


text:
Q: Encode french characters using UTF-8 When I submit a jsp page and the request goes to a portlet controller, I want the french characters on the jsp page to be encoded always using UTF-8 in the portlet controller.
What is the code syntax that I need to use in jsp or portlet controller to ensure this?

A: For me works
  <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

in the top of the JSP


text:
Q: Implementing vertical movement controlls if ( upDownMovement == true) {
                        SELECTED.position.y = mouse.y * scale;
                              }

This is my naive way of implementing a vertical movement control ( as in directly up and down in the Y only). There is a critical problem with it, however. Because initial mouse position is discontinuous with the models original position, there is always a "jump" at the beginning of the movement.
What is the proper way to implement this control? (If there is a library that does this well, I would love to see it.)
I am thinking something like SELECTED.position.y = SELECTED.position.y + mouse.y * scale; but I could vary well be wrong.

A: As I understand it, you should get the initial mouse position (when upDownMovement become true) and use it as a reference. Something like
if (upDownMovement == true) {
  mouse_y_reference = mouse_y_reference || mouse.y;
  SELECTED.position.y += (mouse.y - mouse_y_reference) * scale;
} else {
  mouse_y_reference = null;
}

If you want something smoother, you may use an animation library such as tween.js, to do something like
mouse_y_reference = mouse_y_reference || mouse.y; // must be declared in a higher scope
var toY = SELECTED.position.y + (mouse.y - mouse_y_reference) * scale;
new TWEEN.Tween(SELECTED.position)
  .to({ y: toY }, 100) // adjust the duration here
  .easing( TWEEN.Easing.Elastic.InOut )
  .onComplete(function() {
    mouse_y_reference = null;
  })
  .start();


text:
Q: DROP TABLE IF EXISTS hangs on Waiting for table metadata lock I'm using a dockerized MySQL 5.7.13 as part of an integration test of an application. The way the system works is as follows:

*

*I start up the main application. It opens up a connection to MySQL, but does not perform any queries.

*I start the integration test setup and drop the old table if it was left behind by the previous run:
DROP TABLE IF EXISTS unit_device

*I then go on and create the table like this:
CREATE TABLE IF NOT EXISTS unit_device (
    id CHAR(36) NOT NULL,
    unit_id CHAR(36),
    device_id CHAR(36),
    deleted_at DATETIME,
    PRIMARY KEY (id)
)

*I then insert some values into the table and trigger work in the main application which makes one SELECT:
SELECT unit_id, device_id FROM unit_device WHERE deleted_at IS NULL

*Then I drop the table:
DROP TABLE IF EXISTS unit_device
However, when I try to run this query, it hangs seemingly forever for some reason. If I close the connection from the main application, the query resumes. One thing that seems suspicious is that once the main application has made its select once, I can see the following information in the output of show engine innodb status: 1 read views open inside InnoDB
I must be doing something seriously wrong here, but after hours of research I was still unable to figure out what's causing the hang, or whether the problem is in the test or the main application.

A: I was able to figure it out. I was using the aiomysql library for Python and it turns out that it somehow bypasses the autocommit setting in the database and requires commits by default. However, this somehow applies to SELECT statements as well, but does not work even when called explicitly. I fixed it by adding autocommit=True to the code which creates the pool, as suggested by this note in Github.


text:
Q: Clearing the JavaScript/jQuery Event Queue
We found, during a recent upgrade to Google Chrome (version 55+) where pointer events were introduced  "with a newer standard that unifies both models: pointer events.", we need to modify how we handle events to be backwards compatible. Our application is written specifically for Chrome.
We have been experimenting this morning, trying figure out which event has been fired (based on Chrome version) so we can handle the event appropriately for all of our application's users. As a test I wrote the following:
$(document).on('mousedown touchstart pointerdown', '.foo', function(event){
    console.log( event.type + ": " +  event.which );
    switch(event.type) {
        case 'mousedown':
          console.log('moused!');
          break;
        case 'touchstart':
          console.log('touched!');
          break;
        case 'pointerdown':
          console.log('pointed');
          break;
    };
})

In non-mobile devices both mousedown and pointerdown are registered. In mobile devices all three events are spit out to the console.
CLARIFICATION: What is needed is for none of the other events to fire once the first one is encountered and handled. In other words, if pointerdown fires, for example, then I need to prevent mousedown and touchstart from firing. Subsequent clicks should work as well, so if I get a pointerdown and click again I should get another pointerdown (or whatever event is appropriate for the browser version or device).
I expected break; would cause jQuery to leave the switch(), but that doesn't happen. So I added the .clearQueue() to each case:
$(this).clearQueue();

Once again, I expected that the event would be encountered and handled, the queue would be cleared and I wouldn't have any other events fired.
I was wrong.
I am beginning to feel like I am missing something obvious but I cannot put my finger on it. I have tried .stop(), .finish() as well as combinations of these functions in order to intercept the one function needed (based on browser version) and clear the queue so the rest will not fire.
I thought I understood the JavaScript event queue pretty well, but apparently I am wrong about that too.
Am I missing something obvious? If so, what it is?

A: I believe that .stop() and .finish() are related to working with an animation queue, not an event queue and .clearQueue() is not related to the event queue either:
The JQuery documentation says:

When used without an argument, .clearQueue() removes the remaining
  functions from fx, the standard effects queue. In this way it is
  similar to .stop(true). However, while the .stop() method is meant to
  be used only with animations,  .clearQueue() can also be used to
  remove any function that has been added to a generic jQuery queue with
  the .queue() method.

But, if you have handled an event and wish to stop others from being raised, you could implement your own handled flag in a closure as a work-around:
Here's an example (executable version here):
// These free variables will be shared in the various callback functions below
var handled = false;
var eventType = null;

$(document).on('mousedown touchstart pointerdown', '.foo', function(event){

   // If the current event hasn't been handled or if the current
   // has been handled but the event is the same as the previous fired
   // event, proceed:
   if(!handled || (handled && event.type === eventType)){

     // None of the events have been handled yet.
     // Determine which has fired and act appropriately:

     // Register the current event for comparison later
     eventType = event.type;

     console.log( eventType + ": " +  event.which );

     switch(eventType) {
        case 'mousedown':
          console.log('moused!');
          break;
        case 'touchstart':
          console.log('touched!');
          break;
        case 'pointerdown':
          console.log('pointed');
          break;
     };

     // Flag that one of the events registered earlier has been handled
     handled = true;

   } else {

     // One of the earlier registered events has already been handled

     // Prevent the event from performing its native function
     // (i.e. cancel the event)
     event.preventDefault();

     // Don't allow the event to propagate
     event.stopPropagation();

   }

});

A: You could just return false at the end, and only the first type supported (and first fired) will be caught by any system.
The break works just fine but it  does not affect this issue as these are different events and so fire the handler as many times as the events triggered.

$(document).on('mousedown touchstart pointerdown', '.foo', function(event){
    console.log( event.type + ": " +  event.which );
    switch(event.type) {
        case 'mousedown':
          console.log('moused!');
          break;
        case 'touchstart':
          console.log('touched!');
          break;
        case 'pointerdown':
          console.log('pointed');
          break;
    };
    // added the following line which forces any subsequent events for the same action and also stop the event from bubbling up the dom
    return false;
})
.foo{
  padding:50px;
  margin:10px;
  border:5px double #ccc;
  text-align:center;
}

.foo box for clicking


text:
Q: AWS ubuntu SSL installed but not loading https or http I've followed exactly this youtube video tutorial to install SSL at my AWS Ubuntu Apache2 server. Youtube URL: https://www.youtube.com/watch?v=m06TttS2ZAM
Ubuntu version:  Ubuntu 16.04.5 LTS
Apache version:  Apache/2.4.18 (Ubuntu)
My domain name: pilefo.com
Here is the sites-enabled: 000-default.conf details:
<VirtualHost *:443>
         ServerAdmin admin@pilefo.com
         DocumentRoot /var/www/html
         ServerName pilefo.com
         ServerAlias www.pilefo.com
         SSLEngine on
         SSLCertificateFile /etc/ssl/certs/pilefo_com.crt
         SSLCertificateKeyFile /etc/ssl/certs/pilefo.com.key
         SSLCertificateChainFile /etc/ssl/certs/pilefo_com.ca-bundle
          <Directory /var/www/html>
                Options FollowSymLinks
                AllowOverride All
        </Directory>
</VirtualHost>

#Redirect all http traffic to https

<VirtualHost *:80>
      ServerName pilefo.com
      ServerAlias www.pilefo.com
      Redirect permanent / https://www.pilefo.com
</VirtualHost>

/etc/apache2/apache2.conf file details
link: https://textuploader.com/1avcv
Apache error log
https://textuploader.com/1avcn
https://textuploader.com/1avcn
Thanks in advance.


text:
Q: set focus on contenteditable div with jquery Could you help me understand why the div that is retrieving the focus put the cursor on first char on Firefox and IE 10 (but not on chrome)?
Here is the javascript code:
$('div').on('click', function(e) {
    $(this).html($(this).text());
});

Here is the jsfiddle with the whole context.
[EDIT] Could someone tell me why the cursor is going to the beginning of the sentence?

A: Behavior Difference:
That's because Chrome does not think that the content is changed when you pass the same/exact content but FF/IE do not care whether the content is the same or not; if anything is passed, they think it's modified. Different browser engines do not always act the same way.
$('div').on('click', function(e) {
    $(this).html($(this).text()); // here you pass the same (previous) content
});

To see if the browser (Chrome or FF) interprets this as "content changed"; you can listen to the DOMSubtreeModified event. This will not fire on Chrome but it will fire on FF.
$('div').on('DOMSubtreeModified', function(e) {
    console.log('content changed');
});

Now, if you "really" change the content by passing a "new" value; Chrome will act the same as FF too. For example, try this:
$('div').on('click', function(e) {
    $(this).html($(this).text() + "new content"); // passing different content each time
});

Now, you'll see that the DOMSubtreeModified event is fired.
Why the cursor moves to the beginning:
That's because; when the user clicks the div, he/she actually sets the cursor to some position/index. Then you immediately change the full content; so the position/index is no more available while the content is being replaced. The only valid position is 0 (the beginning index) at that time.
This does not happen in Chrome if the same content is passed bec. (as mentioned before); Chrome does not replace the content if it's the same as the previous content. So the cursor index is never changed. But if you do pass a different content; it will also move the cursor to the beginning.

Here is the fiddle for the DOMSubtreeModified test.

A: The issue is that IE and Firefox have a different implementation of contentEditable.
This means that, when clicked, they select the first element within the editable area.
You can get around this issue by using some code like the following:
var char = 3, sel; // character at which to place caret
content.focus();
if (document.selection) {
  sel = document.selection.createRange();
  sel.moveStart('character', char);
  sel.select();
}
else {
   sel = window.getSelection();
  sel.collapse(content.firstChild, char);
}

However, what I'd recommend is using something like TinyMCE or CKEditor or a JQuery/JQueryUI editor to get the desired effect.
Plus, you get the nice formatting tools too!


text:
Q: Cobol recursive paragraph I am currently learning Cobol language, and I wrote a paragraph with the following structure :
MYPARA.
    EVALUATE TRUE
       WHEN COND1
          ...
       WHEN COND2
          ...
          PERFORM MYPARA
       WHEN OTHER
          ...
    END-EVALUATE
    .

This is a recursion that works great, however I just learned that it must not be done because it can lead to unpredictable results ( In COBOL, is it possible to recursively call a paragraph? ). So is it impossible to have recursion within the same Cobol program ?
I thought about using an intermediary paragraph : MYPARA execute MYPARA2 and MYPARA2 execute MYPARA. Is it exactly the same or different for the compiler/execution ?
The execution works great, but it is clearly stated that a paragraph can't call itself. Any form of recursion between paragraph is possible or forbidden ?
In my case I could wrap the EVALUATE in a PERFORM UNTIL as an alternative to the recursion, but I really wanted to do it that way.

A: Recursion works for most languages and COBOL programs because the return location is pushed onto a stack before the call. When the program executes itself, a new return location is pushed. As each invocation of the program returns, the locations stored on the stack are popped off one-by-one, allowing the return instruction to resume execution at the right places.
For IBM COBOL, the Perform statement does not use a stack. Instead, each performed paragraph has a "resume" address for the end of the paragraph. Normally, this resume address points to the next paragraph. Each Perform statement has a "save" cell to save the target paragraph's resume address. When the perform happens, it copies the resume cell to the save cell, stores the address after the perform statement in the resume cell, then jumps to the paragraph. The end of the paragraph picks up the address in the resume cell and jumps to it, effectively returning to the address after the perform. The instructions there copies the save cell back to the resume cell, restoring the paragraph to the way it was.
This all works great until you realize that the "save" cell is a stack with the capacity of only one entry. This means if the same save cell is used again before a restore happens, the old value is wiped out. The resume cell will never have its old content back. The paragraph will not be able to return to where it supposed to return. The problem may not show up if overwriting does not occur because each perform statement has its own "save" cell. Thus, if we use "->" to represent "performs" and A & B are paragraphs, A->B->B works, but A->B->B->B will get you into an infinite loop when the outermost B is trying to return to A.


text:
Q: Is it possible to create a laser pointer with adjustable beam width? Is it possible to create a (line) laser pointer with adjustable beam width?
I mean instead of having a dot laser pointer, create one where one may press a button to switch from 10m line beam to 5 m line beam to 2.5m line beam .... smaller lengthed beam and so on until it becomes dot-like.
This has uses in doing presentations on a wireless presenter where I want the reader to focus on a line of text rather than only a single thing one points.

A: This could be done, but is a little complicated to do well, or economically.
The simplest was would for the button press to move a cylindrical lens into the beam, this will give you a line instead of a spot. The problem is that the length of the line will depend on how far away you stand from the screen, and if you want to limit the length of the line you might have to also adjust an aperture that would help provide that limit. That is the cheap solution.
More expensive you could have different line generator optics with different angular spread. You would still have the problem of the line being longer the farther away you are from the screen, but you could then switch between different lengths by switching different optics into position.
More complicated you could put a scanner in the laser pointer, that would rotate, or wiggle back and forth mechanically to move the spot in a line. This is hard to make small and depending on what you want to do a little complicated electronically.
There are lots of holographic optics that can be designed to produce different patterns, lines, circles, images etc that are pretty compact, but most will also have a lot of other little dots that may or may not be seen depending on how bright the presentation room is.


text:
Q: Почему в jQuery при добавлении в массив выходит ошибка? Пытаюсь реализовать REST приложение, получаю json пакет и вывожу его в таблицу, но если при этом добавлять данные в массив выходит куча ошибок, просьба сказать что я делаю не так?
Код:
var lebelCh = new Array();
var dataCh = new Array();

function showAllElem(arrElem){
$('table').remove();
$('#getChart').remove();
var tbl = "
";
tbl += "
№ п/п	Имя	Атрибут

    $.each(arrElem, function(i, el) {
        tbl += '
' + i + '	' + el.name + '	' + el.index + '
';
          lebelCh.push(el.name);//тут выходит ошибка
          dataCh.push(el.index);//тут выходит ошибка
    });

tbl += "
";
$(tbl).addClass('mytable').appendTo('#reportBlock');
$('#getBtn').after('<button id="getChart">Показать график</button>');
}

Ошибка
Uncaught ReferenceError: lebelCh is not defined
at Object.<anonymous> (main.js:88)
at Function.each (jquery-3.3.1.min.js:2)
at showAllElem (main.js:86)
at Object.success (main.js:33)
at u (jquery-3.3.1.min.js:2)
at Object.fireWith [as resolveWith] (jquery-3.3.1.min.js:2)
at k (jquery-3.3.1.min.js:2)
at XMLHttpRequest.<anonymous> (jquery-3.3.1.min.js:2)


text:
Q: journalctl prints the entire system log when following [root@utility ~]# uname -rv
2.6.32-042stab093.5 #1 SMP Wed Sep 10 17:39:49 MSK 2014

[root@utility ~]# cat /etc/redhat-release
CentOS Linux release 7.1.1503 (Core)

[root@utility ~]# journalctl --version
systemd 208
+PAM +LIBWRAP +AUDIT +SELINUX +IMA +SYSVINIT +LIBCRYPTSETUP +GCRYPT +ACL +XZ

I'm having a rather odd issue when walking my syslogs through journalctl. In context, I'm trying to actively follow the entire system log to try and troubleshoot an issue with OpenDKIM but I'm making progress in that area.
Essentially, when I run journalctl -f I am presented with the last few lines of the log and the terminal waits for more data to be logged and processed. With this process open in one SSH session, I send a test message from a different session on the same server (both under the root user).
Once I execute the test message, the program dumps content into the system log. I briefly see the content dumped before the journalctl process circles back around and writes out the entire system log to the console from as far back as the logs go all the way to what was just written to the log. Needless to say, this isn't very helpful when you have to wait for months worth of syslogs to be pushed through your SSH session before you can see what the test program wrote to the log.
Anyone have any ideas as to why this is occurring? I'm embarrassed to say I don't even know where to start, but my Google-Fu has revealed no other instances of such an issue.

Hell, maybe my luck with search engines has finally come to a bitter end...

TL;DR: journalctl -f reads out the entire system log rather than just tailing it.


text:
Q: How to create array with variable number of items, then increment some of those items I'm building a javascript widget to help knitters determine the number of stitches to place between increases when faced with a pattern instruction that reads "Increase X number of stitches evenly across a row." The problem is described here.
So far my code works as long as the result is an even number.
I am stuck trying to figure out how to make it work if the number isn't even. I think what I need to do is populate an array with the number of groups of stitches, then increment through the array, adding 1 to each group until there is no leftover.
But I can't figure out how to
a) Populate an array with a variable number of items--e.g.: How many groups of stitches are there? I need that number of items in the array.
b) Store the number of stitches in each group in each item in the array
c) Add 1 to each item in the array until the leftover is 0.
I'm open to other approaches, too.
Here's the code I have thus far. I haven't added the if/else conditional yet, nor have I added the for loop. Any thoughts or ideas will be very much appreciated. Thanks in advance!
$('#calculateIncrease').submit(function() {
//get the number of stitches in the row
var stitchesInRow = $('input#stitchesInRow').val();
//get the number of stitches to increase by
var increaseByHowMany = $('input#increaseByHowMany').val();
//add one to this number
var divideBy = parseInt(increaseByHowMany,10) + 1;
//divide the number of stitches in row by increase plus one
var stitchesBetween = parseInt(stitchesInRow,10)/divideBy;
var leftover = stitchesInRow % divideBy;
//if there is no leftover
//return the result
$('#howManyStitches').html("Put " + stitchesBetween + " stitches between each increase.");
//if there is a leftover
var stitchesPerGroup = Math.floor(stitchesBetween);
//take divideBy, which is also the number of groups of stitches
//create an array that contains the number of groups (divideBy)
var stitchesArray = new Array(divideBy);
//each array item populated by the integer that is the first half of the division
//for each array item, add 1 until leftover = 0
//there should be some groups that get one added and others that do not
return false;
});

A: This is not an answer to the question as it is currently formulated (akonsu already answered the question's title in his comment) and also does not talk directly about that question.
However since I understand what she is trying to accomplish (and she's open to other approaches), I think that this is essentially a really good question,
so I'm posting this to aid other people in understanding what she really wants to accomplish with the code she posted and to help her define in more detail what the algorithm variation and end-result/output could/should be.
She wants to evenly distribute x number (of extra stitches per row) as evenly as possible over y number (of stitches that where on the previous row).

Her current base formula is: y/(x+1)
including rounding that would result in:

----------      10 stitches
-----+-----     add 1, every 5
---+----+---    add 2, every 3.3333
---+--+---+--   add 3, every 2.5
--+--+--+--+--  add 4, every 2
--+-+--+--+-+-- add 5, every 1.6667

A working example (in jsFiddle) could look like:
Javascript:
function handler(){
  var i, d=document,                                    //saving some code
      base=Number(d.getElementById('base').value),      //get row input
       add=Number(d.getElementById('add').value) + 1,   //get stitches to add
       ret='',          //return var
       tmp=0,           //temp var
       crr=0,           //carry var
       per=base/add;    //calculate period

  for (i = 1; i < add; i++) {   //start at 1 instead of 0
    tmp=Math.round(i * per);    //round first period
    ret+=tmp-crr+' + ';         //first period with previous period
    crr=tmp;                    //carry period
  }
  ret+=Math.round(add * per)-crr;          //last normal stitches
  d.getElementById('out').innerHTML=ret;   //output result
}

HTML:
Stitches on row: <input type="text"
                          id="base"
                       value="10"
                    onchange="handler();"
                 >

Stitches to add: <input type="text"
                          id="add"
                       value="1"
                    onchange="handler();"
                 >

<button onclick="handler();">calculate</button>

  Every + is a extra stitch:

I think that would work as she currently expects it to.
However, I think one could then find a pattern in that, and I have no idea how to do that in a simple way. Anyone?
But I think this would only work for something that only goes from left to right, and not in a circle like a sleeve of a sweater. Then she might need something that looks a little more like a 'carousel':
'Carousel' style (formula: ((y+x)/x)-1):

----------      10 stitches
----------+     add 1, every 10
-----+-----+    add 2, every 5
---+----+---+   add 3, every 3.3333
--+---+--+---+  add 4, every 3.5
--+--+--+--+--+ add 5, every 2

As you can see, the distribution is then different.
Good luck with your project!


text:
Q: problems once uploaded to server This all works fine in MAMP but i've uploaded and now the problems start.
heres an image of the code for the link and a grab of the result
First image
Second image
any ideas?

A: You seem to be POSTing to a static HTML file. Try changing the file extension to php, asp, jsp etc. depending on what you're using on the server-side.
Also, for textual content like this, you could simply copy-paste the text intead of capturing screenshots.

A: Problem solved, it was in the .js file, it was pointing to POST and should have been GET


text:
Q: How to find pair relationships between rows in a very large table I have a very large table (60m rows) that contains rows with two columns: a set_id and an object_id. The set_id is used to identify groups of object_ids. In my case, those object_ids can appear in multiple sets.
example:
set_id | object_id
1 | 100
1 | 101
1 | 102
2 | 100
2 | 201
3 | 300
4 | 102
4 | 300
5 | 500

What I need is to retrieve a list of pairs of set_ids that share at least one object_id in common. Each set_id would also be paired with itself. Pairs only show up once (ie: (1,2), but not (2,1)). For the example above:
set_id_A | set_id_B
1 | 1
1 | 2
1 | 4
2 | 2
3 | 3
3 | 4
4 | 4
5 | 5

It's fairly simple to write a query to make this happen. The issue is that my solution doesn't scale well. Here is my code:
-- #original_sets table created

CREATE TABLE #original_sets
    (
        [set_id] INT,
        [object_id]       BIGINT
    );

-- #original_sets populated here from other data
-- removed

-- index created on table:

CREATE CLUSTERED INDEX cx_original_sets
    ON #original_sets ([object_id], [set_id]);

-- code to create the pairs:

            SELECT
                    ck1.[set_id] AS set_id_A,
                    ck2.[set_id] AS set_id_B
            FROM
                    #original_sets ck1
                INNER JOIN
                    #original_sets ck2
                        ON ck1.[object_id] = ck2.[object_id]
                           AND ck1.[set_id] <= ck2.[set_id]
            GROUP BY
                    ck1.[set_id],
                    ck2.[set_id];

It's super fast if the original_sets table is small or even medium size, but once I get to 60m rows, it's really slow. I end up canceling it after 10 hours, so I'm not sure if it would ever finish.
A self join on such a large table is just looking for trouble I know. Is there another method to do this that scales better? Thanks!
Edit 1:
Another thing that might help to improve performance: After I get the set pairs I have another process that that then creates super sets that contain all object ids that are related by the original sets (see: transitive closure clustering  http://sqlblog.com/blogs/davide_mauri/archive/2017/11/12/lateral-thinking-transitive-closure-clustering-with-sql-server-uda-and-json.aspx The diagram at the top shows it nicely)
Because I'm doing that after this, I don't really care about the set_ids themselves, only how they group together the object_ids. So duplicate sets could be eliminated safely. Perhaps doing that first would be a good way to reduce the overall size of the table.
Edit 2:
New version to try and reduce the size of original table
-- #original_sets table created

CREATE TABLE #original_sets
    (
        [set_id] INT,
        [object_id]       BIGINT
    );

-- #original_sets populated here from other data
-- removed

-- index created on table:

CREATE CLUSTERED INDEX cx_original_sets
    ON #original_sets ([object_id], [set_id]);

--added this index:
CREATE CLUSTERED INDEX IDX_original_sets
    ON #original_sets ([set_id], [object_id]);

-- added this part to identify sets with only one object_id
CREATE TABLE #lonely_sets
(
    [set_id] INT PRIMARY KEY
);

INSERT INTO #lonely_sets
SELECT
        [set_id]
    FROM
        #original_sets
    GROUP BY
        [set_id]
    HAVING
        COUNT(*) = 1

--then use that data to eliminate duplicate single object sets (see edit 1 for why)

DELETE FROM #original_sets
WHERE set_id IN
(

SELECT
   [set_id ]
FROM
   #lonely_sets lonely_sets
WHERE
   [set_id ] NOT IN
   (
   SELECT
      MIN(original_sets.[set_id ])
   FROM
      #original_sets original_sets
      INNER join #lonely_sets lonely_sets
        ON original_sets.set_id  =  lonely_sets.set_id
   GROUP BY
      original_sets.[object_id]
   )

)

-- then run this
-- code to create the pairs as before:

            SELECT
                    ck1.[set_id] AS set_id_A,
                    ck2.[set_id] AS set_id_B
            FROM
                    #original_sets ck1
                INNER JOIN
                    #original_sets ck2
                        ON ck1.[object_id] = ck2.[object_id]
                           AND ck1.[set_id] <= ck2.[set_id]
            GROUP BY
                    ck1.[set_id],
                    ck2.[set_id];

The extra work reduces the original_set down to ~16m rows.
With ~1m unique object_ids and ~7m unique set_ids.
Here is the breakdown of the objects per set:
object_count_per_set | sets_with_that_count
67  32
49  8
42  197
41  120
38  1
37  101
35  16
30  23
29  18
28  109
27  1643
26  382
25  43
24  35
23  8
22  492
21  703
20  339
19  1548
18  2176
17  358
16  1156
15  852
14  1755
13  1845
12  2452
11  3073
10  4570
9   4723
8   9726
7   16178
6   35493
5   81091
4   211305
3   724627
2   5360781
1   789573

So overall a much smaller table to deal with, but it took just over an hour to finish (1,035,212,815 rows affected), it's still slow to run.
I know there is a lot of duplicate sets that can be safely eliminated, I just need a good method to do so.

A: You say you have 60m rows in the table and about 50m unique set_ids and 100k unique object_ids.
So on average each object_id has 600 rows. And on average the ck1.[object_id] = ck2.[object_id] AND ck1.[set_id] <= ck2.[set_id] will match 300 rows for each outer row so currently your query is producing and aggregating something in the order of 18 billion rows
The 50 million set ids and 60 million rows means that most sets will only be paired with themselves,
As a first go at this I'd be minded to just find these guaranteed unpaired sets with a simple GROUP BY ... COUNT and then exclude them from consideration in the more expensive part with the triangular self join.
If this query is still too slow please provide information about the characteristics of #paired_sets in terms of numbers of rows and number of distinct object_id and set_id as well as size of the largest object_id in there (number of rows)
CREATE TABLE #lonely_sets
    (
        [set_id] INT PRIMARY KEY
    );

INSERT INTO #lonely_sets
SELECT  [set_id]
FROM #original_sets
GROUP BY [set_id]
HAVING COUNT(*) = 1;

CREATE TABLE #paired_sets
(
    [set_id] INT,
    [object_id] INT,
    PRIMARY KEY  ([object_id], [set_id])
);

INSERT INTO #paired_sets
SELECT [set_id], [object_id]
FROM #original_sets
WHERE [set_id] NOT IN (SELECT ls.set_id FROM #lonely_sets ls);

--Final Select
SELECT [set_id] AS set_id_A, [set_id] AS set_id_B
FROM #lonely_sets
UNION ALL
SELECT
        ck1.[set_id] AS set_id_A,
        ck2.[set_id] AS set_id_B
FROM
        #paired_sets ck1
    INNER JOIN
        #paired_sets ck2
            ON ck1.[object_id] = ck2.[object_id]
                AND ck1.[set_id] <= ck2.[set_id]
GROUP BY
        ck1.[set_id],
        ck2.[set_id];

A: So based on suggestions from Martin, I was pointed in the direction of reducing the size of the table being joined, and here is where I ended up:
I decided to attempt to eliminate duplicate sets (see Edit 1 in my original post above).
This should do two things in my case : bring down the size of the table running the self join on later, and help with scaling over time (new sets are introduced weekly, but they are often duplicates of previous sets).
I used the old XML PATH row concatenation trick (I'm not running 2017, otherwise STRING_AGG might work faster?) to create a semi-colon separated list of all object_ids in each set_id.
This is then used to identify set_ids that contain identical sets of object_ids and can therefore be safely eliminated. This reduced the amount of rows from 60m to 1m. This takes about a 50 minutes in my case. Is there a faster way to identify identical sets? I'm not sure.
A filtered table of sets is then created and the relationship table is created based on self joining that. With the new filtered data, the time to run that part of the query is now only a few minutes.
The slowest part of the process is the XML PATH row concat query at just under an hour. That is not ideal, but because this process is part of an emergency maintenance routine, I'm willing to accept the time it takes to run.
Code :
-- #original_sets table created

CREATE TABLE #original_sets
    (
        [set_id] INT,
        [object_id]       BIGINT
    );

-- #original_sets populated here from other data
-- removed

-- index created on table:

CREATE CLUSTERED INDEX cx_original_sets
    ON #original_sets ([object_id], [set_id]);

CREATE CLUSTERED INDEX IDX_original_sets
    ON #original_sets ([set_id], [object_id]);

----------------------------------------------------------

CREATE TABLE #filtered_sets
    (
        [set_id] INT,
        [object_id]       BIGINT
    );

    INSERT INTO #filtered_sets
    SELECT
         original_sets.set_id,
         original_sets.[object_id]
    FROM
        #original_sets original_sets
        INNER JOIN
        (
            SELECT
                MIN(set_id) AS set_id
            FROM
            (
                    SELECT DISTINCT
                            set_id,
                            STUFF(
                                (
                                    SELECT
                                        '; ' +  CAST(original_sets.object_id AS VARCHAR(20))
                                    FROM
                                        #original_sets original_sets
                                    WHERE
                                        original_sets.set_id = s2.set_id
                                    ORDER BY
                                        original_sets.object_id
                                    FOR XML PATH('')
                                ), 1, 2, ''
                                )                                            AS object_id_list

                    FROM
                            #original_sets s2

                    GROUP BY
                            set_id
            ) a

            GROUP BY
            object_id_list
        ) unique_sets
            ON original_clusters.cluster_id = unique_sets.cluster_id

CREATE CLUSTERED INDEX cx_filtered_sets
    ON #filtered_sets ([object_id], [set_id]);

CREATE NONCLUSTERED INDEX IDX_filtered_sets
    ON #filtered_sets ([set_id],[object_id]);

----------------------------------------------------------
-- then run this
-- code to create the pairs as before:

            SELECT
                    ck1.[set_id] AS set_id_A,
                    ck2.[set_id] AS set_id_B
            FROM
                    #filtered_sets ck1
                INNER JOIN
                    #filtered_sets  ck2
                        ON ck1.[object_id] = ck2.[object_id]
                           AND ck1.[set_id] <= ck2.[set_id]
            GROUP BY
                    ck1.[set_id],
                    ck2.[set_id];

I accepted Martin's answer because it was useful in pointing me where I needed to go. Thanks!


text:
Q: SimpleaudioError: Error opening PCM device I want to use python to play certain muscial notes depending on some results I obteined erlier in my code.
I'm using pydub and I downloaded some .wav sounds in my google colab document. However, I have an error that I can't quit figure out. Here's my code
from pydub import AudioSegment
from pydub.playback import play

note_do = AudioSegment.from_wav(r"/95328__ramas26__c.wav")
note_re = AudioSegment.from_wav(r"/95329__ramas26__d.wav")
note_mi = AudioSegment.from_wav(r"/95330__ramas26__e.wav")
note_fa = AudioSegment.from_wav(r"/95331__ramas26__f.wav")
note_sol = AudioSegment.from_wav(r"/95332__ramas26__g.wav")
note_la = AudioSegment.from_wav(r"/68437__pinkyfinger__piano-a.wav")
note_si = AudioSegment.from_wav(r"/95327__ramas26__b.wav")

for i in range(len(notes_fin)):
  if notes_fin[i]==0:
    play(note_do)
  if notes_fin[i]==1:
    play(note_re)
  if notes_fin[i]==2:
    play(note_mi)
  if notes_fin[i]==3:
    play(note_fa)
  if notes_fin[i]==4:
    play(note_sol)
  if notes_fin[i]==5:
    play(note_la)
  if notes_fin[i]==6:
    play(note_si)

The if statement are based on things I had earlyer in the code. Here's the error I have :
SimpleaudioError                          Traceback (most recent call last)
<ipython-input-39-4842dad5bfc2> in <module>()
     12 for i in range(len(notes_fin)):
     13   if notes_fin[i]==0:
---> 14     play(note_do)
     15   if notes_fin[i]==1:
     16     play(note_re)

2 frames
/usr/local/lib/python3.6/dist-packages/simpleaudio/shiny.py in play_buffer(audio_data, num_channels, bytes_per_sample, sample_rate)
     59 def play_buffer(audio_data, num_channels, bytes_per_sample, sample_rate):
     60     play_id = _sa._play_buffer(audio_data, num_channels, bytes_per_sample,
---> 61                                sample_rate)
     62     return PlayObject(play_id)

SimpleaudioError: Error opening PCM device. -- CODE: -2 -- MSG: No such file or directory

Thank you! :)


text:
Q: iOS: Timer animation on separate thread I have a simple animation to make a label look like its counting upwards, which I put in a timer.
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.01f target:self selector:@selector(animateScore:) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

The animate score selector increments the labels text until it gets to the desired integer then invalidates the timer.
Right now, it stalls while other UI stuff is going such as reloading table view sections.
I tried running this code, but it didn't work:
   dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

     NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.01f target:weakSelf selector:@selector(animateScore:) userInfo:nil repeats:YES];

      [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
     });

A: The preferred way to do this is using a special timer class CADisplayLink, which fires every time the device's screen is updated. Something like:
@property (nonatomic, strong) CADisplayLink *displayLink;

-(void)viewDidLoad {
    // …
    self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(displayLinkDidFire:)];
    [self.displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
    // …
}

-(void)displayLinkDidFire:(CADisplayLink *)displayLink {
    // Update label text
}

A: scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: already adds the timer to the current run loop (which may not be the main run loop since you execute this on a background queue).
Use timerWithTimeInterval:target:selector:userInfo:repeats: instead. This creates the timer but does not add it to the current run loop.


text:
Q: Issue while running "npx react-native run-android". How to solve it? Created a project using npx react-native init AwesomeProject. While running npx react-native run-android in other terminal, I am getting the following error. I tried to follow React Native CLI Quickstart in https://reactnative.dev/docs/environment-setup. I have installed python2, openjdk8, nodejs separately, later deleted them and reinstalled using chocolatey. I have reinstalled AndroidSDK tools, AVD multiple times still getting the same error.
info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag.
Jetifier found 967 file(s) to forward-jetify. Using 8 workers...
info Starting JS server...
'C:\Users\Raja' is not recognized as an internal or external command,
operable program or batch file.
info Launching emulator...
'C:\Users\Raja' is not recognized as an internal or external command,
operable program or batch file.
'C:\Users\Raja' is not recognized as an internal or external command,
operable program or batch file.

error Failed to launch emulator. Reason: Could not start emulator within 30 seconds..
warn Please launch an emulator manually or connect a device. Otherwise app may fail to launch.
info Installing the app...
Starting a Gradle Daemon (subsequent builds will be faster)

Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.2/userguide/command_line_interface.html#sec:command_line_warnings

FAILURE: Build completed with 2 failures.

1: Task failed with an exception.
-----------
* Where:
Build file 'C:\Users\Raja Naveen\Desktop\AwesomeProject\android\app\build.gradle' line: 84

* What went wrong:
A problem occurred evaluating project ':app'.
> Could not open dsl remapped class cache for 7f1u5qpw1jm8dwv3ri20amyrz (C:\Users\Raja Naveen\.gradle\caches\6.2\scripts-remapped\react_dysq7qqrljy3c2uubmf33rsun\7f1u5qpw1jm8dwv3ri20amyrz\dslcf39471ad2848fb82befe662c0627ed4).
   > 0

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
==============================================================================

2: Task failed with an exception.
-----------
* What went wrong:
A problem occurred configuring project ':app'.
> compileSdkVersion is not specified.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
==============================================================================

* Get more help at https://help.gradle.org

BUILD FAILED in 6m 33s

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup. Run CLI with --verbose flag for more details.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081```

A: Make sure you have added the android SDK paths in the enivironment varailble"
export ANDROID_HOME=$HOME/Android/Sdk
export PATH=$PATH:$ANDROID_HOME/emulator
export PATH=$PATH:$ANDROID_HOME/tools
export PATH=$PATH:$ANDROID_HOME/tools/bin
export PATH=$PATH:$ANDROID_HOME/platform-tools

EDIT:
Make sure you have either a running emulator by creating one in Android studio or connected physical devices with USB debugging turned on.

A: You need to set the ANDROID_HOME & JAVA_HOME in your environments variables if you are in Windows and in either the bashrc or the zshr  if you are using a Mac

JAVA_HOME => C:\Program Files\OpenJDK\openjdk-8u262-b10
ANDROID_HOME => C:\Users\laptopName\AppData\Local\Android\Sdk>

P.S: On Windows just enter env in the search bar and click on the first tab then click on New and add those then you are good to go.

A: I think
 > compileSdkVersion is not specified.

is problem.
Add
 android {
    compileSdkVersion 27
    buildToolsVersion '27.0.3'

in build.gradle


text:
Q: CCS MSP430 Bluetopia Linker I am trying to implement the Bluetopia stack using the MSP430F5635 MCU and the CC256 bluetooth chip using Code Composer v7. When I try to build my project, I am getting the error: "unresolved symbol BSC_Initialize ...". I have the BSCAPI header file included so I can't figure out why it cannot find this function.
Below is the relevant code I am using:
#include "BSCAPI.h"
...
int main(void) {
    ...
    Result = BSC_Initialize(&HCI_DriverInformation, 0);
    ...
}


text:
Q: Custom pooling layer, WARNING:tensorflow:Gradients do not exist for variables Below is the code I am trying to custom the global average pooling code. My goal is to change the line "return np.mean(inputs, axis=(1, 2)" and write my own custom pooling method. However, although the code is working, I'm having problems with gradients and I can't get the same result with the global average pooling method. I am getting the below warning. Can you help me please?
WARNING:tensorflow:Gradients do not exist for variables ['conv2d_2/kernel:0', 'conv2d_2/bias:0', 'conv2d_3/kernel:0', 'conv2d_3/bias:0'] when minimizing the loss. If you're using model.compile(), did you forget to provide a lossargument?
WARNING:tensorflow:Gradients do not exist for variables ['conv2d_2/kernel:0', 'conv2d_2/bias:0', 'conv2d_3/kernel:0', 'conv2d_3/bias:0'] when minimizing the loss. If you're using model.compile(), did you forget to provide a lossargument?
import numpy as np
import tensorflow as tf
import math
import os
import random
import itertools
from tensorflow.python.ops import gen_nn_ops
from tensorflow.python.ops import array_ops
import numba as nb
import matplotlib.pyplot as plt
import skimage

from keras import backend as K
random.seed(91)

class LGPooling2D(tf.keras.layers.Layer):
    def __init__(self, pool_size=(3, 3), strides=(2, 2), padding='SAME', data_format='channels_last', **kwargs):
        super(LGPooling2D, self).__init__(**kwargs)

        self.pool_size = pool_size
        self.strides = strides
        self.padding = padding
        self.data_format = 'NHWC' if data_format == 'channels_last' else 'NCHW'
        self.output_dim = 64

    def build(self, input_shape):
        super(LGPooling2D, self).build(input_shape)

    def _pooling_function(self, x, name=None):
        #b = K.shape(x)[0]
        input_shape = tf.keras.backend.int_shape(x)

        b, r,c,channel = input_shape[0],input_shape[1],input_shape[2],input_shape[3]

        def _mid_pool(inputs, is_train):

            return np.mean(inputs, axis=(1, 2)) # we change this part.

        def custom_grad(op, grad):
            if self.data_format == 'NHWC':
                ksizes = [1, self.pool_size[0], self.pool_size[1], 1]
                strides = [1, self.strides[0], self.strides[1], 1]
            else:
                ksizes = [1, 1, self.pool_size[0], self.pool_size[1]]
                strides = [1, 1, self.strides[0], self.strides[1]]
            return gen_nn_ops.max_pool_grad_v2(
                op.inputs[0],
                op.outputs[0],
                grad,
                ksizes,
                strides,
                self.padding,
                data_format=self.data_format
            ), tf.constant(0.0)

        def py_func(func, inp, Tout, stateful=True, name=None, grad=None, rnd_name=None):
            # Need to generate a unique name to avoid duplicates:
            tf.compat.v1.RegisterGradient(rnd_name)(grad)
            g = tf.compat.v1.get_default_graph()
            with g.gradient_override_map({"PyFunc": rnd_name}):
                return tf.compat.v1.py_func(func, inp, Tout, stateful=stateful, name=name)

        def _mid_range_pool(x, name=None):
            rnd_name = 'LGPooling2D' + str(np.random.randint(0, 1E+8))

            with tf.compat.v1.name_scope(name, "mod", [x]) as name:
                z = py_func(_mid_pool,
                            [x, tf.keras.backend.learning_phase()],
                            [tf.float32],
                            name=name,
                            grad=custom_grad, rnd_name=rnd_name)[0]
                z.set_shape((b, channel))

                return z

        return _mid_range_pool(x, name)

    def compute_output_shape(self, input_shape):
        r, c = input_shape[1], input_shape[2]
        sr, sc = self.strides
        num_r =  math.ceil(r/sr) if self.padding == 'SAME' else r//sr
        num_c = math.ceil(c/sc) if self.padding == 'SAME' else c//sc
        return (input_shape[0], input_shape[3])

    def call(self, inputs):
        # K.in_train_phase(self._tf_pooling_function(inputs), self._pooling_function_test(inputs))
        input_shape = tf.shape(inputs)
        output = self._pooling_function(inputs)
        # output = tf.reshape(output, self.compute_output_shape(input_shape))
        return output

    def get_config(self):
        config = {
            'pool_size': self.pool_size,
            'strides': self.strides
        }
        base_config = super(LGPooling2D, self).get_config()
        return dict(list(base_config.items()) + list(config.items()))

def get_model():
    model = tf.keras.Sequential()
    model.add(tf.keras.layers.Conv2D(32, kernel_size=(3, 3),activation="relu",input_shape=input_shape))
    # model.add(tf.keras.layers.SpatialDropout2D(0.15))
    model.add(tf.keras.layers.MaxPooling2D())
    model.add(tf.keras.layers.Conv2D(64, kernel_size=(3, 3),activation='relu'))
    # model.add(tf.keras.layers.SpatialDropout2D(0.1))
    # model.add(tf.keras.layers.MaxPooling2D())
    model.add(LGPooling2D(pool_size=(3, 3), strides=(2, 2)))
    # model.add(tf.keras.layers.GlobalAveragePooling2D())
    # model.add(tf.keras.layers.Flatten())
    # model.add(tf.keras.layers.Dense(100, activation='relu'))
    # model.add(tf.keras.layers.Dropout(0.1))
    model.add(tf.keras.layers.Dense(num_classes, activation='softmax'))
    optim = tf.keras.optimizers.Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=1e-6)
    model.compile( loss="categorical_crossentropy",optimizer=optim, metrics=['accuracy'])
    return model

batch_size = 32
num_classes = 100
epochs = 50

# input image dimensions
img_rows, img_cols = 32, 32

# the data, split between train and test sets
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar100.load_data()

x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 3)
x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 3)
input_shape = (img_rows, img_cols, 3)

x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255.0
x_test /= 255.0
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')

# convert class vectors to binary class matrices
y_train = tf.keras.utils.to_categorical(y_train, num_classes)
y_test = tf.keras.utils.to_categorical(y_test, num_classes)

reduceLROnPlat = tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.4, patience=6, verbose=1, mode='min', min_delta=0.0001, cooldown=5, min_lr=0.00001)
callbacks_list = [reduceLROnPlat]

print('custom pooling')
model = get_model()
# model = get_model(IMG_SHAPE = (32, 32, 3))
tf.keras.utils.plot_model(model, to_file='LbpModel.png', show_shapes=True)

modelcustom = model.fit(x_train, y_train,
                        batch_size=batch_size,
                        epochs=epochs,
                        verbose=1,
                        validation_split=0.10,
                        callbacks=callbacks_list)


text:
Q: Android reconnect to WebSocket with callbackFlow I am working on a multiplayer game server. To do that I implemented an okhttp websocket. I use callbackFlow to handle the callback functions like onMessage or onFailure. This is my repo code:
class WebSocketRepository {

    fun socketEventsFlow(): Flow<GameServerResponse> = callbackFlow {

        val socketListener = object : WebSocketListener() {

            override fun onMessage(webSocket: WebSocket, text: String) {
                val message = Gson().fromJson(text, GameServerResponse::class.java)
                trySendBlocking(message)
            }
        }

        attachWebSocketListener(socketListener)
        awaitClose {
            socket.close(1000, "application in Background")
        }
    }

    private fun attachWebSocketListener(listener: WebSocketListener) {
        val client = OkHttpClient()
        val request = Request
            .Builder()
            .url("ws://10.0.2.2:8080")
            .build()

        socket = client.newWebSocket(request, listener)
    }
}

I then forward pass this Flow through the viewModel to the Activity to for example launch a new fragment. This is the viewModel's code:
class MainActivityViewModel @Inject constructor(
    private val repository: WebSocketRepository
) : ViewModel() {
    val events = repository.socketEventsFlow()
}

I finally collect the flow in the activity like this:
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding

    private val viewModel: MainActivityViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        lifecycleScope.launch {
            lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
                viewModel.events.collect { event ->
                    //Do stuff here
                }
            }
        }
    }
}

There are two problems though.

*

*If the user closes the app (in the background, not fully terminate it), the socket is closed due to the awaitClose statement. I could easily fix that by setting Lifecycle.state.STARTED to Lifecycle.state.CREATED. I worry though that if I do that I would run into problems. For example navigating while the app is in the background. I don't want to create a new socket every time the user closes the app though.

*The second problem is the "more important" one. How do I correctly handle reconncetions with this approach? If for example the internet connections drops the server will detect that the client is not there anymore and terminate the connection. I want the app to try to automatically reconnect though. But I have no clue how to implement that. I believe that I would somehow have to re-collect the viewModel's event Flow. But I have no idea on how to actually do that. Is there a better way to handle reconnections?


text:
Q: ValueError: Input 0 of layer lstm_28 is incompatible with the layer: expected ndim=3, found ndim=4. Full shape received: [None, 50, 21, 8] Input dimensions:
train_ohe :(95036, 50, 21)
y_train :(95036,)
val_ohe :(9911, 50, 21)
y_val :(9911,)

Model :
x_input = Input(shape=(50,))
emb = Embedding(21, 8, input_length=50)(x_input)
bi_rnn = LSTM(50, input_shape=(50,20,50), return_sequences=False)(emb)
x = Dropout(0.3)(bi_rnn)
x_output = Dense(1, activation='relu')(x)
model1 = Model(inputs=x_input, outputs=x_output)
model1.compile(optimizer='adam', loss='mse', metrics=['mse'])

history1 = model1.fit(
    train_ohe, y_train,
    epochs=1, batch_size=256,validation_data=(val_ohe, y_val),callbacks=[es]
    )

Note
Vocab size=20, input_length=50

I tried changing return_sequences for True/False and also tried dimensions of LSTM layer from (50, 20)/(50,20,50) but still got the same error.

A: Looks like you are feeding one-hot vectors to Embedding layer. You should feed sequences of integers. Shape should be (95036, 50).
If you really need to feed one-hot vectors - you have to convert one-hot to integer to feed them into Embedding layer. Try something like that:
x_input = Input(shape=(50, 21))
x = tf.argmax(x_input, axis=-1)
emb = Embedding(21, 8, input_length=50)(x)


text:
Q: Java: Static access using a string? Wasnt too sure on the title for the but I have a file that is used to retrieve certain texture coordinates. The file is called Assets and just contains a bunch of items like what is below...
public static TextureRegion level1;

To get access to this I just use Assets.level1 for another part of the program and thats that.
What I'm wondering is if there is a way to do this through a string, for example instead of Assets.level2 i could do something like Assets.(string) where string = "level2"
Any help will be great

A: Instead of having those as static fields in the Assets class, you should add a static method to Assets:
public static TextureRegion getTextureRegion(String name)
{
    // get it somehow
}

Now, for the "somehow" part: the easiest (and most flexible) way would be to have a Map<String, TextureRegion> (Map is an interface, HashMap would probably be sufficient in this case) in your Assets class that contains the texture regions. How you put data in that map is up to you. For instance:
regions.put("level1", your_level_1_region);

Then, your getTextureRegion becomes:
public static TextureRegion getTextureRegion(String name)
{
    return regions.get(name);
}

The upside of this is that those regions could be determined at runtime (perhaps loaded from a file) instead of being hardcoded.

A: (TextureRegion)Assets.class.getField("level2").get(null)

A: You can access static fields of a class based on a variable by using the Java Reflection API.
TextureRegion lvl = (TextureRegion) Assets.class.getDeclaredField("level1").get(null);


text:
Q: Exit the entire recursion stack I'm calling a function fooA from main() that calls another function fooB that is recursive.
When I wish to return, I keep using exit(1) to halt execution. What is the right way to exit when the recursion tree is deep?
Returning through the recursion stack may not be of help because returning usually clears a part solution I build and I don't want to do that. I want to do execute more piece of code from main().
I read Exceptions can be used, it would be nice if I can get a code snippet.

A: This happened to me while finding the path from root to node of a binary tree. I was using a stack to store the nodes in preorder and the recursion wouldnt stop until the last node returned NULL. I used a global variable, integer i=1, and when I reached the node I was looking for I set that variable to 0 and used while(i==0) return stack; to allow the program to go back up the memory stack without popping my nodes off.

A: The goto statement won't work to hop from one function back to another; Nikos C. is correct that it wouldn't account for releasing the stack frames of each of the calls you've made, so when you got to the function you goto'ed to, the stack pointer would be pointing to the stack frame of the function you were just in... no, that just won't work.  Similarly, you can't simply call (either directly, or indirectly via a function pointer) the function you want to end up in when your algorithm is done.  You'd never get back to the context you were in prior to diving into your recursive algorithm.  You could conceivably architect a system this way, but in essence each time you did this you'd "leak" what was currently on the stack (not quite the same as leaking heap memory, but a similar effect).  And if you were deep into a highly recursive algorithm, that could be a lot of "leaked" stack space.
No, you need to somehow return back to the calling context.  There are only three ways to do so in C++:

*

*Exit each function in turn by returning from it to its caller
backing up through the call chain in an orderly fashion.

*Throw an exception and catch it at the point right after you
launched into your recursive algorithm (which automatically destroys
any objects created by each function on the stack in an orderly
fashion).

*Use setjmp() & longjmp() to do something similar to throwing &
catching an exception, but "throwing" a longjmp() will not destroy
objects on the stack; if any such objects own heap allocations,
those allocations will be leaked.

To do option 1, you have to write your recursive function such that once a solution is reached, it returns some sort of indication that it's complete to its caller (which may be the same function), and its caller sees that fact & relays that fact on to its caller by returning to it (which may be the same function), so on and so on, until finally all stack frames of the recursive algorithm are released and you return to whatever function called the first function in the recursive algorithm.
To do option 2, you wrap the call to your recursive algorithm in a try{...} and immediately after it you catch(){...} the expected thrown object (which could conceivably be the result of the computation, or just some object that lets the caller know "hey, I'm done, you know where to find the result").  Example:
try
{
    callMyRecursiveFunction(someArg);
}
catch( whateverTypeYouWantToThrow& result )
{
    ...do whatever you want to do with the result,
    including copy it to somewhere else...
}

...and in your recursive function, when you finish the results, you simply:
throw(whateverTypeYouWantToThrow(anyArgsItsConstructorNeeds));

To do option 3...
#include <setjmp.h>
static jmp_buf jmp; // could be allocated other ways; the longjmp() user just needs to have access to it.
    .
    .
    .
if (!setjmp(jmp)) // setjmp() returns zero 1st time, or whatever int value you send back to it with longjmp()
{
    callMyRecursiveFunction(someArg);
}

...and in your recursive function, when you finish the results, you simply:
longjmp(jmp, 1); // this passes 1 back to the setjmp().  If your result is an int, you
                 // could pass that back to setjmp(), but you can't pass zero back.

The bad thing about using setjmp()/longjmp() is that if there are any stack-allocated objects still "alive" on the stack when you call longjmp(), execution will jump back to the setjmp() point, skipping the destructors for those objects.  If your algorithm uses only POD types, that's not an issue.  It's also not an issue if the non-POD types your algorithm uses do NOT contain any heap allocations (e.g. from malloc() or new).  If your algorithm uses non-POD types that contain heap allocations, then you're only safe with options 1 & 2 above.  But if your algorithm meets the criteria of being OK with setjmp()/longjmp(), and if your algorithm is buried under a ton of recursive calls at the point it finishes, setjmp()/longjmp() may be the fastest way back to the initial calling context.  If that won't work, option 1 is probably your best bet in terms of speed.  Option 2 may seem convenient (and would possibly eliminate a condition check at the start of each recursion call), but the overhead associated with the system automatically unwinding the callstack is somewhat significant.
It's typically said you should reserve exceptions for "exceptional events" (events expected to be very rare), and the overhead associated with unwinding the callstack is why.  Older compilers used something akin to setjmp()/longjmp() to implement exceptions (setjmp() at the location of the try & catch, and longjmp() at the location of a throw), but there was of course extra overhead associated with determining what objects on the stack need destroyed, even if there are no such objects.  Plus, every time you'd run across a try, it would have to save the context just in case there was a throw, and if exceptions are truly exceptional events, the time spent saving that context was simply wasted.  Newer compilers are now more likely to use what are known as "Zero Cost Exceptions" (a.k.a. Table Based Exceptions), which seems like that would solve all the world's problems, but it doesn't.... It makes normal runtime faster because there is no longer a need to save the context every time you run across a try, but in the event that a throw executes, there is now even more overhead associated with decoding information stored in massive tables that the runtime has to process in order to figure out how to unwind the stack based on the location where the throw was encountered and content of the runtime stack.  So exceptions aren't free, even though they're very convenient.  You'll find a lot of stuff on the internet where people make claims about how unreasonably expensive they are and how much they slow down your code, and you'll also find lots of stuff by people refuting those claims, with both sides presenting hard data to bolster their claims.  What you should take away from the arguments is that using exceptions is great if you expect them to rarely occur, because they result in cleaner interfaces & logic that's free of a ton of condition checking for "badness" every time you make a function call.  But you shouldn't use exceptions as a means of normal communication between a caller and its callees, because that mode of communication is significantly more expensive than simply using return values.


text:
Q: QGIS : how to do elegant multiple replace string? In QGIS I need to do a string conversion, from serbian latin to serbian cyrilic.
In field calculator, i have only this inelegant solution :
replace(replace(replace(replace( etc... ))))

It's long to type all translitterations (about 30), is there a better way to do this ?

Inpired by given links, i did this :
from qgis.core import *
from qgis.gui import *
import string

@qgsfunction(args='auto', group='Custom')
def serbian_latin_to_cyrillic(n):
    capital_letters = {
        u'Џ': u'DŽ',
        u'Њ': u'NJ',
        u'Љ': u'LJ',
        u'А': u'A',
        u'Б': u'B',
        u'В': u'V',
        u'Г': u'G',
        u'Д': u'D',
        u'Ђ': u'Ð',
        u'Е': u'E',
        u'Ж': u'Ž',
        u'З': u'Z',
        u'И': u'I',
        u'Ј': u'J',
        u'К': u'K',
        u'Л': u'L',
        u'М': u'M',
        u'Н': u'N',
        u'О': u'O',
        u'П': u'P',
        u'Р': u'R',
        u'С': u'S',
        u'Т': u'T',
        u'Ћ': u'Ć',
        u'У': u'U',
        u'Ф': u'F',
        u'Х': u'H',
        u'Ц': u'C',
        u'Ч': u'Č',
        u'Ш': u'Š'
    }

    lower_case_letters = {
        u'dž': u'џ',
        u'nj': u'њ',
        u'lj': u'љ',
        u'a': u'а',
        u'b': u'б',
        u'v': u'в',
        u'g': u'г',
        u'd': u'д',
        u'ð': u'ђ',
        u'e': u'е',
        u'ž': u'ж',
        u'z': u'з',
        u'i': u'и',
        u'j': u'ј',
        u'k': u'к',
        u'l': u'л',
        u'm': u'м',
        u'n': u'н',
        u'o': u'о',
        u'p': u'п',
        u'r': u'р',
        u's': u'с',
        u't': u'т',
        u'ć': u'ћ',
        u'u': u'у',
        u'f': u'ф',
        u'h': u'х',
        u'c': u'ц',
        u'č': u'ч',
        u'š': u'ш'
    }

translit_string = ""

    for index, char in enumerate(string):
        if char in lower_case_letters.keys():
            char = lower_case_letters[char]
        elif char in capital_letters.keys():
            char = capital_letters[char]
            if len(string) > index+1:
                if string[index+1] not in lower_case_letters.keys():
                    char = char.upper()
            else:
                char = char.upper()
        translit_string += char

    return translit_string

But when i use the function, and put a field form the table in the parameter of the function, it says the function use only one paramater and it says i put 3 value. Why that ?

I try the second solution, and it gives me some strange result. Beside this, i cannot get the value of a field transmitted in function paramater.
@qgsfunction(args='auto', group='Python')
def serbian_latin_to_cyrillic(field, feature, parent):

    sr_latin = u"Bačka Palanka"

    symbols = (u"džnjljabvgdðežzijklmnoprstćufhcčšDŽNJLJABVGDÐEŽZIJKLMNOPRSTĆUFHCČŠ",
    u"џњљабвгдђежзијклмнопрстћуфхцчшЏЊЉАБВГДЂЕЖЗИЈКЛМНОПРСТЋУФХЦЧШ")

    """tr = {ord(a):ord(b) for a, b in zip(*symbols)}"""
    tr = dict( [ (ord(a), ord(b)) for (a, b) in zip(*symbols) ] )

    return sr_latin.translate(tr)

It gives me this : ÐнµÐ ÐÐÐÐеÐ
If i disable the transliteration function, it gives me this : BaÄka Palanka
Maybe problem with character encoding ?

A: It looks like this has been done successfully in Python.  Have a look at this post on Stack Overflow.
In order to replicate this in QGIS, you'll need to create a function to use in the Field Calculator.
Your custom function will look similar to this:
from qgis.core import *
from qgis.gui import *

@qgsfunction(args='auto', group='Custom')
def serbian(n):
    symbols = (u"abvgdeejzijklmnoprstufhzcss_y_euaABVGDEEJZIJKLMNOPRSTUFHZCSS_Y_EUA"),u"абвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ")
    tr = {ord(a):ord(b) for a, b in zip(*symbols)}

    return n.translate(tr)

If you want to go the other way (cyrillic to latin) which is what was done in the example on Stack Overflow, you just need to reverse the order of the symbols tuple.
You should be able to call this function in your field calculator and pass your fields into it.
Disclaimer: I'm not a QGIS user and I have not tested the above.

A: @mane maybe you can find a solution here > how-to-transliterate-in-qgis-using-python-3. Install the module linked there, Serbian is included in its Natural Languages.


text:
Q: Stripes: can't add to form dynamically created tables by javascript I am creating table dynamically by javascript like this:
function createNewML(id, mlName, mlAddress){
    var table = $("
");
    table.html(addToMLContainer(id, mlName, mlAddress));
    $("#AddedMlsContainer").append(table);
}

function addToMLContainer(id, mlName, mlAddress){
    return '<stripes:text>' + mlName + ' ' + mlAddress + '</stripes:text>	' +
            '<input name="mlFullName" type="hidden" value="' + mlName + ' ' + mlAddress + '" />	' +
            '<input name="mlId" type="hidden" value="' + id + '" />	' +
            '<input type="button" value="Remove" class="remove" onclick="this.closest(\'tr\').remove()"/>	'
}

Here is my form in jsp file
<s:form beanclass="gocardmanager.action.ContentActionBean">

                        Выбранные точки
                        Удалить

                        Card Name
                        Percent
                        Action

Имя

                <input width="200px">

Описание

                <textarea rows="10" cols="45"  name="text"></textarea>

Начало

Окончание

Загруженная картина

                <s:submit name="test" value="Save Changes"/>

        </s:form>

And now I want to pass by form all my values from table and other inputs. But I can't get values from my dynamically created table(AddedMlsContainer).

A: You need to call createNewML() function on document ready to create tables rows. for example:
$(document).ready(function(){
 createNewML('1','testname1','testadd1');
 createNewML('2','testname2','testadd2');
 createNewML('3','testname3','testadd3');
})


text:
Q: Fill Model Class With query Hello I Have the Following Model
public class MainClass
{
    public List<SubClass1> First { get; set; }
    public List<SubClass2> Second { get; set; }
    public List<SubClass3> Third { get; set; }
}

public class SubClass1
{
    public string Prop1 { get; set; }
}

public class SubClass2
{
    public string Prop2 { get; set; }
    public string Prop3 { get; set; }
}

public class SubClass3
{
    public string Prop4 { get; set; }
    public string Prop5 { get; set; }
}

I need to "fill" the MainClass with a linq query result, I'm trying to do it this way:
var resultado = from a in DataContext.Table1
                        join b in DataContext.Table2 on a.Id equals b.CId
                        select new MainClass
                        {
                           First = new SubClass1 ... list query result,

                           Second = new SubClass2 ... list query result,

                           Third = new SubClass3 ... list query result,
                        };

How can I "fill" the SubClasses in order to construct the MainClass.

A: Your code should look like this
var resultado = from a in DataContext.Table1
                    join b in DataContext.Table2 on a.Id equals b.CId
                    select new MainClass
                    {
                       First = ( from i in db.Entity where somecondition).ToList<SubClass1>()
                       , Second = (from s in db.Entity2 where ).ToList<SubClass1>()

}

and so on..


text:
Q: emails are coming with 20 min delay bluehost Here is my php code:
$message = '

Hello and welcome!

My Message

My Message 1

My Message 2

;
                $header = 'From: Company | <test@domain.com>' . "\r\n";
                $header .= "MIME-Version: 1.0" . "\r\n";
                $header .= "Content-type:text/html;charset=utf-8" . "\r\n";
                $from  = '<contact@domain.com>';
                $subject =  'Thank You';
                $joinmail = $_POST['joinmail'];
                global $wpdb;
                 $checkUserEmail = $wpdb->get_results("SELECT * FROM club_members WHERE Email = '".$joinmail."'");
                $ip = $_POST['ip'];
                $to = '';
        $to .= $joinmail;
                if(empty($checkUserEmail)){
                        if(mail($to, $subject, $message, $header)) {
                            global $wpdb;
                            $wpdb->insert(
                                    'club_members',
                                    array(
                                        'Email' => $joinmail,
                                        'IP' => $ip,
                                        'Date' => current_time('M/Y/d H:i:s')
                                    ),
                                    array(
                                            '%s',
                                            '%s',
                                            '%s'
                                    )
                            );
                        }
                }

I am using this code to send email from Wordpress website. My hosting is bluehost. Before migrating site to bluehost it was on hostgator and everything was Ok, no such delay. On bluehost I can receive emails without any delay but when am sending from this email address receipient receives with 20min delay.


text:
Q: Spring + Jersey not able to load spring-config.xml properly (Autowired beans are null) I am making a REST API using Jersey and Spring. I am trying to load the application context for spring called spring-config.xml in my web.xml file.
Scenario 1: I put this file under /WEB-INF and set <param-value>/WEB-INF/spring-config.xml</param-value>, everything works as expected and no problems are encountered.
Scenario 2: I put my spring-config.xml in src/main/resources (i.e. classpath) and set <param-value>classpath*:spring-config.xml</param-value>. In this case, my application is successfully deployed. But for example say I try to make a POST call to http://localhost:8000/rest/authenticate, I get the following error:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type "club.myfpl.services.UserService" available: expected at least 1 bean which qualifies as autowire candidate.
Please help me figure out why placing my spring-config.xml in WEB-INF works and placing it in src/main/resources doesn't. FYI, I am using Intellij, if it matters.
My jersey resource file:
@Path("/authenticate")
@Service
public class AuthenticationRestAPI {

    @Autowired
    UserService userService;

    @POST
    @Produces("application/json")
    @Consumes("application/x-www-form-urlencoded")
    public Response authenticateUser(@FormParam("email") String email, @FormParam("password") String password) {
        try {
            // Authenticate the user using the credentials provided
            authenticate(email, password);
            // Issue a token for the user
            String token = issueToken(email);
            // Return the token on the response
            return Response.ok(token).build();
        } catch (Exception e) {
            return Response.status(Response.Status.UNAUTHORIZED).build();
        }
    }

    private void authenticate(String email, String password) throws Exception {
        if (!userService.authenticateUser(email, password)) {
            throw new Exception();
        }
    }

    private String issueToken(String email) throws Exception {
        User user = userService.fetchUserByEmail(email);
        String token = JWT.create()
                .withIssuer(SecurityConstants.JWT_ISSUER)
                .withExpiresAt(Date.from(LocalDate.now().plus(1, ChronoUnit.DAYS).atStartOfDay(ZoneId.systemDefault()).toInstant()))
                .sign(Algorithm.HMAC256(SecurityConstants.JWT_SECRET));
        userService.createUserAuthToken(user.getUserId(), token);
        return token;
    }
}

My web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:spring-config.xml</param-value>
    </context-param>

    <display-name>MyFPL REST API</display-name>
    <servlet>
        <servlet-name>REST API Servlet</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>club.myfpl.rest</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>REST API Servlet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
</web-app>

My spring-config.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mongo="http://www.springframework.org/schema/data/mongo"
       xmlns:context="http://www.springframework.org/schema/context" xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <mongo:mongo id="mongo" host="127.0.0.1" port="27017"/>
    <mongo:db-factory id="mongoDbFactory" dbname="myFpl" mongo-ref="mongo"/>
    <mongo:template id="mongoTemplate" db-factory-ref="mongoDbFactory"/>

    <context:annotation-config/>
    <context:component-scan base-package="club.myfpl"/>

    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
</beans>

My relevant parts of build.gradle file:
dependencies {
    compile group: 'javax.servlet', name: 'javax.servlet-api', version: '3.1.0'
    compile group: 'javax.el', name: 'javax.el-api', version: '3.0.0'

    compile group: 'org.glassfish.jersey.core', name: 'jersey-server', version: '2.25'
    compile group: 'org.glassfish.jersey.containers', name: 'jersey-container-servlet', version: '2.25'
    compile (group: 'org.glassfish.jersey.ext', name: 'jersey-spring3', version: '2.25') {
        exclude group: 'org.springframework'
    }

    compile group: 'org.springframework.data', name: 'spring-data-mongodb', version: '1.9.2.RELEASE'

    compile group: 'org.springframework', name: 'spring-core', version: '4.3.4.RELEASE'
    compile group: 'org.springframework', name: 'spring-web', version: '4.3.4.RELEASE'
    compile group: 'org.springframework', name: 'spring-context', version: '4.3.4.RELEASE'
    compile group: 'org.springframework', name: 'spring-aop', version: '4.3.4.RELEASE'
    compile group: 'org.springframework', name: 'spring-test', version: '4.3.4.RELEASE'
}


text:
Q: Faster way to get the difference of two lists without set I'm trying to compare two lists and get the new elements, including redundant elements.
For instance, the result of :
l1 = [1,2,3,3,4]
l2 = [3,3,3,4,4,5,6]

Is :
l2 - l1 = [3,4,5,6]

You can easily understand that I can't do it with set because
set(l1) = (1,2,3,4)
set(l2) = (3,4,5,6)

The result would be : (5,6)
I don't want to do it with an iteration such as
[i for i in l1 if i not in l2 ]

Because it's too slow (see benchmark at Get difference between two lists)
Does anyone know how to do it without iteration and keep the redundant elements or iterative methods are the only way ?
Thanks !
Benchmarking of the solutions :
I benchmarked both of the given solutions and here's the result :
import random
init1 = list(range(10000))
init2 = [i*random.randint(1,50) for i in range(10000)]

# Put both solution in function, diff1 = remove method, diff2 = Counter method

import time
tic1 = time.clock()
print(diff1(init2,init1))
toc1 = time.clock()
tic2 = time.clock()
print(diff2(init2,init1))
toc2 = time.clock()
print(toc1-tic1)
print(toc2-tic2)

And the results are :
2.756271607145601   for diff1
0.028116911506909315    for diff2

A: You're looking for multisets, that's exactly what collections.Counter is for:
>>> from collections import Counter
>>> list((Counter(l2) - Counter(l1)).elements())
[3, 4, 5, 6]

A: You can do it as follows:
l1 = [1,2,3,3,4]
l2 = [3,3,3,4,4,5,6]

l3 = l1[:]
l4 = l2[:]

for item in l2:
    if item in l3:
        l3.remove(item)
        l4.remove(item)

>>> print l4
[3,4,5,6]