text:
Q: Can 10-rep users post images? Whats the deal with posting images? I've just spent a long time composing a nice post with images and stuff, only to be told I can't post images unless my rep is 10, but my rep is 10 (on Stack Overflow)! Maybe you mean rep > 10 not rep >= 10?

A: Also (besides the ">" or ">=" question), in such a case it's okay just to put in the link to the picture with a short note asking whoever having 2k rep comes by to put the images in. This happens quite often and works well.
This requirement is still in effect on Stack Overflow, although it's been relaxed on most other sites in the network that see less volume of posts and images. If it becomes a problem anywhere, we can turn this back on.


text:
Q: Using "please" when assigning tasks As a manager I frequently have to assign tasks to my subordinates. I often waver between:

*

*"Can you please do X"

and

*"Can you do X"

I don't have a good feeling for what the difference is, however someone pointed out to me that #1 might sound condescending which is not my intention at all.
The top rated answer in this  previous question seems to corroborate my impression even though the context is ambiguous.
Ultimately, what I'm trying to achieve is be polite and respectful when delegating tasks. Perhaps I should be using different phrasing?

A: Students need to be very careful about where they put the word please. This is even more important when they are writing. (When you are writing, no-one can see your friendly smile. They can't hear your tone of voice either). If you put it in the wrong place, and people misread your tone of voice, it can cause a lot of problems, and probably neither you nor the person you're talking to will understand exactly where the problem came from.
Please

*

*Could you slice it, please?

*Please could you slice it?

*Could you please slice it!

Generally speaking, the natural place for please is at the end of the sentence. When we put it here, it is low pitch and quite quiet. The main musical stress in the sentence will come before the word please. This is the most polite and friendly place to put it. Note that you cannot stress the word please in this position - and if you do you will annoy your listeners.
If you really want to draw attention to your request, or if it is urgent, you can put please at the beginning of the sentence. If you stress the word please here, it will sound as if you are pleading or begging your listener to give you something or do something:

*

*Mum please can I have another ice-cream.

If you aren't begging, then be a little careful about putting please at the front of your sentence. If you stress the please, you will sound like a child begging their parents to do something. If you don't stress it, it sounds a bit impersonal. It is a bit business-like, and is not as friendly as putting it at the end. This is probably because it is more difficult for the listener to say 'no' when you put the please at the beginning. This isn't a problem if you are in a business-like situation or, for example, if you are giving instructions to an employee. Putting please at the beginning of your sentence can be a good signal that this is a serious request.
WARNING: be very careful about putting please in the middle of your sentence. When you do this, you have changed the feeling of the sentence completely. If you put please in the post auxiliary verb position, it is more like an order than a request:

*

*Would you please be quiet!

*Can you please give me a hand!

*Could you please stop!

You can do this, if you want, if you are somebody's parent, or if you have some kind of authority over them. Remember though, that although it may look like a request, this has the function of an order, not a request. It can also sound as if you are annoyed with the person you're speaking to:

*

*Would you please slice it. [and why haven't you already done that!]

In terms of politeness and or friendliness, it is more polite and friendly not to use please at all than to put it in this position in the sentence:

*

*Could you slice it?

The Original Poster's question
It's a good idea to use please as a matter of habit. But it's a bad idea to always put it in the middle of the sentence. It can really upset people sometimes.
A good business-like place to put it, if your someone's manager, is at the beginning of the sentence. But if you're asking someone to do something as a favour, or perhaps something they may not want to do, or don't normally have to do, it's probably best to put it at the end. If I was in the Original Poster's position, I'd use the end position for normal directions, and the front position for more serious or urgent ones.
Lastly, as StoneyB says in his excellent answer, it's our attitude and tone of voice that matters most in these situations. But still be careful with the position of please, it carries extra meaning.
An anecdote
There was a really friendly student in one of the language schools I used to work for. She was very popular with the students and teachers and when she applied for a job in the Admin office at the school at the end of her course everybody was very happy that she got the job.
After about a month all the teachers hated her. It was very confusing because she still seemed to be being very nice to people when she spoke to them and the students still all really liked her. I'm going to call her Caroline, but that wasn't her real name.
A friend of mine and I realised that the teachers were getting really upset by the notes she was sending them, which used to appear in a sealed envelope stuck in their pigeon holes during their coffee break.
Now Caroline had a lot of administration to do. And she needed to get various bits of information from the teachers, who needed to fill in different forms and registers and stuff like that. Now the teachers were very busy and occasionally they would forget this or that bit of paper and so forth. At other times someone in a different department might need some help or something like that and the Powers That Be would ask her to ask a teacher if they could help. Because Caroline was very busy her notes were always very short. They read a bit like this:

Dear Bob,
Could you please bring your form into the office. I really need to put it into the computer!

Dear Mrs Hall,
Could you please help J.R. tidy the library during the break. We have a function there this afternoon.

These little notes seemed a bit officious and unfriendly, especially as she was about thirty years younger than many of the teachers she was writing to. Of course she actually wanted to sound like this:

Dear Bob,
Could you bring your form into the office, please? I really need to put it into the computer!

Dear Mrs Hall,
Could you help J.R. tidy the library during the break, please? We have a function there this afternoon.

We did help Caroline sort it out, but it took a week or so for the other teachers to come round!

A: The words don't matter nearly so much as your tone and demeanour—and your subordinates' past experience with you. Any set of words, no matter how elaborately polite, can be uttered with sarcasm or condescension; and any set of words, no matter how abrupt and demanding, can be uttered with respect.
The fact that you're worrying about this suggests that you probably don't have much to worry about, unless you're trying to overcome prior friction.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Combining functions in one file infilehandle = open ("receipts-10-28-13.txt", "r")

# FUNCTIONS

def stripsigns( astring ):
    """Remove dollar signs"""
    signs = "$"
    nosigns = ""
    for numbers in astring:
        if numbers not in signs:
            nosigns = nosigns + numbers
    return nosigns

def totaltake():
    """Calculate total take"""
    total = 0
    for line in infilehandle:
        values = line.split(':')
        cardnumbers = values[1]
        cardnumbers = stripsigns(cardnumbers)
        total = (total + eval(cardnumbers))
        total = round(total,2)
    return total

# more code etc

def computetax(rate, total):
    total = totaltake() - totaltip()
    taxed = total * rate
    taxed = round(taxed,2)
    return taxed

# more code etc

# VARS

total = totaltake()
tips = totaltip()
tax = computetax(rate,total)

rate = eval(input("Input the tax rate as an integer:"))

# PRINT

print("Total take: $", totaltake())
print("Total tips: $", totaltips())
print("Tax owed: $", computetax(rate,total))

I'm trying to make a file that will look at elements from a txt file and then calculate things based on the numbers in the file. The functions are all either variations of the totaltake(), which is getting numbers from the file and finding the sum, or the computetax(), which takes the numbers the other functions calculate and multiplies/divides/etc. I've tested all the functions individually and they all work, but when I try to put them together in one file, it doesn't give me the output I want, and I don't know why. It prints the value of whatever is first in the vars list, and 0 for everything else -- so for the version of code I have above, it prints
Total take: $ 6533.47
Total tips: $ 0
Tax owed: $ 0

So basically, what am I doing wrong?

A: See Is file object in python an iterable
File objects are iterators, meaning that once a file has been iterated to completion, you cannot iterate over the file again unless it has been reset to the beginning of the file by calling file.seek(0).
When you only call totaltake(), because infilehandle has not yet been iterated, the for loop goes through all the lines in infilehandle, which is why you get the expected result.
However, when you put computetax() together with totaltake(), totaltake() gets called by itself, and then again incomputetax(). Because infilehandle has been iterated to completion the first time totaltake() is called, the for loop is not entered the second time and the initial value for total, 0, is returned.
As the value returned by totaltake() should not change, you should modify computetax() so that you can pass total as a parameter instead of calling totaltake(). You should do the same so that it also takes tips as a parameter instead of recalculating the value.
If you cannot modify computetake(), you could also seek to the beginning of infilehandle by adding infilehandle.seek(0) to the beginning of totaltake(), to allow it to be iterated again.


text:
Q: console.log() não é impresso ao utilizar (ctrl + alt + n) em Ubuntu, com Code Runner instalado Iniciei o estudo de NodeJS utilizando o Windows e ao longo do tempo fiz a mudança para o sistema operacional Ubuntu. Ao mudar de S.O instalei o Node na maquina, VsCode, e a extensão Code Runner, tudo igual ao sistema antigo. Porém ao tentar executar um código diretamente no VsCode utilizando o comando (ctrl + alt + n) recebo o retorno da execução:

[Running] node "/home/Desktop/teste.js"
[Done] exited with code=0 in 0.138 seconds

Porém não recebo o que deveria ser visualizado ao colocar um console.log() no meu código. Ou seja, ao executar
console.log("teste")

deveria aparecer:

[Running] node "/home/Desktop/teste.js"
teste
[Done] exited with code=0 in 0.138 seconds

Mas isso não está ocorrendo... Sabem me informar, o por quê? Agradeço pela ajuda

A: consegui achar a solução. Este erro se dá ao instalar o NodeJs através da Loja de aplicativo do Ubuntu. Ao instala-lo utilizando o terminal, tudo ocorre normalmente, utilizem este tutorial para instalar:
https://www.google.com/amp/s/www.digitalocean.com/community/tutorials/how-to-install-node-js-on-ubuntu-20-04-es.amp


text:
Q: any function type used in kotlin we can easily define a function like:
fun <T> f1(f2: KFunction<T>) {…}

then call it like this:
fun f2() {...}
f1(::f2)

but when I want to call it like this:
f1 {

}

it failed. because it required KFunction<TypeVariable>, but it is actually () -> Unit.
so I rewrite it like this:
fun <K, T : Function<K>> f1(args: Array<Any> = arrayOf(), f2: T) {
    //f2.invoke(args)
    //it failed. I don't know how to call f2
}

f1 {…} //success

So this is the problem. I don't know how to call an arbitary anonymous function type
And I try to call it this way:
inline fun <K, reified T : Function<K>> f1(args: Array<Any> = arrayOf(), f2: T) {
    val typeParams = args.map { it::class.java }.toTypedArray()
    T::class.java.getDeclaredMethod("invoke", *typeParams).invoke(f2, args)
    // success. But I don't know if there is a bug
}

At last, I find kotlin.reflect.jvm.Function.reflect() But it is useless now. So I want to know if there is a better way to do this.
Thanks for any help.

A: This is my final solution. It is generated by a generator. It looks stupid but it is very useful
@Suppress("UNCHECKED_CAST")
fun Function<*>.call(vararg args: Any?): Any? {
    return when(this) {
        is Function0 -> {
            invoke()
        }
        is Function1<*,*> -> {
            (this as Function1<Any?,Any?>).invoke(args[0])
        }
        is Function2<*,*,*> -> {
            (this as Function2<Any?,Any?,Any?>).invoke(args[0],args[1])
        }
        is Function3<*,*,*,*> -> {
            (this as Function3<Any?,Any?,Any?,Any?>).invoke(args[0],args[1],args[2])
        }
        is Function4<*,*,*,*,*> -> {
            (this as Function4<Any?,Any?,Any?,Any?,Any?>).invoke(args[0],args[1],args[2],args[3])
        }
        is Function5<*,*,*,*,*,*> -> {
            (this as Function5<Any?,Any?,Any?,Any?,Any?,Any?>).invoke(args[0],args[1],args[2],args[3],args[4])
        }
        is Function6<*,*,*,*,*,*,*> -> {
            (this as Function6<Any?,Any?,Any?,Any?,Any?,Any?,Any?>).invoke(args[0],args[1],args[2],args[3],args[4],args[5])
        }
        is Function7<*,*,*,*,*,*,*,*> -> {
            (this as Function7<Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?>).invoke(args[0],args[1],args[2],args[3],args[4],args[5],args[6])
        }
        is Function8<*,*,*,*,*,*,*,*,*> -> {
            (this as Function8<Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?>).invoke(args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7])
        }
        is Function9<*,*,*,*,*,*,*,*,*,*> -> {
            (this as Function9<Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?>).invoke(args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7],args[8])
        }
        is Function10<*,*,*,*,*,*,*,*,*,*,*> -> {
            (this as Function10<Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?>).invoke(args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7],args[8],args[9])
        }
        is Function11<*,*,*,*,*,*,*,*,*,*,*,*> -> {
            (this as Function11<Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?>).invoke(args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7],args[8],args[9],args[10])
        }
        is Function12<*,*,*,*,*,*,*,*,*,*,*,*,*> -> {
            (this as Function12<Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?>).invoke(args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7],args[8],args[9],args[10],args[11])
        }
        is Function13<*,*,*,*,*,*,*,*,*,*,*,*,*,*> -> {
            (this as Function13<Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?>).invoke(args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7],args[8],args[9],args[10],args[11],args[12])
        }
        is Function14<*,*,*,*,*,*,*,*,*,*,*,*,*,*,*> -> {
            (this as Function14<Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?>).invoke(args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7],args[8],args[9],args[10],args[11],args[12],args[13])
        }
        is Function15<*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*> -> {
            (this as Function15<Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?>).invoke(args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7],args[8],args[9],args[10],args[11],args[12],args[13],args[14])
        }
        is Function16<*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*> -> {
            (this as Function16<Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?>).invoke(args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7],args[8],args[9],args[10],args[11],args[12],args[13],args[14],args[15])
        }
        is Function17<*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*> -> {
            (this as Function17<Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?>).invoke(args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7],args[8],args[9],args[10],args[11],args[12],args[13],args[14],args[15],args[16])
        }
        is Function18<*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*> -> {
            (this as Function18<Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?>).invoke(args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7],args[8],args[9],args[10],args[11],args[12],args[13],args[14],args[15],args[16],args[17])
        }
        is Function19<*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*> -> {
            (this as Function19<Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?>).invoke(args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7],args[8],args[9],args[10],args[11],args[12],args[13],args[14],args[15],args[16],args[17],args[18])
        }
        is Function20<*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*> -> {
            (this as Function20<Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?>).invoke(args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7],args[8],args[9],args[10],args[11],args[12],args[13],args[14],args[15],args[16],args[17],args[18],args[19])
        }
        is Function21<*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*> -> {
            (this as Function21<Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?>).invoke(args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7],args[8],args[9],args[10],args[11],args[12],args[13],args[14],args[15],args[16],args[17],args[18],args[19],args[20])
        }
        is Function22<*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*,*> -> {
            (this as Function22<Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?,Any?>).invoke(args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7],args[8],args[9],args[10],args[11],args[12],args[13],args[14],args[15],args[16],args[17],args[18],args[19],args[20],args[21])
        }
        is FunctionN<*> -> {
            (this as FunctionN<Any?>).invoke(*args)
        }

        else -> { throw RuntimeException() }
    }
}


