text:
Q: Get the elements of subsets in Balanced Partition using Backpointers I want to implement the Balanced Partition probelm and get the elements of the subsets using backpointers.
I have a question about Backpointers:
With the help of MIT's Dynamic Programming Practice Problems  Nr. 7 and this example code, I managed to get a working program in Processing (since I am a Programming novice...).
Now I want to be able to get the elements of both subsets.
In the MIT Video it is explained that this can be achieved "using the standard trick of maintaining backpointers".
Does anybody have an idea how this could be done?
int N=4;
int[] Weights=new int[N];
int Deviation=5;

void setup()
{
 for(int i=0;i<N;i++)
{
 Weights[i]=10+int(random(-Deviation, Deviation));
 println(i+"   "+Weights[i]);
}

println("-------------------");

BalancedPartition(Weights,N);

}

void BalancedPartition ( int a[] , int n ){

    int sum = 0;
    for( int i = 0 ; i < n ; i++)
        sum += a[i];

    int[] s = new int[sum+1];

    s[0] = 1;
    for(int i = 1 ; i < sum+1 ; i++)
    {
      s[i] = 0;
    }

    int ans = 0;
    int diff = 1000000000;

    for(int i = 0 ; i < n ; i++)
    {
        for(int j = sum ; j >= a[i] ; j--)
        {

            s[j] = s[j] | s[j-a[i]];
            if( s[j] == 1 )
            {

                if( diff > abs( (sum/2) - j) )
                {

                    diff = abs( (sum/2) - j );
                    ans = j;

                 }

            }

        }
    }
println("Sum Set 1: "+ans+"        Sum Set 2: "+(sum-ans)+"          Difference: "+abs(ans-(sum-ans)) );

}


text:
Q: MediaWiki: Automatic font color change to wiki-specific colors Is it possible to make the font color change to the wiki-specific default text (or default color of links) automatically?
For example, you want to define font color with the font tag, and you insert a value that causes the font color to automatically change to the text (or link) color of the wiki.
Something like this: This text will appear in the default link color of this wiki.

A: The link color is set by a CSS rule that looks something like this:
a {
    text-decoration: none;
    color: #0645ad;
    background: none;
}

Since this rule applies only to a elements (i.e. links), the only way (short of JavaScript trickery) to make it automatically apply to a given piece of text on any wiki is to actually wrap that piece of text in a link.  Sorry.
That said, if you just want a piece of text that has a different color on different wikis, that's easy — just wrap it in a span element, give the span a custom class name, and add a CSS rule to your wiki's site stylesheet (Common.css) defining what color the text should have, like this:
HTML (on wiki page):
This text will appear in a color defined in this
wiki's site stylesheet.

CSS (in Common.css):
span.mysterious {
    color: #0645ad;  /* make it look like a link */
}

That way, if you copy the page to a different wiki with different CSS, the text will look different.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to access a webpage that is constructed using Javascript? How can I access data inside the website that is constructed using Javascript. The login is regular and I use Jsoup, however, when I need to execute built-in javascript, Jsoup doesn't see the final version. Unfortunatelly, Android is not a PC and doesn't allow HtmlUnit to be used (as far as I know).
How do I approach getting data generated by JavaScript without using HtmlUnit?


text:
Q: Printing each number in new line in Scheme I need a help to convert this Pascal code to Scheme code:
program reverseorder;
type
arraytype = array [1..5] of integer;

var
arr:arraytype;
i:integer;

begin

for i:=1 to 5 do
    arr[i]:=i;

for i:=5 downto 1 do
    writeln(arr[i]);

end.

I want to accesses to a specific atom and its seems there aren't iteration method in Scheme.

