text:
Q: Efficient Method to do Calculations on Joint Distributions in R If I have the following joint distribution where the top row is the value of Y and the first column on the left are the values of X, what is the most efficient/clean way of going about calculating the covariance and correlation between X and Y?
I was thinking of loading each row into a new variable and just doing the necessary calculations and then running the cov() and cor() functions, but I know there has to be a better way?
Thanks!

|   |  14 | 22  | 30  | 40  | 65  |
|---|-----|-----|-----|-----|-----|
| 1 | .02 | .05 | .10 | .03 | .01 |
| 5 | .17 | .15 | .05 | .02 | .01 |
| 8 | .02 | .03 | .15 | .10 | .09 |

A: You should most definitely use matrix multiplication to get the results. The following is probably not the most efficient way, but it uses the formulas in a straightforward way.
# input data
yvec <- c(14, 22, 30, 40, 65)
xvec <- c(1, 5, 8)
jp   <- matrix(c(.02, .05, .10, .03, .01,
                 .17, .15, .05, .02, .01,
                 .02, .03, .15, .10, .09),
                 nrow=length(xvec), ncol=length(yvec), TRUE)

Ex  <- rowSums(jp) %*% xvec    ## E(X)
Ex2 <- rowSums(jp) %*% xvec^2  ## E(X^2)
Vx  <- Ex2 - (Ex)^2            ## Var(X)
Ey  <- colSums(jp) %*% yvec    ## E(Y)
Ey2 <- colSums(jp) %*% yvec^2  ## E(Y^2)
Vy  <- Ey2 - (Ey)^2            ## Var(Y)
Exy <- xvec %*% jp %*% yvec    ## E(XY)

(Cxy <- Exy - Ex*Ey)           ## covariance
(Rxy <- Cxy /sqrt(Vx * Vy))    ## correlation