text:
Q: Finding specific characters within a list The goal is to make a list from the user's paragraph and iterating so that I can count how many words contain special letters "j,x,q,z".
Example input:
In a hole in the ground, there lived a hobbit. Not a nasty, dirty, wet hole, filled with the ends of worms and an oozy smell, nor yet a dry, bare, sandy hole with nothing in it to sit down on or to eat; it was a hobbit-hole, and that means comfort.
Example output:
1 word with a rare character
I've started the code where I break the user's paragraph into a list but I'm having a hard time iterating through the list and finding each instance of the special letters.
This is what I have so far:
def rareChar(words):
    rareWords = 0
    rareChars = ['j', 'x', 'q', 'z']
    for astring in words:
        wds = words.split()
        for char in wds:
            if char in rareChars:
                rareWords = rareWords + 1
    return rareWords

def CoolPara(words):
    print(rareChar(words), 'word(s) with a rare character')

    # DO NOT CHANGE CODE BELOW

    print(CoolPara(input("Enter: ")))

If I run with the example input, I get an output of '0 word(s) with a rare character'. How could I fix this so that I can get the expected output. Any help would be greatly appreciated as I am still relatively new to coding
Also a quick note: I am only allowed to use the methods/functions of split() and Len()

A: Maybe this could be an opportunity to introduce you to some python features:
from typing import List

def rare_char(sentence: str, rare_chars: List[str]=["j", "x", "q", "z"]) -> List[str]:
    return [word for word in sentence.split() if
            any(char in word for char in rare_chars)]

def cool_para(sentence: str) -> str:
    return f"{len(rare_char(sentence))} word(s) with rare characters"

This answer uses:

*

*typing, which can be used by third party tools such as type checkers, IDEs, linters, but more importantly to make your intentions clear to other humans who might be reading your code.

*default arguments, instead of hardcoding them inside the function. It's very important to document your functions, so that an user would not be surprised by the result (see  Principle of Least Astonishment). There are of course other ways of documenting your code (see docstrings) and other ways of designing that interface (could be a class for example), but this is just to demonstrate the point.

*List comprehensions, which can make your code more readable by making it more declarative instead of imperative. It can be hard to determine the intention behind imperative algorithms.

*string interpolation, which in my experience is less error prone than concatenating.

*I used the pep8 style guide to name the functions, which is the most common convention in the python world.

*Finally, instead of printing I returned a str in the cool_para function because the code below the # DO NOT CHANGE CODE BELOW comment is printing the result of the function call.

A: Ideally you want to use list comprehension.
def CoolPara(letters):
  new = [i for i in text.split()]
  found = [i for i in new if letters in i]
  print(new) # Optional
  print('Word Count: ', len(new), '\nSpecial letter words: ', found, '\nOccurences: ', len(found))

CoolPara('f') # Pass your special characters through here

This gives you:
['In', 'a', 'hole', 'in', 'the', 'ground', 'there', 'lived', 'a', 'hobbit.', 'Not',
 'a', 'nasty,', 'dirty,', 'wet', 'hole,', 'filled', 'with', 'the', 'ends', 'of',
'worms', 'and', 'an', 'oozy', 'smell,', 'no', 'yet', 'a', 'dry,', 'bare,', 'sandy',
'hole', 'with', 'nothing', 'in', 'it', 'to', 'sit', 'down', 'on', 'or', 'to', 'eat;',
'it', 'was', 'a', 'hobbit-hole,', 'and', 'that', 'means', 'comfort']
Word Count:  52
Special letter words:  ['filled', 'of', 'comfort']
Occurences:  3

A: def rareChar(words):
rareWords = 0
rareChars = ['j', 'x', 'q', 'z']

#Split paragraph into words
words.split()
for word in words:
    #Split words into characters
    chars = word.split()
    for char in chars:
        if char in rareChars:
            rareWords = rareWords + 1
return rareWords

def CoolPara(words):
    #return value rather than printing
    return '{} word(s) with a rare character'.format(rareChar(words))

# DO NOT CHANGE CODE BELOW

print(CoolPara(input("Enter: ")))

Input: Hello this is a sentence about zoos
Output: 1 word(s) with a rare character

A: The following code is an edit of yours which results in the proper answer of 1
def main():

    def rareChar(words):
        rareWords = 0
        rareChars = ['j', 'x', 'q', 'z']

        all_words = list(words.split())

        for a_word in all_words:
            for char in a_word:
                if char in rareChars:
                    rareWords = rareWords + 1
        return rareWords

    def CoolPara(words):
        print(rareChar(words), 'word(s) with a rare character')

    # DO NOT CHANGE CODE BELOW

    print(CoolPara(input("Enter: ")))

main()

Answer:
C:\Users\Jerry\Desktop>python Scraper.py
Enter: In a hole in the ground there lived a hobbit. Not a nasty, dirty, wet hole, filled with the ends of worms and an oozy smell, no yet a dry, bare, sandy hole with nothing in it to sit down on or to eat; it was a hobbit-hole, and that means comfort.

1 word(s) with a rare character

A: This code will work for you. Unremark the words input and remark out the words string statement that I used to test the code.
The para method is not needed.
def rareChar(words):
    rareWords = 0
    rareChars = ['j', 'x', 'q', 'z']
    for word in words:
        wds = word.split()
        for char in wds:
            if char in rareChars:
                rareWords = rareWords + 1
    return rareWords

words = 'john xray quebec zulu'
# words = (input("Enter: "))

x = rareChar(words)
print(f"There are {x} word(s) with a rare character")

A: The solution provided by Barb works for a single letter:

CoolPara('f')

But it does not work with mulitple characters as asked by the original poster. For e.g. this does not return the correct results:

CoolPara("jxqz")