A: There are many ways to tackle this problem. With the online interpreter you're using you'll be limited to vanilla Scheme, and the solution will be more verbose than needed, using recursion:
(define lst '(1 2 3 4 5))

(let loop ((rev (reverse lst)))
  (when (not (null? rev))
    (display (car rev))
    (newline)
    (loop (cdr rev))))

With Racket, which is aimed at beginners, you can write a much simpler (albeit non-standard) solution:
(define lst (range 1 6))

(for ([e (reverse lst)])
  (displayln e))

Either way, notice that the procedure for reversing a list is already built in the language, and you don't need to reimplement it - naturally, it's called reverse. And if it wasn't obvious already, in Scheme we prefer to use lists, not arrays to represent a sequence of elements - it's recommended to stop thinking in terms of indexes, array lengths, etc. because that's not how things are done in Scheme.

A: If you don't care about returned value (it's #<undef>) and just want to produce output, you can use for-each:
(for-each print (reverse (list 1 2 3 4 5)))

Output:
5
4
3
2
1

A: Not idiomatic Scheme, but a literal translation of the Pascal code would be:
(let ([arr (make-vector 5)])
     (do ([i 0 (+ i 1)]) ((= i 5)) (vector-set! arr i i))
     (do ([i 4 (- i 1)]) ((negative? i))
         (display (vector-ref arr i))
         (newline)))


text:
Q: Issue with cancelling axios .then logic with interceptors and cancel token I set up an axios response interceptor for my react app. It works fine for catching most errors but one thing i am having trouble with is if the response is a 401 aka the user is not authed, the interceptor sends the user back to the login page. Now this works but the logic inside the .then from the original request still runs. This causes a type error as in the .then logic i am setting a state with the response data. Here is my current attempt at implementing a axios cancel token that is not working. See the code below. What am i missing here? What is the best way to achieve this with out having to add If/Else logic to every axios request to check if "data" is there or is the response is a 401, 200 ...?
AxiosInterceptor.js
    ...
export default withRouter({
    useSetupInterceptors: (history) => {
        axios.interceptors.response.use(response => {
            return response;
        }, error => {
            try {
                if (error.response.status === 401) {
                    history.push("/login");
                    Swal.fire({
                        title: '401 - Authorization Failed',
                        text: '',
                        icon: 'warning',
                        showCancelButton: false,
                        confirmButtonText: 'Close',
                    })
                    throw new axios.Cancel('Operation canceled');
                }
                return Promise.reject(error);
            } catch (error) {
                console.log(error)
            }
        });
    },
});

UserPage.js
    ...
function userPage() {
  var [pageData, setPageData] = useState('');
  var classes = useStyles();

  useEffect(() => {
    const CancelToken = axios.CancelToken;
    const source = CancelToken.source();
    const loadData = () => {
      try {
      axios.post('/api/getUserData', { cancelToken: source.token })
        .catch(function (error) {
          source.cancel();
        })
        .then(res => {
            const data = res.data;
            setPageData(data);
        })
      } catch (error) {
        if (axios.isCancel(error)) {
          console.log('Op Cancel')
        } else {
          throw error;
        }
      }
    };
      loadData();
    return () => {
      source.cancel();
    };
  }, []);

  return (
     ...
  );
}
...

The error i get:
Unhandled Rejection (TypeError): Cannot read property 'data' of undefined

PROGRESS UPDATE:
I added some logic to my back-end that if the login is successful,

*

*i pass the expiration time of the JWT token back to my front end.

*Then push that expiration epoch to my redux store.

*On every request, in my 'AxiosInterceptor.js' file below, before returning a config back, i validate the exp value set in redux.
Now this works fine on initial login, but once the token has expired and you receive the popup from 'Swal.fire' and click 'return' it does two things:

*

*calls logOut action and returns all values to initial state. (This works fine. I validated with redux-devtools-extension)

*Now i can log back in. Everything starts to load fine but then i get the 'Swal.fire' dialog to return back to login page. When logging the user.exp and date.now to console i see some strange behavior(see comments):

// from redux-logger
action SET_EXP @ 20:05:42.721
redux-logger.js:1  prev state {user: {…}, _persist: {…}}
redux-logger.js:1  action     {type: "SET_EXP", payload: 1585267561036}

USEREXP 1585267561036 // this is the new EXP time set in redux, received from back end on login
AxiosInterceptors.js:17 Current Status =  1585267561036 false // first two axios calls on main page validate and indicate not expired
AxiosInterceptors.js:17 Current Status =  1585267561036 false
AxiosInterceptors.js:17 Current Status =  1585267495132 true // this is the value of the previos exp value that was set
AxiosInterceptors.js:17 Current Status =  1585267495132 true
AxiosInterceptors.js:17 Current Status =  1585267352424 true // this is the value that was set two login times ago
AxiosInterceptors.js:17 Current Status =  1585267352424 true

How is this possible? I verified with redux-devtools that once i am
  returned back to the login page, it is indeed empty. It appears the value in   > redux-store is being rolled back to old values? I am using chrome Version
  74.0.3729.131 (Official Build) (64-bit). I have tried with incognito mode and clearing cache and cookies.

New AxiosInterceptor.js ...
export default withRouter({
    useSetupInterceptors: (history) => {
    let user = useSelector(state => state.user)
        axios.interceptors.request.use(config => {
         const { onLogo } = useLogout(history);
                console.log("Current Status = ", user.exp, Date.now() > user.exp)
                if (Date.now() > user.exp) {
                    Swal.fire({
                        title: '401 - Auth Failed',
                        text: '',
                        icon: 'warning',
                        showCancelButton: false,
                        confirmButtonText: 'Return',
                    }).then((result) => {
                        onLogo();
                    })
                    return {
                        ...config,
                        cancelToken: new CancelToken((cancel) => cancel('Cancel')) // Add cancel token to config to cancel request if redux-store expire value is exceeded
                      };
                } else {
                    return config;
                }
              }, error => { console.log(error)});

        axios.interceptors.response.use(response => {
            return response;
        }, error => {
            try {
            if (axios.isCancel(error)) { // check if canceled
                    return new Promise(() => {}); // return new promise to stop axios from proceeding to the .then
                }
                if (error.response.status === 401) {
                    history.push("/login");
                    Swal.fire({
                        title: '401 - Auth Failed',
                        text: '',
                        icon: 'warning',
                        showCancelButton: false,
                        confirmButtonText: 'Close',
                    })
                    throw new axios.Cancel('Operation canceled');
                }
                return Promise.reject(error);
            } catch (error) {
                console.log(error)
            }
        });
    },
});

function useLogo(history) {
    const dispatch = useDispatch()
    return {
        onLogo() {
            dispatch(allActs.userActs.logOut())
            history.push("/login");
        },
    }
}

A: I tracked down the issue to the hook "useSelector" within react-redux. It seems this is some how returning cached data, after it already returned correct data. I am using version 7.2 at his time but i confirmed it also on v7.1. I have not tested on any other versions. I solved this by pulling the data from redux-persist Storage(localStorage) in the getExpire() function below. Not the most elegant solution but my application is now working as it should be.
export default withRouter({
    useSetupInterceptors: (history) => {
        const { onLogout } = useLogout(history);
        const CancelToken = axios.CancelToken;
        const { onExp } = useExp();

        axios.interceptors.request.use((config) => {
            const testexp = onExp();
            if (testexp) {
                Swal.fire({
                    title: '401 - Authorization Failed',
                    text: '',
                    icon: 'warning',
                    showCancelButton: false,
                    confirmButtonText: 'Return',
                }).then((result) => {
                    onLogout();

                })
                return {
                    ...config,
                    cancelToken: new CancelToken((cancel) => cancel('Cancel repeated request'))
                };
            } else {
                return config;
            }
        }, error => { console.log(error) });

        axios.interceptors.response.use(response => {
            return response;
        }, error => {
            try {
                if (axios.isCancel(error)) {
                    return new Promise(() => { });
                }
                return Promise.reject(error);
            } catch (error) {
                console.log(error)
            }
        });
    },
});

function getExpire () {
    var localStore = localStorage.getItem("persist:root")
    if (localStore) {
       let store = JSON.parse(localStore)
       return JSON.parse(store.exp)
    }
    return 0

}

function useExp() {
   // const currentExp = useSelector(state => state.exp)
    return {
        onExp() {
            if (Date.now() > getExpire().exp) {
                return true
            } else { return false }
        },
    }
}

function useLogout(history) {
    const dispatch = useDispatch()
    return {
        onLogout() {
            dispatch(allActions.expAction.setLogout())
            history.push("/login");
        },
    }
}


text:
Q: How can I use List.Contains I have assignment to make Hangman game with methods, so far everything is going ok until I realized that the word that I input by char when has two consecutive characters it can't get the following if statement
if (correctGuesses.Count == randomWord.Length)
{
    Console.WriteLine("You won the word is: {0}", randomWord);
    break;
}

and thus I can never finish the game if the word is something like Green
I was trying to use List.Contains('*') if contains it to continue if not to break and to write the Word thus to win, but it fails if I put '!' in front or if I don't put it, it becomes a endless loop . Could you please help me if there is a way to use Contains in a way that will not search only for one symbol but will check for every single one until there is no more.
I will post the code here.
static string GeneratingRandomWords()
{
    Random r = new Random();

    List<string> words = new List<string>() { /*"Cat", "Dog", "Eagle", "Lion", "Shark",*/ "Green" };
    string word = words[r.Next(0, words.Count)];
    return word;
}

static char Input()
{
    char inputt = char.Parse(Console.ReadLine());
    return inputt;
}

static char[] TransformingCharToInvisible(string randomWord)
{
    char[] charFromString = randomWord.ToCharArray();
    for (int i = 0; i < randomWord.Length; i++)
    {
        charFromString[i] = '*';
    }

    Console.WriteLine(charFromString);

    return charFromString;
}

static int CorrectGuesses(char input, string randomWord, int correct)
{
    if (randomWord.Contains(input))
    {
        Console.WriteLine("Next");
        correct++;
    }

    return correct;
}

static int Lives(string randomWord, char input, int lives)
{
    if (!randomWord.Contains(input))
    {
        Console.WriteLine("Try another one");
        lives--;
    }

    return lives;
}

static List<char> CorrectWord(List<char> correctGuesses, string randomWord, char input)
{
    if (randomWord.Contains(input))
    {
        correctGuesses.Add(input);

        char[] charFromString = randomWord.ToCharArray();
        for (int i = 0; i < randomWord.Length; i++)
        {
            charFromString[i] = '*';
            if (correctGuesses.Contains(randomWord[i]))
            {
                charFromString[i] = randomWord[i];
            }
        }

        Console.WriteLine(charFromString);
    }

    return correctGuesses;
}

static void Main(string[] args)
{
    string randomWord = GeneratingRandomWords();
    TransformingCharToInvisible(randomWord);
    List<char> correctGuesses = new List<char>();
    int lives = 10;
    int correct = 0;
    //bool won = true;

    while (true)
    {
        Console.WriteLine("Write a char");
        char input = Input();
        correct = CorrectGuesses(input, randomWord, correct);
        lives = Lives(randomWord, input, lives);
        if (correctGuesses.Contains(input))
        {
            Console.WriteLine("You've already tried '{0}', and it was correct!", input);
            continue;
        }

        correctGuesses = CorrectWord(correctGuesses, randomWord, input);

        if (lives == 0)
        {
            Console.WriteLine("You lose sorry, try againg next time ");
            break;
        }

        if (correctGuesses.Count == randomWord.Length)
        {
            Console.WriteLine("You won the word is: {0}", randomWord);
            break;
        }
    }
}

A: Here a simplified version of your code where i did not add all the error checking but the basics use the required Contains to check if letters are found
static void Main(string[] args)
{
    var lives = 10;
    var correctGuesses = new List<char>();

    var word = "green";

    while (true)
    {
        Console.WriteLine("Guess a letter? ");

        // deliberatly just check for 1 character for simplicity reasons
        var input = Console.ReadLine()[0];

        // if already guessed give a chance to the user to retry
        if (correctGuesses.Contains(input))
        {
            Console.WriteLine("Letter already guessed");
        }
        else
        {
            // if the word contains the letter
            if (word.Contains(input))
            {
                // add as a correct guess
                correctGuesses.Add(input);

                Console.WriteLine("Letter found");
            }
            else
            {
                // letter dont exist remove a life
                lives--;

                Console.WriteLine("Letter not found");
            }
        }

        // check if the user still have lives
        if (lives == 0)
        {
            Console.WriteLine("You lost");

            break;
        }
        // check if the amount of distinct character in the word match
        // the amount found. This mean the word is completly guessed
        else if (word.Distinct().Count() == correctGuesses.Count())
        {
            Console.WriteLine("You won you found the word");

            break;
        }
    }

    Console.ReadKey();
}

A: I didn't understand you very well
but I modified your code like this :
    private static bool IsCorrectGuess(char input, string actualWord)
    {
        return actualWord.Contains(input);
    }

    private static void WriteCorrectGuesses(ICollection<char> correctGuesses, string randomWord)
    {
        char[] charFromString = randomWord.ToCharArray();
        for (var i = 0; i < randomWord.Length; i++)
        {
            charFromString[i] = '*';
            if (correctGuesses.Contains(randomWord[i]))
                charFromString[i] = randomWord[i];
        }

        Console.WriteLine(charFromString);
    }

    private static string GeneratingRandomWords()
    {
        var r = new Random();

        var words = new List<string>
        {
            /*"Cat", "Dog", "Eagle", "Lion", "Shark",*/ "Green"
        };
        return words[r.Next(0, words.Count)];
    }

    private static char Input()
    {
        return char.Parse(Console.ReadLine() ?? throw new InvalidOperationException());
    }

    private static void Main(string[] args)
    {
        string randomWord = GeneratingRandomWords();

        var correctGuesses = new List<char>();
        WriteCorrectGuesses(correctGuesses, randomWord);

        var lives = 10;
        var correct = 0;
        //bool won = true;

        while (true)
        {
            Console.WriteLine("Write a char");
            char input = Input();

            if (IsCorrectGuess(input, randomWord))
            {
                // correct letter

                int score = randomWord.ToCharArray().Count(item => item == input);

                for (var i = 0; i < score; i++)
                {
                    correctGuesses.Add(input);
                    correct++;
                }

                WriteCorrectGuesses(correctGuesses, randomWord);

                if (correctGuesses.Count == randomWord.Length)
                {
                    Console.WriteLine("You won the word is: {0}", randomWord);
                    Console.Read();
                    break;
                }

                Console.WriteLine("Next");
            }
            else
            {
                // wrong letter
                Console.WriteLine($"Try another one. You still have {lives} to try.");
                lives--;
            }

            if (lives == 0)
            {
                Console.WriteLine("You lose sorry, try again next time ");
                break;
            }
        }
    }


text:
Q: Передать параметр в REST controller Столкнулся с задачей в вебприложении - при смене email у юзера необходимо запросить пароль. С написанием бэкенда проблем нет (пишу на java), с ангуляром пока плаваю.
Метод изначально принимал только email.
Добавил в метод
var passConfirm = vm.passwordConfirmEmail;
В следующей строках где console.log мыло и пароль отображается.
Вызываю свой рест UserExt.updateEmail.query...
function saveEmail() {
        var mod = vm.emailMod;
        var passConfirm = vm.passwordConfirmEmail;

        console.log(mod);
        console.log(passConfirm);

        UserExt.updateEmail.query(mod, function (res) {
            console.log("------query updateEmail-------");
            if (!res || !res.code) {
                $scope.toastr.error('error.occured');
                return;
            }
            var code = res.code;
            console.log(code);

            if (code === 'INCORRECT_EMAIL') {
                $scope.toastr.error('error.incorrect-email');
            } if (code === 'INCORRECT_EMAIL_OR_PASS') {
                $scope.toastr.error('error.incorrect-email-or-password');
            }
            else if (code === 'EMAIL_EXISTS') {
                $scope.toastr.error('msg.email-exists');
            } else if (code === 'EMAIL_CHANGED') {
                $scope.toastr.success('msg.email-changed');
            } else {
                $scope.toastr.error('error.occured');
            }
        }, function () {
            console.log("fail***********************");
            $scope.toastr.error('error.occured');
        });
    }

REST
@RequestMapping(value = "/users-ext/updateEmail",
    method = RequestMethod.POST,
    produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<CodeDto> updateEmail(@RequestBody User user) throws URISyntaxException {

.....
Изначально в параметр принимал @RequestBody String email
Как в ангулар-функцию определить параметр passConfirm что бы его передать дальше в REST Controller? Сейчас приходит null, уверен что лажа в "моем" ангуляре

A: ответ был довольно как оказалось прост, необходимо было создать переменную юзера и в точности отобразить поля обьекта:
function saveEmail() {
        var user = {
            'email':vm.emailMod,
            'password':vm.passwordConfirmEmail
        };

        UserExt.updateEmail.query(user, function (res) {
        .....
        .....


text:
Q: php function returning input I am working on setting up a PHP function that will take inputs from a custom field (ACF-generated) on a page in the wordpress backend and generate HTML. Here's what i'm calling in my PHP/HTML files....
<?php connect_links('github', the_field( 'github_url', 94 ) ); ?>

and here is the code from my functions.php:
<?php
function connect_links($type, $url){
$email = '';
switch ($type) {
    case 'facebook':
        $fa_type = 'fa-facebook-official';
        break;
    case 'github':
        $fa_type = 'fa-github-square';
        break;
    case 'linkedin':
        $fa_type = 'fa-linkedin-square';
        break;
    case 'twitter':
        $fa_type = 'fa-twitter-square';
        break;
    case 'email':
        $fa_type = 'fa-envelope';
        $email = 'mailto:';
        break;
    default:
        $fa_type = 'no-fa-type';
        break;
}
?>
    <a href="<?php if($email) echo $email; echo $url; ?>">
        <i class="fa <?php echo $fa_type; ?> blue-and-white-icon"> </i>
    </a>
<?php
}

?>
Instead of getting the input from the wordpress backend and using it in the function, it runs as if it has no second input then takes the second input and prints it to the HTML in between elements.
My function works as expected when I call it with actual inputs like this:
connect_links('github', 'https://www.github.com/michaeljwiebe' );

A: Looks like you want get_field() which returns a value:
https://www.advancedcustomfields.com/resources/get_field/
Unlike the_field() which prints a value.


text:
Q: Removing incomplete numbers from list Python I'm given this list
[1.3, 2.2, 2.3, 4.2, 5.1, 3.2, 5.3, 3.3, 2.1, 1.1, 5.2, 3.1]

and I'm supposed to remove the elements 1,3, 4.2 and 1.1 so that it becomes
[2.2, 2.3, 5.1, 3.2, 5.3, 3.3, 2.1, 5.2, 3.1]

I have written this code and it becomes wrong. What am I doing wrong?

def removeIncomplete(id):
    numbers_buf = id
    idComplete = id[:]
    for ind, item in enumerate(id):
        if item == 1.3 and item == 4.2 and item == 1.1:
            numbers_buf.remove(item)

        return numbers_buf
        #return idComplete

import numpy as np
print(removeIncomplete(np.array([1.3, 2.2, 2.3, 4.2, 5.1,
3.2, 5.3, 3.3, 2.1, 1.1, 5.2, 3.1])))

#Correct output [ 2.2 2.3 5.1 3.2 5.3 3.3 2.1 5.2 3.1]

A: def removeIncomplete(id):
    numbers_buf = id
    idComplete = id[:]
    for ind, item in enumerate(id):
        if item == 1.3 or item == 4.2 or item == 1.1:
            numbers_buf = np.delete(numbers_buf, np.where(numbers_buf == item))

    return numbers_buf
        #return idComplete

import numpy as np
print(removeIncomplete(np.array([1.3, 2.2, 2.3, 4.2, 5.1,
3.2, 5.3, 3.3, 2.1, 1.1, 5.2, 3.1])))

A: what about using list comprehension
data = [1.3, 2.2, 2.3, 4.2, 5.1, 3.2, 5.3, 3.3, 2.1, 1.1, 5.2, 3.1]
exclude = [1.3, 4.2, 1.1]

out = [val for val in data if val not in exclude]

print(out)
>>>
[2.2, 2.3, 5.1, 3.2, 5.3, 3.3, 2.1, 5.2, 3.1]


text:
Q: Two VPCs which are peered, need to get traffic to VPC B from a device at the other end of the VPN connection AWS networking question - I have 2 VPCs (A & B) which are peered. I have a Site to Site connected to  VPC A. I need to get traffic to VPC B from a device at the other end of the VPN connection.
As you cannot jump across VPC's I'm thinking something like an Nginx proxy on VPC A which is the endpoint the device will forward traffic to, and then the traffic will be pushed onto the final endpoint in VPC B.
Can anyone else think of any other solutions? I cannot put the VPN in VPC B due to compliance issues.

A: Please use below approach.
1)Use the Transit Gateway which will scale as you add multiple vpcs.
2)Use ELB in vpc A and target server could be in vpc B.


text:
Q: Jasmine Spec Helpers not loaded I am trying to write my unit tests with Jasmine and Karma in a Typescript environment.
I have installed karma, karma-typescript, karma-jasmine, jasmine and jasmine-ts.
I have added a custom tsconfig.json to the spec directory and use it in the karma-typescript settings.
Generally, my tests are working, however, it doesn't execute my spec helpers.
Is there something I am missing for it to execute my spec helpers?

For your reference, here is my configuration:
karma.conf.js:

    module.exports = function (config) {
        config.set({

            // base path that will be used to resolve all patterns (eg. files, exclude)
            basePath: '',

            // frameworks to use
            // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
            frameworks: ['jasmine', "karma-typescript"],

            // list of files / patterns to load in the browser
            files: [
                "spec/helpers/chai.ts",
                {pattern: "src/**/*.ts"},
                {pattern: "spec/**/*.ts"}
            ],

            // list of files to exclude
            exclude: [],

            // preprocess matching files before serving them to the browser
            // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
            preprocessors: {
                "src/**/*.ts": ["karma-typescript"],
                "spec/**/*.ts": ["karma-typescript"]
            },

            karmaTypescriptConfig: {
                bundlerOptions: {
                    entrypoints: /\.spec\.ts$/
                },
                tsconfig: "./spec/tsconfig.json",
                coverageOptions: {
                    exclude: [/\.(d|spec|test)\.tsx?/, /\/spec\//]
                }
            },
            specReporter: {
                maxLogLines: 3,             // limit number of lines logged per test
                suppressErrorSummary: true, // do not print error summary
                suppressFailed: false,      // do not print information about failed tests
                suppressPassed: false,      // do not print information about passed tests
                suppressSkipped: true,      // do not print information about skipped tests
                showSpecTiming: false,      // print the time elapsed for each spec
                failFast: false              // test would finish with error when a first fail occurs.
            },
            // test results reporter to use
            // possible values: 'dots', 'progress'
            // available reporters: https://npmjs.org/browse/keyword/karma-reporter
            reporters: ['spec', "karma-typescript", "kjhtml"],

            // web server port
            port: 9876,

            // enable / disable colors in the output (reporters and logs)
            colors: true,

            // level of logging
            // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
            logLevel: config.LOG_INFO,

            // enable / disable watching file and executing tests whenever any file changes
            autoWatch: true,

            // start these browsers
            // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
            browsers: ['Chrome'],

            // Continuous Integration mode
            // if true, Karma captures browsers, runs the tests and exits
            singleRun: false,

            // Concurrency level
            // how many browser should be started simultaneous
            concurrency: Infinity
        })
    }

jasmine.json (Although I have the feeling that it isn't used):

    {
      "spec_dir": "spec",
      "spec_files": [
        "**/*[sS]pec.ts"
      ],
      "helpers": [
        "helpers/**/*.ts"
      ],
      "stopSpecOnExpectationFailure": false,
      "random": false,
      "reporters": [
        {
          "name": "jasmine-spec-reporter#SpecReporter"
        }
      ],
      "project": "./spec/"
    }

tsconfig.json in root:

    {
      "compilerOptions": {
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "lib": [
          "es6",
          "dom",
          "es2015.promise"
        ],
        "module": "commonjs",
        "target": "es5",
        "sourceMap": true,
        "outDir": "./dist/",
        "noImplicitAny": false,
        "allowJs": true,
        "baseUrl": "src",
        "typeRoots": [
          "node_modules/@types",
          "typings"
        ]
      },
      "include": [
        "src/**/*"
      ]
    }

tsconfig.json in spec folder:

    {
      "extends": "../tsconfig.json",
      "compilerOptions": {
        "typeRoots": [
          "../node_modules/@types",
          "typings"
        ]
      },
      "include": [
        "./**/*",
        "../src/**/*"
      ]
    }

spec/helpers/chai.ts is the spec helper that karma is not executing.
The content of that file is:
import * as chai from "chai";
import chaiThings = require("chai-things");
import chaiInterface = require("chai-interface");

chai.should();
chai.use(chaiThings);
chai.use(chaiInterface);

Please see https://github.com/dhilgarth/mjt for a self contained example.

A: So the problem here was that the Karma config had a minor mis-configuration that's easily missed.
The files node of the Karma config is completely valid and matches all the test specs you want Karma to load.
The karmaTypescriptConfig node of the karma config applies an extra filter on the files loaded by Karma, in your case you're only including files loaded by karma that match .spec.ts files.
The bundler couldn't find the helper specs as they didn't match the regex pattern: .spec.ts, even though they're specified under the files node. So the helper scripts were being excluded from the test after they'd been loaded.
The fix to this is to either remove the karmaTypescriptConfig node, reconfigure it to match the helper explicitly or rename the helper to be matched by the given matcher.
I've removed it from the below example. The bundler will bundle all files loaded by Karma by default.
The official documentation states

karmaTypescriptConfig.bundlerOptions.entrypoints - A regex filtering which files loaded by Karma should be executed in a test run, for example only filenames ending with ".spec.ts": /.spec.ts$/.
  This setting can be used to make sure the specs have finished setting up the test environment before other code starts requiring modules, which otherwise could lead to subtle bugs caused by race conditions.
  Defaults to all files, /.*/.

Hope this helps!
karma.conf.js:

module.exports = function (config) {
 config.set({

  // base path that will be used to resolve all patterns (eg. files, exclude)
  basePath: '',

  // frameworks to use
  // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
  frameworks: ['jasmine', "karma-typescript"],

  // list of files / patterns to load in the browser
  files: [
   "spec/helpers/helper.ts", {
    pattern: "src/**/*.ts"
   }, {
    pattern: "spec/**/*.ts"
   }
  ],

  client: {
   clearContext: false // leave Jasmine Spec Runner output visible in browser
  },

  // list of files to exclude
  exclude: [],

  // preprocess matching files before serving them to the browser
  // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
  preprocessors: {
   "spec/helpers/helper.ts": ["karma-typescript"],
   "src/**/*.ts": ["karma-typescript"],
   "spec/**/*.ts": ["karma-typescript"]
  },

  // test results reporter to use
  // possible values: 'dots', 'progress'
  // available reporters: https://npmjs.org/browse/keyword/karma-reporter
  reporters: ['progress', "karma-typescript"],

  // web server port
  port: 9876,

  // enable / disable colors in the output (reporters and logs)
  colors: true,

  // level of logging
  // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
  logLevel: config.LOG_INFO,

  // enable / disable watching file and executing tests whenever any file changes
  autoWatch: true,

  // start these browsers
  // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
  browsers: ['Chrome'],

  // Continuous Integration mode
  // if true, Karma captures browsers, runs the tests and exits
  singleRun: false,

  // Concurrency level
  // how many browser should be started simultaneous
  concurrency: Infinity
 })
}

A: At the moment the only viable options is to store helpers in separate forlder, compile them with tsc and add as .js files to karma.config
Check this PR for steps to make it work: https://github.com/dhilgarth/mjt/pull/1/files
    files: [
        {pattern: "spec/helpers/*.js"},
        {pattern: "src/**/*.ts"},
        {pattern: "spec/**/*.ts"}
    ],

    client:{
      jasmine: {
        helpers: [
          "spec/helpers/*.js"
        ]
      }
    },


text:
Q: OpenAI gym render OSError I am trying to learn Q-Learning by using OpenAI's gym module. But when I try to render my environment, I get the following error,
OSError                                   Traceback (most recent call last)
<ipython-input-1-c269c1129a2f> in <module>
     12     action = 2
     13     new_state, reward, done, _ = env.step(action)
---> 14     plt.imshow(env.render(mode='rgb_array'))
     15     disp
     16

C:\Program Files\Python37\lib\site-packages\gym\core.py in render(self, mode, **kwargs)
    228
    229     def render(self, mode='human', **kwargs):
--> 230         return self.env.render(mode, **kwargs)
    231
    232     def close(self):

C:\Program Files\Python37\lib\site-packages\gym\envs\classic_control\mountain_car.py in render(self, mode)
    116         self.cartrans.set_rotation(math.cos(3 * pos))
    117
--> 118         return self.viewer.render(return_rgb_array = mode=='rgb_array')
    119
    120     def get_keys_to_action(self):

C:\Program Files\Python37\lib\site-packages\gym\envs\classic_control\rendering.py in render(self, return_rgb_array)
    112             arr = arr.reshape(buffer.height, buffer.width, 4)
    113             arr = arr[::-1,:,0:3]
--> 114         self.window.flip()
    115         self.onetime_geoms = []
    116         return arr if return_rgb_array else self.isopen

C:\Program Files\Python37\lib\site-packages\pyglet\window\win32\__init__.py in flip(self)
    319     def flip(self):
    320         self.draw_mouse_cursor()
--> 321         self.context.flip()
    322
    323     def set_location(self, x, y):

C:\Program Files\Python37\lib\site-packages\pyglet\gl\win32.py in flip(self)
    224
    225     def flip(self):
--> 226         _gdi32.SwapBuffers(self.canvas.hdc)
    227
    228     def get_vsync(self):

OSError: exception: access violation reading 0x000000000000001C

I get the same error when I run my code from the command prompt
Also, here is my code,
import matplotlib.pyplot as plt
import gym
from IPython import display
%matplotlib inline

env = gym.make("MountainCar-v0")
env.reset()

done = False

while not done:
    action = 2
    new_state, reward, done, _ = env.step(action)
    plt.imshow(env.render(mode='rgb_array'))
    display.display(plt.gcf())
    display.clear_output(wait=True)

env.close()

I was not able to find this error on the internet with gym, so I am not able to solve it.
I even tried the cartpole environment but ended with the same error.
Any help is appreciated.

A: It is probably due to dynamically using ipython-display.
Change your code to:
import matplotlib.pyplot as plt
import gym
#from IPython import display
#%matplotlib inline

env = gym.make("MountainCar-v0")
env.reset()

done = False

while not done:
    action = 2
    new_state, reward, done, _ = env.step(action)
    #plt.imshow(env.render(mode='rgb_array'))
    env.render(mode='rgb_array')
    #display.display(plt.gcf())
    #display.clear_output(wait=True)

env.close()

This OSError can occur for many reasons, therefore it is difficult to reproduce and debug without verifying everything. But from this error of yours:
C:\Program Files\Python37\lib\site-packages\pyglet\gl\win32.py in flip(self)
    224
    225     def flip(self):
--> 226         _gdi32.SwapBuffers(self.canvas.hdc)
    227
    228     def get_vsync(self):

Since GDI and the ICD share function names like SwapBuffers, a
wglSwapBuffers is needed to avoid ambiguity when loading the proc
dynamically your one display might lock another one. I am not sure but this seems more likely than any other reason.


text:
Q: Store the indices of the selected variables of a listbox in a list I would like to save in an "indice" list all the indexes of the variables selected in the listbox. Any solution? At the moment I select a variable and it returns its index to me. I am not able to select multiple variables and save all indices in a list.
import tkinter as tk
from tkinter.constants import RIGHT, VERTICAL, Y

Ch_Output = ["a","b","c","d","e","f"]

root = tk.Tk()
root.title('Seleziona canale')
root.geometry("400x500")

var_select = str()
indice = int()

def getElement(event):
 selection = event.widget.curselection()
 index = selection[0]
 value = event.widget.get(index)

 result.set(value)
 print('\n',index,' -> ',value)
 global var_select
 global indice
 var_select = value
 indice = index
 #root.destroy()

# scroll bar-------

result =tk.StringVar()
my_frame = tk.Frame(root)
my_scrollbar = tk.Scrollbar(my_frame, orient=VERTICAL)

var2 = tk.StringVar()
var2.set(Ch_Output)

# list box-----------
my_listbox = tk.Listbox(my_frame, width=50, height=20, listvariable=var2)

# configure scrolbar
my_scrollbar.config(command=my_listbox.yview)
my_scrollbar.pack(side=RIGHT, fill=Y)
my_frame.pack()

my_listbox.pack(pady=15)

my_listbox.bind('<<ListboxSelect>>', getElement) #Select click

root.mainloop()

print('\n',indice)

A: By default, you can select only one item. If you want to select multiple items at once you need to specify selectmode to tk.MULTIPLE or tk.EXTENDED.
In your case:
import tkinter as tk
from tkinter.constants import RIGHT, VERTICAL, Y, MULTIPLE

...

selected_index = []
def getElement(event):
     global selected_index
     selected_index = list(event.widget.curselection())
     print(selected_index)
     print("Values: ", [event.widget.get(x) for x in selected_index])
...
my_listbox = tk.Listbox(my_frame, width=50, height=20, listvariable=var2, selectmode=MULTIPLE)
...
root.mainloop()


text:
Q: Copying all the cpp files in a Makefile using VSCode Terminal does not work I'm trying to create a Makefile in VS Code but I don't want to lose time writing all of the .cpp files that I have .
A solution for that , which works on Unix is
 echo *.cpp > Makefile

However when I try this command line in the terminal of VS code, it doesn't work .  I get *.cpp in my Makefile

A: Make file exemple:
NAME     = my_project

IDIR     = include/
IDIR_MY  = ./include

CC       = g++
CFLAGS  += -I $(IDIR) -I $(IDIR_MY)
CFLAGS  += -W -Wall -Wextra

SRCS_DIR        = src/
SRCS_FILES      = *.cpp

SRCS     = $(addprefix $(SRCS_DIR), $(SRCS_FILES))

OBJS     = $(SRCS:.cpp=.o)
RM       = rm -f

all: $(NAME)

$(NAME): $(OBJS)
    $(CC) -o $(NAME) $(OBJS)

gdb:    $(OBJS)
    $(CC) -g -o debug ./*.cpp -I $(IDIR)

clean:
    $(RM) $(OBJS)

fclean: clean
    $(RM) $(NAME)

re: fclean all

and for lunch this say just "make" in your term


text:
Q: How can .NET threads be waiting on a syncblk which is not owned by any thread? I have a crash dump from my app showing a bunch of threads waiting on a syncblk, and the syncblk shows that it has no owning thread.  How is that possible?  I'm trying to reproduce the symptom in a test app, and I can't figure out what could possibly happen to produce that result....having the owning thread exit or die without releasing the syncblk still shows up as owning the object, just the threadid is "XXX"....I've tested using fully managed graceful exit and hard thread termination via pinvoke....I tested a bunch of different combinations of waits without pulses, mismatched enters and exits...nothing produces a syncblk which blocks threads and shows no owner.....I'm running out of ideas
Here is the output from my crashdump that I'm trying to replicate: (Note index #1236)
0:000> !syncblk
Index         SyncBlock MonitorHeld Recursion Owning Thread Info          SyncBlock Owner
 784 0000000004f12eb0            3         1 000000000508a460  32a8  68   00000001a0a20510
 966 0000000004f06928            1         1 00000000052c5da0  2380 114   00000001df3080f8
1085 0000000004f23088            1         1 00000000052c8080  496c 120   00000001a0325238
1144 0000000005160d20            1         1 00000000050968b0   d74  56   00000000ff61b570
1151 0000000004f0c2c8            1         1 000000000508d8b0  3f64  77   000000017f66dc20
1236 0000000004f0b4f8           16         0 0000000000000000     none    000000019f1ec5d8
1261 0000000004f0ffe8            1         1 0000000008f18fc0  446c  94   000000013f8e70b0
1306 0000000004f0e918            1         1 00000000052c91f0  406c 123   000000011f5936f8
1318 0000000004f0e528            3         1 0000000008f1d580  24d8 106   000000015fc73f28
1329 0000000004f0cc58            1         1 0000000005095740  2fbc  53   000000011f36d320
1332 0000000004f15b38            1         1 0000000008f16710  3804  87   000000019f964728
1387 0000000004f22350            1         1 0000000008f18420  5180  92   00000001a008ab08
1515 0000000004f1d5d0            1         1 00000000052c4c30  2b5c 111   00000000ffd3c068
1594 0000000004f19bc0            1         1 000000000508ea20  188c  80   000000012012c538
1660 0000000004f13608            1         1 00000000050892f0  32fc  65   00000001df800940
1682 00000000051608a0            1         1 000000000508c740  1d58  74   00000001bfa03d20
1746 0000000004f14e88            1         1 0000000008f1c9e0   e88 104   000000015f6fcd10
1883 0000000004f19938            1         1 0000000005092e90  27c4  46   00000000ff76d2b0
1886 0000000004f1b760            1         1 0000000008f19b60  2dd4  96   000000019fc07030
2036 0000000004f1ae10            1         1 0000000008f1be40  4f58 102   00000001dfcb9da8
2042 0000000004f12e68            1         1 00000000052c8c20  2300 122   000000015f6aaa98
2049 0000000004f1cda0            1         1 00000000052c9d90  1948 126   00000001df6fd688
2153 0000000004f16d88            1         1 0000000005094ba0  3f04  51   00000000ff677eb8
2262 0000000004f13de8            3         1 00000000052ca360   6fc 127   000000011fd7a450
2358 00000000050fc390            1         1 0000000009221280  3ca0 130   0000000120055ca0
-----------------------------
Total           2553
CCW             3
RCW             2
ComClassFactory 0
Free            1212

A: SyncBlock 000000019f1ec5d8 is the one with no owner. Is also the only one with an even MonitorHeld count. Since the MonitorHeld increments with 1 for the owner and 2 for each waiter my guess would be that this is a resource that was released just before the dump was taken, and there was not yet granted a new owner. Unfair resources signal all waiters on release and the waiters rush to acquire it (this unfair behavior avoid convoy locks). Until the waiters are scheduled and run, and the first waiter grabs the resource, there will be no owner.
See also A high waiter count on a free critical section may indicate a lock convoy:

If you're debugging a performance problem in your application, you may
  run across a critical section in a very strange state: A lot of
  threads are waiting for it, but nobody owns it!
...
This state means that the previous owner of the critical section has
  just exited it and signalled a waiting thread to take it, but that
  thread hasn't yet gotten a chance to run yet

A: What you describe might have several reasons:

*

*Owning thread got unstable with some nasty access violations

*Owning thread got unstable with OutOfMemoryExceptions

*Some part of the system (like a driver...) caused a strange situation

*Some 3rd-party library using native code caused the process to become unstable

*Some essential part of the framework (like GC/memory management/thread management) got unstable and/or died while in the middle of some important operation

Any of the above is rather hard to reproduce...
For a nice summary on syncblk see http://blogs.msdn.com/b/tess/archive/2006/01/09/a-hang-scenario-locks-and-critical-sections.aspx

A: Possibility 1: The syncblk is cleared and the next of the 16 threads will grab it as soon as it is scheduled again.
Possibility 2: You have corrupt memory.


text:
Q: How to include link to app in Facebook Post? I have an IOS app that posts a link to facebook.
Is it possible to have that link point to the app store?
So basically I have a player playing my game, they post their highscore. Their friend sees this post on their friends wall, the click it, takes them to download the app.
The trouble is, how can I get the link to point to the app store if the app isn't published and has no ID when I'm coding the actual app?

A: Then finish app and publish it, and after that update the link.

A: Before uploading the app, obviously you will add it to the iTunesconnect.
In iTunesConnect, you will get the app ID for your app when you will add it.
Use the following format to link it to your app :
http://itunes.apple.com/app/id[app_apple_id]
[app_apple_id] : Replace this (along with square brackets) with the app ID, that you will get after adding the app to iTunesConnect.


text:
Q: How to prevent multiple SelectedIndexChanged events from being thrown? I have a combobox in winforms, which, depending on what you select, determines what's populated in other comboboxes. I filled the initial combobox using a dataview:
combobox_process.DataSource = dataview
combobox_process.DisplayMember = "UserDefine1"
combobox_process.SelectedIndex = -1

Which works fine, except every one of those lines throws the SelectedIndexChanged event. The function that populates the next combobox listens for that event and so it's running three times. I asked a coworker and he suggested just looping through the data and adding them all manually as strings, but I'd prefer to stick with databinding if I can. Especially if, in the future, I need to do something that I can only do with databinding.
Any thoughts? Perhaps some way to disable that event during a portion of this code?

A: Events firing when you not want them to is a common problem in Windows Forms - SelectedIndexChanged is a typical example. One approach I often use is to declare a flag that is set when running a portion of code that I know will fire the event when I'm not interested in listening to it.
An example:
Public Class Form1
    Private m_IsSettingDataSource As Boolean = False

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Try
            Me.m_IsSettingDataSource = True
            combobox_process.DataSource = DataView
            combobox_process.DisplayMember = "UserDefine1"
            combobox_process.SelectedIndex = -1
        Catch
            Throw
        Finally
            Me.m_IsSettingDataSource = False
        End Try
    End Sub

    Private Sub combobox_process_SelectedIndexChanged(sender As Object, e As EventArgs) Handles combobox_process.SelectedIndexChanged
        If Not Me.m_IsSettingDataSource Then
            ' Do what you want to do when not setting data source
        End If
    End Sub
End Class

You can either do this, or like John said, turn off and on the event handler. The flag approach may be better when you know that two or more event handlers will be affected.

A: You could just unbind your event handler before you make the call and then rebind it when the call is done.


text:
Q: Session variables disappearing after header redirect (using XAMPP, PHP) I've searched through many Stack Overflow answers to this question and none seem to work for me.
I've installed XAMPP 3.2.1 and haven't touched the php.ini (well, I did, but changed it back as it didn't fix my problem).
My problem is that sessions don't seem to survive a php header redirect.  I tried interrupting the script on the page the session variables are set and dumping the array -- they are being set correctly.  When I do this after the redirect or even to a test page, $_SESSION is empty.
Cookies are enabled and I've checked that I have a cookie with the sessid (I do).  The sessid stays the same even after redirect.
I have a feeling it has something to do with the php.ini settings or working with localhost as both I've never done before and I've always had success on using external hosting.
And yes, I have session_start before any html tags, even the doctype (it's in a header.php file that I will use on all pages.)
If you need it, here's the code when I set the variables:
        $_SESSION['username'] = $user['username'];
    $_SESSION['userlevel'] = $user['userlevel'];

I can do a var_dump on session and die directly after this and it displays correctly.  I then do a couple of function calls and then redirect using:
header('Location: '.LANDING_PAGE);

LANDING_PAGE equates to '/index.php'.  Sessions are now gone.  When I cut the script just before this header and instead point to a test page to do nothing else but session_start() and var_dump the session vars, the same thing happens, no session vars -- it says:
array(0) { }

I'm stumped.  Am I missing something tiny?  Thanks for any help.
EDIT 1:
Here is the pertinent code:
    <?php
    require_once('McsBackendLibrary.php');
    $indexPage = new McsBackendLibrary;
    $indexPage->checkHandleErrors();
?>

    <form method="post" action="McsUser.php">

            Username:
            <input type="text" name="username" class="accessClass" />

            Password:
            <input type="password" name="password" class="accessClass" />

            <input type="submit" name="submit" class="accessClass" id="accessSub" value="Login" />

    </form>

<?php require_once('footer.php'); ?>

Backend Library is:
 <?php
error_reporting(E_ALL);

//McsBackendLibrary is a library of functions to be used on the webpages of MCS -- intended to separate code from design

    Class McsBackendLibrary {

        public function __construct() {
            require_once('header.php');
            }

        public function checkHandleErrors() {
            if (isset($_SESSION['fatalError'])) {
                echo '
'.$this->session->getSessionVar('fatalError').'

';
                unset($_SESSION['fatalError']);
                }
            }
        }
    ?>

and header is:
    <?php
    require_once('McsUser.php');
    session_start();
    error_reporting(E_ALL);
?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>MCS</title>
    <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
    <link rel="stylesheet" type="text/css" href="McsOpenStyle.css" />

So, the index instantiates a backendlibrary object, the constructor adds the header, the header contains session_start() before any HTML tags.  Here is the portion where it is redirecting:
private function fatalError() {
$_SESSION['fatalError'] = $this->errorDescr;
$this->logError();
header("Location: test.php");
/*
if ($this->errorRefer != "HOME_PAGE") {
    header("Location: ".HOME_PAGE.constant($this->errorRefer));
    exit();
    }
header('Location: '.LANDING_PAGE);*/
exit();
}

As you can see, I interrupt the code with a header to test.php which just var_dumps $_SESSION and I get nothing.  The rest is commented out but it's the code that is usually in.


text:
Q: Check selection and compare to list for python What I am trying to do is check that an input from the user (using raw_input) is a valid option within a global list. Below is what I have up to this point.
def car():
    print "You have selected the 'car' option.",
    print "Are you sure this is what you want?"
    car_sure = raw_input("Enter Yes or No: ").lower()

    if car_sure == "yes":
        car_brand_choice()

    elif car_sure == "no":
        print "You no longer want a car. Taking you back to select your vehicle type."
        type()

    else:
         dead("Not a valid option. You lose your vehicle purchasing opportunity.")

def car_brand_choice():
    print "These are the car brands I can provide to you."
    print "\n".join(car_brands)
    selection = raw_input("Now is your chance to pick which brand you want. ").title()
    print "You selected %s\n" %selection
    print "I have to verify your selection is valid.\n"

    if selection in car_brands:
        print "Valid selection. You may continue."

    else:
        print "Not valid selection."
        print "Go back and select a valid brand.\n"
        car_brand_choice()

start()

The verification will then be used to select a different valid brand or allow the user to proceed with current brand.
The code is formatted properly in Notepad++, I hope. I just don't know how to get the proper formatting to show up here.
I'm sure there is something similar out there already but I just could not find it.

A: You may simply use the in operator.
>>> 'BMW' in car_brands
True
>>> 'bmw' in car_brands
False

As you can see, it's case sensitive. In your case, you could do something like:
if selection.lower() in car_brands:
    print "Valid car brand."
else
    print "Invalid car brand."

Also, I would remove both instances of '\n' from car_brands. That is not a car brand. You should handle line formatting somewhere else.

A: Well, it seems as if you are a beginner.
The thing that you need to solve your problem is in.
selection = raw_input("Now is your chance to pick which brand you want. ")
print "You selected ", selection
if selection in car_brands:
    print "It is in the list"
else:
    print "Its not in the list"

Add this in your car_brand_choice().
For further readings, check the docs


text:
Q: Oracle query GROUP BY with latest record I am trying to get a list of records, grouped by client name within a given time period but am getting every single record rather than grouped records.
The data looks something like this:
ReqTS                      ClientName    ItemID    Outcome
2021-04-25 13:19:20:928    10.20.30.40   ABCD1     X0
2021-04-24 13:20:22:345    10.20.30.40   ABCD2     Y0
2021-04-26 13:21:35:456    10.20.30.40   ABCD3     X2
2021-04-25 13:18:45:589    10.20.40.50   ABCD4     Y1
2021-04-24 13:22:34:832    10.20.40.50   ABCD5     X0

I need to get:
2021-04-26 13:21:35:456    10.20.30.40   ABCD3     X2
2021-04-24 13:22:34:832    10.20.40.50   ABCD5     X0

I tried this but it returns all records:
select reqts, clientname,itemid, outcome
from reqresplog
where logdate <= to_timestamp('04/26/2021', 'mm/dd/yyyy') and logdate >= to_timestamp('04/24/2021', 'mm/dd/yyyy')
group by clientname,reqts,itemid, outcome
order by reqts desc;

A: I'd think of

*

*sorting rows by timestamp in descending order

*within the same client name

(see the ROW_NUMBER analytic function), and then fetch row(s) sorted as the first in that group.
Your result looks wrong for the 2nd group; 25th of April is "later" than 24th.
Sample data till line #8; actual query begins at line #10.
SQL> with reqresplog (reqts, clientname, itemid, outcome) as
  2  (select
  3   to_timestamp('2021-04-25 13:19:20:928', 'yyyy-mm-dd hh24:mi:ss:ff3'), '10.20.30.40', 'ABCD1', 'X0' from dual union all select
  4   to_timestamp('2021-04-24 13:20:22:345', 'yyyy-mm-dd hh24:mi:ss:ff3'), '10.20.30.40', 'ABCD2', 'Y0' from dual union all select
  5   to_timestamp('2021-04-26 13:21:35:456', 'yyyy-mm-dd hh24:mi:ss:ff3'), '10.20.30.40', 'ABCD3', 'X2' from dual union all select
  6   to_timestamp('2021-04-25 13:18:45:589', 'yyyy-mm-dd hh24:mi:ss:ff3'), '10.20.40.50', 'ABCD4', 'Y1' from dual union all select
  7   to_timestamp('2021-04-24 13:22:34:832', 'yyyy-mm-dd hh24:mi:ss:ff3'), '10.20.40.50', 'ABCD5', 'X0' from dual
  8  )
  9  select reqts, clientname, itemid, outcome
 10  from (select r.*,
 11          row_number() over (partition by r.clientname order by r.reqts desc) rn
 12        from reqresplog r
 13       )
 14  where rn = 1;

REQTS                          CLIENTNAME  ITEMID OUTCOME
------------------------------ ----------- ------ ----------
26.04.21 13:21:35,456000000    10.20.30.40 ABCD3  X2
25.04.21 13:18:45,589000000    10.20.40.50 ABCD4  Y1

SQL>

If, for some reason, you still want the 24th of April, change analytic function's parameters. How? No idea, I don't see anything obvious.


text:
Q: Does Windows 7 allow advanced skinning like Windows XP? The Windows 7 Aero interface looks great, but after looking at it for months it gets boring. So I was wondering - is it possible to create advanced skins for Windows 7 that use full Aero capabilities but are redesigned from ground up, including common controls, animations, effects, etc? Windows XP allowed that, although only with a patched uxtheme.dll.
Or do you have to implement a custom shell for that?

A: Here's the kicker:

Windows XP allowed that, although only with a patched uxtheme.dll

That doesn't mean that Windows 7 won't have this feature, but it does mean it won't inherit anything from Windows XP written to do this, because the feature you're thinking of was a hack created outside of microsoft.

A: Yes, download the app from the following site (it allows you to use custom themes WITHOUT needing to patch!  :)  , meaning no need for taking ownership, updating the system file cache or anything like that).
http://uxstyle.com/
Click the button that says "Play with the bits" to download the installer, and install it (no reboot required!).
Next, find a library to download custom themes. Personally, my favorite is here:
http://browse.deviantart.com/customization/skins/windows7/visualstyle/
If you were doing this in XP, then installing the themes is exactly the same... just copy the theme files into C:\Windows\Resources\Themes as you did on XP.
Enjoy the beauty!
Two of my favorite themes:
http://benbackman.deviantart.com/art/Vienna-162878768
http://giannisgx89.deviantart.com/art/Sonye-Theme-for-Win7-v2-155198766 (based on the Office 2010 interface)
While you're at it, here is another great program which compliments custom themes nicely, to change your start button image: http://www.thewindowsclub.com/windows-7-start-button-changer-released . And someplace to start for new orb images: http://www.deviantart.com/#order=9&q=start+orbs .
ENJOY!  :)

A: A search for "windows 7 aero themes" showed up several sites:
http://www.technixupdate.com/free-custom-aero-theme-for-windows-7/
http://www.anewmorning.com/2009/02/02/windows-7-theme-aero-diamond/
to list but two (which actually point to the same theme).
I haven't checked these out (I'm not running Windows 7 on this machine), so I don't know whether they fulfil you criteria completely.
However, this site describes how to download some more from Microsoft:

*

*Right click any blank space in your desktop and then select 'Personalize'.

*At the right side just a little above 'Aero Themes (7)' line, find 'Get more themes online' and click it.

*You will be redirected to the Windows 7 personalization page.

*Scroll in the middle and you will find downloadable Slide Show Themes.

*Just click the 'Download' button to get your preferred theme which will automatically install as a theme pack file.

*Click to begin download and installation.

A: Windows XP technically didn't allow this--the fact that you had to patch uxtheme.dll means it wasn't a feature built into Windows. Windows 7 is the same, nothing has changed--you can still patch your system and use custom themes. The only difference is Windows 7 has Aero, which allows for much cooler styles than XP ever did.


text:
Q: Format the date which is selected through Bootstrap ngbDatepicker in angular 2 HTML code
 <form novalidate [formGroup]="udpateObj">

      Resolution Date:
      <input type="text" id="date"  formControlName="DateP" ngbDatepicker
                                    #d1="ngbDatepicker">

  <form>

code in ts file
let dateVal  = backendDate;// am getting date obj from backend and
  this.udpateObj= new FormGroup({
  DateP: new FormControl(dateVal)
});

I need to show the date which is coming from backend or selected from date picker in dd/mm/yyyy format.

A: You can use the date pipe like in this example:
<input type="text" value = "{{dateObject | myDateFormat: 'dd/mm/yyyy' }}/>

or implement a custom pipe if selected date is not a Date Object. Find here example for custom pipe (using momentjs) applying the format passed in call or the default format 'HH:mm'
import { Pipe, PipeTransform} from '@angular/core';
declare var moment: any;

@Pipe({
  name: 'myDateFormat'
})
export class myDateFormat implements PipeTransform {
   transform(value: any, args: string[]): any {
     if (value) {
         var date = value instanceof Date ? value : moment(value);
         if (args && args.length > 0)
             return moment(date).format(args);
         else
            return moment(date).format('HH:mm');
    }
  }
}


text:
Q: Connecting two nodes with lines through a point in tikz I'm trying to make a very simple flowchart using tikz.
Here is what it looks like now:

And here is what I need it to look like:

I've found an example of a flowchart online using tikz, and here is my style definition:
\tikzstyle{decision} = [diamond, draw, fill=blue!20, text width=4.5em, text badly centered, node distance=3cm, inner sep=0pt]
\tikzstyle{block}    = [rectangle, draw, fill=black!25, text width=5em, text centered, rounded corners, minimum height=4em]
\tikzstyle{line}     = [draw, -latex']
\tikzstyle{cloud}    = [draw, ellipse,fill=red!20, node distance=3cm, minimum height=2em]

and here is my flowchart code:
\begin{figure}[!h]
    \centering
    \begin{tikzpicture}[node distance = 2cm, auto]
        \node [block] (st1) {Stage 1};
        \node [block, right of=st1, node distance=3cm] (st2) {Stage 2};
        \node [block, right of=st2, node distance=3cm] (st3) {Stage 3};
        \path [line] (st1) -- (st2);
        \path [line] (st2) -- (st3);
    \end{tikzpicture}
\end{figure}

If I had just built the image using co-ordinate based shapes, it would have been time consuming but simple just to add the lines and text I need. But since I'm adding these nodes and connecting nodes, I don't know how to add a line with 2 bends.

A: You can use relative coordinates.
\documentclass[tikz,border=10pt]{standalone}
\usetikzlibrary{arrows}
\tikzset{decision/.style = {diamond, draw, fill=blue!20, text width=4.5em, text badly centered, node
                            distance=3cm, inner sep=0pt},
         block/.style    = {rectangle, draw, fill=black!25, text width=5em, text centered, rounded
                            corners, minimum height=4em},
         line/.style     = {draw, -latex'},
         cloud/.style    = {draw, ellipse,fill=red!20, node distance=3cm, minimum height=2em}
}
\begin{document}
    \begin{tikzpicture}[node distance = 2cm, auto]
        \node [block] (st1) {Stage 1};
        \node [block, right of=st1, node distance=3cm] (st2) {Stage 2};
        \node [block, right of=st2, node distance=3cm] (st3) {Stage 3};
        \path [line] (st1) -- (st2);
        \path [line] (st2) -- (st3);
        %% from st1 draw 1 unit down, then 2 units left (put a node), draw vertically up and then right to reach st1.west
        \path[line,dashed] (st1.south) -- ++(0,-1) -- +(-2,0) node[pos=0.5,below]{Blah1} |- (st1.west) ;
        %% draw 1 unit down from st3.south then horizontally left and up to reach st2.south.
        \path[line,dashed] (st3.south) -- +(0,-1) -|  (st2.south) node[pos=0.25,below]{Blah2} ;    \end{tikzpicture}
\end{document}

Change the pos=<dimen> as you wish. I have also used -| to draw the lines which means draw horizontally first and then vertically. Also, use \tikzset instead of \tikzstyle (which is deprecated).


text:
Q: Access aws dynamodb using boto3 when MFA has been set. Getting ClientError Previously when I did not set MFA to login to AWS console I've connected to dynamodb by
dynamo = boto3.resource('dynamodb',
                        region_name='ap-northeast-2',
                        endpoint_url='http://dynamodb.ap-northeast-2.amazonaws.com')
table = dynamo.Table('tablename')

and querying to that table was perfectly fine.
response = table.query(
    KeyConditionExpression =Key("user_id").eq(123123)
)

After I've set MFA for additional security to login to AWS console and now when I execute above code I get:
ClientError: An error occurred (UnrecognizedClientException) when calling the Query operation: The security token included in the request is invalid.

I use tunnel for RDB, is there something like that I could use for connecting to dynamodb or is there a permission I need in order to access dynamodb?

A: When you enable MFA, SDK does not automatically know how to work with it. Your regular IAM user's API and SECRET keys are no longer enough. Instead you need to use temporary credentials created only for your MFA session.
To make MFA work with boto3 you have to explicitly call get_session_token:

MFA-enabled IAM users would need to call GetSessionToken and submit an MFA code that is associated with their MFA device. Using the temporary security credentials that are returned from the call, IAM users can then make programmatic calls to API operations that require MFA authentication.

Using get_session_token you can call sts service which is going to provide you with temporary credentials based on your MFA details:
sts = boto3.client('sts')

mfa_response = sts.get_session_token(
    DurationSeconds=123,
    SerialNumber='string',
    TokenCode='string'
)

The call will return the credentials in mfa_response which you can use to create a new boto3 session. For example:
mfa_session = boto3.session.Session(
      aws_access_key_id=mfa_session['Credentials']['AccessKeyId'],
      aws_secret_access_key=mfa_session['Credentials']['SecretAccessKey'],
      aws_session_token=mfa_session['Credentials']['SessionToken'])

dynamo = mfa_session.resource('dynamodb', ...)

# and the rest of the code


text:
Q: Potential of a particle across a thin razor disk An example of dynamics in $\lvert x\rvert$ potential is the motion of a particle across a thin infinite disk of matter. A model disk reduces to potential of the form $U = -k/(a+|z|)$, when we consider only vertical motion ($k>0$).
How to show that dynamics in the disk reduces to that in $\lvert z \rvert$ potential for $z$ small enough?


text:
Q: How to set an environmental variable in Apache (or OS) and get the value in PHP? I made sure the env module was installed:
a2enmod
Your choices are: access_compat
...
Which module(s) do you want to enable (wildcards ok)?
env
Module env already enabled

I tried setting an environmental variable in "/etc/apache2/apache2.conf" for localhost by adding the following section:
<VirtualHost *:80>
    ServerName localhost
    ServerAdmin me@somewhere.com
    DocumentRoot /var/www/html
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
    SetEnv devmode 1
</VirtualHost>

...restarted Apache using:
sudo /etc/init.d/apache2 restart

...and then getting the value in PHP using:
getenv("devmode")

or:
apache_getenv("devmode")

...but nothing shows up with these functions when accessing the script via a browser on localhost, the values are empty in PHP.  I tried placing the command on it's own, without the VirtualHost section:
SetEnv devmode 1

I tried adding the following line to envvars:
export devmode=1

Update
I also tried putting the VirtualHost section in a dedicated file in /etc/apache2/sites-available, and adding the file with a2ensite.
I am using Linux Mint version 17.3.  What am I doing wrong?

A: Have you tried apache_getenv ?

A: After putting the VirtualHost section into a dedicated file, as I described in the original question, I found that the solution was to run the Apache restart command again:
sudo /etc/init.d/apache2 restart

Then the devmode variable showed up in PHP.


text:
Q: $ P(W_t - W_\tau > 0 \text{ and } \tau Let $W_t$ be a standard Wiener process and $\tau = \min \lbrace t \geq 0 :W_t \geq a \rbrace$, the first time the process reaches level $a$. By symmetry of the Gaussian distribution we have
$$
P(W_t - W_\tau > 0 \mid \tau =s) = P(W_t - W_\tau < 0 \mid \tau =s) = 1/2
$$
Now the statement I don't fully follow is:

Integration over $0 \leq s \leq t$ against the distribution of $\tau$
  gives $$ P(W_t - W_\tau > 0 \text{  and  } \tau <t) =
 \frac{1}{2}P(\tau < t) $$

This is taken from these notes (page 7): http://galton.uchicago.edu/~lalley/Courses/390/Lecture5.pdf
I am unsure of what exactly one integrates against the distribution of $\tau$, and whether this distribution is used explicitly or not, and which rule of probability one uses to assert that integration against the distribution is the step to perform.
If someone could show the intermediate steps it would be greatly appreciated.

A: \begin{align}
P(W_t - W_\tau > 0 \text{  and  } \tau <t)&=P(W_t - W_\tau > 0 \text{  and  } \tau <t\Big|\tau<t)P(\tau<t)\\&+P(W_t - W_\tau > 0 \text{  and  } \tau <t\Big|\tau>t)P(\tau>t)\\
&=P(W_{t-\tau} > 0 )P(\tau<t)+0\times P(\tau>t)\\
&=\frac12P(\tau<t)
\end{align}


text:
Q: How to SSR on specific routes on angular-universal? I am using angular-universal in my PWA app for SEO purpose which is working fine, but it has the following issues
1). PWA app is not working in offline mode.
2). During first time load of the app, it flickers screen component (i think it is due to SSR)
So what I was thinking like if we are able to configure angular-universal like it will only process SSR on specific routes (i.e. product detail page) and rest of the routes will server as a normal angular app, so it will resolve screen flicker issue, also by default on root route it will work as normal angular app so PWA on offline mode will also work.
Is there any way to configure SSR on specific routes?
Here we can see that SSR is applying for every route:
app.set('view engine', 'html');
app.set('views', join(DIST_FOLDER, 'browser'));

app.get('*.*', express.static(join(DIST_FOLDER, 'browser')));

app.get('*', (req, res) => {
  res.render(join(DIST_FOLDER, 'browser', 'index.html'), { req });
});

app.listen(PORT, () => {
  console.log(Node server listening on http://localhost:${PORT});
});


text:
Q: Sort array by unique id, by keeping last in Javascript I'm trying to make unique id list from an array that has multiple same id's. But I want it to keep the last one, not the first one. The code I have here keeps first unique object. Is there an Array.findLastIndex() I can use here. I searched but couldn't find a similar question.
[{id:2,name:'first'}, {id:2,name:'second'}, {id:3}]
    .filter((v, i, a) => a.findIndex((t) => (t.id === v.id)) === i)

That code returns :
[{id: 2, name: "first"}, {id: 3}]

But I want:
[{id: 2, name: "second"}, {id: 3}]

I have wrote the next one which gives me the result, but ideally I do not want to copy and reverse my array twice, it will be quite inefficient for long arrays.
[{id:2,name:'first'}, {id:2,name:'second'}, {id:3}]
  .slice().reverse()
  .filter((v, i, a) => a.findIndex((t) => (t.id === v.id)) === i)
  .reverse()

A: You can store them in a Map id => object, and pull the values back out:

arr = [{id:2,name:'first'},{id:2,name:'second'},{id:3}]

result = [...new Map(arr.map(x => [x.id, x])).values()]

console.log(result)

Since the Map constructor overwrites existing values, you automagically get the last one.
As noted in the comments, after this, the result elements will be ordered by the first occurrence, not by the last:

arr = [
   {id:3,name:'first 3'},
   {id:2,name:'first 2'},
   {id:2,name:'second 2'},
   {id:3,name:'second 3'}]

result = [...new Map(arr.map(x => [x.id, x])).values()]

console.log(result)

If you additionally want to sort by id, as your title suggests, then add
.sort((a, b) => a.id - b.id)

to the above.

A: One solution is to use Array.reduce() to generate an object using the id property as the keys while overwriting previous values. Then you can use Object.values() on the generated object:

let arr = [
  {id:2, name:'first'},
  {id:2, name:'second'},
  {id:3}
];

let res = Object.values(arr.reduce((acc, obj) => (acc[obj.id] = obj, acc), {}));
console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

A: You could reverse the array and take the first found uniqe value. After filtering reverse the result set.

var array = [{ id: 2, name: 'first' }, { id: 2, name: 'second' }, { id: 3 }],
    unique = array
        .reverse()
        .filter((s => ({ id }) => !s.has(id) && s.add(id))(new Set))
        .reverse();

console.log(unique);

A classic approach.

var array = [{ id: 2, name: 'first' }, { id: 2, name: 'second' }, { id: 3 }],
    seen = Object.create(null),
    unique = array.reduceRight((r, o) => {
        if (!seen[o.id]) {
            r.unshift(o);
            seen[o.id] = true;
        }
        return r;
    }, []);

console.log(unique);

A: I like Shidersz answer the most, but here's another possibility:

    let arr = [
      {id:2, name:'first'},
      {id:2, name:'second'},
      {id:3}
    ];

    let res = arr.filter((v, i) => {
      for (let j = i + 1; j < arr.length; j++) {
        if (v.id === arr[j].id) return false
      }
      return true;
    })
    console.log(res);

My guess is that it uses less memory (doesn't have to create an intermediate object) but it probably runs slower due to not using constant time to look for duplicates. Not by much though, since the  lookup is quite scope between current value and next first duplicate.


text:
Q: SP Provider Hosted Add-in: HTTP Request is unauthorized while calling ItemAdded RER I am working on SharePoint Provider hosted app for SharePoint Online. The remote web application is deployed on Azure Web App service(azurewebsites.net) and configured authentication/authorization with Active Directory.
I have remote event receiver for item added event. When I add any item to list it get triggered but it get unauthorized error 401. Error details: The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'Bearer realm="xyz.azurewebsites.net"'.
If I enable Anonymous access to complete azurewebsites then remote event receiver get call.
Does anyone have faced this issue? Based on the error, SharePoint is calling RER with Anonymous scheme but azurewebsite is enabled with Active Directory Authentication. I tried allowing anonymous access to only AppEventReceiver.svc but that didn't worked.
web.config edits
<configuration>
    <location path="~/Services/AppEventReceiver.svc">
        <system.web>
            <authorization>
                <allow users="?"/>
            </authorization>
        </system.web>
    </location>
 <!-- other elements -->
</configuration>

A: I had discussion with experts and they did talked with MS team. The authenticated RER have issues and they failed to get invoked.
Also, Azure Web app does not support 'Anonymous' access to particular resource through web.config.
So to fix this issue, I have to keep the Azure Web App configured with 'Anonymous' access and add additional security that Azure Web App only accessible from restricted IP addresses.


text:
Q: Would it be possible to create a UiPath Custom Activity using Powershell? In UiPath you can create Custom Activities using C# code as seen here. I dont know much about C# and I was wondering if anyone has any clue how or if its even possible to create a custom activity with Powershell and how I would do that.
Finally, any insight on how I could wrap up the code (and Im assuming corresponding dlls) into a nuGet package  would be immensely helpful. Thank you in advance!
I've tried with C#. I got it to work, but as I try to do more complex things, Id like to know if I could leverage powershell as I am much more familiar with it.

A: The page you linked contains a step-by-step guide. You can't use PowerShell to create custom activities, you will need Visual Studio and C#. There is the free Community Edition available that you can use, but check whether the terms apply.
With VS installed, you would go ahead an create a new class library - just follow their guide.
When your activity is done you would need to deploy it as a NuGet Package, and you can use the Package Explorer to do so. This is were you would "wrap up" all binaries created - they become part of said package.
However, since you mentioned PowerShell - not knowing your precise requirements, of course - there is an activity dedicated to executing PowerShell commands in UiPath: the Invoke PowerShell activity. If you're already familiar with PS, if you have plenty of scripts lying around, just use this activity.


text:
Q: Quais as convenções de nomes na criação de base de dados, tabelas e colunas em mysql Gostava de saber que tipo de convenções existem nos nomes atribuídos a base de dados, tabelas e colunas em mysql, é normalmente usado camelCase ou outro tipo de convenção?

A: O MySQL não é Case sensitive no Windows, portanto independente do "case" da criação da tabela, você sempre poderá acessá-la por tabela1 ou TABELA1, o mesmo ocorre com as colunas.
O que não ocorre com o Linux, que é Case Sensitive.
Embora seja configurável (veja como em: https://dev.mysql.com/doc/refman/5.0/en/identifier-case-sensitivity.html)
O que eu sugiro é usar nomenclatura que seja ideal independente da plataforma (Windows ou Linux) e da configuração do MySQL:
Nomes de tabelas:
PEDIDO_DE_VENDA
PEDIDO_DE_VENDA_PRODUTO
CLIENTES_ENDERECOS
E para colunas:
PEDIDO_ID, NUM_ENDERECO, VALOR_UNITARIO


text:
Q: Seg. fault in Multithreaded UDP server Background:
I have a UDP server that can process clients' requests concurrently. Each client sends two datagrams to the server.

*

*First datagram (Type - 1, Client num)

*Second datagram (Type - 2, Client num)

To process all clients concurrently, I initially create a fixed number of server threads and one global UDP socket bound to a known port/address. Then each thread starts to run wherein they block on recvfrom() call on the same global socket. Whichever thread receives a datagram first checks
the type. If it is type 1, it generates a "special" number for the client num it received and stores it. It it is type 2, it sends back the stored "special" number for that client.
Server program:
#define SIZE 1024

int status;
int tnum;
int i;
vector<pthread_t> tid;
struct sockaddr_in server_sock_addr;
const char *server_addr = "127.0.0.1";
int sock;
int reuse = 1;
socklen_t addr_len = sizeof(sockaddr_in);
unordered_map<int, int> dic;

void report(int status){
    if(status < 0){
        perror("Error");
        exit(EXIT_FAILURE);
    }
}

void* server_func(void *arg){
    int bytes;
    char *buf = (char*)malloc(SIZE);
    struct sockaddr_in client_sock_addr;
    int type;
    int num;

    while(1){
        bytes = recvfrom(sock, buf, SIZE, 0, (sockaddr*)&client_sock_addr, &addr_len);
        cout<<bytes<<endl;
        report(bytes);
        memmove(&type, buf, sizeof(int));
        memmove(&num, buf + sizeof(int), sizeof(int));
        if(type == 1){
            dic[num] = num * 1000;
        }
        else if(type == 2){
            while(dic.find(num) == dic.end()){
            };
            memset(buf, 0, SIZE);
            memmove(buf, &dic[num], sizeof(int));
            status = sendto(sock, buf, sizeof(int), 0, (sockaddr*)&client_sock_addr, addr_len);
            report(status);
            cout<<"Mapped number is "<<num<<" - "<<dic[num]<<endl;
        }
        else{
            report(-1);
        }
    }
    free(buf);
}

int main() {

    cout<<"-------------------------------------------"<<endl;
    cout<<"SERVER STARTED on port 5000"<<endl;
    cout<<"-------------------------------------------"<<endl;
    tnum = 4;
    sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    bzero((char*)&server_sock_addr, sizeof(server_sock_addr));
    server_sock_addr.sin_family = AF_INET;
    server_sock_addr.sin_port = htons(5000);
    inet_aton(server_addr, &server_sock_addr.sin_addr);
    setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(int));
    status = bind(sock, (struct sockaddr*)&server_sock_addr, sizeof(server_sock_addr));
    report(status);
    tid.resize(tnum);
    dic.clear();
    for (i = 0; i < tnum; i++) {
        status = pthread_create(&tid[i], NULL, server_func, NULL);
        report(status);
    }
    for (i = 0; i < tnum; i++) {
        pthread_join(tid[i], NULL);
    }
    close(sock);
    return 0;
}

Client program
#define SIZE 1024

int num;
int i;
vector<pthread_t> tid;
vector<int> client_num;
const char *server_addr = "127.0.0.1";
socklen_t addr_len = sizeof(sockaddr_in);

void report(int status){
    if(status < 0){
        perror("Error");
        exit(EXIT_FAILURE);
    }
}

void* client_func(void *arg){
    struct sockaddr_in server_sock_addr;
    int cnum = *((int*)arg);
    char *buf = (char*)malloc(SIZE);
    int type;
    int sock;
    int bytes;
    int status;
    int res;

    sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    bzero((char*)&server_sock_addr, sizeof(server_sock_addr));
    server_sock_addr.sin_family = AF_INET;
    server_sock_addr.sin_port = htons(5000);
    status = inet_aton(server_addr, &server_sock_addr.sin_addr);
    report(status);

    type = 1;
    memset(buf, 0, SIZE);
    memmove(buf, &type, sizeof(int));
    memmove(buf + sizeof(int), &cnum, sizeof(int));
    status = sendto(sock, buf, 2 * sizeof(int), 0, (sockaddr*)&server_sock_addr, addr_len);
    report(status);
    type = 2;
    memset(buf, 0, SIZE);
    memmove(buf, &type, sizeof(int));
    memmove(buf + sizeof(int), &cnum, sizeof(int));
    status = sendto(sock, buf, 2 * sizeof(int), 0, (sockaddr*)&server_sock_addr, addr_len);
    report(status);
    bytes = recvfrom(sock, buf, SIZE, 0, (sockaddr*)&server_sock_addr, &addr_len);
    report(bytes);
    memcpy(&res, buf, sizeof(int));
    cout<<"Mapped number from the server for Client - "<<cnum<<" is "<<res<<endl;
    free(buf);
    close(sock);
}

int main(int argc, char *argv[]) {
    int status;

    if(argc < 2){
        cout<<"Enter number of threads"<<endl;
        exit(EXIT_FAILURE);
    }
    num = atoi(argv[1]);
    tid.resize(num);
    client_num.resize(num);
    for (i = 0; i < num; i++) {
        client_num[i] = i+1;
        status = pthread_create(&tid[i], NULL, client_func, &client_num[i]);
    }
    for (i = 0; i < num; i++) {
        pthread_join(tid[i],NULL);
    }
    cout << "Requested duration has ended. Finishing the program." << endl;
    return 0;
}

Problem I am facing:
When 500 clients send datagrams concurrently, the server works as expected only when I include some kind of COUT statement after the recvfrom() call(First line in while(1) loop). If I delete that cout statement, it gives Segmentation fault because the server gets stuck on the while() loop to check whether an item exists or not. while(dic.find(num) == dic.end()){};. I am not able to figure out the reason for this problem. Please provide me your suggestions.
Thanks.
EDIT:

*

*Having a mutex lock on "dic" data-structure(while writing it) solves the problem(I do not need to use "cout" anymore), but I want to confirm whether this is absolutely the correct fix and want to learn anyother subtle points that I could out of this program, because I'd building a much bigger version of this program soon with lots of global datastructures to be shared by all threads


text:
Q: $H^2(X,\mathbb{Z})$,$H_2(X,\mathbb{Z})$of smooth complex projective variety$X$ is there some example that: $X$ is a smooth complex projective variety, second singular cohomology $H^2(X,\mathbb{Z})$ has nontrivial torsion subgroup?

A: Feng, try this:
Consider a surface $\Sigma$ in $\mathbb{P}^3$. There is an action of $\mu_p$ (roots of unity) on $\mathbb{P}^3$ where the coordinate $z_i$ is sent to $\zeta^i z_i$ under the action of $\zeta \in \mu_p$. Assume $\Sigma$ is fixed by this action. Then $H^2(\Sigma/\mu_p,\mathbb{Z})_{tors} = \mathbb{Z}/p\mathbb{Z}$. (Recall that by Lefschetz theorem $\Sigma$ is simply connected.) Why? Consider a nontrivial character of $\mu_p$. This gives you descent data for descending the trivial line bundle on $\Sigma$ to $\mathcal{L}$ on $\Sigma/\mu_p$. This will have $p$-torsion Chern class $c_1(\mathcal{L})$ in $H^2$.

A: The universal coefficient theorem says that $H^2(X;\Bbb Z) \cong \text{Hom}(H_2(X;\Bbb Z),\Bbb Z) \oplus \text{Ext}(H_1(X;\Bbb Z),\Bbb Z)$. Because complex projective varieties are compact and triangulable, $H_2(X)$ and $H_1(X)$ are finitely generated, so $\text{Hom}(H_2(X);\Bbb Z),\Bbb Z)$ is torsion-free, and $\text{Ext}(H_1(X;\Bbb Z),\Bbb Z)$ is the torsion subgroup of $H_1(X;\Bbb Z)$.
So, equivalently, your question asks "Are there smooth projective complex varieties with torsion in $H_1(X;\Bbb Z)$?" And the answer is yes; take an Enriques surface, for instance, which has $\pi_1(E) = \Bbb Z/2$ because it has the simply-connected $K3$ surface as a double cover.


text:
Q: No possible to upgrade expo sdk version I have a react native expo peoject, I was testing it using expo go on android phone.
But right now I update the movile app and when I try to scan the QR code to test the app, it show me that the sdk expo on the movile just support 47, 45 and 45 sdk version, but the project is using 44 sdk version.
On the project I'm using "expo-cli upgrade" to the the 46 sdk version, but I get this error:
┌─────────────────────────────────────────────────────────────────────────┐
│                                                                         │
│   There is a new version of expo-cli available (6.0.8).                 │
│   You are currently using expo-cli 5.1.3                                │
│   Install expo-cli globally using the package manager of your choice;   │
│   for example: `npm install -g expo-cli` to get the latest version      │
│                                                                         │
└─────────────────────────────────────────────────────────────────────────┘
Warning! Your git working tree is dirty.
It's recommended to commit all your changes before proceeding, so you can revert the changes made by this command if necessary.

√ Would you like to proceed? ... yes

√ You are currently using SDK 44.0.0. Would you like to update to the latest version, 47.0.0? ... yes

× Failed to install expo package with error: yarnpkg exited with non-zero code: 1
yarnpkg exited with non-zero code: 1
Error: yarnpkg exited with non-zero code: 1
    at ChildProcess.completionListener (C:\Users\Bosatzu\AppData\Roaming\nvm\v14.15.1\node_modules\expo-cli\node_modules\@expo\spawn-async\src\spawnAsync.ts:65:13)
    at Object.onceWrapper (events.js:422:26)
    at ChildProcess.emit (events.js:315:20)
    at ChildProcess.cp.emit (C:\Users\Bosatzu\AppData\Roaming\nvm\v14.15.1\node_modules\expo-cli\node_modules\cross-spawn\lib\enoent.js:34:29)
    at maybeClose (internal/child_process.js:1048:16)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:288:5)
    ...
    at Object.spawnAsync [as default] (C:\Users\Bosatzu\AppData\Roaming\nvm\v14.15.1\node_modules\expo-cli\node_modules\@expo\spawn-async\src\spawnAsync.ts:26:19)
    at YarnPackageManager._runAsync (C:\Users\Bosatzu\AppData\Roaming\nvm\v14.15.1\node_modules\expo-cli\node_modules\@expo\package-manager\src\NodePackageManagers.ts:309:31)
    at YarnPackageManager.addAsync (C:\Users\Bosatzu\AppData\Roaming\nvm\v14.15.1\node_modules\expo-cli\node_modules\@expo\package-manager\src\NodePackageManagers.ts:258:16)
    at upgradeAsync (C:\Users\Bosatzu\AppData\Roaming\nvm\v14.15.1\node_modules\expo-cli\src\commands\info\upgradeAsync.ts:496:7)
    at actionAsync (C:\Users\Bosatzu\AppData\Roaming\nvm\v14.15.1\node_modules\expo-cli\src\commands\info\upgradeAsync.ts:42:3)

I'm using SO windows 10.
This is the package.json file:
{
  "scripts": {
    "start": "react-native start",
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "web": "expo start --web",
    "eject": "expo eject"
  },
  "dependencies": {
    "@fortawesome/fontawesome-svg-core": "^1.2.35",
    "@fortawesome/free-brands-svg-icons": "^5.15.3",
    "@fortawesome/free-regular-svg-icons": "^5.15.3",
    "@fortawesome/free-solid-svg-icons": "^5.15.3",
    "@fortawesome/react-native-fontawesome": "^0.2.6",
    "@gorhom/bottom-sheet": "^3.6.6",
    "@material-ui/core": "^4.12.2",
    "@react-native-async-storage/async-storage": "~1.15.0",
    "@react-native-community/datetimepicker": "4.0.0",
    "@react-native-community/masked-view": "^0.1.10",
    "@react-native-picker/picker": "2.2.1",
    "@react-navigation/material-bottom-tabs": "^5.3.15",
    "@react-navigation/material-top-tabs": "^6.0.4",
    "@react-navigation/native": "^5.9.4",
    "@react-navigation/stack": "^5.14.5",
    "axios": "^0.21.4",
    "core-js": "^3.20.3",
    "expo": "^44.0.0",
    "expo-checkbox": "~2.0.0",
    "expo-cli": "^5.1.3",
    "expo-dev-client": "^0.8.6",
    "expo-font": "~10.0.4",
    "expo-location": "~14.0.1",
    "expo-splash-screen": "~0.14.1",
    "expo-status-bar": "~1.2.0",
    "expo-updates": "^0.11.7",
    "moment": "^2.29.1",
    "native-base": "^3.1.0",
    "qrcode": "^1.5.0",
    "radio-buttons-react-native": "^1.0.4",
    "react": "17.0.1",
    "react-dom": "17.0.1",
    "react-native": "0.64.3",
    "react-native-air-progress-bar": "0.0.5",
    "react-native-backdrop": "^2.1.2",
    "react-native-count-to": "0.0.2",
    "react-native-countdown-component": "^2.7.1",
    "react-native-date-picker": "^4.1.1",
    "react-native-dialog": "^8.0.1",
    "react-native-gesture-handler": "^2.1.0",
    "react-native-hide-show-password-input": "^1.2.0",
    "react-native-ico": "^28.7.4",
    "react-native-ico-material-design": "^3.3.1",
    "react-native-loading-spinner-overlay": "^2.0.0",
    "react-native-maps": "0.29.4",
    "react-native-material-design": "^0.3.7",
    "react-native-modal-datetime-picker": "^13.0.0",
    "react-native-pager-view": "5.4.9",
    "react-native-paper": "^4.9.2",
    "react-native-propel-kit": "^1.0.1",
    "react-native-qrcode-svg": "^6.1.2",
    "react-native-reanimated": "^2.3.1",
    "react-native-safe-area-context": "^3.3.2",
    "react-native-screens": "^3.10.1",
    "react-native-snackbar": "^2.4.0",
    "react-native-snap-carousel": "^3.9.1",
    "react-native-stars": "^1.2.2",
    "react-native-svg": "^12.1.1",
    "react-native-tab-view": "^3.1.1",
    "react-native-unimodules": "~0.15.0",
    "react-native-vector-icons": "^8.1.0",
    "react-native-web": "0.17.1",
    "react-navigation-stack": "^2.10.4",
    "reanimated-bottom-sheet": "^1.0.0-alpha.22",
    "rn-qr-generator": "^1.2.0",
    "sentry-expo": "^4.0.5",
    "styled-components": "^5.3.1",
    "styled-system": "^5.1.5"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9"
  },
  "private": true,
  "name": "parking-app-front",
  "version": "1.0.0"
}

I hope you can help me out with this

A: You can solve this problem by doing the following steps:

*

*delete yarn.lock or package-lock.json and node_modules.

*run yarn install or run yarn (if you are using npm you can run npm install.

*if all the above steps worked fine then run `expo upgrade.

this would do the trick.


text:
Q: Regex for repeated numbers with predifined start I've got something for the regex experts here. I'm trying to check if there are any repeated sequences in a decimal number. At the moment I've got this working:
(\d{2,}?)\1

The problem is that this does not work very well with numbers like 0.00035 or 11125.5
Here it matches the 0.000 or the 111 as repeated sequences, and I don't want that to happen.
Is there a way to modify this regex to make it so it will only check after the decimal point, and exclude X number of zeroes from the first decimal places?

A: You can do it with this pattern:
[0-9]+\.0*+[0-9]*?([0-9]{2,})\1[0-9]*

The pattern uses a possessive quantifier 0*+ to prevent to match repeated zeros after the decimal separator. (the possessive quantifier forbids backtracking).
[0-9]*? has a non-greedy quantifier to be sure to find the first repeated sequence.


text:
Q: Conjugate of difference of convex functions I am reading through this tutorial on DC programming and the author makes a startling claim without proof:
If $g$ and $h$ are two lower semi-continuous convex function, then the conjugate function of their difference
$$(g-h)^*(y) \equiv \sup\{x'y - (g-h)(x)\} = h^*(y) - g^*(y) $$ where $h^*$ and $g^*$ are their conjugates respectively $g^*(y) \equiv \sup\{x'y - g(x)\}$, etc.
I'm not able to convince myself that this statement is true. Any ideas / suggestions on how its proof might go?

A: The claim is false. In general, the conjugate of $g-h$ is not even finite: e.g., $g\equiv 0$, $h(x)=x^2$.
And when it is finite, the equality has no reason to hold. Let $g(x)=Ax^2$ and $h(x)=Bx^2$ with $A>B>0$. Then $g^*(x)=\frac{1}{4A}x^2$, $h^*(x)=\frac{1}{4B}x^2$, and $(g-h)^*(x)=\frac{1}{4(A-B)}x^2$. Obviously, we should not expect $1/(A-B)$ to be equal to $1/B-1/A$.
The analogous statements for sums and scalar multiples are also false.
The Legendre transform is very nonlinear.