text:
Q: Hackerrank: Plus Minus I'm trying to find the fraction of positive, negative, and zero in the array but the function is not returning anything.

var noOfPostive = 0;
var noOfNegative = 0;
var noOfZero = 0;

function plusMinus(arr) {
  /*
   * Write your code here.

   */
  var length = arr.length;

  for (var i = 0; i < arr.length; i++) {
    if (i > 0) {
      noOfPostive += 1;
    } else if (i < 0) {
      noOfNegative += 1;
    } else {
      noOfZero += 1;
    }

    var FractionOfPostive = noOfPostive / length;
    var FractionOfNegative = noOfNegative / length;
    var FractionOfZero = noOfZero / length;
    return FractionOfPostive, FractionOfPostive, FractionOfZero;

  }
}

plusMinus([-4,3,-9,0,4,1]);

A: This is a simple and fast solution:
you can use the filter function to iterate in the array and get a new array only with the numbers that fulfill the condition; positive (n> 0), negative (n <0) and neutral (n == 0) numbers. In the same variable you can calculate the size of the returned array and divide it by the size of the original array, so you get the fraction, which you must format to only 6 decimal places with toFixed(6) and print an output in the requested format.
function plusMinus(arr) {
    let positive = arr.filter(number => number > 0).length / arr.length;
    let negative = arr.filter(number => number < 0).length / arr.length;;
    let zeronums = arr.filter(number => number == 0).length / arr.length;;
    return console.log(positive.toFixed(6) + '\n' + negative.toFixed(6) + '\n' + zeronums.toFixed(6))
}

A: I'd use reduce() to get the result, combined with Math.sign() which will return 0, 1 or -1 depending on if the number is 0, positive or negative. Below will return an array of arrays, each holding the identifier for +,0,- as the first element, and the fraction as the second one.

function plusMinus(arr) {
  return Object.entries(arr.reduce((a, b) => {
    let sign = Math.sign(b);
    a[sign] = (a[sign] || 0) + 1;
    return a;
  }, {})).map(e => [e[0], e[1] / arr.length]);
}

console.log(plusMinus([-4, 3, -9, 0, 4, 1]));

A: I did this simple code in Python where first it takes the nos of elements of the array from the user and then the array elements.
After this only comparison is done and the counter is incremented.
Here's the code:
pos=0
neg=0
z=0

n = int(input().strip())
arr = [int(arr_temp) for arr_temp in input().strip().split(' ')]

for num in arr:
    if num>0:
        pos+=1

    elif num == 0:
        z+=1
    elif num<0:
        neg+=1

print(pos/n)
print(neg/n)
print(z/n)

A: function plusMinus(arr) {
    let decimal = 6;
    let length = arr.length;
    let positive = arr.filter(val => val > 0).length;
    let negative = arr.filter(val => val < 0).length;
    let zero = arr.filter(val => val == 0).length;

    function findRatio(num) {
        return console.log(parseFloat(num / length).toPrecision(decimal));
    }

    findRatio(positive);
    findRatio(negative);
    findRatio(zero);
}

A: First of, when you are looping in an array with for, you are actually storing the index in i, so you still need to check the value at that index in the array:
let value = arr[ i ]

Secondly, your return statement was inside your for loop, so it didn't even run once before it returned.
Thirdly, your return values need to be a single value or object, so you can't return a, b, c;, as only c would be returned.
See below for all of the above applied. Also note that I have moved your variables to inside your function definition - if you run this function twice it will always reset its values to zero, so it does not keep increasing the amount (your numbers would become bigger than 1 after a single run). I have also used let variables inside blocks (like let i and let value - these don't do anything in particular, but they have to do with scoping and memory. If inside a block, use let, but don't worry too much there).

function plusMinus( arr ){

  var pos = 0;
  var neg = 0;
  var zero = 0;
  var length = arr.length;

  for( let i = 0; i < length; i++ ){

    let value = arr[ i ];

    if( value > 0 ){

      pos += 1;

    } else if( value < 0 ) {

      neg += 1;

    } else {

      zero += 1;

    }

  }

  var FractionOfPostive = pos / length;
  var FractionOfNegative = neg / length;
  var FractionOfZero = zero / length;

  return {
    FractionOfPostive,
    FractionOfNegative,
    FractionOfZero
  };

}

console.log( plusMinus([-4,3,-9,0,4,1]) );

A: You need do perform couple of fixes in your code. The following typos exist in your code.
Inaccurate return statement :
return can not send multiple variable as a result. You need to store your result in an array and send the array back to caller.
Not ofchecking array value :
if(i>0) doesn't mean anything. If you need to check if the array value is positive or not then you need to do
if(arr[i]>0)

Misplaced last curly brace of for loop :
also you have typo in your for loop. You've extended your for loop to the end of the function.That means your positive or negative count also inside the for loop. That means they will loose the previous computed result during each iteration.

var noOfPostive = 0;
var noOfNegative = 0;
var noOfZero = 0;

function plusMinus(arr) {
  /*
   * Write your code here.

   */
  var length = arr.length
  var result = []
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] > 0) {
      noOfPostive += 1;
    } else if (arr[i] < 0) {
      noOfNegative += 1;
    } else {
      noOfZero += 1;
    }

    }
    var FractionOfPostive = parseFloat(noOfPostive / length);
    var FractionOfNegative = parseFloat(noOfNegative / length);
    var FractionOfZero = parseFloat(noOfZero / length);

 result.push(FractionOfPostive,FractionOfNegative,FractionOfZero)
    return result;

}

console.log(plusMinus([-4,3,-9,0,4,1]));

Consider not using a For-Loop:
Here you have seen that you misplaced the last curly brace of your for loop.Thus you got unexpected result.Loops sometime creates problem.To avoid using for loops you can use ES6 Generator functions for this purpose instead of a for loop.This is  functional approach to solve this problem.
function plusMinus(arr) {

    var length = arr.length
    var result = []

    function* generateResult(){
       var positives = arr.filter((index,elem) => elem>0)
       yield positives.length
       var negatives = arr.filter((index,elem) =>elem<0)
       yield negatives.length
       var zeros = arr.filter((index,elem) => elem==0)
       yield zeros.length
    }

    var start = generateResult()

    var FractionOfPostive = parseFloat(start.next().value / length);
    var FractionOfNegative = parseFloat(start.next().value / length);
    var FractionOfZero = parseFloat(start.next().value / length);

    return {FractionOfPostive,FractionOfNegative,FractionOfZero};

}

A: function plusMinus(arr) {

    let positives = 0
    let negatives = 0
    let zeros = 0
    const length=arr.length

    for (var i = 0; i < arr.length;i++){
        if (arr[i] > 0) {
            positives++
        } else if (arr[i] < 0) {
            negatives++
        } else {
            zeros ++
        }
    }

    const positiveRatio = Number(positives / length).toFixed(6)
    const negativeRatio = Number(negatives / length).toFixed(6)
    const zeroRatio = Number(zeros / length).toFixed(6)

    console.log(positiveRatio)
    console.log(negativeRatio)
    console.log(zeroRatio)
}

A: function plusMinus($arr) {
$countArr = count($arr);
$positive = 0;
$negative = 0;
$zero = 0;
for($i = 0; $i < $countArr; $i++){
    if($arr[$i] > 0){
        $positive += 1;
    }
    if($arr[$i] === 0){
        $zero += 1;
    }
    if($arr[$i] < 0){
        $negative += 1;
    }
}
$fractionPositive = number_format($positive/$countArr, 6);
$fractionNegative = number_format($negative/$countArr, 6);
$fractionZero = number_format($zero/$countArr, 6);

printf("%f\n%f\n%f",$fractionPositive, $fractionNegative, $fractionZero);

}

A: I made the code even simpler with Math.sign(), check this out
// Complete the plusMinus function below.
function plusMinus(arr) {
    let neg= arr.filter(elem => Math.sign(elem)=== -1).length/arr.length;
    let pos= arr.filter(elem => Math.sign(elem)=== 1).length/arr.length;
    let zer = arr.filter(elem => Math.sign(elem)=== 0).length/arr.length;

    return console.log(pos+ '\n' + neg+ '\n' + zer)

}

Math.sign() return 1 for positive number and -1 for negative numbers and 0 for zero,
so here I used array.filter() method to filter those elements which are positive negative and zero respectively and obviously filter() returns a new array, so I took the length of the returned array and divided it with the length of the input array and directly stored it in the variable. That's it. Kudos

A: I am not a big fan of if-else condition so I have used a switch case here.

function plusMinus(arr) {

    let totalPos=0, totalNe=0, totalZe=0, arrLen = arr.length;

    for(let value of arr){

        switch(true){

           case (value > 0):
            totalPos++;
            break;

            case (value < 0):
            totalNe++;
            break;

            case (value == 0):
            totalZe++;
            break;
        }

    }

    console.log(`${(totalPos/arrLen).toFixed(6)} \n ${(totalNe/arrLen).toFixed(6)} \n ${(totalZe/arrLen).toFixed(6)}`);

}

plusMinus([-4,3,-9,0,4,1]);

A: Works fine for me.
def plusMinus(arr):
    length = len(arr)
    positiveCount = 0
    negativeCount = 0
    zeroCount = 0
    for i in range(length):
        if (arr[i] > 0):
            positiveCount += 1;
        elif(arr[i] < 0):
            negativeCount += 1;
        elif(arr[i] == 0):
            zeroCount += 1;

    print("{0:.4f}".format(positiveCount / length));
    print("%1.4f "%(negativeCount / length));
    print("%1.4f "%(zeroCount / length));
    print();

if __name__ == '__main__':
    n = int(input().strip())

    arr = list(map(int, input().rstrip().split()))

    plusMinus(arr)

A: Python Version
def plusMinus(arr):
    # Write your code here
    positive_integer = len(list(filter(lambda x: x> 0, arr)))
    negative_integer = len(list(filter(lambda x: x < 0, arr)))
    zero_integer = len(list(filter(lambda x: x == 0, arr)))
    print(positive_integer/len(arr))
    print(negative_integer/len(arr))
    print(zero_integer/len(arr))

A: I have tried your code, your logic not have any problem. The problem is:
First, your variable declaration is outside the function.
Second, your return is inside the for - loop.
Third, Instead using return, I prefer use console.log() like this:
console.log(FractionOfPostive);
console.log(FractionOfNegative);
console.log(FractionOfZero);

I hope this work and helping you.

A: I did it in this way which is easy to understand for beginner developers too
  // Write your code here
let posetiveCount = 0;
let negativeCount = 0;
let zeroCount = 0;
arr.forEach((num) => {
    // Count Posetive Numbers
    if(num > 0)  ++posetiveCount;

    // Count Negative count
    if(num < 0) ++negativeCount;

    // Count Zero
    if(num == 0) ++zeroCount;
});

// Calculationg Posetive Ration with 6 desimal
let posetiveNumRatio =  posetiveCount / arr.length;
let negativeNumRatio = negativeCount / arr.length;
let zeroNumRatio = zeroCount / arr.length;

// Console The Result
return console.log(posetiveNumRatio.toFixed(6) + '\n' + negativeNumRatio.toFixed(6) + '\n' + zeroNumRatio.toFixed(6))

}