Here is slightly improved version of Barb's solution:
def CoolPara(letters):
    new = [i for i in text.split()]
    found = list()
    for i in new:
        for x in i:
            for l in letters:
                if x == l:
                    found.append(i)
    print("Special letter words: ", found)
    print("word(s) with rare characters ", len(found))


text:
Q: Using NSUserName() on C I'm trying to read the username via NSUserName(). I tried the following code:
#include <stdio.h>
#include <Foundation/Foundation.h>

int main()
{
    NSString *userName = NSUserName();

    printf("username %ls\n", userName);

    return 0;
}

and compile it via:
gcc -o username -framework Foundation username.c
Several things:
1- #include <Foundation/Foundation.h> generates a LOT of errors.
2- how can I convert an NSString to char*
on 1 I am adding the -framework switch to GCC but I think the Foundation.h is not ready for C? And on 2 I tried setting char *userName = NSUserName(); but that wasn't the way to do it.
Any ideas? The code has to be C, not objective-C (as the title states)
Thanks!

A: Here's a pure-C equivalent to NSUserName():
#include <pwd.h>
#include <unistd.h>

...

struct passwd *pwent = getpwuid(getuid());
printf("Username: %s\n", pwent->pw_name);

As a bonus, this will compile and work on all UNIX-based operating systems (e.g, Linux), not just Mac OS X.

A: change the file extension of the file holding your code from .c to .m and I bet you will have a better compiling experience.
On my machine, when I drop your code into a file named "MrAleph.m", here is what I get:
[/tmp]:;gcc -o test -framework Foundation MrAleph.m
MrAleph.m: In function 'main':
MrAleph.m:8: warning: format '%ls' expects type 'wchar_t *', but argument 2 has type 'struct NSString *'
MrAleph.m:8: warning: format '%ls' expects type 'wchar_t *', but argument 2 has type 'struct NSString *'

And to fix those warnings, just change one line of code to:
printf("username %s\n", [userName UTF8String]);

A: I don't see why you'd want to do this. OS X has a way to get the same information from C, and that way is getlogin().
Foundation is an Objective-C framework and NSString is an Objective-C class. Calling it without employing Objective-C is not a simple task. Essentially, you will need to link in Foundation, include objc/objc.h for id, prototype NSUserName() yourself, use the Objective-C runtime API to get the selector for UTF8String, use the Objective-C runtime API to send the message to the string and then print the result.
All this to avoid calling getlogin().


text:
Q: Under Construction page For Website Without Redirect I wanted to know if there is some way to change something simple, such as a htaccess file, a js file, or a php file, and then all of the webpages on my site will show an under construction page. I do not really care all that much if the user has to be redirected, but I want the origonal url of the page to be displayed in the address bar (not the one of the Under Construction page) and I want the user to be redirected before anythign else is executed, such as JS functions, or even the page loading.
Any help would be greatly appreciated!
Thank you!
--EDIT--
Ok, so I have figured out how to redirect the user, and it works great. Now, my only problem is, how do I make the url of the under construction page, appear as the original page? What I want to do, is if the user goes to mysite.com/page.html, I want the user to be redirected to mysite.com/underconstruction.html, but I want them to see mysite.com/page.html as the address in the address bar. Any ideas? I am not so sure about the mod_rewrite. I am looking up a few tutorials right now, but I am just learning how to edit the htaccess, and mod_rewrite seems a bit complicateed for a beginner, so if you dumb it down a bit for me, it would help out alot.

A: We use apache mod_rewrite for this.
It checks to see if a maintenance.html file exists, and it it does, serves up that page.
To turn it on, we just do:
> mv maintenance.html.bak maintenance.html

and to hide it again:
> mv maintenance.html maintenance.html.bak

Here is out httpd.conf for this:
# Check for maintenance file and redirect all requests
RewriteCond %{DOCUMENT_ROOT}/system/maintenance.html -f
RewriteCond %{SCRIPT_FILENAME} !maintenance.html
RewriteRule ^.*$ /system/maintenance.html [L]

A: htaccess is definitley the way to go.
At least it fullfills your "I want the user to be redirected before anythign else is executed, such as JS functions, or even the page loading".
I can't say for sure if it will display the original URL, you'll need to try that out.
Personally, my whole site is PHP and each page is a template, which includes header.php, css.php, menu.php, and footer.php, so a (possibly one line) change to common include file is all that I would need. I only mention it since you seem to be totally redesigning your website and might want to consider doing something similar (if you are not keen on raw PHP, look at a tempalting system like Smarty)


text:
Q: Can we integrate XLSX and Syncfusion Library with LWC We have some custom requirement to export our data into excel with custom and conditional cell styling. We have explored two libraries (xlsxjs and syncfusion) and would like to know whether it is compatible with salesforce Lightning Web Components.
Please suggest if there is any other way to achieve the same without the mentioned libraries.
 PFA sample of expected excel file on export.

A: Greetings from Syncfusion.
It is possible to create Excel document using Syncfusion XlsIO similar to the shared screenshot.
But you have mentioned that you are exporting data to Excel, and we request you to share the below details.

*

*Platform you are using

*Control you are using to export data to Excel.

It would be helpful for us if you could share these details, so that we will check the compatibility from our side.
You can also mail the requested details to support@syncfusion.com
I work for Syncfusion.
Regards,
Mohan.


text:
Q: Class path resource [] cannot be resolved to URL because it does not exist in multimodule project I'm comming with popular erorr which is:  class path resource [db/file.xml] cannot be resolved to URL because it does not exist.
I'm using Spring Boot with version 1.3.5.RELEASE and I'm trying to use liquibase with it.
My project is multimodule. In module A I have Main class within which I run whole application.
In module B under (path from repository root) B/src/main/resources/db/file.xml I have an xml with with changesets. In module A in application.properties I have this configuration:
...
liquibase.change-log=classpath:db/db.changelog.project-master.xml

spring.jpa.hibernate.ddl-auto=none
spring.h2.console.enabled=true

db/db.changelog.project-master.xml is file within module A.
Under this file (db.changelog.project-master.xml) I have include that shoudl include this changesets from another module (module B)
<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                   xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
                   xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.0.xsd">

    <include file="db/file.xml" />

</databaseChangeLog>

I have tried also with  <include file="classpath:db/file.xml" />.Unfortuantely when I run application from module A I get:
Caused by: liquibase.exception.ChangeLogParseException: Error Reading Migration File: class path resource [db/file.xml] cannot be resolved to URL because it does not exist
    at liquibase.parser.core.xml.XMLChangeLogSAXParser.parseToNode(XMLChangeLogSAXParser.java:112)
    at liquibase.parser.core.xml.AbstractChangeLogParser.parse(AbstractChangeLogParser.java:17)
    at liquibase.changelog.DatabaseChangeLog.include(DatabaseChangeLog.java:404)
    at liquibase.changelog.DatabaseChangeLog.handleChildNode(DatabaseChangeLog.java:267)
    ... 25 more
Caused by: java.io.FileNotFoundException: class path resource [db/file.xml] cannot be resolved to URL because it does not exist

Could you tell me what is wrong?

A: I'm not sure about the answer but I think the path you are specifying "<include file="db/file.xml" />" will search for the file inside "db" directory of Module A and will fail to find one. Can you try specifying the absolute path for "file.xml" while you are including it in the master changelog file.
Let's consider below is your project structure:
--project
---------module A
         -src
            -main
             - resources
              - db
               - db.changelog.project-master.xml
---------module B
          -src
             -main
              - resources
               - db
                - file.xml

The master changelog file won't be able to find "file.xml" inside "db" directory of Module A. I think providing absolute path of file.xml could prove to be helpful.
<include file="B/src/main/db/file.xml" />
or may be try providing path for "file.xml" relative to the location of master changelog file.
Pardon if my understanding of your question was wrong.
Cheers!!


text:
Q: Collect common denominator of sum I have a sum where each term shares the same denominator, e.g., a/Z + b/Z + .... I want to factor out the Z. Although simplify can do it, it takes too long. I've tried collect and factor, but neither does what I want.
Is there a SymPy function that can be used for this?

A: The function you are looking for is together:
>>> together(x/z + y/z)
(x + y)/z

See its docs for more information.

A: I am not sure I understand what you want, but perhaps fraction would be useful. For example:
>>> from sympy import *
>>> x, y = symbols('x y')
>>> f =  (x**2 + 1) / (2*y)
>>> (num, den) = fraction(f)
>>> den
2*y


text:
Q: Zsh, splitting the expansion of %~ I'm at my wits end with this. I'm using zsh and trying to simply split the expansion of %3~ on the / character. This works fine with the expansion of $(pwd) and $PWD - both of which are also path-like strings.
I'm trying to split a string using the following code ("${(@s./.)a}") - where a is either a=$(pwd) or a=%3~. Again this code works with pwd, but not %3~.
I'm still a bit new to shell scripting -- but as far as I understand it, there should be no discrepancy. No matter what I do, I cannot get the expansion of %~ to split properly. Things I've tried:
# Ran from /home/me/code
a=%3~
b=$(pwd)
c=$PWD
d="/test/1/2"

e=$(echo "$a")
f="/$a"

echo $a # ~/code
echo $b # /home/me/code
echo $c # /home/me/code
echo $d # /test/1/2
echo $e # ~/code
echo $f # /~/code

("${(@s./.)a}") # ~/code
("${(@s./.)b}") # home me code
("${(@s./.)c}") # home me code
("${(@s./.)d}") # test 1 2
("${(@s./.)e}") # ~/code
("${(@s./.)f}") # /~/code

I'm actually starting to think that zsh is just intentionally inconsistent. I'm sure I'm just missing something, though. I've also tried ("${(ps./.)a}"), because as I read it that should do the same. I've also tried IFS-based splitting, setting IFS="/". Again, works for normal strings - does not work for %~. ???
EDIT: For the sake of completeness, this is within a .zsh-theme file where. I suppose maybe this matters? I'm technically not the one executing it (it's being ran by oh-my-zsh), so maybe something weird is happening at that level.

A: You are attempting to use an prompt escape outside of the context where prompt escapes are normally evaluated. so the variable contains the string %3~, you attempt to split the string %3~ resulting in %3~ and i am assuming it is later assigned to PS1/PROMPT which zsh then expands %3~.
If you would like to perform parameter expansions and have the string %3~ treated like a prompt escape you can use the parameter expansion flag % like so ${(%)a}