text:
Q: Linear search for word in String array from text file I am trying to figure out how to read a list of Strings in a text file and return the position of the word found. I'm not sure why this isn't working. Can someone tell me what I'm doing wrong? It returns -1 for each word and the words are definitely in there.
public class LinearSearch extends SearchAlgorithm
{
public int search(String[] words, String wordToFind) throws ItemNotFoundException {
    for (int i = 0; i < words.length; i++) {
        if (words[i] == wordToFind) {
            return i;
        }
        else {
            return -1;
        }
    }
    return -1;
}

public final static String FILE_AND_PATH = "longwords.txt";
/*
 * TODO: Be sure to change the FILE_AND_PATH to point to your local
 * copy of longwords.txt or a FileNotFoundException will result
 */

//Note how we deal with Java's Catch-or-Declare rule here by declaring the exceptions we might throw
public static void main(String[] args) throws FileNotFoundException {
    File file = new File("/Users/myName/Desktop/compsci/HOMEWORK/recursion/longwords.txt");
    Scanner input = new Scanner(file);
    int wordCount = 0;
    ArrayList<String> theWords = new ArrayList<String>();

    //read in words, count them
    while(input.hasNext())  {
        theWords.add( input.next() );
        wordCount++;
    }

    //make a standard array from an ArrayList
    String[] wordsToSearch = new String[theWords.size()];
    theWords.toArray(wordsToSearch);

    //start with the linear searches
    tryLinearSearch(wordsToSearch, "DISCIPLINES");
    tryLinearSearch(wordsToSearch, "TRANSURANIUM");
    tryLinearSearch(wordsToSearch, "HEURISTICALLY");
    tryLinearSearch(wordsToSearch, "FOO");

A: You can't compare Strings with words[i] == wordToFind. You have to use words[i].equals(wordToFind).
You also should remove the else block within the for loop.

A: Your loop is returning on the first iteration. Remove the else block.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to compare filenames with difference in special character encoding? I am working with a system that syncs files between two vendors. The tooling is written in Javascript and does a transformation on file names before sending it to the destination. I am trying to fix a bug in it that is failing to properly compare file names between the origin and destination.
The script uses the file name to check if it's on destination
For example:
The following file name contains a special character that has different encoding between source and destination.
source:               Chinchón.jpg // hex code: ó
destination :         Chinchón.jpg // hex code: 0xf3

The function that does the transformation is:
export const normalizeText = (text:string) =>  text
  .normalize('NFC')
  .replace(/\p{Diacritic}/gu, "")
  .replace(/\u{2019}/gu, "'")
  .replace(/\u{ff1a}/gu, ":")
  .trim()

and the comparison is happening just like the following:
const array1 = ['Chinchón.jpg'];
console.log(array1.includes('Chinchón.jpg')); // false

Do I reverse the transformation before comparing? what's the best way to do that?

A: If i got your question right:
// prepare dictionary
const rawDictionary = ['Chinchón.jpg']
const dictionary = rawDictionary.map(x => normalizeText(x))

...

const rawComparant = 'Chinchón.jpg'
const comparant = normalizeText(rawComparant)
console.log(rawSources.includes(comparant))


text:
Q: When to use Spring Prototype vs Request vs Session scope? Any real life example I want to know when should I exactly use the prototype, request and session scope in Spring? I have understood that singleton returns the same object instance if the bean is requested.
Then why should we consider other spring scopes?
Explanations with examples would help a lot to understand the need for it.

A: Here is an explanation of Spring bean scopes with associated examples:
Prototype
What-> it provides a different instance every time for each request
When-> your bean contains a state (i.e. object attributes) which you want to keep isolated, and you want to be sure it does not get re-used at the next request
Request
What-> it provides a different instance every time for each HTTP request, available only in the context of a Web Application
When-> your bean models an incoming entity (i.e. Product object) which you need to capture and process within that web request
Session
What-> it provides a different instance for each HTTP Session, available only in the context of a Web Application
When-> local caching associated to a specific user, for example a ShoppingBasket or a UserSession, you normally you call this a Stateful application

A: Used in the backend to batch process millions of records.
Data had to be converted to XML and sent to a third party.
In one thread, we processed 10 objects. The next thread processed 10 objects. During multiple thread processing, we wanted to ensure that these data objects did not interfere with each other.


text:
Q: feof() returning true when EOF is not reached I'm trying to read from a file at a specific offset (simplified version):
typedef unsigned char u8;
FILE *data_fp = fopen("C:\\some_file.dat", "r");
fseek(data_fp, 0x004d0a68, SEEK_SET); // move filepointer to offset
u8 *data = new u8[0x3F0];
fread(data, 0x3F0, 1, data_fp);
delete[] data;
fclose(data_fp);

The problem becomes, that data will not contain 1008 bytes, but 529 (seems random). When it reaches 529 bytes, calls to feof(data_fp) will start returning true.
I've also tried to read in smaller chunks (8 bytes at a time) but it just looks like it's hitting EOF when it's not there yet.
A simple look in a hex editor shows there are plenty of bytes left.

A: Opening a file in text mode, like you're doing, makes the library translate some of the file contents to other stuff, potentially triggering a unwarranted EOF or bad offset calculations.
Open the file in binary mode by passing the "b" option to the fopen call
fopen(filename, "rb");

A: Is the file being written to in parallel by some other application? Perhaps there's a race condition, so that the file ends at wherever the read stops, when the read is running, but later when you inspect it the rest has been written. That would explain the randomness, too.

A: Maybe it's a difference between textual and binary file. If you're on Windows, newlines are CRLF, which is two characters in file, but converted to only one when read. Try using fopen(..., "rb")

A: I can't see your link from work, but if your computer claims no more bytes exist, I'd tend to believe it.  Why don't you print the size of the file rather than doing things by hand in a hex editor?
Also, you'd be better off using level 2 I/O  the f-calls are ancient C ugliness, and you're using C++ since you have new.
int fh =open(filename, O_RDONLY);
struct stat s;
fstat(fh, s);
cout << "size=" << hex << s.st_size << "\n";

Now do your seeking and reading using level 2 I/O calls, which are faster anyway, and let's see what the size of the file really is.


text:
Q: Unexpected '+' Error. Expected ']' in accessing indices of an array I have some php code where I look into a file, read till EOF then use a PHP script to insert them into a mysql database. Here's the code:
$array = array();
while(!feof($filehandle)) {
        $line = fgets($filehandle);
        array_push($array, $line);
}
$i = 0;
while($i < count($array)-1) {
        $insert = mysqli_query( $dbhandle, "INSERT INTO " . $table_name . "(column1, column2, column3) VALUES ('$array[$i]' , '$array[$i+1]', '$array[$i+2]')");
        $i += 3;
}

When I run this, it has an error at my mysqli_query line syntax error, unexpected '+', expecting ']'
I've tried to do string concatenation:
'$array[$i]' ,'".$array[$i+1]." ,
and this runs without an error, but the data isn't popping up in my db.
As a temp solution, I have $j = $i + 1 and $k = $i + 1 which i use to index my array, and seems to work fine...
Any idea what is going on here? Thanks in advance.

A: You can't use expressions inside strings like regular variables and arrays.
This is okay:
echo "$arr[0]";

This is not:
echo "$arr[$i+1]";
echo "strtolower('test')";
echo "1+1"; // would output "1+1" and not "2"

You want to enclose the array inside curly braces:
echo "${arr[$i+1]}"; // outputs the correct result
echo "{$arr[$i+1]}"; // outputs the correct result

This only works for variables:
echo "${myVar}"; // ok
echo "{strtolower('test')}"; // won't work

Also, as @MarcinNabialek said, I think you need to change your while:
while($i < count($array)-3) {


text:
Q: feeding input to variable from txt line by line in python I have a variable DOMAIN which takes url as input. I want to feed it list of URLs one by one from txt file.
My txt file looks like this:
www.yahoo.com
www.google.com
www.bing.com

I am doing this:
with open('list.txt') as f:
    content = f.readlines()
content = [x.strip() for x in content]
DOMAIN = content

But the variable DOMAIN takes all URLs once, not separately. It must process one URL as whole and second on another operation.
On a side note, this DOMAIN variable is feed to scrapy for crawling.
part of codebase:
from scrapy.selector import HtmlXPathSelector
from scrapy.spider import BaseSpider
from scrapy.http import Request
with open('list.txt') as f:
    content = f.readlines()
# you may also want to remove whitespace characters like `\n` at the end of each line
content = [x.strip() for x in content]
DOMAIN = content
URL = 'http://%s' % DOMAIN

class MySpider(BaseSpider):
    name = DOMAIN
    allowed_domains = [DOMAIN]
    start_urls = [
        URL
    ]

errors:
scrapy.downloadermiddlewares.retry] DEBUG: Retrying <GET http://['www.google.com', 'www.yahoo.com', 'www.bing.com']>
executing as scrapy runspider spider.py

full working script for single url---
from scrapy.selector import HtmlXPathSelector
from scrapy.spider import BaseSpider
from scrapy.http import Request

DOMAIN = 'google.com'
URL = 'http://%s' % DOMAIN

class MySpider(BaseSpider):
    name = DOMAIN
    allowed_domains = [DOMAIN]
    start_urls = [
        URL
    ]

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        for url in hxs.select('//a/@href').extract():
            if not ( url.startswith('http://') or url.startswith('https://') ):
                url= URL + url
            print url
            yield Request(url, callback=self.parse)

A: Ok, so you are assigning the list of domains you are creating to DOMAIN.
content = DOMAIN

You then need to concatenate 'http://' to each of these:
with open('list.txt') as f:
    content = f.readlines()
content = [x.strip() for x in content]
domain_list = content
web = 'http://'
start_url = [web + s for s in domain_list]

Then you have a list of all your URL's, which you could use to connect.  I'm not sure what you are doing after this, but I think it should involve iterating over the list of start urls?
for url in start_url:
    scrapy.Request(url)

Hope this helps,

A: With these lines:
DOMAIN = content
URL = 'http://%s' % DOMAIN

You can made DOMAIN point to the list you have just created from your file, and then concatenated http:// and a string representation of the list, so you get this:
`http://['www.google.com','www.yahoo.com', 'www.bing.com']'

Hence your error. You need a to concatenate the 'http://' to each entry of the list - you can simply do it while you read the file by iterating over the file directly in a list comprehension rather than using readlines():
with open('list.txt','r') as f:
    url_list = ['http://'+line.strip() for line in f]

Which will yield a list you can then iterate over with scrapy:
['http://www.google.com','http://www.yahoo.com', 'http://www.bing.com']

Note that reading the while file in at once can be considered inefficient if it's a really big file. In that case you could remove the need to read the whole file into a list, and just the requests as you process the file line-by-line:
with open('list.txt','r') as f:
    for line in f:
        url = 'http://'+line
        request = scrapy.http.Request(url)
        # Do something with request here

Also, note that you should not use all UPPERCASE for variable names, these are generally used only for constants. Have a look at PEP8 - The Python Style Guidelines for more guidance on naming conventions. Of course these are guidelines, not rules, but it will make is easier for others to follow your code later on if you follow them.


text:
Q: How do I remove user input from a list variable? If I had a variable list and wanted to remove the user input from that list, how would I go about doing so?
people = ('Jim', 'Tim', 'Kim','Ben')
print('please choose a person')
print(people)
user_name = input(#if say Kim is typed)
print('Hi', user_name,)
print('Now pick another person')
print()<------ # print the people variable without user_name

A: Tuples are inmutable, so you must use a list instead.
So, convert the tuple to a list:
l = list(people)

Remove the desired item:
l.remove(user_name)

Print the the new list:
print(l)


text:
Q: Assign a new value based on other column's value So I have a dataframe Fruit that have structure look like this
Fruit Sales
Apple 1000
Pear  2000
Peach  400
Banana 200
...

I want to create a new column 'Tag' that assigns value 'Others' to the fruit with sales below rank 10 (sort by sales in descending order), for fruit above(including) rank 10, assign their fruit name to the 'Tag'. So it should look like this assuming Peach and Banana are below sales rank 10.
Fruit Sales  Tag
Apple 1000   Apple
Pear  2000   Pear
Peach  400   Others
Banana 200   Others
...

First, I sort the Fruit dataframe first by sales volume and take the first 10 records:
Top_fruit = Fruit.sort_values(by='Sales',ascending = False)[:10]

Second, I create a Fruit_test dataframe with 'Tag' field added to process the loc function to find the Fruit that's not in the top 10 rank list (ie, Top_fruit) and assign 'Others' to the Tag field.
Fruit_test = Fruit.copy()
Fruit_test['Tag'] =Fruit['Fruit']
Fruit_test.loc[~Fruit_test['Fruit'].isin((Top_fruit)),'Tag'] = 'Others'

However, I keep getting Keyerror: Fruit. Did I do something wrong?

A: You can do it with just one line of code:
df['Tag'] = df.apply(lambda row: row['Fruit'] if row['Sales'] > 10 else 'Other', axis=1)

Test it:
import pandas as pd

df = pd.DataFrame(
    [['Apple', 1000], ['Pear', 2000], ['Peach', 8], ['Banana', 5]],
    columns=['Fruit', 'Sales'])

print(df, '\n\n------------\n')

df['Tag'] = df.apply(
    lambda row: row['Fruit'] if row['Sales'] > 10 else 'Other', axis=1)

print(df)

Ouput:
    Fruit  Sales
0   Apple   1000
1    Pear   2000
2   Peach      8
3  Banana      5

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

    Fruit  Sales    Tag
0   Apple   1000  Apple
1    Pear   2000   Pear
2   Peach      8  Other
3  Banana      5  Other


text:
Q: aquivo .conf do swagger erro:mismatched character expecting Eclipse Meu Eclipse me mostra que os arquivos cors.conf e nginx.conf estão com erro. Ao analisar ele aponta os seguintes problemas.
No cors.conf:
    add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
#
# Custom headers and headers various browsers *should* be OK with but aren't
#
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type' always;
#
# Tell client that this pre-flight info is valid for 20 days
#
add_header 'Access-Control-Max-Age' $access_control_max_age always; // ERRO --> mismatched character 'a' expecting '{'

if ($request_method = OPTIONS) { // ERRO --> mismatched character 'r' expecting '{' e tbm no viable alternative at input '='

  return 204;
}

A aplicação funciona normalmente mas não sei como tirar esses erros. Acho que deve ser alguma configuração do Eclipse pois isso aconteceu depois de um update e eu não alterei esses arquivos.

A: Como sugerido nos comentários, o problema é de configuração do Eclipse. Alterando as associações de arquivos os avisos de erro somem. Dessa maneira Windows -> Preferences -> General -> Editor -> File assocations


text:
Q: How to add to an intermediary table in Entity Framework I have the following entity:
class Car
{
    public string make;
    public string model;
    public string registration;
}

We have multiple dealerships and we want to ensure that dealer1 can only see cars that belong to them, and dealer2 can only see their cars.
We don't want to implement this check in the everyday business logic of our applications since it could lead to inconsistent enforcement of the rules, so I'm creating a thin wrapper around Entity Framework which does that.
I have another entity:
class Dealer
{
    public Guid id;
}

I don't want car to reference dealer, so instead I plan to have my wrapper code look like this:
void AddCar(Car car, Dealer dealer)
{
    // Some authorization logic goes here

    *Add dealer if not already added

    context.Add(car)

    *Add link between car and dealer to third table
}

Is there any way to add data to a third link table without defining a new class to represent that link for every type of entity? E.g. can I just do like a dumb table insert or something like that?
I've tried to simplify my example as much as possible for clarity, but the reality is that I'm trying to make the wrapper generic as I have no idea what entities exist across all the micro services it will be used in (and nor should I)

A: You can execute SQL queries in entity framework by using ExecuteSql.
int carId = 1;
int dealerId = 1;
using (var context = new AppDbContext())
{
    var sql = $"INSERT INTO [CarDealer] ([CarId], [DealerId]) VALUES ({carId}, {dealerId})";
    var rowsModified = context.Database.ExecuteSql(sql);
}


text:
Q: BreakPoint are not working in ipad? I have seen many question like this before but in my case it is not working only on iPad.
I have breakpoints that are not working in iPad but when I Run my application on Simulator or on the iPhone all the breaking point are working properly.
I have tried install SDK again, Delete the previous build, clean , clean all target & Load Symbols Lazily.

A: Try deleting the app from the iPad, restart, clean the project, run normaly, stop, activate breakpoints, and re-try.

A: Sometimes when Xcode is started and device is already connected to MAC, the device appears in XCode even if the device iOS version is higher than the XCode iOS version. At this time the break point doesn't work.


text:
Q: Find rotation matrix in OpenGL Take this with a grain of salt, I have practically no knowledge of linear algebra. That said, my problem lies within a rotation matrix that I have multiplied to my current matrix several times. Essentially, I'm trying to be able to gain the original matrix before transformation( correct terminology?). So in theory, I should be able to have "undo"ed the rotation matrix. I have heard of transposing the matrix that has had the rotation matrix applied to however I don't even know how I would obtain that. Every method I have theorized on how to do this ultimately has resulted in having to know what the original matrix prior to the rotation matrix being applied to it was ( or some way to find out ). Is there a way to do this in OpenGL and/or mathematically speaking?
Thanks in advance. Best Regards.

A: After having spoken to Mike some more, I have determined that he has underlying problems that first need to addressed before attempting to tackle this. It appears as though he is using deprecated OpenGL (glPush/Pop), and does not have access to the matrices in question. I have instructed him to learn modern opengl, and then come back to this topic at a later date.
However, I have found out that you can indeed extract a rotation from a RTS Transformation matrix. In OpenTK, which he is using, this is done by using ExtractRotation() of a Matrix4, which gives you a quarternion. You then use the ToEulerAngles() function of the Quaternion to get a Vector3 that symbolizes the rotation in radians. The last step is then to convert those radians to degrees, using something like this:
        /// <summary>
        /// Converts radians to degrees.
        /// </summary>
        /// <param name="radians">The angle in radians.</param>
        public static float ToDegrees(float radians)
        {
            return radians * 57.29578f;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="radians"></param>
        /// <returns></returns>
        public static Vector3 ToDegrees(Vector3 radians)
        {
            return new Vector3(ToDegrees(radians.X),ToDegrees(radians.Y), ToDegrees(radians.Z));
        }

And this will get you the rotation of the xy and z components. It should be noted one final time that this only works for RTS Transformations. And as a final opinion, none of this should be used in performance sensitive code; instead, I'd suggest storing the rotation somewhere so you can quickly reference it instead of attempting to extract it, and if needed be, sync and build the transformation matrix on a layer beneath it.


text:
Q: How to write and read csv file each row python I have this code which in python 2 :
import io
from nltk.corpus import stopwords
import pandas as pd
from Sastrawi.StopWordRemover.StopWordRemoverFactory import    StopWordRemoverFactory

factory = StopWordRemoverFactory()
stopwords = factory.get_stop_words()
stop_words = set(stopwords)

file1 = open('sample/wah.csv', 'rb')

line = file1.read()# Use this to read file content as a stream:
words = line.split()
for r in words:
    if not r in stop_words:
        appendFile = open('sample/wewe.csv','a')
        appendFile.write(" "+r)
        appendFile.close()

But the results are connected to each other, how to keep it separate each row or line ?

A: import csv as c

with open("C:\\Users\\Yogesh\\Desktop\\csvData.csv") as csv_file:
    csv_reader = c.reader(csv_file, delimiter=',')
    NumberOfLine = 0
    for i in csv_reader:
        if NumberOfLine == 0:
            print(f'Column names are {", ".join(i)}')
            NumberOfLine += 1
        else:
            print(f'\t{i[0]} , {i[1]} .')
            NumberOfLine += 1
    print(f'Number of lines  {NumberOfLine}')
    enter code here

A: import io
from nltk.corpus import stopwords
import pandas as pd
from Sastrawi.StopWordRemover.StopWordRemoverFactory import    StopWordRemoverFactory

factory = StopWordRemoverFactory()
stopwords = factory.get_stop_words()
stop_words = set(stopwords)

file1 = open('sample/wah.csv', 'rb')

appendFile = open('sample/wewe.csv','a')

for line in file1.readline() # Process each line separately
    words = line[:-1].split()
    for r in words:
        if not r in stop_words:
             appendFile.write(r + " ")
    appendFile.write("\n")
appendFile.close()

This will write all sentences line by line. Side Note: This won't create a csv file, if I am correctly inferring what you want.
However, this code can be easily modified to do that.


text:
Q: Regex to match but not include a word before another word I have two specific words in a line say dog and cat.
And say dog appears before cat.
How do I make a regex which tells me all the lines containing dog and cat, but show just the words after dog till cat, including cat, but NOT dog.

A: Option 1: Lookbehind
(?<=dog).*?cat

Details:

*

*The (?<=dog) lookbehind asserts that what precedes the current position is dog

*.*? lazily matches all characters up to...

*cat matches literal characters

Option 2: \K (PCRE, Perl, Ruby 2+)
dog\K.*?cat

The \K tells the engine to drop what was matched so far from the final
Option 3: Capture Group (JavaScript and other engines that don't support the other two options)
dog(.*?cat)

The parentheses capture what you want to Group 1. You have to retrieve the match from Group 1 in your language.


text:
Q: My MacBook Pro doesn't sleep when lid closed Normally,

When you close the lid of your MacBook, it goes to sleep. There's no system setting you can tweak, and no command you can run, to change this

But, just like reported here -- My MacBook Pro doesn't sleep when its lid is closed. I'm sure because I have an external monitor:

*

*when my Mac is plugged in and I close its lid, the external monitor goes black immediately, then goes all the way to sleep (takes about five or six seconds), the orange light turns on, but that last only for about two seconds, after that power light become green again, and the monitor eventually lights up. It'll response to my mouse move/click, even the lid remains closed.

*If is on battery, when I close the lid, MacBook goes to sleep.

I hope this is a well known issue and there is an easy fix, because this is a brand new MBP, and I'm really really new to Mac and don't know much about it.
System Version: macOS 10.15.7 (19H2)
Kernel Version: Darwin 19.6.0

A: This is expected behavior and it's called clamshell mode. With an external display and mouse/keyboard, closing your laptop lid allows you to continue working on the external devices. The momentary blackout is due to switching graphics modes. To put the machine fully to sleep, simply choose Sleep from the Apple menu.


text:
Q: How to determine if any file in a directory has changed Is there a way for Chef to determine if it has changed any file in a given directory?  I'd like to restart a server process if any settings in a conf.d directory are updated.
I'm sure it's possible to write a list of md5sums to a file on each chef-client run, and compare current to previous iterations.  But that's a fair bit of code to address what seems to be a common scenario.  Is there a better way?

A: Chef provides a concept called notifications.
This allows you to define that a change in one resource triggers execution of another resource. The mentioned restart of a service after the config file changed is probably the most common use case.
template "/etc/foo/conf.d/example.conf" do
    notifies :restart, "service[foo]"
end

service "foo" do
    supports :restart => true, :reload => true
    action :enable
end

By default, notifications are :delayed, which means that they are triggered at the end of the Chef run. This helps you to avoid e.g. a service to restart once for every single changed configuration file. If you want an immediate notification, use
notifies :restart, "service[foo]", :immediately

Of course, you can use Chef's notifications not only for services, but for any resource. More examples are given in the documentation.

A: You can use inotifywait utility from the inotify-tools package


text:
Q: Count data in stored procedure mysql We have a system containing a school protocol where we want to be able to insert a class and the subject of the class and then be able to see an overview af all the students attendance of this specific subject in the specific class.
I tried to create a stored procedure with no luck.
Our data tables looks like the following:

We would like to make it so when you give 2 values (keaclass_is and subject_id) in the Stored Procedure you will get back a view of how many times a username_fk has been attending a subject out of all the possible occurrences with the same keaclass_id. Therefore we need to check the amount of occurrences the subject has had on the date too.
As an example we want the outcome to look like the following:

So Nadi6548 has been attending subject_id 2, 4 out of 4 possible occurrence and nico4108 has only been attenting subject_id 2, 1 out of 4 possible occurrence.


text:
Q: I am trying to create multiple popup with read more buttom problem is here, when i am using this code in my loop with multiple post , popup open only one read more button ,it's does not working with all read more button

Page Content

        <button id="button">Show Popup</button>

            X

Some Popup Content

http://polestarllp.com/polestarnew/category/blog/

A: You are repeating IDs, it won't work. try using classes instead of IDs.
instead of
document.getElementById("popupclose");
use
jQuery(".popupclose");
Complete code.
HTML

<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"> <?php //the_post_thumbnail('category-thumbnail'); ?><?php if ( has_post_thumbnail() ) { the_post_thumbnail(); } ?> <?php the_excerpt(); ?>

 <button class="button">Readmore</button>

 X

 <?php echo do_shortcode('[contact-form-7 id="333" title="Front-contact-us"]');?>

JS
jQuery(".button").click(function(){
    jQuery(this).closest('.overlay').show();
    jQuery(this).closest('.popup').show();
});

jQuery(".popupclose").click(function(){
    jQuery(this).closest('.overlay').hide();
    jQuery(this).closest('.popup').hide();
});


text:
Q: $\langle TT\rangle$ correlator of the boundary CFT from metric fluctuations in the bulk gravity
*

*Is there a reference which explains how the $\langle TT\rangle $ correlation of the boundary conformal field theory (CFT) can be holographically calculated from the bulk gravity? (..I am often getting referred to some paper by Skenderis et. al but I would like to see some more explicit explanation of the idea..)

In the following we defined $C_T$ as the coefficient of the leading singularity of the $\langle TT\rangle $ correlation.

Roughly that I understand the following possible algorithm works -

*

*first expand the gravity Lagrangian about an AdS background making a fluctuation (say $h$ ) along two orthogonal spatial directions of the boundary. Like say add to the metric two off-diagonal components of the type, $g_{xy} = g_{yx} = \epsilon h (r,z)$ where $x,y,z$ are 3 randomly chosen orthogonal spatial directions on the boundary and $r$ is the bulk direction orthogonal to the boundary.

*Now pick out all terms in the Lagrangian which are quadratic in $h$ and focus on all the terms which have a $\partial_r$ and rewrite those terms by pulling out a total derivative in $r$. (...I don't know how to make sense of this if one has terms of the kind $(\partial _r h)(\partial_r ^2 h)$ (and such terms do occur in examples I have tried)

*Now in this "boundary Lagrangian" which is formed by the total derivatives in $r$ and quadratic in $h$ terms substitute a Fourier expansion for $h$ as $h(r,z) = \sum_p e^{ipz}H_p(r)$.

*Now apparently there is (a universal? irrespective of the gravity Lagrangian?) value for this $H$ function which makes the fluctuation go on-shell and for Gauss-Bonnet gravity that apparently is, $H_p(r) = c BesselK[ d/2, (L^2p)/(\sqrt{f_\infty} )]$. And this $c$ is determined by demanding that $H_p (r \rightarrow \infty) = 1$ (where $r=\infty$ is the boundary) [...here its not clear to me as to how will this $f_\infty$ be defined from just the GB Lagrangian - AFAIK this $f_\infty$ is a parameter that is defined only when one is looking for asymptotically $AdS$ blackholes in GB gravity)

*Now expand in a power series in $r$ about $r=\infty$ this boundary Lagrangian and then (for any of its Fourier mode $k$?) for a d-dimensional boundary if the $d$ is even then this $C_T$ is given by the coefficient of the $k^dlog k$ terms and for $d$ odd this is given by the $k^d$ term.

*

*I would like to know if I understand the above algorithm right and if so then what is the reference for its derivation.


text:
Q: How to setup up the folder structure of angular 2 app? I have been following the Angular 2 Tour of Heroes tutorial and Quick Start guide on anuglar.io. In the tutorials all the of the files are directly under the app folder. I have started my own project and I want to set up the folder structure where I Have a components folder, services folder, and directives folder all under the app folder for the project. Under each of these folders I would also like to have folders the house each individual component to include the ts, js, map, and the html files relating to the component so for instance. It would look something like this:
-My_Project
  - app
     - components
        -app
          - app.component.ts
          - app.component.js
          - app.component.map
          - app.component.html
        -logon
          - logon.component.ts
          - logon.component.js
          - logon.component.map
          - logon.component.html
      - services
         -user
          - user.services.ts
          - user.services.js
          - user.services.map

so on and so forth.
I understand about using absolute and relative paths and using ../ to move up to the parent folder and ../../ to go back two folders in the path, but for some reason it doesn't seem to be working with the lite server. This works just fine when i run the app with Windows IIS 7.5. When I try to run the compiler I get errors of the following nature:
app - Copy/app.component.ts(6,32): error TS2307: Cannot find module './logon/logon.component'.
I am using the following to reference the logon.component file from the app.component file.
 import { LogonComponent } from '../logon/logon.component';

Also I have some PHP files in a php folder located in the Project folder. This again works fine when ran on Windows IIS 7.5 but when i try and run it with the lite server I get a 404 error when these php files are needed.
Edit
Here is my tsconfig.json
{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  }
}

Here is my pacakage.json
"scripts": {
    "start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" ",
    "lite": "lite-server",
    "postinstall": "typings install",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "typings": "typings"
  },


text:
Q: Let $(X,d)$ be any metric space. Show that if $F\subset X$ is closed, then $F^c$ is open. Not sure if this proof is correct.
Suppose that $F⊂X$ is closed. Let $x∈F^c$ so $x∉F$. Since $x∈F^c$ , then the neighborhood $N(x)\cap F=∅$. Thus $N(x)\cap F^c≠∅$ so $x∈F^c$ must be an interior point of $F^c$. Thus $F^c$ is open.

A: This is not correct.
First of all, you need to supply the argument that "Since $F$ is closed and $x\not\in F$, hence $x$ is not a limit point of $F$ and therefore there exists a neighbourhood of $x$ which doesn't intersect $F$".
Next, $N(x)\cap F^c\neq\emptyset$ doesn't imply that $x$ is an interior point of $F^c$, you need $N(x)\subset F^c$, and that is exactly what follows from $N(x)\cap F=\emptyset $
Hope it helps:)


text:
Q: Hide Global Navigation when Printing in SharePoint 2013 I am trying to hide the top navigation when printing.  I am currently using the following CSS to do so:
<style>
@media print
{#ms-breadcrumb-top{display:none !important;
    }
}
</style>

However, the above is still showing the top navigation when printing.  Any assistance is greatly appreciated.

A: You may try the below css as well :
<style type="text/css">
  #s4-titlerow {    display:none;

  }
</style>

Source:
Hide The Top Navigation On A SharePoint 2013 And Office 365 Site Using CSS
Or try the below css :
<style type="text/css"> .ms-breadcrumb-top { display: none; } </style>

A: If you're using on prem environment, you should be using this selector:
#DeltaTopNavigation { display: none; }

Currently you're using the selector to hide the ribbon, which is different from the navigation.


text:
Q: Touchpad not recognized on Asus N550JK - TP500L (FocalTech) I'm installing a new laptop and the touchpad is not fully recognized. Specifically, two finger scrolling does not work.
extract from /proc/bus/input/devices
I: Bus=0011 Vendor=0002 Product=0001 Version=0000
N: Name="PS/2 FocalTech FocalTech Touchpad in mouse emulation mode"
P: Phys=isa0060/serio1/input0
S: Sysfs=/devices/platform/i8042/serio1/input/input5
U: Uniq=
H: Handlers=mouse0 event4
B: PROP=1
B: EV=7
B: KEY=30000 0 0 0 0
B: REL=3

Also, xinput list gives me:
⎡ Virtual core pointer  id=2    [master pointer  (3)]
⎜   ↳ Virtual core XTEST pointer id=4   [slave  pointer  (2)]
⎜   ↳ ELAN Touchscreen id=10    [slave  pointer  (2)]
⎜   ↳ PS/2 FocalTech FocalTech Touchpad in mouse emulation mode id=14   [slave pointer  (2)]
⎣ Virtual core keyboard                     id=3    [master keyboard (2)]
    ↳ Virtual core XTEST keyboard               id=5    [slave  keyboard (3)]
    ↳ Power Button                              id=6    [slave  keyboard (3)]
    ↳ Video Bus                                 id=7    [slave  keyboard (3)]
    ↳ Video Bus                                 id=8    [slave  keyboard (3)]
    ↳ Sleep Button                              id=9    [slave  keyboard (3)]
    ↳ USB2.0 HD UVC WebCam                      id=11   [slave  keyboard (3)]
    ↳ Asus WMI hotkeys                          id=12   [slave  keyboard (3)]
    ↳ AT Translated Set 2 keyboard              id=13   [slave  keyboard (3)]

And finally, synclient tells me there is no synaptics driver active:

Couldn't find synaptics properties. No synaptics driver loaded?

So, it seems the touchpad is not recognized as a synaptics touchpad. It works, but not the synaptics specific parts.
It's in mouse emulation mode (no idea what it means). And it works together with other pointing devices, especially the touchscreen (I can confirm this works).
I have tried adding i8042.nomux=1 to the kernel parameters, but it didn't change anything... Any hint ?

A: I finally came to this bug report: https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1372609
It seems FocalTech touchpad needs a specific driver, and that work is in progress to integrate it into the mainline kernel.
currently, there seem to be a ppa to get a dkms driver for this touchpad : http://ppa.launchpad.net/hanipouspilot/focaltech-dkms
After trying this, I can confirm the following procedure works :

*

*add ppa
sudo add-apt-repository ppa:hanipouspilot/focaltech-dkms

*update the packages database
sudo apt-get update

*install the dkms driver
sudo apt-get install focaltech-dkms

*reboot
The touchpad in now recognized. Two finger scrolling works, for example. Also, the zone where the buttons are won't make the cursor move.
Thanks for the community that retro-engeniered this (Asus just replied "no linux support nor technical information" to a request ! Very bad point to them (see the afore-mentioned bug report)).


text:
Q: How to dynamically pass API data to MongoDB database I am building a boat visualizer using AISHub APIs. After inquiring the APIs I am able to obtain a json file with the vessels and filter with only the vessel I am interested in, and inject them into a table on the webpage. The API gives the following fileds:
[NAME, MMSI, LONGITUDE, LATITUDE]. I can correctly connect to MongoDB as I npm start.
The problem: I would like to send also this data to a collection in to MongoDB database every 5 minutes. I tried many different way to do that, but none of them seems to be working.
It was very difficult to think which parts of the code to pass and which not, but below I believe there are enough information to understand what the problem is:
app.js is where I set the MongoDB connection
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var mongoose = require('mongoose');
const bodyParser = require('body-parser');
const vesselController = require('./controllers/VesselController');
require('./config/keys');

var app = express();
app.use(cors());
app.options('*', cors());

// DB Config
const db = require('./config/keys').MongoURI;

const options = {
    useNewUrlParser: true,
    reconnectTries: Number.MAX_VALUE,
    poolSize: 10
};

mongoose
    .connect(db, options)
    .then(() => console.log('MongoDB Connection established'))
    .catch((err) => console.log('Error connecting MongoDB database due to: ', err));

const PORT = process.env.PORT || 3000;

app.use(bodyParser.urlencoded({ extended: true, limit: '50mb' }));
app.use(bodyParser.json({ limit: '50mb' }));
app.use(cors());

app.route('/vessels/all').get(vesselController.getBaseAll);
app.route('vessels/:id/track').get(vesselController.getCurrent);
app.route('/vessels').get(vesselController.getHistory);

app.listen(PORT, console.log(`Server started on port ${PORT}`));

module.exports = app;

index.js is where I am caching the data (and where I think the app should send data to MongoDB)
var express = require('express');
var router = express.Router();
var axios = require('axios');
const NodeCache = require('node-cache');
const myCache = new NodeCache();

let hitCount = 0;

/* GET home page. */
router.get('/', function(req, res, next) {
    res.render('index', { title: 'Express' });
});

const mmsiOfInterest = [
    '367029520',
    '366909730',
    '367128570'
];

const shipNamesOfInterest = [
    'MICHIGAN',
    'JP BOISSEAU',
    'DELAWARE BAY'
];

router.get('/hello', async function(req, res, next) {

    const allData = myCache.get('allData');

    if (!allData) {
        hitCount++;
        console.log(`hit ${hitCount} number of times`);
        const { data } = await axios.get(
            'http://data.aishub.net/ws.php?username=KEY&format=1&output=json&compress=0&latmin=11.42&latmax=58.20&lonmin=-134.09&lonmax=-52.62'
        );
        const [ metaData, ships ] = data;
        console.log(data);

        const shipsOfInterest = ships.filter(
            (ship) => mmsiOfInterest.includes(ship.MMSI) || shipNamesOfInterest.includes(ship.NAME)
        );
        myCache.set('allData', shipsOfInterest, 70);
        res.send(data);
        return;
    }
    res.send(allData);
});

module.exports = router;

VesselController.js: is where I have the functions for getting different information such as currect vessel, all vessels, history of vessels
module.exports.getBaseAll = (req, res) => {
    Promise.all([
        Compnanies.find(),
        Vessels.find(),
        Positions.aggregate([
            {
                $sort: {
                    date: -1
                }
            },
            {
                $group: {
                    _id: '$callsign',
                    details: {
                        $push: '$$ROOT'
                    }
                }
            },
            {
                $replaceRoot: {
                    newRoot: {
                        $arrayElemAt: [ '$details', 0 ]
                    }
                }
            }
        ])
    ])
        .then(([ companies, vessels, positions ]) => {
            // apply vessels detail table as join:
            positions.forEach((pos) => {
                vessels.forEach((ves) => {
                    if (pos.callsign == ves.callsign) {
                        p._detail = ves;
                    }
                });
                companies.forEach((com) => {
                    if (p._detail.company == com.number) {
                        p._detail = com;
                    }
                });
            });
            res.status(200).json(positions);
        })
        .catch((err) => {
            return res.status(500).send(err);
        });
    console.log(vesselController.getBaseAll);
};

module.exports.getHistory = (req, res) => {
    var id = req.param.id;
    Positions.find(
        {
            callsign: id,
            date: {
                $gte: new Date(Date.now() - 1000 * 60 * 60 * 24)
            }
        },
        (err, task) => {
            if (err) {
                return res.status(500).send(err);
            }
            res.status(200).json(task);
        }
    );
    console.log(vesselController.getHistory);
};

module.exports.getCurrent = (req, res) => {
    var currentPos = Positions.find({
        date: {
            $gte: new Date(Date.now() - 1000 * 60 * 60)
        }
    });
    currentPos.exec((err, task) => {
        if (err) {
            return res.status(500).send(err);
        }
        res.status(200).json(task);
    });
    console.log(vesselController.getCurrent);
};

In LatitudeLongitude.js I set the proper format according to MongoDB documentation
const mongoose = require('mongoose');

const LatitudeLongitudeSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    mmsi: {
        type: Number,
        required: false
    },
    longitude: {
        type: Number,
        required: false
    },
    latitude: {
        type: Number,
        required: false
    }
});

const LatitudeLongitude = mongoose.model('LatitudeLongitude', LatitudeLongitudeSchema);
module.exports = LatitudeLongitude;

users.js is where I set the router.post
var express = require('express');
var router = express.Router();

const LatitudeLongitude = require('../models/LatitudeLongitude');

/* GET users listing. */
router.get('/', function(req, res, next) {
    res.send('respond with a resource');
});

router.post('/vessles/map', function(req, res) {
    const { name, mmsi, longitude, latitude } = req.body;
    let errors = [];

    // Check required fields
    if (!name || !mmsi || !longitude || !latitude) {
        errors.push({ msg: 'No data received' });
    }
    if (
        LatitudeLongitude.findOne({ mmsi: mmsi }).then((pos) => {
            if (pos) {
                // vessel exists
                const newVessel = new Vessles({
                    name,
                    mmsi,
                    longitude,
                    latitude
                });
            }
        })
    );
});

module.exports = router;

Below the collection set inside MongoDB, which is clearly empty:

How can I successfully pass information from the API I mentioned above, into my MongoDB?
What I have donbe so far:
I tried many different ways to pass data from the API to MongoDB every 5 minutes. Among the dirfferent approaches, the one I included in this post are, I think, the most effective, however there is something missing I can't catch/understand.
I believe that the file index.js should be the one that is in charge of taking care of doing that, as I pre-set all the check in that file. However I am now confused whether that is the right location or not.
the reasons why you see the routes as app.route('/vessels/all').get(vesselController.getBaseAll); in the app.js file is because I will use that as end point api check with Postman once everything is working. I figured I would leave it there so you see how I designed the process.
Thanks for shedding light on this matter.

A: In my opinion, you should first test my approach by attaching following code to your server.js file. then refactor it

setInterval( () => {
        fetch('http://your/get/route').
         then( updateDB() ).
         catch(doWhateverYouWant());
     },3000
  );


text:
Q: phpMyAdmin Error Code 403 System Info:
Synology NAS 412+
phpMyAdmin 4.4.7
MariaDB 5.5.43
Files located at /volume1/web/phpMyAdmin/
Issue description:
Logging into phpMyAdmin I am presented with the error code 403
Error in processing request
Error code: 403
Error text: Forbidden

Questions:

*

*What file do I need to change

*Where is it located

*how do I restart the http server (if necessary) from cmd

I know it's something to do with phpMyAdmin permissions, but I just can't seem to see how or what to change.

A: Got it. I had a .htaccess file in the /web directory which had been written to by iThemes Security plugin. It had disabled all access. I just replaced this file with a fresh copy which I found on the wordpress help forum. Here's the contents should anyone want to do the same.
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

A: Im using Wordpress and had the same problem when accessing my phpmyadmin because of .htaccess made by iThemes Security plugin.
I fixed this error by removing the edits made by iThemes in .htaccess.
Error text:
Error in processing request
Error code: 403
Error text: Forbidden (rejected) It seems that the connection to server has been lost.
Please check your network connectivity and server status.

Fehler beim Bearbeiten der Anfrage
Fehlercode: 403
Fehlertext: Forbidden (rejected)
Es scheint, dass die Verbindung zum Server verloren gegangen ist.
Bitte überprüfen Sie Ihre Netzwerkverbindung und den Serverstatus.


text:
Q: How to remove space between div elements? I have two div elements and I want to remove the space between them, which is filled with the background color at the moment. This is what it looks like. I want to remove the space between the green section and where the background image ends for the first div element. Here is the HTML for the page:

        Log Out

Welcome to Ripple.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. A aliquam commodi doloremque esse itaque iusto, labore laborum maxime odio, quidem quos, repellat rerum? Ab, asperiores aspernatur assumenda atque distinctio dolor dolore eveniet facilis, id illo ipsa ipsam minus nemo nobis porro quam quia quibusdam quis ratione rerum soluta suscipit temporibus vel vitae voluptate. Accusamus dignissimos ea esse expedita itaque mollitia nobis, numquam odio, quaerat qui vel voluptatibus?

                <button class="search_button" >Search for a location</button>
                <button class="search_button">Search for a song</button>

Collections Near Me

And the CSS:
.main-left {
    vertical-align: top;
    margin-top: 0;
    margin-left: 0;
    position: relative;
    background-color: #85dcba;
    text-align: left;
    width: 100%;
    float: top;
    left: 50%;
    transform: translate(-50%);
}

.main-search {
    vertical-align: top;
    background-color: #d2fdff;
    text-align: left;
    margin: 0;
    padding-top: 2em;
    position: relative;
    top: 0;
    width: 100%;
    left: 50%;
    transform: translate(-50%);
}

.hero-image {
    background-image: url("main_background.jpg");
    background-size: cover;
    background-repeat: no-repeat;
}

.title {
    color: black;
    font-family: Roboto, sans-serif;
    font-size: 3em;
    margin-top: 0.5em;
    margin-left: 10px;
    margin-bottom: 0.5em;
}

.content {
    color: black;
    font-family: Roboto, sans-serif;
    font-size: 1em;
    margin: 1em;
}

.welcome-text {
    top: 5%;
    left: 5%;
    max-width: 35%;
}

A: You could try setting the margin values of the elements manually. I see you've set the padding- Which refers to the internal distance of contents to edge, but not the margin- which refers to the distance between seperate elements.
Also, nice looking design so far!

A: Display flex has a nifty way of removing undesirable whitespace from the html
So place flex on the wrapper of these elements, in this case the body tag
css
body {
   display: flex;
   flex-direction: column;
}

A: There is a gap because div is block element, if you want to remove the gap between div use display: inline-block to remove it.
body > div { display: inline-block; }

This will display an element as an inline-level block container. Please refer to CSS Display

A: Set margin-top of the .title to zero and for space between the .main-search and .title, give padding-bottom to .main-search as well. Below is how it will look like:

body{
   background-color: #c5ffff;
}

.main-left{
vertical-align: top;
margin-top: 0;
margin-left: 0;
position: relative;
background-color: #85dcba;
text-align: left;
width: 100%;
float: top;
left: 50%;
transform: translate(-50%);
}

.main-search{
vertical-align: top;
background-color: #d2fdff;
text-align: left;
margin: 0;
padding: 2em 0;
position: relative;
top: 0;
width: 100%;
left: 50%;
transform: translate(-50%);
}

.hero-image{
background-image: url("https://picsum.photos/500/500");
background-size: cover;
background-repeat: no-repeat;
}

.title{
color: black;
font-family: Roboto, sans-serif;
font-size: 3em;
margin-top: 0;
margin-left: 10px;
margin-bottom: 0.5em;
}

.content{
color: black;
font-family: Roboto, sans-serif;
font-size: 1em;
margin: 1em;
}

.welcome-text{
top: 5%;
left: 5%;
max-width: 35%;
}

        Log Out

Welcome to Ripple.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. A aliquam commodi doloremque esse itaque iusto, labore laborum maxime odio, quidem quos, repellat rerum? Ab, asperiores aspernatur assumenda atque distinctio dolor dolore eveniet facilis, id illo ipsa ipsam minus nemo nobis porro quam quia quibusdam quis ratione rerum soluta suscipit temporibus vel vitae voluptate. Accusamus dignissimos ea esse expedita itaque mollitia nobis, numquam odio, quaerat qui vel voluptatibus?

            <button class="search_button" >Search for a location</button>
            <button class="search_button">Search for a song</button>

Collections Near Me

A: remove margin-top:0.5em; on your title class.
.title {
color: black;
font-family: Roboto, sans-serif;
font-size: 3em;
 margin-top: 0.5em;  <-- REMOVE
margin-left: 10px;
margin-bottom: 0.5em;


text:
Q: Sending large data to wcf service returns me "504 (Gateway Time-out) error" I am trying to describe my problem detailed. Our aim is sending objects to wcf service which is processed and respond with another object. If we send 1000, 2000 object, we have a successful result. But when we increase the size of object like 10.000, 20.000 the server waited 1-1.30 minutes then responded 504 gateway error.
Firstly, on client side, we upload a file then read it to the server side. We initialize object of reading data and send this object to service. My controller like:
public ActionResult SaleNotification(NOTIFICATION_OBJECT notificationItem, HttpPostedFileBase files)
{

    if (files != null)
    {
        List<NOTIFICATION_ITEM_OBJECT> fileItems = new List<NOTIFICATION_ITEM_OBJECT>();
        using (var package = new StreamReader(files.InputStream))
        {
            package.ReadLine();
            while (!package.EndOfStream)
            {

                var values = package.ReadLine().Split(';');
                if (values[0] != "" && values[1] != "" && values[2] != "" && values[3] != "")
                {
                    fileItems.Add(new NOTIFICATION_ITEM_OBJECT
                    {
                        GT = values[0],
                        SN = values[1].ToUpper(),
                        BN = values[2].ToUpper(),
                        XD = values[3]
                    });
                }
            }
        }
        notificationItem.NOTIFICATION_ITEMS.AddRange(fileItems);
    }
    var res = _serviceRepository.SendNotification(Security.Decrypt(SERVICE_PASS_ENCRYPT, true), notificationItem);
    return PartialView("PartialResult", res);

}

Sending notification to service part, I tried to send the whole object at one time maybe that part my approach was wrong. Here is my code:
    public NOTIFICATION_RESULT_OBJECT SendNotification( string password, NOTIFICATION_OBJECT notification)
    {
        var res = new NOTIFICATION_RESULT_OBJECT();
        try
        {
            var client = new serviceClient();
            if (client.ClientCredentials != null)
            {
                client.ClientCredentials.UserName.Password = password;
            }

            using (new OperationContextScope(client.InnerChannel))
            {
                #region header
                var requestMessage = new HttpRequestMessageProperty();
                OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestMessage;
                #endregion

               //Some codes service request initialize

                ServicePointManager.ServerCertificateValidationCallback = delegate (object s, System.Security.Cryptography.X509Certificates.X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
                var response = client.notify(serviceRequest);

                res.NOTIFICATION_ID = response.NOTIFICATIONID;
                foreach (var item in response)
                    res.PRODUCT_RESULT_LIST.Add(new PRODUCT_RESULT()
                    {
                        GT = item.GT,
                        RC = item.RC,
                        SN = item.SN,
                        BN = item.BN,
                        XD = item.XD.ToString("dd/MM/yyyy", new CultureInfo("tr-TR")),
                    });
                return res;
            }

        }
        catch (Exception ex)
        {

            Log4NetFunction.InsertLog(ex);
            return res;
        }
    }
}

I have a configuration on my bindings about maxReceivedMessageSize, sendTimeout, receivedTimeout etc. Here is an example of one of my bindings:
<binding name="serviceBinding" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647"  openTimeout="00:10:00"
             closeTimeout="00:10:00"  sendTimeout="00:15:00" receiveTimeout="00:10:00">
      <security mode="Transport">
        <transport clientCredentialType="Basic" proxyCredentialType="Basic" realm="" />
        <message clientCredentialType="Certificate" algorithmSuite="Default" />
      </security>
    </binding>

In my debug I couldn't find any error it send 20000 object successful on locally or there is no log about this error on server. So I couldn't find any solution. How can I solve this problem? Is my approach wrong?

A: Maybe your service refuses to serialize the data with so many data members.
Please try to set the readerQuotas property of your binding.
<binding  allowCookies="false"  maxBufferPoolSize="2147483647" maxBufferSize="2147483647"
      maxReceivedMessageSize="2147483647"   openTimeout="00:10:00"
         closeTimeout="00:10:00"  sendTimeout="00:15:00" receiveTimeout="00:10:00"  >
      <readerQuotas maxArrayLength="2147483647" maxNameTableCharCount="2147483647"
          maxStringContentLength="2147483647" maxDepth="2147483647"
          maxBytesPerRead="2147483647" />
      <security mode="None" />
    </binding>


text:
Q: Replace a string with array values in Twig I searched on Google for some options to replace a string with some array values in Twig, but I couldn't find anything useful.
Is it possible to replace a string with array values in Twig?
I tried to code something like this:
{% set foo = ['.JPG', '.BMP'] %}
{% for Item in ProductImage %}

{% endfor %}

In clasic PHP is working this way:
$photoarray = array('JPG', 'BMP');
str_replace($photoarray,"jpg", $image);

A: The arguments of your filter call is slightly incorrect, it should be something like this:
{% if Item.PictureName ends with '.jpg' %}

{% endif %}

As described in the replace filter docs:

replace¶
The replace filter formats a given string by replacing the
placeholders (placeholders are free-form):
{{ "I like %this% and %that%."|replace({'%this%': foo, '%that%':
"bar"}) }}
{# outputs I like foo and bar    if the foo parameter equals to the
foo string. #}
{# using % as a delimiter is purely conventional and optional #}
{{ "I like this and --that--."|replace({'this': foo, '--that--':
"bar"}) }}
{# outputs I like foo and bar #}
Arguments¶
from: The placeholder values


text:
Q: Plone FormGen Override Subject Line I am new to Plone and am working a form in Plone 4.1. I would like to override the form mailer subject line so it is a string from the input from a subject field from the form and then the form name. I am not sure how to write this though.

A: Go to the form, click on "Contents", click on the Mail-adapter, click on "Edit, click on "Overrides" and insert this line in the field "Subject Expression":
python: folder.Title() +  ': ' + request.form['subjekt']

Where subjekt stands for the field-name you want to get the value of.
Here's a helpful doc about the available context-variables:
https://docs.plone.org/working-with-content/managing-content/ploneformgen/override_defaults.html


text:
Q: React-Spring too lazy with amount number of lists I use React-Spring in my app.
use Transition to add animation when components mount or unmount.
less then 20 lists, it work well, but more then 25 lists, it work too lazy or freeze.
I try to reproduce on codesandbox, but it has no problem.
Is there anything to solve this problem?
cords on sandbox are almost same as my apps code.
here is test on sandbox:
https://codesandbox.io/s/react-spring-work-test-0qill
and this is App test page:
https://if-then-planning.com/spring-test/


text:
Q: How to do a Unit test (Junit 4) to a method that works in a Class that has a Constructor with an unknown object parameter I need to know how to solve this issue
public class SigFX extends SigProduct {

    private FX fx;

    public SigFX(final ReportRo row) {
        super(row);
        fx = (FX) getTrade().getProduct();
    }

    @Override
    public Object getStrtDt() {
        return getTrade().getTradeDate();
    }

    @Override
    public Object getEndDt() {
        return getTrade().getSettleDate();
    }
}

I need to start Unit Tests (JUnit 4) for this class methods but I don´t really know how to solve the way I instantiate SigFX in my testClass because it has an Object type ReportRo as parameter.

A: you can do this in this way:
final ReportRo row = new ReportRo(); //I don't know class ReportRo, so it might be possible that you have to add some parameters to constructor.

final SigFX sigFX = new SigFX(row);

//you can access your methods of sigFX as usual and test it as you want


text:
Q: Ordering custom post type by multiple custom fields I was wondering if you'd be able to help with an issue i'm having?
I have implemented a fix that you came up with in this post:
How to order custom post type by multiple custom fields? however when I add the filter no posts are being displayed.
What I'm trying to achieve is to order a league table by points and then by goal difference.
This is my function in functions.php
function orderbyreplace($orderby ) {
global $wpdb;
return str_replace($wpdb->prefix.'postmeta.meta_value', 'mt1.meta_value, mt2.meta_value ASC', $orderby);
}

And here's the query in my template file
$args = array(
              'post_type'=>'standings',
              'orderby' => 'meta_value_num',
              'meta_key' => '_pts',
              'meta_query' => array(
                    array(
                        'key' => '_pts',
                        'value' => '0',
                        'type' => 'NUMERIC',
                        'compare' => '!='
                    ),
                    array(
                        'key' => '_dif',
                        'value' => '0',
                        'type' => 'NUMERIC',
                        'compare' => '!='
                    )
                ),
            );

            add_filter('posts_orderby','orderbyreplace');
            $loop = new WP_Query( $args );
            remove_filter('posts_orderby','orderbyreplace');

If you could spare a few minutes of your time to have a look over this and make any suggestions you may have and point anything out where I might have gone wrong that would be greatly appreciated.
EDIT
I've changed the code to the following and it is know returning posts however it's only ordering them by the first meta_key and ignores the other.
function orderbyreplace($orderby) {
                global $wpdb;
                return str_replace($wpdb->prefix.'postmeta.meta_value_num', 'mt1.meta_value, mt2.meta_value DESC', $orderby);
            }

            $args = array(
              'post_type'=>'standings',
              'orderby' => 'meta_value_num',
              'meta_key' => '_pts',
              'meta_query' => array(
                    array(
                        'key' => '_pts',
                    ),
                    array(
                        'key' => '_dif',
                    )
                ),
            );

            add_filter('posts_orderby','orderbyreplace');
            $loop = new WP_Query( $args );
            remove_filter('posts_orderby','orderbyreplace');

Many thanks,
Ben


text:
Q: how to reload / refresh a entity like  in A-frame? Is that possible to only reload / refresh a entity like   in A-frame? not the whole A-frame page
<img id="front" src="assets/png/front.png">

because i want to change the image

A: You can use javascript to manipulate the dom in the aframe. For exmaple you can flush the data changes to the dom like this:
document.querySelector('img').flushToDOM();

You also can change the attributes of an entity like this:
entity.setAttribute('img', { src: 'assets/png/front.png' });


text:
Q: Get resource from another project for local variable in view ASP.NET C# I'm trying to get a resource value for internazionalization based on the value of an foreach variable.
My resource project is named Resources, I reference this on my main project.
reference properties
When i want to use it. only use something like this: Resources.resourceKey
The Problem
Now I need to use this but resourceKey is in a variable on a loop
@foreach (var item in Model) {

            @Html.DisplayFor(modelItem => Resources.item.Rating)

}

This obviusly not working, in Resources has no exists any key named item
My solution (Not working)
Create a Resource Manager and try to get a string
@{
    System.Reflection.Assembly resourcesAssembly;
    resourcesAssembly = System.Reflection.Assembly.Load("Resources");

    System.Resources.ResourceManager rm = new
       System.Resources.ResourceManager(resourcesAssembly.FullName,
       resourcesAssembly);
}

@foreach (var item in Model) {

            @Html.DisplayFor(modelItem => rm.GetString(item.Rating))

}

What i'm doing wrong??
Really thnx for help

A: First of all - using the reflection on View is bad style :)
It seems like everything is OK. You are creating ResourceManager from another Assembly. If it is created correctly (view in debug) and you can see your resources in debug-watch - try to check your Culture and that your resource key is set for this culture. ResourceManager chooses the resource string depending on your thread's culture. By default it is you operating system culture.
From MSDN:

If no usable set of localized resources is found, the resource manager
  falls back on the default culture's resources. If the resource manager
  cannot load the default culture's resource set, the method throws a
  MissingManifestResourceException exception or, if the resource set is
  expected to reside in a satellite assembly, a
  MissingSatelliteAssemblyException exception. If the resource manager
  can load an appropriate resource set but cannot find a resource named
  name, the method returns null.
  MSDN article

So, if you don't see the exception - check if your resource-key is specified for choosen culture.


text:
Q: Squid add LAN IP, squid username and squid port in query when using url_rewrite_program I use squid as transparent proxy with SSL Bump interception.
Squid HTTP and HTTPS ports configuration are :
http_port 3127 transparent
https_port 3129 intercept ssl-bump generate-host-certificates=on cert=/opt/squid/ssl_cert/cert.crt key=/opt/squid/ssl_cert/cert.key options=NO_SSLv2,NO_SSLv3

I wrote the following URL program to force safe search for Google and duckduckgo :
#!/usr/bin/perl
use strict;
use URI::URL;

# Turn off buffering to STDOUT
$| = 1;

# Read from STDIN
while (<STDIN>) {
    # Do some trimming
    s/^\s*//;
    s/\s*$//;

        my $string = $_;

    # Google Safe search
        if ($string =~ m/^http(s?)\:\/\/([a-z]+\.)?google\.([a-z]{2,3})(\.[a-z]{2,3})?\/.*(\?(as_)?q=)|(\#(as_)?q=)|(\&(as_)?q=)/) {
                #print "OK rewrite-url=\"$string", "&safe=active\"";
                if ($string !~ m/&safe=active/) {
                        print "OK url=\"$string", "&safe=active\"";
                        print "\n";
                } else {
                        print "OK\n";
                }
        }

        # Duckduckgo safe search
        elsif ($string =~ m/^http(s?)\:\/\/([a-z]+\.)?duckduckgo\.([a-z]{2,3})(\.[a-z]{2,3})?/) {
                #print "OK rewrite-url=\"$string", "&kp=1\"";
                if ($string !~ m/&kp=1/) {
                        print "OK url=\"$string", "&kp=1\"";
                        print "\n";
                } else {
                        print "OK\n";
                }
        }

        # If no one match, url still intact
        else {
                print "ERR\n";
        }
}

In squid configuration I add the following line :
url_rewrite_program /opt/squid/bin/url_rewriter

url_rewriter rewrite URL well when testing in CLI :
./url_rewriter
https://www.google.fr/?q=test
OK url="https://www.google.fr/?q=test&safe=active"
https://www.duckduckgo.com/
OK url="https://www.duckduckgo.com/&kp=1"

It works perfect in browser except that squid always add LAN IP, user name and squid port in the query. For example, it add this in the Query :
"%20192.168.1.18/192.168.1.18%20benoit%20GET%20myip=-%20myport=3129"

For google I get this :
https://www.google.fr/?q=test%20192.168.1.18/192.168.1.18%20benoit%20GET%20myip=-%20myport=3129&safe=active

instead of :
https://www.google.fr/?q=test&safe=active

For duckduckgo, I get
https://duckduckgo.com/%20192.168.1.18/192.168.1.18%20benoit%20GET%20myip=-%20myport=3127&kp=1

instead of :
https://duckduckgo.com/&kp=1

Why do I have this behavior ? Did I miss something ?
I can post more configuration if needed.

A: Yes you missed a tiny detail. Squid doesn't add the myip= etc. stuff later, but before it sends the url to your rewriter. That means you have to remove it before you hand it back to squid.
Not all versions of squid do so, but it's documented up to version 3.4
TomTomTom

A: I found the solution by myself.
Yes, I missed to give version of Squid and it was an important information in my case. I use Version 3.5.20
There is a new directive named url_rewrite_extras from squid 3.5
http://www.squid-cache.org/Doc/config/url_rewrite_extras/
By default it add : "%>a/%>A %un %>rm myip=%la myport=%lp" in every query when using URL-rewriter/redirector helper program.
So I add the option to overwrite this value. I had to set a space as value because url_rewrite_extras "" add a dash "-" to query.
url_rewrite_extras " "
url_rewrite_program /opt/squid/bin/url_rewriter


text:
Q: SWT browser not working properly in RCP application I am using SWT browser in RCP application. When I call this URL in browser by code,
browser = new Browser(parent, SWT.NONE);
browser.setUrl("fakepath/version3/login.html");
browser.clearSessions();

Webpage was not opened properly. Although I have ensure that it conforms to CSS in IE as well. Please see the attached image. Do I need to add set any property in the meta tag? Thanks in advance.


text:
Q: How to kill one tab of google chrome using pid I want to close one tab of chrome. I tried killing the pid of the tab, but the tab doesn't close instead says "Aw, Snap! Something went wrong while displaying this webpage. To continue, reload or go to another page". How can I get rid of this.

A: You can't kill tabs by PID. Here's the next-best thing: it's possible to kill an unresponsive tab (or set of tabs) by interactively navigating to Chrome Task Manager in Chrome:

*

*Hamburger Icon (three lines in top-right);

*More Tools;

*Task Manager and clicking on the tab name;

*Then clicking the "End Process" button at the bottom.

A: You can't close a tab by killing the process. The process represents a renderer that the main browser uses the execute and draw a page, which it then copies to the screen. The "Aw, Snap!" is what the browser displays when the renderer responsible for that tab crashes or is killed. The proper way to close the tab would ideally be via a command-line switch, but there is none that I know of at this time.

A: This may be helpful for you. Probably a whole bunch of Chrome windows/tabs have become "unresponsive".
If you go to the Windows GUI Task Manager and kill the ProcessTree of all the Chrome.exe 'processes' eventually, you will click on one, that will kill all the Chrome Windows & Tabs. then if you re-open Chrome, you'll get a tan colored bar that asks if you want to restore the previous pages, that will reopen everything you had before.
Problem with this issue: Time consuming, if you go to admin CMD window and issue a taskkill command to '/F' (forcefully) kill everything with the imagename of CHROME, they will all die instantly, but when you reopen Chrome, it won't remember anything or ask if you want to restore anything; unless you kill the one 'master' PID of the ChromeBrowser itself. I can't find anything unique about that process to kill it without having to lookup it's dynamic PID every time.
My solution:

*

*RightClick in the Chrome "Title-Bar" and choose: "Task Manager" (the Shift+Esc shortcut, is slower, and often doesn't work). At the top of the list, you'll see "Browser" with a chrome icon. This is the only entry you can't select and click on [End-Process] in the column, find it's "Process-ID"

*From an ADMIN-CMD Window issue this command:
taskkill /F /FI "PID eq _ _ _ _" (fill in the blanks with the PID)
Then Chrome will die almost instantly, and when you reopen, it will offer to restore previous pages.

*the easiest way to handle this is with a batch-file using the "SET /p" feature to allow you to just type in the PID number in order to make it run, more or less automatically.

A: The message you see is the one that you are supposed to see if a tab is killed.  That tab is not using any memory or resources of any kind until you reload it.  If you have 3,000 open tabs and all but one are killed (and therefore have this message), your computer will run smoothly.  If you want to close the tab and lose the URL and cached information, the just close it.  With the 'X'.


text:
Q: how to include a file in HTML URL's query string while call python Request POST? I am in need of passing a image file as a query string in the URL while calling post from Python's request package. When this image is passed as an url it works. For example,
auth = {'app_id':'user_id','app_key':'user_key'}
url = 'https://api.kairos.com/v2/media'
queryParams = { "source": "http://static.goal.com/4321800/4321812_news.jpg"}
rply    = req.post(url, headers=auth, params = queryParams, verify=False)

The above code works. The url that is hit becomes
"https://api.kairos.com/v2/media?source=http%3A%2F%2Fstatic.goal.com%2F4321800%2F4321812_news.jpg"

I have a need to replace the url passed as a value to key 'source' in queryParams. When I do this like below,
queryParams = { "source": "messi.jpg"}

I get an error saying "An invalid media URL was sent". The URL this time is,
https://api.kairos.com/v2/media?source=messi.jpg

When I try the same thing using cURL (as a debug), like below,
curl -X POST -H "app_id: user_id" -H "app_key: user_key" -F "source=@messi.jpg" "https://api.kairos.com/v2/media"

This works fine.
Now can anyone help me translate this cURL into python Requests POST call?
I had tried passing this file as 'files' in POST. Does not work either. It says source in URL missing. (Source is a mandatory query in URL). Wondering how to pass this file as value to this query 'source' in the url!!!


text:
Q: var.replace is not a function I'm using the below code to try to trim the string in Javascript but am getting the error mentioned in the title:
function trim(str) {
    return str.replace(/^\s+|\s+$/g,'');
}

Edit:
I fixed the problem.... sorry I should have put the code on how I was calling it too.... realized I accidentally was passing the object of the form field itself rather than its value.

A: You are not passing a string otherwise it would have a replace method. I hope you didnt type function trim(str) { return var.replace(blah); } instead of return str.replace.

A: You should probably do some validations before you actually execute your function :
function trim(str) {
    if(typeof str !== 'string') {
        throw new Error('only string parameter supported!');
    }

    return str.replace(/^\s+|\s+$/g,'');
}

A: Did you call your function properly? Ie. is the thing you pass as as a parameter really a string?
Otherwise, I don't see a problem with your code - the example below works as expected
function trim(str) {
    return str.replace(/^\s+|\s+$/g,'');
}

trim('    hello   ');  // --> 'hello'

However, if you call your functoin with something non-string, you will indeed get the error above:
trim({});  // --> TypeError: str.replace is not a function

A: In case of a number you can try to convert to string:
var stringValue = str.toString();
return stringValue.replace(/^\s+|\s+$/g,'');

A: My guess is that the code that's calling your trim function is not actually passing a string to it.
To fix this, you can make str a string, like this: str.toString().replace(...)
...as alper pointed out below.

A: You should use toString() Method of java script for the convert into string before because replace method is a string function.

A:
Replace wouldn't replace numbers. It replaces strings only.

This should work.
function trim(str) {
    return str.toString().replace(/^\s+|\s+$/g,'');
}

If you only want to trim the string. You can simply use "str.trim()"

A: probable issues:

*

*variable is NUMBER (instead of string);
num=35;    num.replace(3,'three');                =====> ERROR
num=35;    num.toString().replace(3,'three');     =====> CORRECT !!!!!!
num='35';  num.replace(3,'three');                =====> CORRECT !!!!!!

*variable is object (instead of string);

*variable is not defined;

A: I fixed the problem.... sorry I should have put the code on how I was calling it too.... realized I accidentally was passing the object of the form field itself rather than it's value.
Thanks for your responses anyway. :)

A: make sure you are passing string to "replace" method. Had same issue and solved it by passing string. You can also make it to string using toString() method.


text:
Q: Using external js and css in polymer element I have a Polymer element that uses an external js and css.  I invoke a js function on dom ready.  It works fine in Chrome.
In Firefox 47.0 and IE Edge, it doesnt work as expected.  In both these cases, the cvtable.css in the code below is not downloaded in Firefox and IE.
In Firefox, the js function window.cvtable.createTable() gets called; but in IE it doesnt even get called.
Thanks
<link rel="stylesheet" href="/cis/css/cvtable.css" type="text/css">
<script type="text/javascript" src="/cis/js/cvtable.js"></script>

<dom-module id="cis-home-index-perf-table">
  <template>
    <div id="indices_perf_div" class="debug" style="float:left;clear:none;overflow:auto;width:813px;height:250px;">
  </template>
  <script>
    Polymer({
      is: 'cis-home-index-perf-table',
      ready: function () {
        var fundDetailsJSON =
          '"some json":"some json value"';
        $(document).ready(function () {
          window.cvtable.createTable(fundDetailsJSON);
        });
      }
    });
  </script>
</dom-module>

A: After hours of debugging, this turned out to be an issue where i had not closed the div in the template.  I was using Brackets IDE, and it never indicated a missing closing tag.  Need some ways to handle these issues.


text:
Q: Why would react-chartjs-2 not be able to see the data it needs to render? Thanks for any tips and or help! I've hit a wall here trying to get a chart to render. I've reverted to testing a very simple approach (code below) and I am still getting the following error:
TypeError: Cannot read properties of undefined (reading 'map')
I can log the data being set from the useEffect call, but I cant understand why its not making it into the Line graph. From the debugger (on utils.ts) I can see that (currentData = {labels: undefined, datasets: Array(0)}) and nextDatasets = undefined.
I'm starting to wonder if there is some version mismatch somewhere, anyways thanks for any ideas!
import React, { useState, useEffect } from "react";
import {Line} from "react-chartjs-2";

function Graph() {
    const  myLabels =  ['monday', 'tuesday', 'wednesday', 'thursday', 'friday'];
    const [data, setData] = useState({});
    useEffect(() => {
        setData({
            labels: myLabels,
            datasets: [
                {
                    label: 'The Level',
                    data: [21, 53, 65, 12, 32]
                },
            ]
        });
    }, [])
    console.log(data.datasets);
    return(

            <Line data={data} />

    )}

export default Graph;

The following version are in use:
"react": "^17.0.2" with
"chart.js": "^3.6.2",
"react-chartjs-2": "^4.0.0"

A: After some reading... I re-visited my approach and came up with the following, I'm not sure this is the proper way to go about things, still learning so if anyone has any helpful comments they'd be welcomed!
I'm not sure I completely understand at this point, but I think that the main problem I had was related to the useEffect() being used to build the data for the graph, as opposed to maybe effect the graph once it's there.
import React  from "react";
import { useState } from "react";
import 'chart.js/auto';
import { Chart } from 'react-chartjs-2';

function Graph() {

    const [chartData, setChartData] = useData();

    return(

            <Chart type='line' data={chartData} />

    )
}

export default Graph;

const useData = ( data = {} ) =>  {
    const [state, setState] = useState(data);
    data = {
        labels: ['monday', 'tuesday', 'wednesday', 'thursday', 'friday'],
        datasets: [
            {
                label: 'The Level',
                data: [21, 53, 65, 12, 32]
            },
        ]
    }

return [data]
}

A: By default data is blank, that's why it gives an error so just you have to ensure that if data is available then you can draw the line chart.
Just change one line of code: {data.datasets ? <Line data={data} /> : ""}
import React, { useState, useEffect } from "react";
import { Line } from "react-chartjs-2";

function Graph() {
  const myLabels = ["monday", "tuesday", "wednesday", "thursday", "friday"];
  const [data, setData] = useState({});
  useEffect(() => {
    setData({
      labels: myLabels,
      datasets: [
        {
          label: "The Level",
          data: [21, 53, 65, 12, 32]
        }
      ]
    });
  }, []);
  console.log(data.datasets);
  return (

      {data.datasets ? <Line data={data} /> : ""}

  );
}

export default Graph;


text:
Q: Why is Redirect URL Fully Qualified in Azure AD B2C? Why does the redirect URL have to match completely?  Wouldn't matching at the domain level be sufficient enough for proper security?
What if I had hundreds of paths?
example urls:

*

*https://myawesomesite.com

*https://myawesomesite.com/account/profile

*https://myawesomesite.com/games/fungame/points

*https://www.myawesomesite.com/games/fungame/points
...
I would have to enter the 4 above redirect urls into my B2C app configuration.

A: This is actually discussed in RFC 6819 "OAuth 2.0 Threat Model and Security Considerations" sections 4.1.5, 4.2.4 and 5.2.3.5.

4.1.5. Threat: Open Redirectors on Client
An open redirector is an endpoint using a parameter to automatically
redirect a user agent to the location specified by the parameter value
without any validation. If the authorization server allows the client
to register only part of the redirect URI, an attacker can use an open
redirector operated by the client to construct a redirect URI that
will pass the authorization server validation but will send the
authorization "code" or access token to an endpoint under the control
of the attacker.
Impact: An attacker could gain access to authorization "codes" or access tokens.
Countermeasures:
o Require clients to register full redirect URI (Section 5.2.3.5)."

Section 5.2.3.5 talks about the cases where this may be too restrictive and purposes alternate solutions.
Often times, the state parameter can also be used to redirect deterministically as suggested by Chris. However, you have to ensure that such a solution also does not end up being an open redirector, so the state parameter will either need to be protected (e.g. encrypted/signed), or used in conjunction with cookies.

A: It is common (and easiest) for all authentication requests to contain two redirect URLs:

*

*One (often known as the reply URL) that is passed in the "redirect_uri" parameter, which must be registered with Azure AD B2C, to which all authentication responses are returned from Azure AD B2C to the relying party application. An example of this is https://www.myawesomesite.com/oidc-signin.

*Another (often known as the return URL) that is round-tripped in the "state" parameter, which doesn't have to be registered with Azure AD B2C, to which the end user is returned after the relying party application has handled the authentication response. An example of this is https://www.myawesomesite.com/games/fungame/points.

An authentication handler, such as the ASP.NET Core authentication middleware, manages these redirect URLs for you.
For instance, when the authentication handler creates the authentication request, it encodes the currently protected URL (e.g. https://www.myawesomesite.com/games/fungame/points) in the "state" request parameter.
To ensure this URL isn't tampered with, the "state" parameter should be protected, using encryption or signing.
When the authentication handler processes the authentication response, assuming it is a successful response, it creates an identity cookie and redirects the end user from https://www.myawesomesite.com/oidc-signin to the originally protected URL in the "state" response parameter.


text:
Q: ASP.NET AJAX Timer on iOS Safari I'm attempting to display a real-time Arrivals/Departures list on an iPad / iPod Touch / iPhone that automatically refreshes every few seconds. ASP.NET AJAX UpdatePanels work fine, but the AJAX Timer never fires in iOS Safari browsers.
Is there a way to get an ASP.NET AJAX Timer to work on iOS devices? Or is there some way I can put a bit of manual JS in there for these browsers that trigger the timer's Tick event?


text:
Q: Return absolute number, and percentage together I am trying to calculate the total number of [visits] from my hospital database, so that I can use the result to read from my Python script and send out weekly summary to our team every week. So, I am wondering if anyone can help me out for my query since I am still learning SQL.
Goal Table format:
 - Date (prefer dd/mm/yyyy)
 - Patient_Name (e.g John)
 - Patient_Id (e.g 12345)
 - Visits
 - Professionals (Categorical Variables: Nurse, Doctor, Assistant Nurse)

So, I want to get a query that can list out total visits by nurse in specific date range and percentage of total visits from all professionals for the specific patient in a week.  For example, Nurse visit patient (John) 15 times, and Assistant Nurse visits 10 times while Doctor pay visits 5 times/week, so my final table would be this:
      ____________________________________________
     |____Date_____|__Prof__|__Visits_|___Percen__|
     |06/01/2018   | Nurse  |   15    |   0.5     |
     |02/11/2017   | A-Nurse|   10    |   0.33    |
     |19/04/2016   | Nurse  |    5    |   0.16    |
     |

Below is my SQL Statement on my SSMS, and I used case statement for Professionals data since based on patient needs, sometimes therapists visits instead of nurse/doctor so I would like that part to be dynamic:
SELECT  CONVERT(VARCHAR(10), [myDate], 101), SUM([visits]) AS [Date] , [Professionals], ((SELECT [Visits] from MyHospitalTable)* 100 / (Select SUM([Visits]) From MyHospitalTable)) as Percen
FROM
(SELECT
   Count(*) as [total],
   [Date] as [myDate],
   [Patient_id] as [myPatient_Id],
   [Patient_Name] as [myPatient_Name],
   [visits] as [visits],
   CASE
          WHEN [Professionals] LIKE '%Nurse%' THEN 'Nurse'
          WHEN [Professionals] LIKE '%Therapist%' THEN 'Therapy'
          else 'Unknown'
          END AS [Professionals]
   FROM [MyHospitalTable]
 ) a
GROUP BY [myDate]

I understand that my query is not correct, and need improvement, and if anyone can please help me out getting the data, that would be awesome.
Thanks in advance.

A: You can  calculate the grand total using window function and find the percentage.
Below give you an idea how to do that. it is not exactly compatible with your table though.
;with ct as (
    select MyDate, sum(Visits) Visits
      , count(Visits) over (partition by MyDate order by MyDate) TotalVisits
    from HospitalTable
    group by MyDate
)
select MyDate, Visits, (Visits * 100 / TotalVisits)
from ct


text:
Q: Why, on a linux router, clients can still connect even after the network adapter is down or the iptables routing is disabled? I have a Linux machine which I use as a wireless VPN router. It has a very classic router setup, whose highlights are:

*

*openvpn to connect to the VPN, which is connected to eth0, and makes the tun0 adapter available for tunneled traffic.

*-t nat -A POSTROUTING -o tun0 -j MASQUERADE rule for forwarding the traffic to wlan0.

I wanted to entirely block the traffic under certain conditions, but I don't understand why the packets keep flowing even if I remove the above conditions.
For example, if on a client I have a Firefox session open, and I remove the iptables routing rule (iptables -t nat -F), something strange happens - some websites still keep working, but the vast majority won't connect.
If I use a bittorrent client, again, something strange happens - when I close the vpn connection (so that tun0 is dropped), the BT client stops downloading, but plugging iftop on the router, after tun0 is dropped I observer a number of connections showing up from the client machine to a number of internet addresses.
Why this happens?
I have a solution, which is to terminate hostapd, but I don't understand why the traffic is so "resilient".


text:
Q: moment date difference is not working I am trying to do date difference using moment but it is showing incorrect days figure

var before = moment('25-Sep-2017 13:44','DD-MMM-YYYY HH:mm');
var now = moment('25-Sep-2017 13:46','DD-MMM-YYYY HH:mm');

console.log(
  moment(now - before)
  .format('D[ day(s)] H[ hour(s)] m[ minute(s)] s[ second(s) ago.]')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>

A: Use moment diff to calculate the difference between two moment objects, instead of -, so you will have now.diff(before) instead of moment(now - before).
Then you can use moment.duration(Number); to create a duration:

Moment.js also has duration objects. Where a moment is defined as single points in time, durations are defined as a length of time.

You can use moment-duration-format plug-in to get the duration value in the form of: 'D[ day(s)] H[ hour(s)] m[ minute(s)] s[ second(s) ago.]'. See format method docs for more info.
Note that using moment-duration-format:

Leading tokens are automatically trimmed when they have no value.

you can use { trim: false } option to stop that behavior.
Here a live sample:

var before = moment('25-Sep-2017 13:44','DD-MMM-YYYY HH:mm');
var now = moment('25-Sep-2017 13:46','DD-MMM-YYYY HH:mm');

console.log(
  moment.duration( now.diff(before) )
  .format('D[ day(s)] H[ hour(s)] m[ minute(s)] s[ second(s) ago.]')
);

// With trim: false
console.log(
  moment.duration( now.diff(before) )
  .format('D[ day(s)] H[ hour(s)] m[ minute(s)] s[ second(s) ago.]', { trim: false })
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>


text:
Q: Control Menu Items based on Privileges of Logged In User with spring security Based on this link I have incorporated the spring security core module with my grails project... I am using the Requestmap concept by storing each role, user and requestmap inside the database only...
Now my requirement is to provide the menu items based on the users assigned roles... For e.g.:
If my "User" Main Menu have following Items :
Dashboard
Import User
Manage User
And if I have assigned a roles of Dashboard and Import User to the user with a username "auditor" then, only following Menu items should be displayed on the screen :
User (Main Menu)
-> Dashboard (sub menu)
-> Import User (sub menu)
I have explored the Spring Security ACL plugin for the same, but it's using the Domain classes to get it working...
So, wanted to know the convenient way to do so...
Thanks in advance...

A: The ACL plugin seems like overkill. I'd use the taglib that comes with the plugin; see section "6.1 SecurityTagLib" in the docs.
Wrap the code in the GSP that renders the submenus with <sec:ifAllGranted roles="...">menu code here</sec:ifAllGranted>


text:
Q: tf.Session() seemingly not closed even after exiting the with block I am saving two graphs; one with a 2X2 zero tensor and the other with a ones tensor of the same size. I restore one of them depending on a condition.
import tensorflow as tf

def save_zero():
    # save a 2x2 variable filled with zeros
    with tf.Graph().as_default():
        session = tf.Session()
        with tf.name_scope('dummy_graph'):
            tf.Variable([[0.0, 0.0], [0.0, 0.0]], name='a', dtype=tf.float32)
        init_op = tf.global_variables_initializer()
        session.run(init_op)
        saver = tf.train.Saver()
        saver.save(session, 'zero')
        session.close()

def save_one():
    # save a 2x2 variable filled with ones
    with tf.Graph().as_default():
        session = tf.Session()
        with tf.name_scope('dummy_graph'):
            tf.Variable([[1.0, 1.0], [1.0, 1.0]], name='a', dtype=tf.float32)
        init_op = tf.global_variables_initializer()
        session.run(init_op)
        saver = tf.train.Saver()
        saver.save(session, 'one')
        session.close()

def test(boolean):
    with tf.Session() as session:
        if boolean:
            saver = tf.train.import_meta_graph('one.meta')
            saver.restore(session, './one')

            session.run(session.graph.get_operation_by_name('init'))
            tensor = session.graph.get_tensor_by_name('dummy_graph/a:0')
        else:

            saver = tf.train.import_meta_graph('zero.meta')
            saver.restore(session, './zero')

            session.run(session.graph.get_operation_by_name('init'))
            tensor = session.graph.get_tensor_by_name('dummy_graph/a:0')

        return session.run(tensor)

save_zero()
save_one()
print(test(False))
print(test(True))

Both the calls to test return zeros. Observing the ops in the session suggests that the session in test is being reused across the two calls which AFAIK is not supposed to happen as the session is closed when test returns:
def test(boolean):
    with tf.Session() as session:
        if boolean:
            saver = tf.train.import_meta_graph('one.meta')
            saver.restore(session, './one')
            # contains duplicate ops (suffixed with '_1')
            [print(op.name) for op in session.graph.get_operations()]
            session.run(session.graph.get_operation_by_name('init'))
            tensor = session.graph.get_tensor_by_name('dummy_graph/a:0')
        else:

            saver = tf.train.import_meta_graph('zero.meta')
            saver.restore(session, './zero')

            session.run(session.graph.get_operation_by_name('init'))
            tensor = session.graph.get_tensor_by_name('dummy_graph/a:0')

        return session.run(tensor)

Is this a bug or am I missing something?

A: TL;DR: The tf.Session is closed between the two calls to test() in your code, but you are running into a problem because the two sessions are sharing the same tf.Graph. Create each session with a fresh tf.Graph to avoid the problem.
In particular, the nodes created when you call tf.train.import_meta_graph() in the call to test(False) remain in the graph when subsequently call tf.train.import_meta_graph() in the call to test(True). This means that each of the two calls to session.graph.get_tensor_by_name('dummy_graph/a:0') will return the same node (which was created when you first called test()).
There are a few ways to avoid this problem. The simplest is to create the tf.Session with its own graph:
def test(boolean):
    # Session will use its own graph.
    with tf.Session(graph=tf.Graph()) as session:
        if boolean:
            # ...

A: To add more details to mrry answer, here's exactly what's happening:
During checkpoint saving, you are creating new graph each time, so you are saving in both checkpoints a tensor dummy_graph/a:
zero.data-00000-of-00001: dummy_graph/a - [0, 0,
one.data-00000-of-00001: dummy_graph/a - [1, 1,

During first load call you first create a graph with variable dummy_graph/a, load [0, 0, into it, then call init op which will overwrite this value with [0, 0,
During second load call, your import_meta_graph will append to existing default graph. Since there's a name conflict, it will append _1 to nodes, so now your graph will have nodes dummy_graph/a and dummy_graph/a_1 and corresponding init nodes init and init_1
During second restore, your saver will restore your [1, 1, ... checkpoint into dummy_graph/a. Then you call init which will overwrite the value of dummy_graph/a with [0, 0, .... You then return the value of dummy_graph/a
Note that after second restore, your session has two variables, and the second one is not initialized. Curiously,  tf.report_uninitialized_variables() does not show it, even though sess.run('dummy_graph/a_1:0') will throw Attempting to use uninitialized value error, that seems like a bug.