A: this what Idid
function plusMinus(arr) {
    let positive = 0;
    let negative = 0;
    let zero = 0;
    const length = arr.length;

    for (let i = 0; i < arr.length; i++){
        if (arr[i] > 0) {
            positive +=1
        } else if (arr[i] < 0) {
            negative += 1
        } else {
            zero += 1
       }
     }
function log(a, b, c) {
    console.log(a);
    console.log(b);
    console.log(c);
}

const positiveRatio = (positive / length).toFixed(6);
const negativeRatio = (negative / length).toFixed(6);
const zeroRatio = (zero / length).toFixed(6);

return log(positiveRatio, negativeRatio, zeroRatio)
}

A: This solution works. i had to create an additional function to handle the rounding off
function plusMinus(arr) {
    let length = arr.length
    let positive = 0
    let negative = 0
    let zero = 0
    for (let i = 0; i < length; i++){
        if (arr[i] > 0) {
            positive++
        }
        else if (arr[i] < 0) {
            negative++
        }
        else if (arr[i] == 0) {
            zero++
        }
    }

    const ratioPositive = round((positive / length))
    const ratioNegative = round((negative / length))
    const ratioZero = round((zero / length))

    console.log( ratioPositive + "\n" + ratioNegative + "\n" + ratioZero )

}

function round(value) {
    return Number(value).toFixed(6);
  }

plusMinus([-4, 3, -9, 0, 4, 1])

Output:
0.500000
0.333333
0.166667

A: The following function works:
function plusMinus(arr) {
    let zero = parseFloat(arr.filter(val = > val == 0).length / arr.length).toPrecision(6)
    let pos = parseFloat(arr.filter(val = > val > 0).length / arr.length).toPrecision(6)
    let neg = parseFloat(arr.filter(val = > val < 0).length / arr.length).toPrecision(6)
    console.log(pos)
    console.log(neg)
    console.log(zero)
}

A: Here result is for [positive, negative, zero] counts, in forEach loop corresponding value is incrementing.
function plusMinus(arr) {
  const result = [0, 0, 0]
  arr.forEach(item =>
    result[item > 0 ? 0 : item ? 1 : 2]++
  )
  console.log(result.map(item => (item / arr.length).toFixed(6)).join('\n'))
}

A:

var arr = [-4, 3, -9, 0, 4, 1];

function plusMinus(arr) {
  var n = arr.length;
  var positive = 0,
    negative = 0,
    zero = 0;

  for (var i = 0; i < n; i++) {
    if (arr[i] > 0) {
      positive += 1;
    } else if (arr[i] < 0) {
      negative += 1;
    } else {
      zero += 1;
    }
  }

  var pos = positive / n;
  var neg = negative / n;
  var zer = zero / n;
  console.log(pos.toFixed(6) + "\n" + neg.toFixed(6) + "\n" + zer.toFixed(6));
}

plusMinus(arr);

A: Here is a simple solution that involves using a for-of loop, array destructuring, and template literals.

function plusMinus(arr) {

    let count = [0, 0, 0];

    let [count1, count2, count3] = count;

    let length = arr.length;

    for (let val of arr) {

      if (val > 0) {

          count1++

      }
      else if (val < 0) {

          count2++
      }
      else {

          count3++

      }

    }

 console.log(`${(count1/length).toFixed(6)}\n ${(count2/length).toFixed(6)}\n ${(count3/length).toFixed(6)}`);
}

plusMinus([-4,3,-9,0,4,1]);

A: const plusMinus = function (num, arr) {
let positives = 0, negatives = 0, zeros = 0;
for(let i = 0; i < arr.length; i++) {
    if (arr[i] > 0) {
        positives ++
    } else if (arr[i] < 0) {
        negatives ++
    } else if(arr[i] === 0) {
        zeros ++
    }
}
 console.log((positives / arr.length).toFixed(6));
 console.log((negatives / arr.length).toFixed(6));
 console.log((zeros / arr.length).toFixed(6));
};

plusMinus(6, [-4, 3, -9, 0, 4, 1]);

A: function plusMinus(arr) {
    let no_positive = 0
    let no_negative = 0
    let no_zero = 0

    for (let i=0; i<arr.length; i++) {
        if (arr[i] < 0) {
            no_negative++
        }

        if (arr[i]>0) {
            no_positive++
        }

        if (arr[i]==0) {
            no_zero++
        }
    }
    var posRatio = (no_positive/arr.length).toFixed(6);
    var negRatio = (no_negative/arr.length).toFixed(6);
    var zeroRatio = (no_zero/arr.length).toFixed(6);
    console.log(posRatio)
    console.log(negRatio)
    console.log(zeroRatio)
}

A: There is an issue in your for loop. You need to write your if statement via checking the array values subject to your index variable in the loop. You can compare your solution with the one below.
function plusMinus(arr) {
  let plus = 0;
  let minus = 0;
  let zero = 0;
  const arrLen = arr.length;
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] > 0) {
        plus++;
    } else if (arr[i] < 0) {
        minus++;
    }
    else {
        zero++;
    }
  }

  return console.log(
    (plus / arrLen).toFixed(6) +
    "\n" +
    (minus / arrLen).toFixed(6) +
    "\n" +
    (zero / arrLen).toFixed(6) +
    "\n"
  );

}

A: function plusMinus(arr) {
    let n=arr.length;
    let poscount=0
    let negcount=0
    let zerocounnt=0
    for(let i=0;i<n;i++){
        if(arr[i]>0){
            poscount+=1
        }else if(arr[i]<0){
            negcount+=1
        }else{
            zerocounnt+=1
        }
    }
    console.log((poscount/n).toFixed(6))
    console.log((negcount/n).toFixed(6))
    console.log((zerocounnt/n).toFixed(6))
}
plusMinus([-4 3 -9 0 4 1])

A: To refactor your code you need to return statement as below:
function plusMinus(arr) {
// Your code here
   return result(countPositive, countNegative, countZero);
}

function result(pos, neg, zero) {
    console.log(pos);
    console.log(neg);
    console.log(zero);
}

Another way of writing code is as below :
function plusMinus(arr) {
// Write your code here
let arrLen = arr.length;
let countPositive = (arr.filter(num => num>0).length/arrLen).toFixed(6);
let countNegative = (arr.filter(num => num<0).length/arrLen).toFixed(6);
let countZero = (arr.filter(num => num===0).length/arrLen).toFixed(6);
return result(countPositive, countNegative, countZero);
}

function result(pos, neg, zero) {
    console.log(pos);
    console.log(neg);
    console.log(zero);
}


text:
Q: I got failed to load on cloud scheduler page I want to create function has ability to refresh itself every 1 minute
but when I try write code below I got error on CMD
const functions = require('firebase-functions');

    exports.scheduledFunction = functions.pubsub.schedule('every 1 minutes').onRun((context) => {
      console.log('This will be run every 1 minutes!');
    });

CMD when I write firebase deploy
Error: HTTP Error: 400, Billing must be enabled for activation of service '[cloudscheduler.googleapis.com]' in project '45545844354(fake number)' to proceed.

When I visit cloud scheduler I got error message
Failed to load

About cloud scheduler , I should pay for this service and how much ?
I want only run 2 functions working everyday

A: The message is telling you that you need to have a billing method enabled for this project.  Please read the documentation about scheduled functions for more information.  It's clear that you need to be on the Blaze billing plan, and what the costs are.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How should I index my data in ElasticSearch to solve this situation? I'm building a search engine for a game (path of exile). In this game, items have sockets.

*

*items can have from 0 to 6 sockets

*some sockets can be linked

*there are 3 types of sockets (Red, Green, Blue)

*when 3 sockets are linked (for instance), we consider that they're all linked to each other, not just to the closest one.

Example of an item with 5 linked sockets and 1 lonely sixth socket.

My goal is to allow users to search for items with specific socket colors and links with ElasticSearch.
A user would describe the socket combination like that:
"RRRBB" would be an item with 5 linked sockets, 3 red and 2 blue.
"GGG RB" would have 3 green socket linked and 1 red and 1 blue linked.
Still following?
When I index an item, I order the linked sockets alphabetically and by group size (group size might not be necessary): "RB GGB" would become "BGG RB".
And I would reorder the user input the same way before doing the search.
So, searching for an exact combination is super easy and fast(?). I wouldn't even need to analyze the data, would I?
But I would like these scenarios to work:
"ggg" would find "ggg rb" -> this is easy with just a whitespace analyzer?
But what I'm struggling with is:
"brr* r b" would match "bgrr r b" -> the way I'm doing things right now: as soon as a group has a *, I add * between every subgroup, so I would search for: bg* r b.
It works, but I think it's really inefficient, right? (even with small optimizations like remove the first and last * if the first and last letters are B or R).
Do you have an idea on how to index the data (analyzers, as a string or terms or...) to make this possible and fast?
The End.


text:
Q: Rg.Plugins.Popup doesn't work only in release mode (Xamarin.forms) I am using Rg.Plugins.Popup and it's work fine in debug mode...but when I try the release mode or when I generate an apk it doesn't work. Did someone see something like that?
I guess the others plugins are not there as well
-------------- Update ----------------------
now it works in release mode with no reason, I dont Know why... but in installed apk it doesnt work

A: if i use proguard with linker my app crashes. I only select the sdk and user assemblies linker option & it works fine.


text:
Q: Hang with "SYSLINUX 6.04 EDD 6.04-perl Copyright (C) 1994-2015 H. Peter Anvin et al" while boot from bootable usb With coreboot BIOS SeaBIOS payload trying to boot to bootable USB but facing hang with message "SYSLINUX 6.04 EDD 6.04-perl Copyright (C) 1994-2015 H. Peter Anvin et al". normal boot works on already install linux OS. any hint to approach this issue will be appreciated.
enabled SeaBIOS debug logs, it continuously dump below message: could it be due to IRQ not set properly?
xhci_doorbell: slotid 1, epid 3 xhci_process_events: ring 0x000ea600 [trb 0x000ea660, evt 0x000ea700, type 32, eidx 7, cc 1]
xhci_poll_intr: st 1000000 ct 1038000 [ 0x000eb9f6 <= 0x4e647fa0 / 8 ] xhci_trb_queue: ring 0x000ea600 [nidx 8, len 8] xhci_doorbell: slotid 1, epid 3