text:
Q: I am getting A RenderFlex overflowed by 57 pixels on the bottom Hi I am new to Flutter and I came across this error that is in the title I looked here as well but nothing seems to help, the layout looks just fine when I star the app however I am getting an error which drives me crazy. One of the solutions that I found was to add  resizeToAvoidBottomPadding: false which I did but the error is still present.
Widget build(BuildContext context) {
return Scaffold(
  resizeToAvoidBottomPadding: false,
  body: Stack(
    children: <Widget>[
      Container(
        padding: EdgeInsets.symmetric(horizontal: 20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Expanded(
              flex: 3,
              child: SizedBox(),
            ),
            _title(),
            SizedBox(
              height: 50,
            ),
            _displayUserNameAndPassword(),
            SizedBox(
              height: 20,
            ),
            _submitButton(),
            Container(
              padding: EdgeInsets.symmetric(vertical: 10),
              alignment: Alignment.centerRight,
              child: Text('Forgot Password ?',
                  style:
                      TextStyle(fontSize: 14, fontWeight: FontWeight.w500)),
            ),
            _divider(),
            _facebookButton(),
            Expanded(
              flex: 2,
              child: SizedBox(),
            ),
          ],
        ),
      ),
      Align(
        alignment: Alignment.bottomCenter,
        child:  _createAccountLabel(),
      ),
    ],
  ),
);

}

A: You need to use ListView instead of Column.
In column when keyboard appears for text field it caused renderflexed overflow error.
Thanks


text:
Q: Delete specific column in an array I have an numpy array of size NxD called X.
I have created a mask of size D represented by a numpy vector with 1 and 0 called ind_delete
I would like to delete all column of X corresponding to 1 in ind_delete.
I have tried:
X = np.delete(X,ind_delete,1)

but it obviously does not work. I have tried to find an easy way to to that on python but as it is trivial in matlab, it seems not as much here. Thanks for pointing out the best way to achieve it.

A: Boolean array indexing:
>>> x = np.array([[1, 2, 3],
...               [4, 5, 6]])
>>> d = np.array([1, 0, 1])
>>> x[:, d==1]
array([[1, 3],
       [4, 6]])

A: You need to create a boolean array and you can select what you want:
X = X[ind_delete!=1]

Selects the positions for where the value is not 1.


text:
Q: finding valid pairs of brackets don't work? I am doing a coding question without looking at the answer and I am struggling to find what's wrong with my thought process

question is to find all combinations of the valid n pairs of brackets

public class Foo{
    public void printCombinations(String prefix, int open, int close, int n){
        if (open > n) {
            return;
        }
        if (close > n) {
            return;
        }
        if (open == n && close == n){
            System.out.println(prefix);
            return;
        }
        printCombinations(prefix + "(", open + 1, close, n);
        printCombinations(prefix + ")", open, close + 1, n);
    }
    public static void main(String []args){
        HelloWorld w = new HelloWorld();
        w.printCombinations("", 0, 0, 3);
    }
}

When I ran this program, it seemed to print out all combinations instead of ones with valid brackets. I was thinking printCombinations(prefix + "(", open + 1, close, n);would ensure that I print opening bracket first then recursively call printCombinations(prefix + ")", open, close + 1, n); I see one output with something like )))(((. How is this possible if ( is added first?

A: it's because after the recursive calls for printCombinations(prefix + "(", open + 1, close, n) are finished on the stack, your code begin to recur printCombinations(prefix + ")", open, close + 1, n). It's why you would get one of string output that begins with ), not because of the order you place these two recursive calls. To fix, you need have a condition under which close is always less than open. As follows,
public class Foo{
    public void printCombinations(String prefix, int open, int close, int n){
        if (open > n) {
            return;
        }
        if (close > n) {
            return;
        }
        if (open == n && close == n){
            System.out.println(prefix);
            return;
        }
        printCombinations(prefix + "(", open + 1, close, n);
        if (close < open) {
            printCombinations(prefix + ")", open, close + 1, n);
        }
    }
    public static void main(String []args){
        Foo w = new Foo();
        w.printCombinations("", 0, 0, 3);
    }
}


text:
Q: Custom CSS Based on ID with appendTo('head') So I am working on a Chrome/Firefox extension that will look for a specific element and extract the innerHTML within it. After that, I need to style it and make the background red. The part that I am struggling with is getting the background color to change to red whenever such element has data in it based on its id. I am using appendTo('head') for the css.
var message = $(node).find('span.mention.style-scope.yt-live-chat-text-message-renderer');
if (message.length < 1) return;
var messageID = $('.style-scope yt-live-chat-text-message-renderer').attr('id');
$('<style type="text/css">.style-scope yt-live-chat-text-message-renderer #id' + messageID + ' { background-color: #FF0000; }</style>').appendTo('head');

The last line is the issue. I have used this code before, but have not attached an id on it, so I am not sure where to go from here on.
Any pointers would be great, and if you need more information, I can do my best to provide you with it. Thanks!
EDIT:
This is what I am trying to target:
<yt-live-chat-text-message-renderer class="style-scope yt-live-chat-item-list-renderer x-scope yt-live-chat-text-message-renderer-0" id="CjkKGkNLYlR2dUNlNjlNQ0ZVT3ZxZ29kR2FrS3ZREhtDTDdxejlxZTY5TUNGY25YbkFvZGR2a0JjdzA%3D" author-type="">

A: #id' + messageID + ' is actually rendering as #id<messageId> instead of #<messageId>
You are missing class identifier . next to yt-.. so css cannot find that element.
Also,
You can just use ID to refer that element, no need to add any other class like .style-scope .yt-live-chat-item-list... as the ID is unique for a page.
It is a very bad practice to add something like this to head.

A: remove #id+messageID  and used #+messageID. please refer the code below:
$('<style type="text/css">.style-scope yt-live-chat-text-message-renderer #' + messageID + ' { background-color: #FF0000; }</style>').appendTo('head');

Your code contains % symbol due to which CSS compiler is not able to find the selector


text:
Q: Mutating array while reading, not enumerating If I have two different threads via GCD accessing an NSMutableArray and one is merely creating a new array based off the mutable array while the other thread is deleting records from the array, should I expect this to be a problem?  That is, shouldn't the copy, which I presume is merely "reading" the array, just get whatever happens to be in the array at that moment? I am not enumerating the array in either thread, but it is still crashing. As soon as I remove the read routine, it works fine.
Here is the "read" :
  dispatch_async(saveQueue, ^{

    NSDictionary*tempstocks=[NSDictionary dictionaryWithDictionary:self.data];

It crashes on this thread with: *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[9]'
Here is what is happening on another thread:
[self.data removeObjectForKey:item];

I know you cannot mutate while enumerating, but I'd think it would be okay to read while mutating, you might not know which version of the mutated object you get, but I wouldn't think this is a problem, but clearly it is. Perhaps the dictionaryWithDictionary method is performing an operation that first sees X objects but by the time the routine is done it contains X-Y objects, thus it is not "capturing" the entire self.data dictionary in one snap when it runs dictionaryWithDictionary and is instead enumerating over self.data which would essentially be the same problem as mutation while enumeration?

A: I guess that you might create three different queues using GCD: one for save, second one for something else and last one to operate with NSMutableArray.
dispatch_async(saveQueue, ^{
    dispatch_barrier_async(_queue, ^{
            NSDictionary*tempstocks=[NSDictionary dictionaryWithDictionary:self.data];
        });
});

dispatch_async(anotherQueue, ^{
    dispatch_barrier_async(_queue, ^{
            [self.data removeObjectForKey:item];
        });
});

It's like @synchronize but using GCD.
More info: GCD Reference/dispatch_barrier_async and http://www.mikeash.com/pyblog/friday-qa-2011-10-14-whats-new-in-gcd.html
EDIT
I have made a couple of performance test in order to understand which of the way is faster:
- (void)usingSynchronized
{
    dispatch_queue_t writeQyeue = dispatch_queue_create("com.tikhop.writeQyeue", DISPATCH_QUEUE_CONCURRENT);
    dispatch_sync(writeQyeue, ^{
        for(size_t i=0; i<10000; i++)
            @synchronized (arr) {
                [arr replaceObjectAtIndex:0 withObject:[NSNumber numberWithInt:1]];
                [arr replaceObjectAtIndex:0 withObject:[NSNumber numberWithInt:2]];
                [arr replaceObjectAtIndex:0 withObject:[NSNumber numberWithInt:3]];
                [arr replaceObjectAtIndex:0 withObject:[NSNumber numberWithInt:4]];
            }
    });
}

- (void)usingGCD
{
    dispatch_queue_t writeQyeue = dispatch_queue_create("com.tikhop.writeQyeue", DISPATCH_QUEUE_CONCURRENT);
    dispatch_sync(writeQyeue, ^{
        for(size_t i=0; i<10000; i++)
            dispatch_barrier_async(_queue, ^{
                [arr replaceObjectAtIndex:0 withObject:[NSNumber numberWithInt:5]];
                [arr replaceObjectAtIndex:0 withObject:[NSNumber numberWithInt:6]];
                [arr replaceObjectAtIndex:0 withObject:[NSNumber numberWithInt:7]];
                [arr replaceObjectAtIndex:0 withObject:[NSNumber numberWithInt:8]];
            });
    });
}

arr = [NSMutableArray arrayWithCapacity:1];
[arr addObject:@(0)];

[self usingSynchronized];
[self usingGCD];

I got the following result:

A: You cannot assume that any operation on NSDictionary is thread-safe. And almost all f them are not. You really need to set up a mutex, @synchronize access to your array or use a gcd serial queue for access.

A: dictionaryWithDictionary: is internally enumerating the argument, so you are basically mutating while enumerating.
Also, in general, you should never write to an object if another thread is going to access it in any way unless you use some sort of synchronization primitive.
Your reasoning that it "reads" whatever it's there at the moment is not valid in general. Here is a little more info on the problems inherent in multithreading Usage of registers by the compiler in multithreaded program


text:
Q: How to Add a Client System To a Server I have recently installed Windows Server 2008 R2 on one my system and now want to add my client to that server.
Almost all the systems have been added but two of them are refusing to add by showing this error
a domain controller for the domain xxxx could not be contacted ..

Any ideas on why this is happening?

A: When you have Active Directory issues, you should first check DNS. If everything looks OK there, you should ask yourself "What DNS issue did I miss?" and then check DNS again.
I'll bet my bonnet that you aren't using the Domain Controller as the DNS server on the clients that are having a problem. Set the IP for the DNS servers on the Windows clients having the issue to use the Domain Controllers and the Domain Controllers alone for DNS.


text:
Q: Может ли пользователь узнать о существовании страницы, ссылок на которую нет Суть вопроса
Вопрос чисто теоретический, касается структуры сайта. Каким образом посетитель сайта может узнать о существовании страницы, на которую не существует ни одной ссылки, за исключением метода тыка в адресной строке?
Пример

На рисунке изображена полная структура сайта. Она состоит из:

*

*Главная, страница белого цвета (Путь: /)

*Страницы с информацией, серый цвет (Пути: /about, /offers, /contacts)

*Страница с информацией об истории, тёмно-серый цвет (Путь: /history)

Пользователь заходит на сайт и видит на шапке три ссылки, каждая из которых ведёт на разные страницы. В страницу с историей основания некой компании, выделенная тёмным цветом, нельзя попасть, так как в шапке, да и везде в общем, ничего не перенаправляет клиента туда.
Итог
Верно ли утверждение, что перебор возможных вариантов в адресной строке для получения доступа в недоступную страницу, является единственным вариантом туда попасть? Может ли продвинутый пользователь каким-нибудь образом получить полную карту сайта?
Вопрос крайне тупой, но очень интересно теоретически знать ответ на него.


text:
Q: I want to build a Chrome extension which automate Ctrl+f with word fed/stored in the tool for all websites I visit I have a requirement to highlight some particular words on any websites I visit. So that I don't have to use control+f manually and find the word on a web page.
I have seen some chrome plugin (Highlight This: finds and marks words
) but that is not finding on all websites maybe only for the website which allows scraping. I have some internal websites where I need to do ctrl+f every time for the same set of words.
Exactly this plugin is as per my requirement but this does not work internal or restricted websites. I know how to create extension but not sure what logic or piece of code would do this work.
When ever I visit a website or any URL the words stored in the plugin should highlight as it gets highlited with ctrl+f.

A: Here's a start. Not fully tested.
  let searchTerms = ['law', 'software', 'news', 'health'];

  let elems = document.querySelectorAll("h1, h2, h3, h4, h5, h6, p, a")
  for (let i = 0, total = elems.length; i < total; i++) {
    let element = elems[i];
    if (element && element.innerText) {
      let innerText = element.innerText;
      for (let j = 0; j < searchTerms.length; j++) {
        const reg = new RegExp(searchTerms[j], 'gi')
        const matches = innerText.toLowerCase().match(reg) || []
        if (matches.length) {
          for (let n = 0; n < matches.length; n++) {
            element.innerHTML = innerText.replace(reg, '' + searchTerms[j] + '');
          }
        }
      }
    }
  }

A: I would use the chrome.storage.sync.set API  chrome.storage.api.  You could set your text that searched and store it in a variable, then everytime you use the extension, you can have it reference that variable.  Without any code, I'm going off of my own experience.  So I'm including a bit of my example to show you how I used the chrome.storage api, so that maybe you could find it useful as well.
Here's a snippet of my code, it is a chrome extension that adds a url to the local storage so that way when I log into a firewall, I don't have to continually copy the string/text I'm wanting to input.
function cfs_add(){
var url = prompt('Please provide url', 'test.com');
chrome.storage.sync.set({'name': url}, function() {
  console.log("saved url!!" );
});
};
cfs_add()

...

chrome.storage.sync.get(['name'], function(results) {
  if(results.variable_name == undefined) {
  }
  document.getElementById('state').innerHTML = "Current URL: " + String(results['name'])
  document.getElementById('state').style.color = "lightblue"

})
Make a function that automatically searches and highlights the word stored in the local storage/chrome.storage.


text:
Q: Virtualenvwrapper environments not visible in finder or terminal Using OSX 10.9.2
Just getting to grips with virtualenv and virtualenvwrapper. I am having an issue where the environments I create with virtualenv are visible in both terminal and finder, but environments that I create with virtualenvwrapper are not.
Here are the steps I take in terminal.
virtualenv virt_env/virt1 --no-site-packages

Successfully creates a virtualenv called virt1
source virt1/bin/activate

Activates the virtualenv
(virt1)localhost:virt_env brendan$

I have several of these virtual environments set up and working and I am able to install packages in each, as I would expect. I am able to switch between them and remove them as necessary. I am also able to see them in Finder and in Terminal.
However when I create virtual environments using virtualenvwrapper it appears that I am able to work with them but I am not able to see them.
Here are the steps I take with virtualenvwrapper
localhost:~ brendan$ mkvirtualenv virt_env/virt4
New python executable in virt_env/virt4/bin/python
Installing setuptools, pip...done.
(virt4)localhost:~ brendan$

I am able to work with this e.g.
(virt4)localhost:~ brendan$ sudo easy_install yolk

And I am able to deactivate and reactivate it. e.g.
deactivate
localhost:~ brendan$
workon virt_env/virt4
(virt4)localhost:~ brendan$

But when I go to finder I am only able to see the environments (virt1, virt2, virt3) that I created via virtualenv and not the environments (virt4) that I created using virtualenvwrapper
I am using these tutorials
Virtualenv
Virtualenvwrapper

A: Make sure that you've defined your WORKON_HOME environment variable to tell virtualenvwrapper where to put your environments (see the documentation)

A: MacOS X is a Unix-based system, and so doesn't list files and directories whose names begin with a dot. You are probably storing your virtualenvs is a directory called .virtualenvs, which is therefore invisible.
For details of how to find the pesky thing see, for example, http://www.macosxtips.co.uk/index_files/quickly-show-hidden-files.php


text:
Q: Posts are not displaying correctly after deactivate So, I have a problem with displaying for a few posts.After a post was deactivated, on main isn't showing anymore, but the space is still here, even if I have an @if condition.By default, on my page I have 7 posts on every page, but here is remaining only the posts which is activated ( table event, column activate)
Here is the code from main

                @foreach($events as $event)
        @if($event->active != 1)

                                category->category_url }}">

category->color }} noticeboard-topic-category">
                                         / {{ $event->category->category }}

                                <?php
                                    $video_content = preg_replace("/]+\>/i", "", $event->information);
                                    preg_match('/src="([^"]+)"/', $video_content, $video);
                                ?>

                                <?php
                                    $match = '';
                                    $str = $event->information;
                                    $start = "";

                                    $pattern = sprintf(
                                        '/%s(.+?)%s/ims',
                                        preg_quote($start, '/'), preg_quote($end, '/')
                                        );

                                    if (preg_match($pattern, $str, $matches)) {
                                        list(, $match) = $matches;
                                    }
                                ?>
                                @if(isset($match) && $match != '')

                                @elseif(isset($video[1]))

                                @else

                                    <?php preg_match('/<img.+src=[\'"](?P<src>.+?)[\'"].*>/i', $event->information, $image); ?>
                                    @if(isset($image['src']))

                                        <?php $img = str_replace('&', '&', $image['src']); ?>

                                    @else

                                        <?php $img = "thumbnail/".$event->user->profile_picture; ?>
                                        @if(@getimagesize($img))

                                        @else
                                            <?php $img = "assets/img/main/img12.jpg"; ?>

                                        @endif
                                    @endif
                                @endif

id }}_{{ Slugify::slugify($event->subject) }}">{{ $event->subject }}

                                    @if($event->user->role[0]->pivot->role_id == 1)

                                    @else

                                    @endif
                user->username }}">{{ $event->user->username }}

 Event

 category->category_url  }}">{{ $event->category->category }}

                                <?php
                                    $information = preg_replace("/]+\>/i", "", $event->information);
                                    $Output = preg_replace('//i','', $information);
                                ?>

{{ str_limit(trim(strip_tags(preg_replace(array('/\s{2,}/', '/[\t\n]/'), ' ', $Output))), 200) }}

id }}_{{ Slugify::slugify($event->subject) }}" name="{{ $event->subject }}" description="{{ $event->subject }}">

id }}_{{ Slugify::slugify($event->subject) }}" name="{{ $event->subject }}" description="{{ $event->subject }}">

id }}_{{ Slugify::slugify($event->subject) }}" name="{{ $event->subject }}" description="{{ $event->subject }}">

id }}_{{ Slugify::slugify($event->subject) }}" name="{{ $event->subject }}" description="{{ $event->subject }}">
                                            id }}_{{ Slugify::slugify($event->subject) }}">

{!! $event->event_comment_count !!}

{!! $event->views !!}

id }}" id="changeview">id }}">{!! $event->event_like_count !!}

                                id }}_{{ urlencode(str_replace(' ', '-', $event->subject)) }}">Read more...

          @endif
                @endforeach

My controller
public function viewAllEvent($category_id = null,$event_type_id = null,$country_id = null,$starting_date = null,$username = null,$search = null,$page = null)
    {

        // $eventrecommended = Event::with('user','category','country','event_type','event_like')->withCount('event_like','event_comment')->whereHas('user.contact', function ($query) use ($id) {
        //                 $query->where('contacts.user_id', '=', $id);
        //             })->orWhere('events.public', '=', 1)->orWhere('events.user_id', '=', $id);
        // if($page == ""){
        //     return redirect('view-all-event/1');
        // }

            $data = $this->data;

            $data['title'] = "View All Event";
            $data['breadcrumbs'] = "Events";

            $page = Input::get('page');
            $perPage = 7;
            $offset = ($page * $perPage) - $perPage;

            $data['evnetTypeList'] =  \App\EventType::all();
            $data['countryList'] = [''=>'Country'] + \App\Country::lists('country','code')->toArray();

            $data['category'] = Input::get('category');
            $data['event_type'] = Input::get('event_type');
            $data['country'] = Input::get('country');
            $data['starting_date'] = Input::get('starting_date');
            $username = Input::get('username');
            $search = Input::get('search');
            $data['login_user'] = $username;
            $data['search'] = $search;

            $categoryID =  \App\Category::pluck('id');

            $event = Event::with('user','category','country','event_type')->withCount('event_like','event_comment')->whereHas('user', function($query) {
                        $query->where('deleted_at', '=', null);
                    })->whereIn('category_id',$categoryID);

            $eventrecommended = Event::with('user','category','country','event_type','event_like')->whereHas('user', function($query) {
                    $query->where('deleted_at', '=', null);
                })->withCount('event_like','event_comment')->whereIn('category_id',$categoryID);

            if ($user = Sentinel::check())
            {
                if(!$user->inRole('admins'))
                {
                    $id = $user->id;

                    $event = $event->Where(function($query1) use($id){
                            $query1->where('public','=', 1)->orWhereHas('user.contact', function ($query) use ($id) {
                                $query->where('user_id', '=', $id);
                                })->orWhere('user_id','=',$id);
                    });

                    $eventrecommended = $eventrecommended->Where(function($query1) use($id){
                            $query1->where('public','=', 1)->orWhereHas('user.contact', function ($query) use ($id) {
                                $query->where('user_id', '=', $id);
                                })->orWhere('user_id','=',$id);
                    });
                }
            }
            else{
                $event = $event->where('public','=', 1);
                $eventrecommended = $eventrecommended->where('public','=', 1);

            }

            return view('event.view_all_event',$data);
    }