A: Sounds like the drivers to allow your system to continue reading from the USB are not on the USB.
Have you tried "system rescue cd" instead?  That works on a LOT of systems.
Alternatively, try a few old Ubuntu installer ISOs - I've found those work sometimes when sysresccd does not (e.g. on Macs)
Another option: boot a DVD and install a fresh linux on your USB stick (i.e. don't use an ISO on it)


text:
Q: How to select one value from MySQL table row laravel Database image
how can i get one value from bank_id row ?
i have two table...one is bank name with id
other is state with state name and bank_id(equal with bank table)
state table's bank_id every row have multipal value..like 1,2,3 or 9,5,7
my question is how can i get all state name where bank id ?
please help me..
mycontroler.php
     public function getState(Request $request)
     {

  $states = DB::table("states")
    ->where("bank_id",$request->bank_id)
    ->pluck("name","id");
    return response()->json($states);

}

A: Try this
  $states = DB::table("states")
    ->where("bank_id",$request->bank_id)
    ->get();

A: Acording laravel documentation:
$states = DB::table('states')->where('bank_id', $request->bank_id)->get();


text:
Q: Flask-Admin Bootstrap 4 X-editable date causes error @Joes I think I've found an error/bug in Flask-Admin's X-editable dates, but only in Bootstrap 4.
Notice in the below code, template_mode='bootstrap3' works fine, but `template_mode='bootstrap4' causes the error.
Code to reproduce the error:
import os
import datetime

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import flask_admin as admin
from flask_admin.contrib.sqla import ModelView

# Create application
app = Flask(__name__)

# Create dummy secrey key so we can use sessions
app.config['SECRET_KEY'] = '123456789'

# Create in-memory database
app.config['DATABASE_FILE'] = 'sample_db.sqlite'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + app.config['DATABASE_FILE']
app.config['SQLALCHEMY_ECHO'] = True
db = SQLAlchemy(app)

# Instantiate the admin class with Bootstrap mode
# admin = admin.Admin(app, 'Example', template_mode='bootstrap3')
admin = admin.Admin(app, 'Example', template_mode='bootstrap4')

# Models
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Unicode(64))
    email = db.Column(db.Unicode(64))
    date_added = db.Column(db.Date)

    def __unicode__(self):
        return self.name

class UserAdmin(ModelView):
    column_searchable_list = ('name', 'email')
    column_editable_list = ('name', 'email', 'date_added')
    column_display_pk = True

    can_set_page_size = True
    # the number of entries to display in the list view
    page_size = 5

# Add Flask-Admin views
admin.add_view(UserAdmin(User, db.session))

# Flask normal views
@app.route('/')
def index():
    return 'Click me to get to Admin!'

def build_sample_db():
    """Populate a small db with some example entries"""

    db.drop_all()
    db.create_all()

    first_names = [
        'Harry', 'Amelia', 'Oliver', 'Jack', 'Isabella', 'Charlie','Sophie', 'Mia',
    ]
    last_names = [
        'Brown', 'Smith', 'Patel', 'Jones', 'Williams', 'Johnson', 'Taylor', 'Thomas',
    ]

    for i in range(len(first_names)):
        user = User()
        user.name = first_names[i] + " " + last_names[i]
        user.email = first_names[i].lower() + "@example.com"
        user.date_added = datetime.date.today()
        db.session.add(user)

    db.session.commit()
    return

# Build a sample db on the fly, if one does not exist yet.
app_dir = os.path.realpath(os.path.dirname(__file__))
database_path = os.path.join(app_dir, app.config['DATABASE_FILE'])
os.remove(database_path)
if not os.path.exists(database_path):
    build_sample_db()

if __name__ == '__main__':
    # Start app
    app.run(debug=True, host='0.0.0.0')

Here's what the Flask-Admin view looks like with Bootstrap 4, before the error:

Here's what the error looks like in the JavaScript console, when I click on the "editable" date field:

Here's what it looks like using the template_mode='bootstrap3' (i.e. what it's supposed to do):

A: Seems it's related to this issue and the data-template that needs to be removed.
Flask-Admin doesn't remove the data-template for this date field since it's just given a data-role='x-editable' instead lf x-editable-combodate.
There are at least two ways of fixing this (in the JavaScript "forms.js" or in the XEditableWidget class's get_kwargs() method). I chose to fix it in the get_kwargs() method as follows:
class XEditableWidget(object):
    # ...
    def get_kwargs(self, field, kwargs):
        """
            Return extra kwargs based on the field type.
        """
        if field.type == 'StringField':
            kwargs['data-type'] = 'text'
        # ...
        elif field.type == 'DateField':
            kwargs['data-type'] = 'combodate'
            kwargs['data-format'] = 'YYYY-MM-DD'

            # Remove the following so JavaScript doesn't have to do it
            # kwargs['data-template'] = 'YYYY-MM-DD'

            # Use the following so it adjusts the template
            kwargs['data-role'] = 'x-editable-combodate'

Here's what happens in the "form.js" file on page-load (i.e. where the data-template attribute is removed, in the latest Flask-Admin "master" branch):
            case 'x-editable':
                // No removal of the "data-template" attribute
                $el.editable({
                    params: overrideXeditableParams,
                    combodate: {
                        // prevent minutes from showing in 5 minute increments
                        minuteStep: 1,
                        maxYear: 2030,
                    }
                });
                return true;
            case 'x-editable-combodate':
                // Fixes bootstrap4 issue where data-template breaks bs4 popover.
                // https://github.com/flask-admin/flask-admin/issues/2022
                let template  = $el.data('template');
                $el.removeAttr('data-template');
                $el.editable({
                    params: overrideXeditableParams,
                    template: template,
                    combodate: {
                        // prevent minutes from showing in 5 minute increments
                        minuteStep: 1,
                        maxYear: 2030,
                    }
                });
                return true;

The resulting popover is a tiny bit ugly now, for some reason, but functionally it works at least!

A: This has worked for me. Added the below function before loading Admin(**).
def patch_admin_datetime():
    from flask_admin.form.fields import DateTimeField
    def patched_init(self, label=None, validators=None, format=None, **kwargs):
        format = format or '%Y-%m-%d %H:%M:%S'
        super(DateTimeField, self).__init__(label, validators, format, **kwargs)
    DateTimeField.__init__ = patched_init

 patch_admin_datetime()

 #Admin(**) ->


text:
Q: Vaadin 23 StatelessAuthentication JWT and JSESSIONID I have configured my Vaadin23 application with stateless authentication model and Keycloak SSO. I use JWT token with Cookie in order to restore the user session on application redeploy. At first glance everything is working fine. But, from time to time, users claim that they are moving to the home page after some time of using the website when they click something on the page. There are no issues at the log. I suspect that this issue maybe related to JWT token or HTTP session expiration. By default, my JWT token lives 1800 secs (30 mins). Also, I have the following properties for my Spring Boot application:
server.servlet.session.timeout=1d
spring.session.timeout=1d
server.servlet.session.tracking-modes = cookie
server.servlet.session.cookie.http-only=true
server.servlet.session.cookie.secure=true

vaadin.heartbeatInterval=300
vaadin.pushLongPollingSuspendTimeout=60000
vaadin.maxMessageSuspendTimeout=7000
vaadin.websocket.idle.timeout=45000
vaadin.compatibilityMode = false

Right now, I have no idea where to dig in order to catch and fix this issue. So, I'll appreciate any help in order to solve this. Please advise, where I should dig in order to shed light on this issue.


text:
Q: Can the Flash run faster than light? While trying to find out who was faster, Superman or the Flash (the answer is the Flash), I found out that the Flash can travel back and forth through time on occasion.
Does that mean that the Flash can travel faster than light?
What is the limit to the Flash's speed?

A: Depends on which Flash we're talking about here, but the short answer is yes he can.  The 2 main modern Flashes, Barry Allen and Wally West are both capable of running faster than light.  They run into issues running so fast though, as they start to brush up against the Speed Force.

A: The Flash did run as fast as light before but nearly got sucked into the speed force. It was Shayera Hol (Hawkgirl) who first found the wormhole and asked 6 other members to help pull the Flash OUT of the speed force!

A: Superman can go 15.75 times the speed of light, which is over 10 billion (the speed of light is 670 million mph) mph and Flash beat him pretty bad in a race so way over 10 billion mph.
Answer: Way faster than the speed of light!

A: It's easy, the clear winner here is The Flash. I mean when you talk about something called the speed force, no other DC superhero has this kind of power to posses and it sounds pretty darn amazing. If you compare to superman, I mean he needs to go through just basic flight - flies in the air breaking the laws of physics. Yeah, yeah we get the point. So thanks to Albert Einstein's theory about relativity, it is said that the faster you move, it is slower for time to pass for you - or something. General relativity is just basic relativity; different kinds of angles you see from a perspective of different observers. But with special relativity, it's more focused on the speed of light where things get more complicated. So, Barry Allen just broke the law of Relativity and he going faster than the speed of light can make time slow down for him way faster.

A: In one of the Flash, he was saving people in Japan or something... and to save them all he ran 13 trillion times the speed of light (apparently).
Also, Barry Allen as the Flash died saving the world, he ran so fast that he actually died. Furthermore, Barry Allen achieved coming back to Earth, and when he did, he was so fast that when ever he ran, he killed other speedsters.


text:
Q: Using AWS Glue version 3.0, however spark version is not 3.1 Created a glue job using a notebook using glue 3.0. Info shows that it is indeed glue 3.0.
However sc.version shows 2.4.3.
Glue 3.0 supports spark 3.1. Thats what the documentation says. Any one else seen this issue?
expecting spark version 3.1


text:
Q: MySQL ucfirst doesn't work I have this table:
CREATE TABLE IF NOT EXISTS `events` (
  `evt_id` int(11) NOT NULL AUTO_INCREMENT,
  `evt_name` varchar(50) CHARACTER SET utf8 NOT NULL DEFAULT 'ucfirst',
  `evt_description` varchar(100) DEFAULT NULL,
  `evt_startdate` date NOT NULL,
  `evt_enddate` date DEFAULT NULL,
  `evt_starttime` time DEFAULT NULL,
  `evt_endtime` time DEFAULT NULL,
  `evt_amtpersons` int(11) DEFAULT NULL,
  `sts_id` int(11) NOT NULL,
  `adr_id` int(11) DEFAULT NULL,
  `evt_amtPersonsSubs` tinyint(4) NOT NULL DEFAULT '0',
  `evt_photo` varchar(50) DEFAULT NULL,
  `sys-mut-dt` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `sys-mut-user` varchar(20) DEFAULT NULL,
  `sys-mut-id` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`evt_id`),
  KEY `sts_id` (`sts_id`),
  KEY `adr_id` (`adr_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=12 ;

But when I add in data into evt_name my first character is not capitalized. Any ideas?
Further information:
MySQL client version: 5.1.37
I want to do this in the database so that I don't have to do ucfirst with php always.

A: ...what?
If I'm reading this right, it will just set the default value of evt_name to the string ucfirst. Try inserting a blank row and see if I'm reading that right.
If you're really against using ucfirst in PHP, you'll probably have to still call ucfirst every time in the query. Or you could only use ucfirst on display, and not in the database.

A: ucfirst is a function...you defined it as Default-Value for the cell. Use it like this:
INSERT INTO events SET evt_name = UCFIRST($value)


text:
Q: Entity Framework 6: método de remoção não funciona Estou tentando excluir um objeto utilizando o repository pattern, mas o problema é que ao chamar o método para a remoção não acontece nada, nem lança exceção.
FinanceiroController.cs:
[HttpPost]
public ActionResult DeleteConfirmed(int id)
{
    var financa = _financeiroApp.ObterFinanca(id); // Aqui retorna o objeto sem nenhuma exceção.
    _financeiroApp.Remover(financa);

    return RedirectToAction("Index");
}

RepositoryBase.cs:
public void Remover(T obj)
{
    banco.Set<T>().Remove(obj); // Não remove, mas também não lança nenhuma exceção.
    banco.SaveChanges();
}

Não consigo entender, pois ao obter o objeto ele fica dentro do contexto e, sendo assim, deveria ser removido sem nenhum problema.

A: Se seu objetivo é excluir, você pode altera o seu Remove por DeleteObject
ObjectContext.DeleteObject(entity) marca a entidade como excluídos no contexto. (EntityState é excluído depois disso.) Se você chamar SaveChanges depois o Entity Framework envia uma instrução SQL DELETE para o banco de dados. Se não há restrições de referência no banco de dados a entidade será excluído, caso contrário, uma exceção é lançada.
Seu EntityCollection.Remove(childEntity), marca o relacionamento entre pai e filho Entity como eliminados. Se o relacionamento tem uma restrição de integridade referencial, chamando o método Remove em um dependentes marcas objeto tanto o relacionamento e o objeto dependente para exclusão. Isto ocorre porque a restrição indica que o objecto dependente não pode existir sem um relacionamento ao pai.
Remover retorna falso quando o objeto especificado não está na coleção.
Raferencia


text:
Q: effects of javascript not work in ajax reply I am new in AJAX. I have searched a lot on Internet but only got basic AJAX steps. Now I am writing codes using AJAX but a common problem I am facing continuously.
When I place return text in the particular id of HTML page, Javascript effects do not work. CSS works fine but Javascript effects like table sorting, jQuery effects or any other effect does not work. I know I am missing some concept here. But didn't get any effective answer.
Please suggest me what should I do? And what is the concept behind this...

A: The new HTML you're adding to the DOM (page) didn't exist when your jquery ran the first time and bound events to elements on the page.  You're probably using $("something").click(...) or .bind("click", ...).  Instead of these use the delegate function from jquery.  Delegate is generally more flexible and faster than live.  For instance you can not stopPropagation in a 'live' binding.
Jquery Delegate
Why Delegate is better than Live
Here is another SO answer that explains the benefits of delegate

A: What's most likely happening is that your events are getting unbound because you update the DOM with new elements. The easiest solution is to use the live method to bind to events : http://api.jquery.com/live/
Or you can simply rebind the events to the elements after insertion to the DOM just as easily.
EDIT
As user kasdega points out, another alternative is to use delegate : http://api.jquery.com/delegate/ Delegate works by using the bound root elements as the context to rebind events to DOM elements that may appear in the future.


text:
Q: Copy veryhidden sheet The following code works until sheet codenamed Template is VeryHidden.  Please help!!
y = ActiveWorkbook.Worksheets.Count

namePrompt = InputBox("Enter a name for the new sheet", "Add Sheet")

If namePrompt = "" Then Exit Sub

Template.Copy after:=Worksheets(y - 1)

ActiveSheet.Name = namePrompt

A: You can test to see if the sheet is VeryHidden, and if so you can unhide it before copying...
Sub Tester()

    Dim y, namePrompt, wasHidden

    y = ActiveWorkbook.Worksheets.Count

    namePrompt = InputBox("Enter a name for the new sheet", "Add Sheet")

    If namePrompt = "" Then Exit Sub

    Application.ScreenUpdating = False
    If Template.Visible = xlSheetVeryHidden Then
        Template.Visible = xlSheetVisible
        wasHidden = True
    End If

    Template.Copy after:=Worksheets(y - 1)

    ActiveSheet.Name = namePrompt

    If wasHidden Then Template.Visible = xlSheetVeryHidden

End Sub


text:
Q: Clear column based on a value appearing in another column I feel like this should be really simple but I have been stuck on this all day.
I have a dataframe that looks like:
Name    Date    Graduated    Really?

Bob     2014      Yes
Bob     2020                   Yes
Sally   1995      Yes
Sally   1999
Sally   1999                   No
Robert  2005                   Yes
Robert  2005      Yes

I am grouping by Name and Date. In each group, if "Yes" appears in Graduated, then clear the Really? column. And if "Yes" doesn't appear in the group, then leave as is. The output should look like:
Name    Date    Graduated    Really?

Bob     2014      Yes
Bob     2020                   Yes
Sally   1995      Yes
Sally   1999
Sally   1999                   No
Robert  2005
Robert  2005      Yes

I keep trying different variations of mask = df.groupby(['Name','Date'])['Graduated'].isin('Yes') before doing df.loc[mask, "Really?"] = Nonebut receive AttributeError (I assume my syntax is incorrect).
Edited expected output.

A: Try this:
s = df['Graduated'].eq('Yes').groupby([df['Name'],df['Date']]).transform('any')
df['Really?'] = df['Really?'].mask(s,'')


text:
Q: Install riscv spike simulator'; Failed to run dtc: No such file or directory Child dtb process failed I try to install the riscv tool to my Ubuntu 18.04.4 LTS server.
Use the following git repo and follow its build procedure:

*

*spike simulator

*GNU tool
Installation (Newlib)

*riscv pk
Issue spike pk hello, gives me

Failed to run dtc: No such file or directory
  Child dtb process failed

I have already installed the device-tree-compiler through apt command.
And checked with which dtc, outputs /usr/bin/dtc
What might be the problem?
Any help would be appreciated.
I run those commands on a command-line interface, not capable to run any graphic user interface. Not sure if that causes this problem.
The spike simulator is my first attempt to execute riscv code, I am also welcome to other recommendations.

A: I figure it out by creating a symbolic link using ln -s $(which dtc) and the problem is solved.


text:
Q: how to add "new tab" in the open a specific page or set of pages setting in google chrome ** How to add/include a blank "new tab" in the "open a specific page or set of pages" setting in google chrome? **
I am unable to include a blank new tab in the list of pages to open on startup of chrome.
I installed momentum extension, I want to see the momentum's new tab along with other pages when starting chrome.
Is there any url link that i can include for momentum's tab page


text: Q: How do I change the editor form vim to nano? While using the command sudo apt edit-sources, accidentally chose vim instead of nano and don't know how to change it. I used sudo update-alternatives --config editor but it doesn't change the editor I use in the sudo apt edit-sources command.


text:
Q: Data in column instead of rows I am getting data from SQL Server into an Excel sheet. Its a customer table containing 20 records. The columns are Customer Code, Customer Name and Customer Short Name.
What I need is instead of data coming in rows (from row 2 to row 21)... it should come in columns..  i.e. 1st three rows of column A contains respective headers (code, name and short name) and column B first row contains value of code, second row value of name and third row value of short name... same continue to column C, D, E..... till all 20 records..
Is it possible in excel?

A: In Excel, you can easily transpose the array with your data. Consider the following sample data in the range A1:C4:

You could now select the entire range and copy it via CTRL+C -> Paste -> Transpose (T). A second possibility would be to enter the following formula in, e.g., cell E1: =TRANSPOSE(A1:C4). This is a dynamic array formula in the current version (Microsoft 365). If you have an older version, you have to enter the formula as a legacy array formula by confirming the formula with Ctrl+Shift+Enter.
The result is as follows:

Edit: Dynamic setting of range
Theoretically, assuming that the data structure remains the same in terms of the number of columns and rows, the formulaic approach will update the transposed array accordingly as the original data is updated. In the specification above, the range A1:C4 is hard coded. While it is very likely that the number of columns will remain the same (could also be dynamically adjusted), in practice additional rows could be added/deleted from the data. In this case, you can specify the number of rows dynamically, which solves this problem:
=TRANSPOSE(INDEX(A:C,1,1):INDEX(A:C,COUNTA(A:A),3))


text:
Q: Regex isn't working properly with PHP or not getting how to implement this There is something really I couldn't understand is how can I check my previous match with the next character and set starting and ending character please guys help me.
Here is an Example of my string
..A..B..A...B.A.B

What I'm trying to do is starting of string:
1=> Check the first character is .. or A
2=> and the Second thing is String cannot be like this ..A..A it must be like ..A..B.. and sequence.
3=> Ending character must be .. or B and won't be A
However, I can match the first character like so ^([A]{1}|[.]{1,100}) But when I'm trying this same way with ending character it is not working and I'm not getting how to do the step 2.
Save my day guys. Thanks
Failed Regex: ^[\.{1,40}|A{1}]+(?!A)+(B)+(?!B)+(B|\.{1,40})$

A: This regex should match the description you've given:
^(?:\.+?)?(A\.+?B\.?|\.\.)+$

^ is the start of the string (or line if m modifier is used).
(?:\.+?)? is one or more ., but it optional.
A\.+B\.? is looking for an A any amount of .s then a B and an optional ..
| is an alternative pattern we'll look at
\.\. are 2 .s
+ allows for the whole group to occur once or more
$ is the end of the string (or line, again depends on modifier being used)
Demo: https://regex101.com/r/OUJxxc/3/ (Probably with a clearer description than I provided)


text:
Q: How add a file to an existing zip file using Golang We can create a zip new file and add files using Go Language.
But, how to add a new file with existing zip file using GoLang?
If we can use Create function, how to get the zip.writer reference?
Bit confused.

A: After more analysis, i found that, it is not possible to add any files with the existing zip file.
But, I was able to add files with tar file by following the hack given in this URL.

A: you can:

*

*copy old zip items into a new zip file;

*add new files into the new zip file;

zipReader, err := zip.OpenReader(zipPath)
targetFile, err := os.Create(targetFilePath)
targetZipWriter := zip.NewWriter(targetFile)

for _, zipItem := range zipReader.File {
    zipItemReader, err := zipItem.Open()
    header, err := zip.FileInfoHeader(zipItem.FileInfo())
    header.Name = zipItem.Name
    targetItem, err := targetZipWriter.CreateHeader(header)
    _, err = io.Copy(targetItem, zipItemReader)
}

addNewFiles(targetZipWriter) // IMPLEMENT YOUR LOGIC

A: Although I have not attempted this yet with a zip file that already exists and then writing to it, I believe you should be able to add files to it.
This is code I have written to create a conglomerate zip file containing multiple files in order to expedite uploading the data to another location.  I hope it helps!
type fileData struct {
    Filename string
    Body     []byte
}

func main() {
    outputFilename := "path/to/file.zip"

    // whatever you want as filenames and bodies
    fileDatas := createFileDatas()

    // create zip file
    conglomerateZip, err := os.Create(outputFilename)
    if err != nil {
        return err
    }
    defer conglomerateZip.Close()

    zipWriter := zip.NewWriter(conglomerateZip)
    defer zipWriter.Close()

    // populate zip file with multiple files
    err = populateZipfile(zipWriter, fileDatas)
    if err != nil {
        return err
    }

}

func populateZipfile(w *zip.Writer, fileDatas []*fileData) error {
    for _, fd := range fileDatas {
        f, err := w.Create(fd.Filename)
        if err != nil {
            return err
        }

        _, err = f.Write([]byte(fd.Body))
        if err != nil {
            return err
        }

        err = w.Flush()
        if err != nil {
            return err
        }
    }
    return nil
}

A: This is a bit old and already has an answer, but if performance isn't a key concern for you (making the zip file isn't on a hot path for example) you can do this with the archive/zip library by creating a new writer and copying the existing files into it then adding your new content. Something like this:
zw := // new zip writer from buffer or temp file
newFileName := // file name to add
reader, _ := zip.NewReader(bytes.NewReader(existingFile), int64(len(existingFile)))
for _, file := range reader.File {
    if file.Name == newFileName {
        continue // don't copy the old file over to avoid duplicates
    }
    fw, _ := zw.Create(file.Name)
    fr, _ := file.Open()
    io.Copy(fw, fr)
    fr.Close()
}