And in the second photo is my noticeboard, which I have same problem...

A: Add to your $event in your controller
where('active', 0)

and delete the if statment in your view
 @if($event->active != 1)
 @endif


text:
Q: SBT 0.13.0 - can't expand macros compiled by previous versions of Scala Given the following:
src/main/scala/net/Equals5.scala
package net

import scala.language.experimental.macros
import scala.reflect.macros.Context

case class Equals5(value: Int) {
    require(value == 5)
}

object Equals5 {
    implicit def wrapInt(n: Int): Equals5 = macro verifyIntEquals5

    def verifyIntEquals5(c: Context)(n: c.Expr[Int]): c.Expr[Equals5] = {
    import c.universe._

    val tree = n.tree match {
      case Literal(Constant(x: Int)) if x == 5 =>
        q"_root_.net.Equals5($n)"
      case Literal(Constant(x: Int)) =>
        c.abort(c.enclosingPosition, s"$x != 0")
      case _ =>
        q"_root_.net.Equals5($n)"
    }
    c.Expr(tree)
  }
}

build.sbt
val paradiseVersion = "2.1.0-M5"

scalaVersion := "2.11.7"

libraryDependencies += "org.scala-lang" % "scala-reflect" % "2.11.7"

libraryDependencies += "org.scalatest" % "scalatest_2.10" % "3.0.0-M7"

project/build.properties
sbt.version=0.13.0

I can compile successfully, but trying to run the following test:
src/test/scala/net/Equals5Test.scala
package net

import org.scalatest.Matchers

import org.scalatest._
import org.scalatest.prop.Checkers._

class Equals5Test extends FlatSpec with Matchers {

    "Trying to create an `Equals5` case class with an invalid Int" should "fail to compile" in {
        "Equals5(-555)" shouldNot compile
    }
}

gives a compile-time error:
.../Equals5Test.scala:11: can't expand macros compiled
      by previous versions of Scala
[error]         "Equals5(-555)" shouldNot compile
[error]                                   ^

Looking at this answer, I expected that using scala 2.11 with sbt 0.13.0 would've fixed this issue.
Please let me know how to resolve this compile-time error.

A: You are specifically requesting ScalaTest version which is compiled for Scala 2.10, so its macros like compile won't be expanded correctly (and it's quite likely not to be compatible with Scala 2.11 in other ways as well). (Also current SBT version is 0.13.9, so you may want to update to it as well.)


text:
Q: Which would be efficient on Multi Core system - A process with multiple threads or multiple processes with a single thread? Suppose there is a system with 8 cores having 1 thread each and 32 GB of RAM. I want to run in case 1 -> 4 threads of in a single process (threads are independent so no synchronization needed) and case 2 -> 4 processes with single threads each. Keeping aside the memory consumption and the time taken to create them, is there going to be a significant difference in execution times in the above cases on a Linux system ? Why/why not ?
Most of the operating system books deal with single core and single threaded systems.

A: Switching threads is cheaper than switching processes since switching threads only requres changing the stack. Switching processes may require invalidating the TLB and slow loading the new page mappings.


text:
Q: How can I find private IP address of a device? I 'm trying to detect IP address of a Wireless Access Point device, connected via Ethernet on my router. Router's configuration page shows status of the Ethernet port is up, but no device connected.
If I 'm correct, any device attached on the router, requests for a private IP address (at least this happens when I attach another device). However, seems that no IP has been assigned on this device. Is this possile?
nmap result:
Starting Nmap 6.00 ( http://nmap.org ) at 2014-03-09 18:30 EET
Nmap scan report for 192.168.1.1
Host is up (0.058s latency).
Not shown: 997 closed ports
PORT     STATE SERVICE
22/tcp   open  ssh
23/tcp   open  telnet
8080/tcp open  http-proxy

Nmap scan report for 192.168.1.103
Host is up (0.00019s latency).
All 1000 scanned ports on 192.168.1.103 are closed

Nmap scan report for 192.168.1.111
Host is up (0.00083s latency).
Not shown: 991 closed ports
PORT     STATE SERVICE
135/tcp  open  msrpc
139/tcp  open  netbios-ssn
445/tcp  open  microsoft-ds
1025/tcp open  NFS-or-IIS
1026/tcp open  LSA-or-nterm
1027/tcp open  IIS
1028/tcp open  unknown
1029/tcp open  ms-lsa
1030/tcp open  iad1

Nmap scan report for 192.168.2.68
Host is up (0.045s latency).
Not shown: 999 closed ports
PORT   STATE    SERVICE
25/tcp filtered smtp

Nmap done: 65536 IP addresses (4 hosts up) scanned in 172.36 seconds

Hosts detected:

*

*192.168.1.1    -> Router

*192.168.1.103  -> VirtualBox

*192.168.1.111  -> PC

*192.168.2.68   -> unknown

How can I ensure if an IP has already been assigned and how can I find it's IP?

A: *

*Connect AP directly to PC

*Start tcpdump -ni eth0 on PC

*Reboot AP

*Look carefully to tcpdump output. AP should announce his IP, or try to request it via DHCP.

A: Try logging into your router and see what ip address it has assigned.
I am correct to think that your subnet mask is 255.255.255.0 on your hosts?
You can also scan all active ip address using an app called angry ip. http://angryip.org/w/Download


text:
Q: Parse elements from json array using boost here is the json I want to parse:
{"jsonrpc":"2.0","method":"subscription","params":{"channel":"book.BTC-PERPETUAL.raw","data":{"type":"change","timestamp":1635513739435,"prev_change_id":6807100702,"instrument_name":"BTC-PERPETUAL","change_id":6807100703,"bids":[["new",60772.0,50.0], "demo"],"asks":[]}}}

and here is my code to get the values from a child:
boost::property_tree::ptree pt;
boost::property_tree::read_json(ss, pt);
    std::cout << "\njsonrpc: " << pt.get<std::string>("jsonrpc") << std::endl;
    std::cout << "\nmethod: " << pt.get<std::string>("method") << std::endl;
    std::cout << "\nparams: " << pt.get<std::string>("params") << std::endl;
    std::cout << "\nparams.channel: " << pt.get<std::string>("params.channel") << std::endl;
    std::cout << "\nparams.data: " << pt.get<std::string>("params.data") << std::endl;
    std::cout << "\nparams.data.timestamp: " << pt.get<std::string>("params.data.timestamp") << std::endl;
    std::cout << "\nparams.data.instrument_name: " << pt.get<std::string>("params.data.instrument_name") << std::endl;

but when I tried to parse the array values like ("params.data.bids") it return nothing
I need help in parsing an array

A: You should use a JSON Library:
Live On Compiler Explorer
#include <boost/json.hpp>
#include <boost/json/src.hpp> // header-only for Compiler Explorer
#include <iostream>
namespace json = boost::json;

int main() {
    auto req = json::parse(R"({
            "jsonrpc": "2.0",
            "method": "subscription",
            "params": {
                "channel": "book.BTC-PERPETUAL.raw",
                "data": {
                    "type": "change",
                    "timestamp": 1635513739435,
                    "prev_change_id": 6807100702,
                    "instrument_name": "BTC-PERPETUAL",
                    "change_id": 6807100703,
                    "bids": [
                        ["new", 60772.0, 50.0], "demo"],
                    "asks": []
                }
            }
        })") .as_object();

    auto& params = req["params"].as_object();
    auto& data   = params["data"].as_object();
    std::cout << "jsonrpc:                     " << req["jsonrpc"].as_string()    << "\n";
    std::cout << "methdo:                      " << req["method"].as_string()     << "\n";
    std::cout << "params.channel:              " << params["channel"].as_string() << "\n";
    std::cout << "params.data:                 " << params["data"]                << "\n";
    std::cout << "params.data.timestamp:       " << data["timestamp"]             << "\n";
    std::cout << "params.data.instrument_name: " << data["instrument_name"]       << "\n";

}

Prints
jsonrpc:                     "2.0"
methdo:                      "subscription"
params.channel:              "book.BTC-PERPETUAL.raw"
params.data:                 {"type":"change","timestamp":1635513739435,"prev_change_id":6807100702,"instrument_name":"BTC-PERPETUAL","change_id":6807100703,"bids":[["new",6.0772E4,5E1],"demo"],"asks":[]}
params.data.timestamp:       1635513739435
params.data.instrument_name: "BTC-PERPETUAL"
bid: ["new",6.0772E4,5E1]
bid: "demo"

Adding the asks/bids:
for (auto& bid : data["bids"].as_array()) {
    std::cout << "bid: " << bid << "\n";
}
for (auto& ask : data["asks"].as_array()) {
    std::cout << "ask: " << ask << "\n";
}

Prints
bid: ["new",6.0772E4,5E1]
bid: "demo"

Alternative / Bonus
You can also use value_to conversion to your own types:
struct request {
    std::string jsonrpc, method;
    struct params_t {
        std::string channel;
        struct data_t {
            std::string type;
            size_t timestamp, prev_change_id, change_id;
            std::string instrument_name;
            std::vector<json::value> bids, asks;
        } data;
    } params;
};

See it Live
Or flattened:
struct request {
    using values = std::vector<json::value>;
    std::string jsonrpc, method, channel, type, instrument_name;
    size_t      timestamp, prev_change_id, change_id;
    values      bids, asks;

    friend request tag_invoke(json::value_to_tag<request>, json::value const& v)
    {
        auto& params = v.at("params");
        auto& data   = params.at("data");
        return request{
            value_to<std::string>(v.at("jsonrpc")),
            value_to<std::string>(v.at("method")),
            value_to<std::string>(params.at("channel")),
            value_to<std::string>(data.at("type")),
            value_to<std::string>(data.at("instrument_name")),
            value_to<size_t>(data.at("timestamp")),
            value_to<size_t>(data.at("prev_change_id")),
            value_to<size_t>(data.at("change_id")),
            value_to<values>(data.at("bids")),
            value_to<values>(data.at("asks")),
        };
    }
};

See it Live As Well
#include <boost/json.hpp>
#include <boost/json/src.hpp> // header-only for Compiler Explorer
#include <iostream>
namespace json = boost::json;

struct request {
    using values = std::vector<json::value>;
    std::string jsonrpc, method, channel, type, instrument_name;
    size_t      timestamp, prev_change_id, change_id;
    values      bids, asks;

    friend request tag_invoke(json::value_to_tag<request>, json::value const& v)
    {
        auto& params = v.at("params");
        auto& data   = params.at("data");
        return request{
            value_to<std::string>(v.at("jsonrpc")),
            value_to<std::string>(v.at("method")),
            value_to<std::string>(params.at("channel")),
            value_to<std::string>(data.at("type")),
            value_to<std::string>(data.at("instrument_name")),
            value_to<size_t>(data.at("timestamp")),
            value_to<size_t>(data.at("prev_change_id")),
            value_to<size_t>(data.at("change_id")),
            value_to<values>(data.at("bids")),
            value_to<values>(data.at("asks")),
        };
    }
};

int main() {
    auto req = value_to<request>(json::parse(R"({
            "jsonrpc": "2.0",
            "method": "subscription",
            "params": {
                "channel": "book.BTC-PERPETUAL.raw",
                "data": {
                    "type": "change",
                    "timestamp": 1635513739435,
                    "prev_change_id": 6807100702,
                    "instrument_name": "BTC-PERPETUAL",
                    "change_id": 6807100703,
                    "bids": [
                        ["new", 60772.0, 50.0], "demo"],
                    "asks": []
                }
            }
        })"));

    std::cout << "jsonrpc:              " << req.jsonrpc << "\n";
    std::cout << "methdo:               " << req.method << "\n";
    std::cout << "params.channel:       " << req.channel << "\n";
    std::cout << "data.timestamp:       " << req.timestamp << "\n";
    std::cout << "data.instrument_name: " << req.instrument_name << "\n";

    for (auto& bid : req.bids) std::cout << "bid: " << bid << "\n";
    for (auto& ask : req.asks) std::cout << "ask: " << ask << "\n";
}


text:
Q: some tables wont load into MySQL after running. How do i find the specific problem as im using spring boot to set up my schema, advice? My class among others don't generate in mysql whilst schema is created. Other tables even those that reference these tables are generated but, I don't know what's causing the problem. How can i find the specific sql related issue? Whats worse is though they tell me where they dont complete the command and how its processed.I used this technology for an earlier project.
my class
@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "appetizer")
public class Appetizer {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column( nullable = false)
    private String name;
    @Column( nullable = false)
    private float price;
    @Column( nullable = false)
    private String desc;
    @OneToMany(mappedBy="appetizer", cascade = CascadeType.ALL)
    private Set<Review> reviews;

    public Appetizer(String name, float price, String desc) {
        this.name = name;
        this.price = price;
        this.desc = desc;
    }
}

its reference
@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "reservation")
public class Reservation {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column( nullable = false)
private String email;

@Column( nullable = false)
private int tableNum;
@Column( nullable = false)
private float price;
@Column( nullable = false)
private LocalDateTime dateOfEvent;
@Column( nullable = false)
private String firstName;
@Column( nullable = false)
private String lastName;

@OneToMany( mappedBy="reservation", cascade = CascadeType.ALL)
private Set<Order> orders;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "transaction_id")
private Transaction transaction;
public Reservation(String email, int tableNum, float price, LocalDateTime dateOfEvent, String firstName, String lastName) {
    this.email = email;
    this.tableNum = tableNum;
    this.price = price;
    this.dateOfEvent = dateOfEvent;
    this.firstName = firstName;
    this.lastName = lastName;
}
}

error stack
  org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "create table appetizer (id bigint not null auto_increment, desc varchar(255) not null, name varchar(255) not null, price float not null, primary key (id)) engine=InnoDB" via JDBC Statement
    at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
    at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlString(AbstractSchemaMigrator.java:581) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
    at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlStrings(AbstractSchemaMigrator.java:526) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
    at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.createTable(AbstractSchemaMigrator.java:293) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
    at org.hibernate.tool.schema.internal.GroupedSchemaMigratorImpl.performTablesMigration(GroupedSchemaMigratorImpl.java:74) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
    at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.performMigration(AbstractSchemaMigrator.java:220) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
    at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.doMigration(AbstractSchemaMigrator.java:123) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:196) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:85) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:335) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:471) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1498) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58) ~[spring-orm-5.3.20.jar:5.3.20]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.3.20.jar:5.3.20]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:409) ~[spring-orm-5.3.20.jar:5.3.20]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:396) ~[spring-orm-5.3.20.jar:5.3.20]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.3.20.jar:5.3.20]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863) ~[spring-beans-5.3.20.jar:5.3.20]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800) ~[spring-beans-5.3.20.jar:5.3.20]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620) ~[spring-beans-5.3.20.jar:5.3.20]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.20.jar:5.3.20]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.20.jar:5.3.20]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.20.jar:5.3.20]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.20.jar:5.3.20]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.20.jar:5.3.20]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1154) ~[spring-context-5.3.20.jar:5.3.20]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:908) ~[spring-context-5.3.20.jar:5.3.20]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.20.jar:5.3.20]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:734) ~[spring-boot-2.7.0.jar:2.7.0]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408) ~[spring-boot-2.7.0.jar:2.7.0]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:308) ~[spring-boot-2.7.0.jar:2.7.0]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306) ~[spring-boot-2.7.0.jar:2.7.0]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1295) ~[spring-boot-2.7.0.jar:2.7.0]
    at com.divinpopina.demo.DivinpopinaApplication.main(DivinpopinaApplication.java:10) ~[classes/:na]
Caused by: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc varchar(255) not null, name varchar(255) not null, price float not null, pr' at line 1
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120) ~[mysql-connector-java-8.0.29.jar:8.0.29]
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.29.jar:8.0.29]
    at com.mysql.cj.jdbc.StatementImpl.executeInternal(StatementImpl.java:763) ~[mysql-connector-java-8.0.29.jar:8.0.29]

my properties
##for crud application
# DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url=jdbc:mysql://localhost:3306/divinapopina?useSSL=false&serverTimezone=UTC&useLegacyDatetimeCode=false
spring.datasource.username=root
spring.datasource.password=***** //the stars arent the password just censored.
## dont know what this one does
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# Hibernate
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type=TRACE

##for log in
spring.jpa.show-sql=true

A: You can not have a field named 'desc' in MySQL. It is a reserved keyboard that MySQL uses. All reserved keywords: here.

A: try adding the value to your join table by fetch= lazy or eager


text:
Q: Will std::list::back() produce core dump? Imagine that there are lots of threads and every thread will do one of three below operation:
auto a = list.back(); // without mutex protection
list.pop_back();      // with mutex protection, guarantee list is not empty
list.push_front();    // with mutex protection

It is pretty sure that operation 1) will get unpredictable value.
Will operation 1) cause core dump?
PS: Elements of list is a struct containing a shared_ptr and a integer. I only want to get the value of integer and I can handle the unexpected value sometimes. What I want is never find core dump.
I tried call list.back() first and then pop_back()
or
call list.back() when list is empty().
All tries cannot produce core dump.

A: It is guaranteed that operation 1 causes Undefined Behavior. Possible forms of Undefined Behavior include segfaults and/or core dumps, but also deleting every file on your hard disk.
What is not guaranteed is the exact form of Undefined Behavior you get. This can even vary from run to run. (Assuming of course that you get the chance of running your program again, before your harddisk is erased).
If you can live with an "unpredictable" value, and want less overhead then a mutex, then there's std::atomic<> with memory_order_relaxed. But that's mostly useful for a single value, not for a complex datastructure like std::list.
In short: lock the mutex on every list operation.


text:
Q: Redhat OSP13 undercloud upgrade fails Error at the end :
2019-12-20 17:07:40,622 INFO:
2019-12-20 17:07:40,623 INFO: [2019-12-20 17:07:40,621] (os-refresh-config) [ERROR] Aborting...
2019-12-20 17:07:40,641 DEBUG: An exception occurred
Traceback (most recent call last):
  File "/usr/lib/python2.7/site-packages/instack_undercloud/undercloud.py", line 2441, in install
    _run_orc(instack_env)
  File "/usr/lib/python2.7/site-packages/instack_undercloud/undercloud.py", line 1618, in _run_orc
    _run_live_command(args, instack_env, 'os-refresh-config')
  File "/usr/lib/python2.7/site-packages/instack_undercloud/undercloud.py", line 675, in _run_live_command
    raise RuntimeError('%s failed. See log for details.' % name)
RuntimeError: os-refresh-config failed. See log for details.
2019-12-20 17:07:40,643 ERROR:
#############################################################################
Undercloud upgrade failed.

Reason: os-refresh-config failed. See log for details.

While looking at the logs, I found there was a warning :
Warning: ModuleLoader: module 'openstacklib' has unresolved dependencies - it will only see those that are resolved. Use 'puppet module list --tree' to see information about modules.

There seems to be a lot of 'Unmet Dependencies' when I run 'puppet module list --tree' is run. I tried installing one of them manually using 'puppet module install' command but the dependency still seems to be present.
Is there anything else to be done to get the undercloud upgrade to work ?


text:
Q: Pyspark - Groupby and collect list over multiple columns and create multiple columns I have the below dataframe over which I am trying to group by and aggregate data.
Column_1 Column_2 Column_3
A        N1       P1
A        N2       P2
A        N3       P3
B        N1       P1
C        N1       P1
C        N2       P2

Required Output:
Column_1 Column_2 Column_3
A        N1,N2,N3 P1,P2,P3
B        N1       P1
C        N1,N2    P1,P2