Then you would return the new writer and append files as needed. If you aren't sure which files might overlap you can turn that if check into a function with a list of file names you will eventually add. You can also use this logic to remove a file from an existing archive.

A: Now in 2021, there is still no support for appending files to an existing archive.
But at least it is now possible to add already-compressed files, i.e. we don't anymore have to decompress & re-compress files when duplicating them from old archive to new one.
(NOTE: this only applies to Go 1.17+)
So, based on examples by @wongoo and @Michael, here is how I would implement appending files now with the minimum performance overhead (you'll want to add error handling though):
zr, err := zip.OpenReader(zipPath)
defer zr.Close()
zwf, err := os.Create(targetFilePath)
defer zwf.Close()
zw := zip.NewWriter(zwf)
defer zwf.Close() // or not... since it will try to wrote central directory

for _, zipItem := range zrw.File {
    if isOneOfNamesWeWillAdd(zipItem.Name) {
        continue // avoid duplicate files!
    }
    zipItemReader, err := zipItem.OpenRaw()
    header := zipItem.FileHeader // clone header data
    targetItem, err := targetZipWriter.CreateRaw(&header) // use cloned data
    _, err = io.Copy(targetItem, zipItemReader)
}

addNewFiles(zw) // IMPLEMENT YOUR LOGIC


text:
Q: How does a electron revolve in Rutherford's model? How can an electron revolve in a circular orbit because circular motion is an accelerated motion and  acc. charged particle is a source of E.M. Wave. So,it should radiate out energy and hence would loose energy; so from where does it get energy from?

A: Actually, you have rediscovered the flaws of Rutherford's atomic model .
Now, in order to solve this, Bohr proposed postulates, one of them is:

Electrons while moving in a certain orbit cannot radiate energy and can only take pre-ascertained orbits.

What he said is based on the fact that Energy can't be radiated continuously. It is discrete in nature. If it had happened, we would have got continuous emission spectra as the electron would radiate at all the possible frequencies while collapsing with the nucleus. Thus, energy ought not to be continuous.
The electron can radiate energy to a certain frequency when it moves from higher orbit to lower orbit.
To think of it, suppose there is a ladder. There are certain points where there are steps. While you are descending, you have to place your feet at the next step, not in between. This is called Quantization of Energy!
Now, why is not energy continuous? This let the foundation of quantum mechanics. How did it start?
Let me brief.
It all started with blackbody radiation. Every body radiates EM waves due to the conversion of kinetic energy of the colliding molecules above $OK$ . Now, a perfect blackbody can radiate almost at every frequency. When classical physicists wanted to explain the blackbody radiation, they were in dilemma.  They thought that the walls contain oscillators(they didn't know about electron) which would excite every frequency of the EM field. Now, since it is a container , the waves will interfere with each other to produce standing waves of several modes. Now, after reading wave mechanics, you will know that the high frequency waves will have infinite number of modes. So, in order to radiate at those frequencies, the oscillator has to give high energy to vibrate all those modes. Since, the modes are infinite, energy radiated at high frequency would be infinite!
This is the famous Ultraviolet Catastrophe !

A: According to Quantum Mechanics, the electron actually has a wave function described by the Schrodinger Equation and it has different energy levels and its energy levels are quantized. At the  most stable state the ground state ($n = 1$, $l = 0$, $m_l = 0$), it does not radiate energy, it only radiates energy when going between levels from higher to lower levels and absorbs energy when going from lower to higher levels. The photons it absorbs and emits must also be in the form $13.6~\text{eV/(n^2)}$, where $n$ is called the principle quantum number, and $eV$ is energy in the units of electron volts.


text:
Q: Linker error: /usr/bin/ld: cannot find -lc I am trying to compile this code for some time. Specifically, I am trying to compile the avx2 code using the given mac. However, I am always getting the following error.
I have looked up a lot but unable to find a solution. I will be very glad if you help me to find a solution.

/usr/bin/ld: cannot find -lc
collect2: error: ld returned 1 exit status
make: *** [test/test_kyber] Error 1

gcc version

gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-11)
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Clang version :

clang version 3.4.2 (tags/RELEASE_34/dot2-final)
Target: x86_64-redhat-linux-gnu
Thread model: posix

Output running the make command.

/usr/bin/gcc -Wall -Wextra -O3 -fomit-frame-pointer -msse2avx -mavx2 -march=native -static -o test/test_kyber kyber.c poly.c polyvec.c fips202.o fips202x4.c precomp.c ntt.c verify.c indcpa.c consts.c kex.c nttlevels0t4.s nttlevels5t7.s mul_coefficients.s polyvec_pointwise_acc.s poly_add.s poly_sub.s cbd.s poly_freeze.s crypto_stream_aes256ctr.c keccak4x/KeccakP-1600-times4-SIMD256.o randombytes.c test/test_kyber.c
/usr/bin/ld: cannot find -lc
collect2: error: ld returned 1 exit status
make: *** [test/test_kyber] Error 1

A: thanks a lot for your help and time. I understood the problem. The makefile adds a -static flag, but on our office machines we don't have static libc.a. Hence, the error "cannot find -lc". I removed the static flag and it works fine for now.
I think we don't need a static libc.a, but I will have to check more closely.


text:
Q: e2fsck -n + how to know if need to run e2fsck in order to fix corrupted blocks? we want to check the filesystem on the disks as /deb/sdc  .... /dev/sdg on each linux redhat machine
the target is to find what are the disks that required e2fsck ( as e2fsck -y /dev/sdb . etc )
according to man page
-n     Open  the filesystem read-only, and assume an answer of `no' to all questions.  Allows e2fsck to be used non-interactively.  This option may not be specified at
          the same time as the -p or -y options.

when we run the command ( only example )
 e2fsck -n   /dev/sdXX

we get
e2fsck 1.42.9 (28-Dec-2013)
Warning!  /dev/sdc is mounted.
Warning: skipping journal recovery because doing a read-only filesystem check.
/dev/sdc: clean, 94/1310720 files, 156685/5242880 blocks

so what need to capture from e2fsck output , that required to run  e2fsck ?
e2fsck process
init 1

umount /dev/sdXX

e2fsck -y /dev/sdXX  ( or e2fsck -C /dev/sdXX for full details )

init 3

A: You probably are looking for the output of tune2fs rather than e2fsck
tune2fs -l /dev/sdXX |grep "Filesystem state\|Last checked\|Check interval"

which should yield something like this:
Filesystem state:         clean
Last checked:             Mon Nov 28 16:03:44 2016
Check interval:           31536000 (12 months)


text:
Q: What's the meaning of 'statistical break'? And how to calculate it? I am reading a paper named "EPRI-GTC Overhead Electric Transmission Line Siting Methodology", and in this paper the author uses "the first statistical break in its histogram" to determine the corridor boundary. And there is no description about the meaning of 'statistical break' and how to calculate it in this paper.
I can't find any info about the term 'statistical break' by Google. Please help me if you know something about it.
Here are some sentences in this paper:

In each scenario, the Macro Corridor boundary is determined by the first statistical break in its histogram.
The boundaries of these corridors are chosen by the first statistical break in the histogram.

A: Breaks of the histogram are the boundaries of different bins (example here). They can be set by a user or calculated using one of the many possible algorithms (see e.g. R's hist function documentation). However, the breakpoints are subjective in their nature - they can vary depending of the algorithm you used or parameters of the algorithm, so using them as a statistical criteria without mentioning the algorithm or heuristic used for determining them seems strange for me.


text:
Q: Get value of a Pandas GroupBy Object group.Units[group['Channel'].map(lambda x: x.startswith('F'))]

gives me a Series
0    4

How can I get only the value from this GrupBy Object? I.e.:
4

A: group.Units[group['Channel'].map(lambda x: x.startswith('F'))].values[0]


text:
Q: Mysql joins headache
I have this database. It does not contain all the tables, but for my problem what is included in the picture is enough.
The database is designed for transportation companies.
So, I have a booking. Any booking can have multiple addresses. These types are (routing_type: pick-up, stop, drop-off). My addresses are either a street address or an airport.
Inside routing table is use either the address_id or the airport_id to tell which type the routing is. If airport_id has a number than address_id is NULL.
In my booking_routing table I have as many entries as there are routing types for a specific booking. If I have 3 addresses for a specific booking, I will have 3 entries in booking_routing (maybe Pick-up, then Stop and then Drop-off). Usually there are only two addresses necessary, pick-up an drop-off.
PROBLEM: I try to create a query in which I will have displayed my Pick-up and Drop-off point on the same line with other fields from the booking.
Example:
Booking_ID   Account_ID   ...   Pick-Up       Drop-Off
121             32                      1 Main St           IAD, AA-322
Right now I only managed to get them using LEFT JOIN on two lines.
Like this:
Booking_ID   Account_ID   ...   Address_Type       Address
121             32                        Pick_up           1 Main St
121             32                        Drop-Off           IAD, AA-322
SELECT
b.booking_id as ID, a.account_id as Acc_ID,
MAX(CASE WHEN br.routing_type_id = 1 THEN -- 1=pick-up
    Concat(ad.address_line1, " ", api.code, " ", aii.code, "-", ap.flight_number) END) as Pick_up,
    MAX(CASE WHEN br.routing_type_id = 4 THEN  -- 4=drop-off
             Concat(ad.address_line1, " ", api.code, " ", aii.code, "-", ap.flight_number) END) as Drop_off

FROM booking b
left JOIN account a ON b.account_id = a.account_id
left join booking_routing br ON b.booking_id = br.booking_id
left join routing r ON br.routing_id = r.routing_id
left join routing_type rt ON br.routing_type_id = rt.routing_type_id
left join address ad ON r.address_id = ad.address_id
left join airport ap ON r.airport_id = ap.airport_id
left join airport_info api ON ap.airport_info_id = api.airport_info_id
left join airline_info aii ON ap.airline_info_id = aii.airline_info_id

group by b.booking_id, a.account_id;

A: You can achieve this by using MAX and CASE:
SELECT Booking_Id,
   Account_Id,
   MAX(CASE WHEN Address_Type = 'Pick_up' THEN Address END) Pick_Up,
   MAX(CASE WHEN Address_Type = 'Drop-Off' THEN Address END) Drop_Off
FROM YourTables...
GROUP BY Booking_Id, Account_Id

SQL Fiddle Demo


text:
Q: mysql error after trying put in SQL I'm trying to insert tables from phpmyadmin in SQL, such as:
INSERT INTO users
(
    steam VARCHAR(35) NOT NULL DEFAULT '',
    name VARCHAR(32) NOT NULL DEFAULT '',
    length INT NOT NULL DEFAULT 0,
    unban VARCHAR(32) NOT NULL DEFAULT '',
    reason VARCHAR(64) NOT NULL DEFAULT '',
    banned SMALLINT NOT NULL DEFAULT 0,
    leaves SMALLINT NOT NULL DEFAULT 0,
    PRIMARY KEY (steam)
);

But I'm getting an error:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'VARCHAR(35) NOT NULL DEFAULT '', name VARCHAR(32) NOT NULL DEFAULT '', length ' at line 3

What am I doing wrong?

A: Tables need to be exist in db before inserting value in that. so make sure that you are inserting value in that table which have existence in your database.
To create a table you need to fire the below query.
CREATE TABLE users
(
    steam VARCHAR(35) NOT NULL DEFAULT '',
    name VARCHAR(32) NOT NULL DEFAULT '',
    length INT NOT NULL DEFAULT 0,
    unban VARCHAR(32) NOT NULL DEFAULT '',
    reason VARCHAR(64) NOT NULL DEFAULT '',
    banned SMALLINT NOT NULL DEFAULT 0,
    leaves SMALLINT NOT NULL DEFAULT 0,
    PRIMARY KEY (steam)
);

After creating the table you can directly insert value from you phpmyadmin or you can also do that by executing the below query.
INSERT INTO users VALUES
('steam value', 'name of user', '4', 'any unban value', 'any reason value', '0', '0');

if you want insert value from you php file than you must need to make a database connection & after that you can use mysql_query() function in insert value in you db

A: You should create table first:
CREATE TABLE users
(
    steam VARCHAR(35) NOT NULL DEFAULT '',
    name VARCHAR(32) NOT NULL DEFAULT '',
    length INT NOT NULL DEFAULT 0,
    unban VARCHAR(32) NOT NULL DEFAULT '',
    reason VARCHAR(64) NOT NULL DEFAULT '',
    banned SMALLINT NOT NULL DEFAULT 0,
    leaves SMALLINT NOT NULL DEFAULT 0,
    PRIMARY KEY (steam)
);

once it created you can insert:
INSERT INTO users VALUES
('user steam value', 'user name', 3, 'unban value', 'reason value', 0, 0);


text:
Q: Strange error when using Predictive Intelligence tags We began to implement PI this week and I came across this error:

ReferenceError:  SaveAnalyticData is not defined

Which references this:
    <script type="text/javascript">
        absoluteBaseUrl = "http://pages.s7.exacttarget.com/";
        SaveAnalyticData(7281803, '1daf6168-ab88-4d85-8fd5-08d6e72d16a2', 'a0459de1-4eed-4843-901b-eafb3272596d');
    </script>

Anyone know what am I missing?

A: My mistake, I had adblock turned on for the website and hadn't noticed it.
I just disabled and it worked fine.


text: Q: Make PyCharm use a new shell terminal for script output? When launching a script from PyCharm, either for simple running or debugging, how can I make it open up a dedicate shell terminal instead of using PyCharm's built in Output window? I working on some terminal text based gui apps, and the built in output window is not all suitable for that.


text:
Q: nc.variables[i].units is showing an error while extracting datat from netcdf file nc.variables[i].units is showing an error attribute not found. i am  trying to extract data from  netcdf file. how to extract data of a particular longitude or latitude?
from netCDF4 import Dataset

nc=Dataset("test.nc",'r')

for i in nc.variables:

    print(i,nc.variables[i].units,nc.variables[i].shape)

lat=nc.variables['lat'][:]
print(lat)

the output is as follows:
area meter2 (128, 256)
lat degrees_north (128,)
Traceback (most recent call last):
File "C:\Users\harsh\Desktop\cv\test_netcdf.py", line 7, in <module>
print(i,nc.variables[i].units,nc.variables[i].shape) #nc.variable[i].units
File "netCDF4\_netCDF4.pyx", line 4303, in
netCDF4._netCDF4.Variable.__getattr__
File "netCDF4\_netCDF4.pyx", line 4114, in
netCDF4._netCDF4.Variable.getncattr
File "netCDF4\_netCDF4.pyx", line 1392, in netCDF4._netCDF4._get_att
File "netCDF4\_netCDF4.pyx", line 1857, in
netCDF4._netCDF4._ensure_nc_success
AttributeError: NetCDF: Attribute not found

A: Take a closer look at this section
for i in nc.variables:

    print(i,nc.variables[i].units,nc.variables[i].shape)

In this for loop i is not an integer. Since this is evaluated as a for each loop it represents the current variable, not the index at which that variable exists. You have a few options here
Option one: use range instead
for i in range(len(nc.variables)):

    print(i,nc.variables[i].units,nc.variables[i].shape)

Option two: use a zip to have a reference to the variable and an integer
As pointed out by Bart, Enumerate is a nicer way of doing this. See his comment below for that
for i, variable in zip(range(len(nc.variables)), nc.variables):

    print(i, variable.units, variable.shape)

Option three: avoid using i altogether
for variable in nc.variables:

    print(variable.units, variable.shape)


text:
Q: Minitest: How to test a method I'm trying to test the method in my code, but the second test is returning the error undefined local variable or method 'params'
What's the correct way to test the method? or is there a change i need to make to how the main.rb is set up?
code:
require 'sinatra'
require 'sinatra/reloader'

def get_products_of_all_ints_except_at_index()
  @array = [1, 7, 3, 4]
  @total = 1
  @index = params[:index].to_i
  @array.delete_at(@index)
  @array.each do |i|
    @total *= i
  end
end

get '/' do
  get_products_of_all_ints_except_at_index
  erb :home
end

test:
ENV['RACK_ENV'] = 'test'

require 'minitest/autorun'
require 'rack/test'

require_relative 'main.rb'

include Rack::Test::Methods

def app
  Sinatra::Application
end

describe 'app' do
  it 'should return something' do
    get '/'
    assert_equal(200, last_response.status)
  end

  it 'should return correct result' do
    get_products_of_all_ints_except_at_index
    assert_equal(24, @total)
  end
end

A: You aren't passing any params with your get request, try:
get '/', :index => '1'

A: Tthe first test works since there is a default params map setup for you when calling get '/'. But when you call the method directly params is nil and that is why you get the error. The best way here is to send in the data you need to you method. Something like:
def get_products_of_all_ints_except_at_index index
  @array = [1, 7, 3, 4]
  @total = 1
  @array.delete_at(index)
  @array.each do |i|
    @total *= i
  end
end

get '/' do
  get_products_of_all_ints_except_at_index params[:index].to_i
  erb :home
end

Finding things in the request is normally good to do in the outermost layer in the code. Then you business code will get higher testability also!


text:
Q: Split string lines and make a data frame I have a small data from a text file read via readLines. The file had characters like # and I think that is the reason read.table was unable to read it. Here is the first five lines dput:
files<-c("\trfinal\t\t", "eq1\t\t\t", "0.ster6\t1.00\t(1.00,1.00)\t.",
     "1.ster6\t0.65\t(0.47,0.88)\t0.006", "0.parkinson\t1.00\t(1.00,1.00)\t.",
     "1.ster6#0.parkinson\t1.00\t(1.00,1.00)\t.")

\t means white space between strings. I would like to split this text lines and put them into a 4 column grid (data frame).
I tried strsplit(files, "[\\t]") but it doesn't really do the trick. Any help ?

A: You can disable the treatment of # as the comment.char in read.table:
read.table(text=files, sep='\t', comment.char="")
#                    V1     V2          V3    V4
# 1                     rfinal
# 2                 eq1
# 3             0.ster6   1.00 (1.00,1.00)     .
# 4             1.ster6   0.65 (0.47,0.88) 0.006
# 5         0.parkinson   1.00 (1.00,1.00)     .
# 6 1.ster6#0.parkinson   1.00 (1.00,1.00)     .

A: If the "\t" just represents a tab delimiter, try read.delim:
read.delim(text = files)
#                     X rfinal         X.1   X.2
# 1                 eq1     NA
# 2             0.ster6   1.00 (1.00,1.00)     .
# 3             1.ster6   0.65 (0.47,0.88) 0.006
# 4         0.parkinson   1.00 (1.00,1.00)     .
# 5 1.ster6#0.parkinson   1.00 (1.00,1.00)     .

You can also consider the stringi package. Here, I've treated the "\t" as a fixed pattern:
library(stringi)
stri_split_fixed(files, "\t", simplify = TRUE)
#      [,1]                  [,2]     [,3]          [,4]
# [1,] ""                    "rfinal" ""            ""
# [2,] "eq1"                 ""       ""            ""
# [3,] "0.ster6"             "1.00"   "(1.00,1.00)" "."
# [4,] "1.ster6"             "0.65"   "(0.47,0.88)" "0.006"
# [5,] "0.parkinson"         "1.00"   "(1.00,1.00)" "."
# [6,] "1.ster6#0.parkinson" "1.00"   "(1.00,1.00)" "."

Overall, though, it's not clear what is supposed to be treated as a header and so on, and it would be better to implement @musically_ut's suggestion about using comment.char and trying to resolve the issue at the source.


text:
Q: Null comparison is not happening to the fields in where clause Null comparison is not happening to the fields in where clause.
Code is as below. Its just a sample code where null comparison is not happening.
create or replace function document_history
    (V_process_id IN)
    return varchar2
AS
    V_document_id number;
    V_process_status varchar2(10);

select document_id, process_status
into V_document_id, V_process_status
from document_details
where process_id =V_process_id ;

update staging2
set (country,land) = (select country, land
                      from staging
                      where document_id =V_document_id);
commit;

return null;
end document_history;

Here if input varible V_document_id is null, sub query will not return any value where I'm expecting the output for null value also.
I tried below scenarios to get output for the subquery:

*

*select country, land from staging where nvl(document_id,'*') = nvl(V_document_id,'*');

*select country, land from staging where document_id = nvl(V_document_id,null);

*I declared one variable with null value and used in the nvl function,
nl_variable:=null;
select country, land from staging where document_id = nvl(V_document_id,nl_variable);

*I tried trim(V_document_id).
Only for 1st option, query would return the value.
Wherein, my real procedure/functions are big and they have many columns in where clause which needs to return the value if input is null and I cant use  nvl(input,'*') on all the columns in where clause and also cant use IS NULL (as comparison should be like (document_id =V_document_id)).
Could someone help me, how null comparison can be done here?

A: Looks like I can purpose a solution. This solution, in fact, is a hack
Just replace
document_id =V_document_id

with
decode(document_id,V_document_id,1,0)=1

From Oracle documentation

However, Oracle considers two nulls to be equal when evaluating a DECODE function. Please refer to DECODE for syntax and additional information.


text:
Q: framer motion is not transitioning when switched between keyframe animations I have 2 keyframe animation variants and when I switch between them I want it to happen with the transition. How can I make it transition all the props when switched from one keyframe animation to another (currently it happens instantly)?
const variants = {
  ...,
  horizontalWiggle: {
    x: ["40px", "80px"],
    y: [0, 0],
    transition: { duration: 0.5, yoyo: Infinity }
  },
  verticalWiggle: {
    x: [0, 0],
    y: ["8px", "40px"],
    transition: { duration: 0.5, yoyo: Infinity }
  }
}

Using with framer motion as so:
<motion.div
 className="wiggle"
 variants={variations}
 initial="init"
 animate={vertical ? "verticalWiggle" : "horizontalWiggle"}
/>

Link to the sandbox: https://codesandbox.io/s/long-surf-405lho?file=/src/App.js

A: You have two options:

*

*You should not specify 0 for axis which you do not want to animate. That way there will be no instant jump and will be smooth animation between variants.

*The idea is start new animation (new variant) from last position of previous variant. Another words: you need to stop old animation and start new animation from the same value (the same keyframe). That way there also will be no instant jump.

Full example here:

NOTE: if you need to animate between variants - you could create one more variant with animation from STATE-1 to STATE-2.
Like here:

Short Example:

const variations = {
  ...
  horizontalWiggle: {
    x: [0, 40, 80, 0],
    transition: { duration: 1, repeat: Infinity }
  },
  verticalWiggle: {
    y: ["0px", "20px", "40px", "0px"],
    transition: { duration: 1, repeat: Infinity }
  }
};


text:
Q: Video and audio with gstreamer or lib+gstreamer I need to read streams of cams and want to use c++. And i have a pipeline it works when use OpenCV, but without audio.
pipeline="rtspsrc protocols=tcp location=" + urlStream_ + " latency=300 ! decodebin3 ! videorate ! videoconvert ! video/x-raw,framerate=30/1,format=(string)BGR ! appsink drop=1"

I'm new to gstreamer and I can't find a correct way to read audio and video in the tutorials.
I'm on https://gstreamer.freedesktop.org/ but I still haven't found something that makes it work. Can someone help me?
I'm sorry the english.
any answer would welcome!


text:
Q: How do I iterate over a range of revision ID's when querying WikipediR? I am using WikipediR to query revision ids to see if the very next edit is a 'rollback' or an 'undo'
I am interested in the tag and revision comment to identify if the edit was undone/rolled back.
my code for this for a single revision id is:
library(WikipediR)

wp_diff<- revision_diff("en", "wikipedia", revisions = "883987486", properties = c("tags", "comment"), direction = "next", clean_response = T, as_wikitext=T)

I then convert the output of this to a df using the code
library(dplyr)
library(tibble)
diff <- do.call(rbind, lapply(wp_diff, as.data.frame, stringasFactors=FALSE))

This works great for a single revision id.
I am wondering how I would loop or map over a vector of many revision ID's
I tried
vec <- c("883987486","911412795")
for (i in 1:length(vec)){
wp_diff[i]<- revision_diff("en", "wikipedia", revisions = i, properties = c("tags", "comment"), direction = "next", clean_response = T, as_wikitext=T)
}

But this creates the error
Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE,  :
  arguments imply differing number of rows: 1, 0
When I try to convert the output list to a dataframe.
Does anybody have any suggestions. I am not sure how to proceed.
Thanks.

A: Try the following code:
# Make a function
make_diff_df <- function(rev){
  wp_diff <- revision_diff("en", "wikipedia", revisions = rev,
                          properties = c("tags", "comment"),
                          direction = "next", clean_response = TRUE,
                          as_wikitext = TRUE)

  DF <- do.call(rbind, lapply(wp_diff, as.data.frame, stringasFactors=FALSE))

  # Define the names of the DF
  names(DF) <- c("pageid","ns","title","revisions.diff.from",
                  "revisions.diff.to","revisions.diff..",
                  "revisions.comment","revisions..mw.rollback.")
  return(DF)
}

vec <- c("883987486","911412795")

# Use do.call and lapply with the function
do.call("rbind",lapply(vec,make_diff_df))

Note that you have to fixed the names of the DF inside the make_diff_df function in order to "rbind" inside do.call could work. The names with the 2 versions from the example are pretty similar.
Hope this can help


text:
Q: How can I have an ASP.NET templated composite control? I am trying to add a template to a simplified composite control containing a Label and a TextBox.  I want my mark up to look something like this:
<test:FormItem ID="fi" runat="server" Title="MyTitle" Text="My Text!">
    <TestTemplate>

            <%# Container.Title) %>

        <%# Container.Text %>
    </TestTemplate>
</test:FormItem>

I have a templateContainer class that has properties for the TextBox and Label.
public class TemplateContainer : WebControl, INamingContainer
{

    public TextBox Text { get { return m_item.Text; } }
    public Label Title { get { return m_item.Title; } }

    private FormItem m_item;

    public TemplateContainer(FormItem item)
    {
        m_item = item;
    }

}

In the main FormItem class I have a CreateControlHierarchy() method that is being called from CreateChildControls():
protected virtual void CreateControlHierarchy()
    {

        m_itemTemplateContainer = new TemplateContainer(this);
        TestTemplate.InstantiateIn(m_itemTemplateContainer);

        Controls.Add(m_itemTemplateContainer);

    }

What I WANT is for the Template to render the actual control.  Instead, it's calling ToString() on the control and displaying System.Web.UI.WebControls.Label and System.Web.UI.WebControls.TextBox.  Is there a way to make the template add the controls to it's collection instead of just calling ToString() on them?
Note: I've also tried adding the textbox and label to the controls collection of the container which does the same thing.

A: Ok. So I tried a few things and I came up with an OK solution.
First, I tried to use methods in the data binding expression and then keep track of where in the container's Control collection the textbox or label would go.  However, the CompiledTemplateBuilder (which is what .Net internally builds for ITemplates specified in mark up) put all of the markup before and after both binding expressions into one DataBoundLiteral control and the Control collection was already built when the method was called.
What did work was to create a new WebControl which serves as a place holder for the controls within the composite control.  It has one property Control and when set, it add the control to it's Controls Collection.
public class FormItemPlaceHolder : WebControl, INamingContainer
{
    public WebControl Control
    {
        get
        {
            if(Controls.Count == 0)
                return null;
            return Controls[0] as WebControl;
        }
        set
        {
            if (Controls.Count != 0)
                Controls.Clear();
            Controls.Add(value);
        }
    }

}

Then in the mark up, I create a control of this type and bind it's Control property to the correct property in the container.
<test:FormItem ID="fi" runat="server" Title="MyTitle" Text="My Text!">
    <TestTemplate>

        <test:FormItemPlaceHolder ID="ph" runat="server"
            Control='<%# Container.Title %>' />

         <test:FormItemPlaceHolder ID="ph2" runat="server"
             Control='<%# Container.Text %>' />
    </TestTemplate>
</test:FormItem>

Does anyone have a better solution?

A: The container should not define the controls, just the data.
It is in the markup that you should define the actual controls of the data, and assign them the values in from the container.
E.g.
public class TemplateContainer : UserControl
{
    public string Text { get { return m_text; } }
    public string Title { get { return m_title; } }

    private string m_text;
    private string m_title;
    private FormItem m_item;

    public TemplateContainer(FormItem item)
    {
        m_item = item;
    }

}

And in the markup:
   <test:FormItem ID="fi" runat="server" Title="MyTitle" Text="My Text!">
        <TestTemplate>
            <asp:Label runat="server" Text='<%# Container.Title) %>' />

            <asp:TextBox runat="server" Text='<%# Container.Text %>' />
    </TestTemplate>
</test:FormItem>

If you are trying to create a composite control that does not require controls to be added in the markup, then why are you using a Template? If it is just for styling then perhaps creating your own Style object may be more effective?


text:
Q: How can I Embed text inside image?
I want to display a custom text (mainly person info) inside an image like it's shown above. How can I do it in android? For example, I have a known size of this image (it differs from device to device) and want to display it with the different text size inside it in the special place.

A: You can use, for example, RelativeLayout.
Make your ImageView be match_parent and use some container for your text lines in bottom of parent RelativeLayout.
Example:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:scaleType="fitXY"
        app:srcCompat="@drawable/ic_launcher_background"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <LinearLayout
        android:padding="20dp"
        android:background="#92fffaaa"
        android:layout_alignParentBottom="true"
        android:layout_width="match_parent"
        android:layout_height="200dp">

        <TextView
            android:textSize="20sp"
            android:text="Some test text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

</RelativeLayout>

Result:

A: Try this (adjust dimensions as your requirement)
<RelativeLayout
    android:layout_width="200dp"
    android:layout_height="150dp">

    <ImageView
        android:scaleType="centerCrop"
        android:src="@drawable/your_image"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <LinearLayout
        android:background="#64000000"
        android:padding="8dp"
        android:gravity="center_vertical"
        android:orientation="vertical"
        android:layout_alignParentBottom="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:text="Title"
            android:textColor="#ffffff"
            android:textSize="16sp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:text="Sub Title"
            android:textColor="#ffffff"
            android:textSize="14sp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </LinearLayout>

A: I've done something similar previously.

*

*Use Framelayout.

*Add ImageView in frame layout with match_parent constraints.

*Add LinearLayout having background="#80000000" and layout_gravity="center" in FrameLayout which contains your two TextViews.

Let me know in case this does not work.


text:
Q: Find all primes $p>2$ for which $x^2+x+1$ is irreducible in $\mathbb{F}_p[x]$
Find all primes $p>2$ for which $x^2+x+1$ is irreducible in $\mathbb{F}_p[x]$

Attempt. Since $x^2+x+1$ is of degree 2, it is reducible iff it has a root in $\mathbb{F}_p$. It has a root in $\mathbb{F}_p$ iff $x^3-1=(x-1)(x^2+x+1)$ has a root other than 1. The latter has a root other than $1$ iff $\mathbb{F}_p$ has elements of order $3$, which happens iff $3\mid |\mathbb{F}_p^{\times}|=p-1$, which happens iff $p\equiv 1\bmod 3$. So $x^2+x+1$ is irreducible iff $p\not \equiv 1\bmod3 $.
I am getting a different answer than my professor, who has $p\equiv 1\bmod 3$. If I am incorrect, were am I going wrong?
Update. Now I am unsure about my own reasoning. What if $1$ is a root of $x^2+x+1$? I don't know why I am considering roots of $x^2+x+1$ other than $1$ when $1$ can be a root.

A: This seems correct. For example, when p = 7, we have $x^2 + x + 1 = (x - 2)(x+3)$, so that the answer definitely can't be p is congruent to 1 mod 3.

A: We can write $x^2+x+1=4^*((2x+1)^2+3)$, where $4^*$ is multiplicative inverse of $4$ modulo $p$. Now, the last expression can be made equal to 0 iff $-3$ is quadratic residue mod $p$, which you can use quadratic reciprocity to see that it happens iff $p\equiv 1\mod 6$.

A: By the way, there is a general result which says that for $p \nmid n$ the cyclotomic polynomial $\Phi_n$ is irreducible over $\mathbb{F}_p$ if and only if $[p]$ generates $(\mathbb{Z}/n)^{\times}$. Here, $n=3$, and the only non-generator of $(\mathbb{Z}/3)^{\times}$ is $[1]$. Hence, $\Phi_3=X^2+X+1$ is irreducible over $\mathbb{F}_p$ if and only if $p \not\equiv 1 \bmod 3$.


text:
Q: "Быки и коровы". Подскажите как правильно считать "Коров" Не могу придумать нормальный алгоритм для подсчета коров, программа при вводе двух одинаковых двузначных чисел("3 6 3 6"сравниваем с "3 6 7 5") считает 4 коровы.
#include "std_lib_facilities.h"
//"БЫки и Коровы" v0.2
int main(int argc, char const *argv[])
{
    bool condit=false,
         condit1=true;//условие
    vector<int> num;//вектор для хранения загадонного числа
    int h=0,//загадонные числ
        j=0,//отгадываемые числа
        cow=0,//коровы
        bull=0;//быки
    hello_user("Быки и Коровы", 1);
    cout<<"Читай правила внимательно!\n\n"
        <<"///////////////////////////\n\n"
        <<"Компьютер загадыват четырех значное число,\n"
        <<"а ваша задача его отгадать.\n"
        <<"Компьютер будет вам помогать:\n"
        <<"Коровы - это отгаданые числа, но стоят не на своих местах.\n"
        <<"Быки - это отгаданые числа, которые стоят на своих местах.\n\n"
        <<"///////////////////////////\n\n";

    cout<<"Если ты понял правиа нжимай 'Enter'\n";
    do{
    cin.clear(); // сбрасываем флаг ошибки
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    if(condit1==true){
       //загадываем число
        for (int i = 0; i < 4; ++i)
        {
            h=randint(10);
            num.push_back(h);
            if(num.size()>4)num.clear();
            //cout<<num[i]<<endl;
        }
        condit1=false;
        cout<<"Можешь отгадывать я загадал числа от 0 до 9\n";
        array_print(num);}
    //////цикл для ввода чисад/////
    {   vector<int> num1;//для вводимого ползователем числа
        for (int i = 0; i < num.size(); ++i)
    {
        cin>>j;
        num1.push_back(j);
    }
    array_print(num1);//создано для просмотра вектора
    //////////////////////////////

    for (int i = 0; i < num.size(); ++i)
    {
        if(num1[i]==num[i]) bull++;
        if(num1[0]==num[i]) cow++;
        if(num1[1]==num[i]) cow++;
        if(num1[2]==num[i]) cow++;
        if(num1[3]==num[i]) cow++;
    }
    }
    cout<<"Быков: "<<bull<<'\n'
        <<"Коров: "<<cow<<endl;
    if(bull==4){
        cout<<"Ты победил!\n"
            <<"Я загодал число: \n";
            array_printl(num);
            num.clear();
            condit=true;
            condit1=true;
            char i =' ';
            i = ask_user("Хочешь сыграть еще");
            if(i=='y'){
                condit=false;}
        }
    cow=0;
    bull=0;
    }while(condit==false);
    return 0;
}

"std_lib_facilities.h"
#include <limits>
#include <iostream>
#include <fstream>
#include <sstream>
#include <cmath>
#include <cstdlib>
#include <string>
#include <list>
#include <vector>
#include <algorithm>
#include <stdexcept>

using namespace std;

void array_printl(vector<int> & arr)
{
    for (int i = 0; i < arr.size(); ++i) cout<<arr[i];
        cout<<endl;
}

void array_print(vector<int> & arr){for (int i = 0; i < arr.size(); ++i) cout<<i<<" Ячейка массива:"<<arr[i]<<endl;}

char ask_user(string question)
{
    cout<<question<<" ? (yes/no)\n";
    string answer = " ";
    cin>>answer;
    if(answer=="yes"||answer=="y") return 'y';
    if(answer=="No"||answer=="n") return 'n';

}

A: Так вам наверное надо исключить из дальнейших расчётов то число, которое отгадано:
for (int i = 0; i < num.size(); ++i)
{
    if(num1[i]==num[i]) { bull++; continue;}
    if(num1[0]==num[i]) { cow++; continue;}
    if(num1[1]==num[i]) { cow++; continue;}
    if(num1[2]==num[i]) { cow++; continue;}
    if(num1[3]==num[i]) { cow++; continue;}
}


text:
Q: Is config.xml is created after the domain creation or when admin server starts for the first time in Weblogic? I read this in the official documentation but I am confused about config.xml.
When you start a server instance in a domain for the first time, WebLogic Server creates the following subdirectories in the domain directory:
Files containing security information
logs directory for storing domain-level logs
For each server running in the domain, a directory for storing server logs and HTTP access logs

A: The config.xml file is created during the domain creation.


text:
Q: mysql not using index w/ group_concat I've got a simple temp table that I'm creating below
CREATE  TEMPORARY TABLE IF NOT EXISTS Helper0910912001524518044820 (
    usergroupID INT,
    StoreID INT ,
    INDEX st (`usergroupID`)
    ) engine=memory AS
SELECT  usergroup0.*
    from
    (
        SELECT  156825 as usergroupID,
                MVStoreID as StoreID,
                1 as assignmentCount
            FROM  MVMasterEntity_AttachedStores
    ) usergroup0 ;

/* queryTime - 0.5284 seconds */
I then query against it with the following query....
Select usergroupID, group_concat(StoreID) as Inspects
    from Helper0910912001524518044820
    group by usergroupID;

but am not having any luck with getting this query to use indexes.  I've tried the following indexes.
( StoreID ) , ( StoreID, UsergroupID ), ( UsergroupID ), ( UsergroupID, StoreID )

The explain that I get is always the same.
id  select_type table   type    possible_keys   key key_len ref rows    Extra
1   SIMPLE  AssHelper0910912001524518044820 ALL                 903452  Using filesort

Any help explaining why I can't use indexes for this query would be greatly appreciated.

A: No index is useful.  There is only one value of usergroupID (as you have written the query), so there is no use for it to be indexed.
So, the Optimizer decides to simply read the data without using any index.
One thing you can do is to get rid of the extra layer of SELECTs.
Another thing is to get rid of assignmentCount, since it is not used.
To achieve the same result set, simply do (without a tmp table):
SELECT  156825 AS usergroupID,
        GROUP_CONCAT(MVStoreID) as Inspects
    FROM  MVMasterEntity_AttachedStores

With this formulation, INDEX(MVStoreID) would probably help.
(I suspect you watered down the actual code too much, and I have not answered your real question.)


text:
Q: Как сделать ссылки на рубрики (WordPress) Как передать посты из категорий в category.php
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀   ⠀  Допустим нажали(кликнули) на Дома, должны выйти все посты из категории Дома и т.д.
Ссылки на категории:
Знаю, что здесь нужно что-то дописать, но что именно я не понимаю =(

 Дома
 Краски
 Одежда

Шаблон(category.php)
Тут косяк в свойстве 'category' я его пометил комментом.

<?php
global $post;

$myposts = get_posts([
'numberposts' => 12,
'category'    => 2, // ***** Вот тут косяк, здесь можно указать лишь одну категорию =(
                    // ***** Как сюда передать посты из той категории на которую кликнули мышкой

]);

if( $myposts ){
foreach( $myposts as $post ){
setup_postdata( $post );
?>

<a class ="News_Link_1" href="<?php the_permalink() ?>">

<?php the_post_thumbnail(
array(),
array(
'class' => 'News_img_1'
)
); ?>

<?php the_title(); ?>

<?php }} wp_reset_postdata(); ?>

Есть решение, но это костыль =(
⠀⠀⠀ ⠀ ⠀⠀⠀ ⠀ ⠀⠀⠀ ⠀ ⠀⠀⠀ ⠀ ⠀⠀⠀ ⠀ ⠀⠀⠀ ⠀ ⠀⠀⠀ ⠀ ⠀⠀⠀ ⠀ ⠀⠀⠀ Не хочется создавать 50 страниц в админке WordPress, 50 шаблонов с ⠀⠀⠀⠀⠀⠀ ⠀  ⠀⠀⠀ ⠀ одинаковым html и 50 циклов с разными значениями 'category'


text:
Q: Django - Edit data in db I have a question regarding editing/saving data in database using Django.
I have template that show data from database. And after each record i have link that link you to edit page.
But now is the question how to edit data in db without using admin panel?
I run thought tutorial in djangobook but i didn't see how to achieve this without using the shell
Thanks in advice!

A: Have a look at the "Working with forms" section in the Django documentation.

A: You can use Django authenticaion system to create users and giving them permissions to modify the data.


text:
Q: Glassfish 3.1.2's JDBCRealm has a new Password Encryption Algorithm field. What is it for? The Glassfish JDBC realm features several different properties you can set.
I am interested in the Digest Algorithm and Password Encryption Algorithm properties (that's how they show up in the admin console).
The second one is new as of Glassfish 3.1.2 as near as I can tell.
I have consulted the official Glassfish 3.1.1 documentation but it does not address the new property, and does not really explain what the first property is used for.
There is a documentation bug that references a bug number (13363269) that must point to a defunct bug system because I can't find the bug to which it refers.  This phantom bug presumably details what the Password Encryption Algorithm property is for, but alas seems to be lost to the mists of time.
From the command line, the property is named (improbably): digestrealm-password-enc-algorithm.  It looks like this will live on next to the digest-algorithm property.
I attempted to read the source code, but the JDBCRealm.java file appears to be missing although I am doubtlessly simply looking in the wrong place.  A prior copy that I found does not reference the property anywhere.
What are these two properties for?  I have a hazy sense that together they ensure that if I use the realm to login with a plaintext password I can somehow delegate the hashing-and-comparing operations to the realm, provided of course that the hashes used to store the original password and the hashes used on the incoming password were calculated the same way.
The manual also indicates that if I want to use digest authentication that I should be specifying the jdbcDigestRealm JAAS context.  If I don't want to use digest authentication, then I should be specifying the jdbcRealm JAAS context.  To my eyes, this looks like yet another place where I am effectively specifying what kinds of hashing algorithms are involved.
Thanks in advance for any pointers.

A: I wrote about this (related issue) here - Glassfish 3.1.2 JDBCRealm configuration.
In short, the password encryption field does not seem to be mandatory at all anymore - so just storing passwords as SHA 256 hashes should work well enough.


text:
Q: How can you use the fetch API to get the HTML source of a page? I wanted to know how I can use the fetch() function in javascript to return the source of a page from a different origin. I already know that if you want to get the HTML source you do something like this:
const getData = async () => {
  const res = await fetch('http://example.com')
  const data = await res.text()
  console.log(data)
}

When I tried using the above function, I got a cors error. I then tried adding, {mode: 'no-cors'} to the options but, that didn't return any response. I have done some research and found nothing useful. Is it possible to get the source of a website from a cross-origin request? Thanks.


text:
Q: Connecting a decoupling capacitor straight to the ground plane I had always thought that if an IC is grounded to the ground plane then connecting a decoupling capacitor to VDD on one side and straight to ground plane on other side as shown below is acceptable:

However as I understand this poorly spelled guide from the depths of the internet tells me I was wrong all along and the correct way is to run a trace from the IC ground pin to the capacitor and THEN connect to the ground plane:

I believe I was using d) which is somehow wrong. Can anyone more experienced shed some light on this topic, which one of these is the preferred method? Thank you.

A: It is to do with the direction the current flows, how hard that is and what that can cause.
What happens with d, for example, is that switching noise from the uC can take reasonable current spikes. These currents are injected directly into the ground plane and its set of capacitance and inductance. At some stage that energy is partly compensated by the decoupling capacitor, but it will be too late. The spike is already in the ground domain and the current might induce a running spike or oscillation along the ground plane, because it's not simply a metal plate. It has a very difficult set of mathematical equations going on inside it regarding its own inductance and capacitance to other copper areas.
Granted an actual ring on a ground plane is not easy to achieve, especially with a small loop, but better to have a bogeyman that's not likely to ever happen, than assume all sunshine every day.
You want all noise spikes to always see the capacitor before it sees anything else, on both tracks, so you know it will prefer taking energy from the capacitor rather than your power planes and inject its noise directly into the rest of your system.
EDIT:
There are (limited) reasons to use D. In the case of your first picture might be one. If the traces need to be long for your components to see the cap directly, the via to the plane might be the lesser of two evils. A long trace will pinch off the switching current available to the uC/complex-chip. And it might use those currents to generate noise back into the chip, if you happen to run it below the substrates (rare as it may be). But in general the rule of the chip seeing the capacitance first on both traces is a good one and most uC/uP/FPGA type devices have their pins such that this is possible with very short traces. Some parts of the ATTiny and PIC type families excluded, but what do you want for a single $?
Although, you can see that the Tiny261-family has a lot of AD and also chose to put the power pins next to each other for both domains. Coincidence?

A: It all depends on specific component switching characteristics and specific PCB. For most designs it will not matter at all. For designs where it matters, wher the switching frequency is very high, you should understand why are you even bothering with the decoupling capacitors. Once the clock edge occurs, many transistors inside switch at the same time, and to work properly all of them need the VDD supply to remain stable, otherwise their outputs will not work well. And since all of them are actually driving other tansistors gates, the initial current is quite high. So the current pulse comes from the decoupling capacitor. If the trace inductance between it and IC pin is high, it will not allow sufficient current. This is by the way why sometimes you will need 0201 caps- smaller case has smaller inductance. Now, vias usually have lower inductance that several mm trace. Plane has almost zero inductance, if there is not much holes in it.