I am able to do it over one column by creating a window using partition and groupby.
Then I use collect list and group by over the window and aggregate to get a column. THis works for one column.
How to perform the same over 2 columns. Kindly help

A: The agg function of the group by can take more than one aggreation function. You can add collect_list twice:
df.groupby('Column_1').agg(F.collect_list('Column_2'), F.collect_list('Column_3')).orderBy('Column_1').show()

prints
+--------+----------------------+----------------------+
|Column_1|collect_list(Column_2)|collect_list(Column_3)|
+--------+----------------------+----------------------+
|       A|          [N1, N2, N3]|          [P1, P2, P3]|
|       B|                  [N1]|                  [P1]|
|       C|              [N1, N2]|              [P1, P2]|
+--------+----------------------+----------------------+

For a simple grouping there is no need to use a Window.


text:
Q: What is the `unit` setting used for in ElasticSearch's geo distance sort? In the documentation it says:

unit
  The unit to use when computing sort values. The default is m (meters).

How is the unit setting used? Is the sorting process affected by the unit chosen? For example, if I set it to miles (mi) would I get a less granular sort than if I used meters (m)? I don't need the distance value for each record in the results, so it does not matter to me which unit is used, unless it does affect the accuracy of the sort.
https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-sort.html#geo-sorting

A: The sort is apply after the unit conversion. Lucene, makeDistanceValueSource return the distance in the desired units (KM, Yard...) and the sort if apply after that.
Also note the accurate is so high, i am really not sure changing units could affect the sort order ;)


text:
Q: BufferedReader sometimes read text, sometimes doesn't I'm trying to read from a .java the methods I have on it, also the classes, I'm using taggs to identify them and stored them, the problem is that using BufferedReader sometimes just doesn't work, the buffer skips a lot of lines for a reason that I can't understand, sometimes when checking the file by myself I just put random spaces between lines, and that fixes some parts, but I can't get the Buffer read all my text without skipping anything, my code so far is like this:
    public class ReadFile {
        public static void main(String[] args) {
        int numclas=0,numbase=0,numbaseagr=0,numbmet=0,numag=0;
        String mt="//MT";
        String[] nomclass2 = new String[10];
        String[] nommetodo2 = new String[50];
        boolean metodo=false;
        BufferedReader in = null;
        try {
          in = new BufferedReader(new FileReader("\\Program.java"));
          String read = null;
          while ((read = in.readLine()) != null) {
          read = in.readLine();
          String[] splited = read.trim().split("\\s+");

          for(int i=0;i<splited.length;i++){
            System.out.println(splited[i]);

            if(splited[i].equals("class")){
               nomclass2[numclas]=splited[i+1];
               numclas=numclas+1;
        }

           if (splited[i].equals(mt)){
            metodo=true;
        }

            if (splited[i].equals("public")){
                if (splited[i+1].equals("static")){
                    nommetodo2[numbmet]=splited[i+3];
                    numbmet=numbmet+1;
                }
                if (splited[i+1].equals("int")||splited[i+1].equals("double")||splited[i+1].equals("String")||splited[i+1].equals("boolean")){
                nommetodo2[numbmet]=splited[i+2];
                numbmet=numbmet+1;
                }

        if (splited[i].equals("int")||splited[i].equals("double")||splited[i].equals("String")||splited[i].equals("boolean")){
                nommetodo2[numbmet]=splited[i+1];
                numbmet=numbmet+1;
                }
        metodo=false;
        }

        if ((splited[i].equals("int")||splited[i].equals("double")||splited[i].equals("String")||splited[i].equals("boolean"))&&metodo){
                nommetodo2[numbmet]=splited[i+1];
                numbmet=numbmet+1;
                metodo=false;
                }

        }

}
 } catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
 } finally {
try {
    in.close();
} catch (Exception e) {
}
 }

Now let me show you the .java I'm trying to read:
 import java.text.DecimalFormat;
 import java.io.*;
 //Main file of the program 1
 public class Program1 {
  //MT
  public static void main (String args []) {
  DecimalFormat format=new DecimalFormat("##.##");
  System.out.println("How many data do you want to insert?");
  int num=Leer.Int();
  Fila lista=new Fila();
  Fila lista2=new Fila();
  double x=0.0;
  for(int i=0;i<num;i++){
  x=Leer.Double();
  lista.addNum(x);
        }
    double prom=0.0;
    double desv=0.0;
    prom=lista.getprom();
    desv=lista.getdevst();
    System.out.println("The mean for column 1 is: "+format.format(prom));
    System.out.println("The Std.Dev for column 1 is: "+format.format(desv));
    System.out.println("How many data do you want to insert?");
num=Leer.Int();
x=0.0;
for(int i=0;i<num;i++) {
x=Leer.Double();
lista2.addNum(x);
        }
    prom=0.0;
desv=0.0;
prom=lista2.getprom();
desv=lista2.getdevst();
    System.out.println("The mean for column 2 is: "+format.format(prom));
System.out.println("The Std.Dev for column 2 is: "+format.format(desv));
    }
}

And the result when I print the array
Date:
12/12/12
import
java.text.DecimalFormat;
//Main
file
of
the
program
1
//MT
DecimalFormat
format=new
DecimalFormat("##.##");
so on...

See how in the //MT the Buffer skips a lot of lines, a lot of this is happening (see how it ignores the first lines of the program), and I don't know how to fix it, because sometimes when I try to "fix it" and add some spaces in the lines, I get a nullpointer and the program ends.
Any help will be appreciated, thank you.

A: This is just a partial answer - at the very least your program is skipping every other line:
while ((read = in.readLine()) != null)

will read a line from the file. The line is immediately discarded because the immediately following statement:
read = in.readLine();

reads and processes the next line from the file.
(also, 'splited' should be 'splitted' along with numerous other spelling mistakes but they're not really affecting your program, just it's readability :-))


text:
Q: Things to consider while upgrading to domino 9.0 from domino 8.5.3? Need suggestions regarding upgrading our servers from 8.5.3 to 9.0
Currently our domino server and notes client that developers using are of version 8.5.3 with UP1.
I saw there are many new features and useful fixes done 9.0.
We are planning to upgrade to 9.0. Please let me know what the things to be consider for successful upgrade, what will happen to databases created in 8.5.3, and does controls used from Extension library?
Any other important points to be considered for this.

A: The general upgrade questions better belong onto the serverfault forum. However there are a few things you want to look at when upgrading to 9.x:

*

*Make it the latest version: 9.0.1

*There can be only one: make sure that you don't carry the 8.5x Extlib forward. The 9.0 library contains all 8.x controls. Check if you had to "hack around" some of the behaviours and retest those

*Take advantage of the new OpenNTF Domino API

*Use the new IBM OneUI 3.0.2 (unless your are into Bootstrap of course)

*Use the new ability to send embedded experience eMails

*Recheck that you use VersionControl and ODS51/52 on all your databases

*Boost your Designer Performance thx @timtripcony

... and use the upgrade cheat sheet - works well for any version


text:
Q: Retrieve huge amount of data in Web API I have a web api which allows the user to retrieve data real time and by batch. The problem however is that I have a data which has over 30 million of records which causes a bottleneck in a by batch request. I use paging in my get method which returns a default of 10 records per api request but still the 10 records take time in retrieving because of the bulk pull of data.
Here is the sample of my get method :
 public async Task<IHttpActionResult> Get(int pageno = 1, int pagesize = 10)
    {
        int skip = (pageno - 1) * pagesize;
        int total = db.webapi_customer_charges.Count();
        var cc = await db.webapi_customer_charges
            .OrderBy(c => c.hospital_number)
            .Skip(skip)
            .Take(pagesize)
            .ToListAsync();

        return Ok(new Paging<webapi_customer_charges>(cc, pageno, pagesize, total));
    }

Is there a way or workaround or like best practice when it comes to retrieval of huge amount of data ? Thank you.

A: Not sure how you can do it with EF, since I assume it retrieves the whole set before you can skip or take, but I think it would be faster if you called a stored proc on Sql Server side and just pass in the min and max row numbers. That way you would only get the amount of data you need from the server on each call.
Here is a link to how you can call a stored proc with EF. If you don't find a better solution give it try it should be quite simple to make a select and use the ROW_NUMBER() in Sql to filter based on your input params.


text:
Q: Custom attributes? Is it possible to assign custom attributes to symbols and check them later?
SetAttributes[a, b]

says
Attributes::attnf: b is not a known attribute.

A: No, I do not believe it is.  As the documentation for your error message says:

The attributes available in each version of Mathematica are fixed and cannot be changed.

The system attributes are low level properties that fundamentally change the evaluation of symbols.  I think it makes sense that these are not mixed with high-level user constructs, even though at times that would be quite convenient.
For an alternative remember that you can attach Options to a symbol, e.g.:
Options[a] = {"Attributes" -> {"b"}};

OptionValue[a, "Attributes"]

{"b"}

You could also use a single DownValues rule such as:
a["Attributes"] = {"b"};

a["Attributes"]

{"b"}


text:
Q: How to concatenate elements of two list to form a new list (pandas.DataFrame) I am trying to use DataFrame from Pandas. How can I append calculated values in a for loop to pandas.DataFrame Sequentially ?.
One way around is to push all calculated values into an arrays (wlines and peaktype) and select elements based on indexing into a new array (new_list) and pass the new_list to DataFrame. For example (see below):
wlines = [427.397, 431.958, 450.235, 557.029,  587.092, 605.613, 645.629,
          665.223, 669.923, 681.311, 690.468]

peaktype = [0.5,    0.5,    1.0,    0.5,    1.0,    0.5,    0.5,    0.5,
            0.5,    0.5,    0.5]

new_list = [427.397, 0.5]


text:
Q: what is a coloring in set theory? I've been interested in the Open Coloring Axiom,  but I couldn't find a formal definition for Coloring. Is there an actual definition for Coloring? Is a coloring a function?

A: A coloring of a set $A$ with a set $C$ of colors is a function $f:A\to C$.  Usually (and in particular in OCA) the set $A$ being colored is obtained from some other set $X$, for example as the set of $2$-element subsets of $X$.
A coloring $f$ as above is almost equivalent to a partition of $A$ into pieces indexed by $C$, namely the pieces $f^{-1}(\{c\})$ for $c\in C$. Here "almost" refers to the detail that pieces in a partition are supposed to be nonempty, whereas $f$ is not required to be surjective.