text:
Q: Regular Expression(pattern) Attribute Separation I am using the logstash filter grok and I need a pattern(regEx) for this expression:

van=FpP2N410E%252FbhMY%252FBvfstlbL6YmtlPKiQ%253D&colour=7&hv=2701

I tried it with this solution, but the "colour" wasn't seperated from the "van".

((colour=%{NUMBER:Colour})|(van=%{GREEDYDATA:VAN}))&((colour=%{NUMBER:Colour})|(
  hV=%{NUMBER:hV}))

I need the OR because of different orders of the attributes.

A: Solution is to define a new pattern VAN [A-Za-z0-9%]+

((colour=%{NUMBER:Colour})|(van=%{VAN:VAN}))&((colour=%{NUMBER:Colour})|(
  hV=%{NUMBER:hV}))

A: Don't reinvent the wheel - the kv{} filter was designed for such things, and it would allow the parameters to be in any order.


text:
Q: Logical expression configuration tool UI Recently i have a requirment from bussines for build a tool that configure our application data input like these:
if ( "field x1" equal "value 1" and "field x2" equal "value 2" ) or ("field x3" equal "value 3" ) ...
then
set value of "field y" to "value y"
now i have build the engine ( BRMS like engine ) and the UI that looks like :
http://www.telerik.com/help/aspnet-ajax/filter-basics.html
or
http://devexpress.com/Products/NET/Controls/ASP/Grid/filter_editor.xml
but our business says that is difficult to use.
Have any idea for Logical Expression presentation and input UI different from these?
I really appreciate your help.
Thanks anyway.

redpajama_set_name: RedPajamaStackExchange


text:
Q: jQuery search div by id with accent character I have a problem with my dynamic search. I want to find div with id containing specific text and it works well until I try to find something with accent characters for ex. Ł.
I am using this selector:
$('.user-row[id*='+searchText+']')

I've tried inputs and
val().indexOf(searchText) > 0

but it didn't work either.

A: The only problem I can think of is that you aren't using HTML 5.

The HTML 4.01 spec states that ID tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens (-), underscores (_), colons (:), and periods (.).
HTML5 gets rid of the additional restrictions on the id attribute.

https://mathiasbynens.be/notes/html5-id-class
So in HTML 5 special accented characters such as the described Ł are definitely allowed within an id.
JSFiddle to demonstrate: http://jsfiddle.net/7cq25865/
$('.user-row[id*='+searchText+']')

does work.

A: Ok, so I made stupid mistake. I was assigning divs ids with php strtolower. Then I was lowering search text, but strtolower didn't work with accent characters so my div was named with Ł not ł. That's why it wasn't found by selector. mb_strtolower did work. Case closed :D

A: Also found a interesting fact with Jquery here, not related to this question though.
Jquery ID selector normally will only select the first element that matches, however for any id names includes accented letters, ID selector will pick up all of them.
Example here :

$('#lesschars').css({backgroundColor: 'blue'});

$('#someŁchars').css({backgroundColor: 'red'});

ID with no accent, will select first element

ID with no accent, will select first element

ID with accent, selects both

ID with accent, selects both

Yeah, I know, there shouldn't be same ID in one page, but good to know this difference


text: Q: High Frequency radio wave propagation time What is the maximum time for an HF radio wave to reach its destination regardless of propagation mode? Since electromagnetic waves' speed is close to the light speed in the air, can we say it is always lower than e.g. 1 second? Or, atmospheric conditions, reflection etc. may cause it to be as long as 10 seconds or more?


text:
Q: get directory from full path If i have:
C:\temp\foo\bar\
(NOTE: bar is a directory)
how can i parse out:
bar

A: It looks like a bunch of people have withdrawn their answers, which is possibly a shame.
This one's got to be worth stating, only for the "teach a man to fish" quality of it - it's short, elegant and made of two separate things that, once learned, can be re-applied to other problems.
string lastPiece = wholePath.Split('\\').Last();

Last will throw if the list is empty.

A: The simplest way to do this without creating a new DirectoryInfo instance is to use the Path.GetFileName static method.  This is located in System.IO.
using System.IO;

string lastFolderName = Path.GetFileName(@"C:\Folder1\Folder2");

The variable would be set to "Folder2".
This is quite a bit more efficient that creating a new instance of the DirectoryInfo class!

A: I figured it out.
DirectoryInfo info = new DirectoryInfo(sourceDirectory_);
string currentDirectoryName = info.Name;

A: I can think of 4 ways instantly
1

*

*If the string ends with a slash remove it

*Use Path.GetFilename (or numerous other System.IO methods)

2

*

*Split the string on slashes into an array

*Get the last index of the array

3

*

*Create a Uri class with it in the constructor

*Use the Segments property

4

*

*The linq way someone mentioned above

A: Try
System.IO.Path.GetFileName("C:\\temp\\foo\\bar");

A: Just use:
string dirname = new DirectoryInfo(@"C:\temp\foo\bar\").Name;

According to MSDN this returns the name of the directory, not the full path.
Link to MSDN Library
Hope this helps.........

A: string dirname = new DirectoryInfo(path).Name;
Console.WriteLine(dirname);

A: In Unix this is known as the basename, a quick google came up with this link for a C# version. I'm sure there are others ...

A: if the answers above do not satisfy your needs, why not just substring the string from the last .
string dirName = originalDirName.Substring(originalDirName.LastIndexOf("\\") + 1);

sure, you should do some checking if the originalDirName does not end on a \ and if the originalDirName is longer than zero and actually contains \ characters.

A: Try this
string DirName = System.IO.Directory.GetParent(@"C:\temp\foo\bar\").Name;


text:
Q: How do I create a zipfile from a non-physical file? I have a project called "MyApp".  MyApp will use a java library I am creating called "MyLibrary".  I am writing a function in "MyLibrary" to unzip a zip file in "MyApp"(or whatever app is using "MyLibrary") "resources" dir.
Reading https://community.oracle.com/blogs/kohsuke/2007/04/25/how-convert-javaneturl-javaiofile I cannot create a File via a path because it is not a "physical file".  I was using zip4j, but its constructor takes a File or String rather than an InputStream.  So I cannot do this:
ZipFile zipfile = new
        ZipFile("src/main/resources/compressed.zip");
downloadedZipfile.extractAll("src/main/resources");

java.io.File javadoc and http://www.mkyong.com/java/how-to-convert-inputstream-to-file-in-java/ indicate there isn't a way to convert an InputStream to a File.
Is there another way to access the zip file in the project that is using my library?  Thank you in advance.
UPDATE:
The zipIn lacks entries, so the while loop won't extract the file out.
InputStream in = getInputStream("", JSON_FILENAME);
    ZipInputStream zipIn = new ZipInputStream(in);

    ZipEntry entry;
    try {
        while ((entry = zipIn.getNextEntry()) != null) {
            String filepath = entry.getName();
            if(!entry.isDirectory()) {
                extractFile(zipIn, filepath);
            }
            else {
                File dir = new File(filepath);
                dir.mkdir();
            }
            zipIn.closeEntry();
        }
        zipIn.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

private void extractFile(ZipInputStream zipIn, String filepath) {
    BufferedOutputStream bos = null;
    try {
        bos = new BufferedOutputStream(new FileOutputStream(filepath));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    byte[] bytesIn = new byte[BUFFER_SIZE];
    int read = 0;
    try {
        while ((read = zipIn.read(bytesIn)) != -1) {
            bos.write(bytesIn, 0, read);
        }
        bos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Will the file be extracted into the home directory of "MyApp" when using this code that belongs to "MyLibrary"?

A: If you have a InputStream to your virtual ZIP file you can use java.util.zip.ZipInputStream to read the ZIP entries:
InputStream in = ...
ZipInputStream zipIn = new ZipInputStream(in);

ZipEntry entry;
while ((entry = zipIn.getNextEntry()) != null) {
     // handle the entry
}


text:
Q: Android JavaCV facerecogniser - Fatal signal 11 when training faceRecogniser? So my project is to make a face recognition(not detection) app for Android. My plan is to use JavaCV with the contrib library facerecogniser. However when training the recogniser the app crashes with this error:
Fatal signal 11 (SIGSEGV) 0xdeadbaad (code=1). the error logs can be found here:
Error Logs
The code I'm using to do this is as follows:
 MatVector images;
 CvArr labelsCV;

 final int numberOfImages = 20;
 File faceDir = new File("/sdcard/FaceDB");

 images = new MatVector(numberOfImages);

 ArrayList<Integer> labels = new ArrayList<Integer>();
 IntPointer iPoint = new IntPointer();

 CvArr image;
 // Load an image:
 image = cvLoadImage(faceDir + "/s1/1.pgm");
 // And put it into the MatVector:
 images.put(0, image);
 // and put the label in
 labels.add(0);

  for (Integer i: labels){
         iPoint.put(i);
  }

  labelsCV = new CvArr(iPoint);

  FaceRecognizerPtr model = createFisherFaceRecognizer(0,1000);
  // Then train it. See how I call get(), to get the FaceRecognizer inside the FaceRecognizerPtr:
  model.get().train(images, labelsCV);

I'm not sure but it could be something to do with my labelsCV variable and pointer, I'm not really sure how to do this.
Any help would be much apreciated thanks


text:
Q: change label text from another controller in titanium alloy I want to change text of label and make its visiblity true from another controller.
win_drawer_governmentNotification.xml
<Label id="filterCount" text="2"></Label>

win_drawer_governmentNotification.tss
"#filterCount":{
borderRadius: 100,
borderWidth: 1,
borderColor: "#f26418",
left: 46,
color: "#fff",
backgroundColor: "#f26418",
top: 15,
width: "8%",
textAlign: Titanium.UI.TEXT_ALIGNMENT_CENTER,
verticalAlign: Titanium.UI.TEXT_VERTICAL_ALIGNMENT_CENTER,
visible : false,
font: {
    fontSize: Alloy.CFG.fonts.f_10,
    fontFamily: Alloy.CFG.font_family.calibri
}

},
Now I want to change text of label filterCount from another controller in a function
I tried below code.
win_drawer_governmentNotification_filter.js
function applyFilter(e) {
var controller = Alloy.createController('win_drawer_governmentNotification');
Ti.API.info('controller = ' + controller);
var filterLabel = controller.filterCount;
Ti.API.info('filter label = ' + filterLabel);
Ti.App.fireEvent("win_drawer_governmentNotification:filterCount", {
    text : "1",
    visible : true
});

win_drawer_governmentNotification_filter.xml
<View id="view_apply_main" onClick="applyFilter">
  <View id="view_apply">
    <Label id="lbl_apply" text="APPLY FILTERS"/>
  </View>
</View>

I tried different solutions from stackoverflow still haven't found solution like in
win_drawer_governmentNotification_filter.js
controller.filterCount.text = "1";
controller.filterCount.visible = true;

Can someone please help me what I am doing wrong? I am new to titanium.
Thanks in advance.


text:
Q: SQL returning empty dataframe I've built a query that retrieves multiple rows from the database and it works great running directly from SQL Server Management Studio. When I tried the same query in python's pyodbc I keep getting empty DF. Cursor is working perfectly, all parameters are strings. What am I missing?
Error
def get_general_tables(conn, cursor, boletim, area, year, city):
    print(boletim, area, year, city)

    get_t1_query = f'''
                SELECT t2.Acao as Acao,\
                    SUM(t1.ValorD) as Dot,\
                    SUM(t1.ValorE) as Emp,\
                    SUM(t1.ValorL) as Liq,\
                    SUM(t1.ValorP) as Pag\
                FROM View_General as t1\
                    INNER JOIN Boletins as t2\
                    ON (t1.DescProg = t2.Prog\
                    AND t1.Desc = t2.Acao)\
                WHERE (t1.NameCity = ? AND t1.Year = ? AND t2.Area = ? AND t2.Boletim = ?)\
                GROUP BY t2.Acao
                '''
    params = [city, ano, area, boletim]
    cursor.execute(get_t1_query, params)#.fetchall()
    df = pd.DataFrame(cursor.fetchall())
    print(df)

If I use a single parameter I get the expected result. Error persists with pd.read_sql approach:
df = pd.DataFrame(pd.read_sql(get_t1_query, con = conn, params=params))


text:
Q: TypeError: Cannot read property 'room' of undefined I use socketIO to create chat with room and namespace.
It works very well but sometimes I'm facing an error in log and I don't know why... maybe when too much inputs/outputs ?
TypeError: Cannot read property 'room' of undefined at Socket.socket.on (/appli/chatvideodiff/server/server.js:107:48)

see below piece of my code :
var fs = require('fs');
const cmd = require('child_process');
const express = require('express');
const path = require('path');
const http = require('http');
const https = require('https');
const socketIO = require('socket.io');
const url = require('url');

var {Message} = require('./utils/message');
const {isRealString} = require('./utils/validation');
const {Users} = require('./utils/users');

const dotenv = require('dotenv');
dotenv.config();

var options = {

    key: fs.readFileSync(process.env.KEY),
    cert: fs.readFileSync(process.env.CERT),
    ca: fs.readFileSync(process.env.CA),
    index: false,
    setHeaders: function (res, path, stat) {
        res.set('x-timestamp', Date.now());
    },
};

const port = process.env.PORT || 3000;
const publicPath = path.join(__dirname, '../public');
var app = express();

var server = http.createServer(options, app);

var io = socketIO(server);

var users = new Users();
var messages = new Message;

var viewersCount = [];

app.use(express.static('../public', options));

app.get('/chat/:room', function (req, res) {
  var room = req.params.room;
  var fqdn = req.headers.host;
  var proto =  process.env.PROTO;
  var lien = proto + '://' + fqdn+'/index.html?room=' + room;
  res.redirect(lien);

});

const io_chat = io.of("/chat").on('connection', (socket) => {
  console.log("New user connected on chat from "+socket.handshake.headers['x-forwarded-for']);

  socket.on('join', (params, callback) => {
    if (!isRealString(params.name) || !isRealString(params.room)) {
      var destination = '/urlincorrecte';
      socket.emit('redirect', destination);
      return false;
    }

    socket.join(params.room);
    users.removeUser(socket.id);

    users.addUser(socket.id, params.name, params.room, socket.handshake.headers['x-forwarded-for'] || socket.handshake.address.address);
    io_chat.to(params.room).emit('updateUserList', users.getUserList(params.room));

    var user = users.getUser(socket.id);
    var msgJoin = messages.getMessageList(user.room);   <== issue on this line

    if (user !== undefined) {
      socket.emit('history', msgJoin);
    } else {
    }
  callback();
  });
...

error line is this one (near the end) : var msgJoin = messages.getMessageList(user.room);
if you have an idea, thanks
Nico


text:
Q: An accumulated computing error in SSE version of algorithm of the sum of squared differences I was trying to optimize following code (sum of squared differences for two arrays):
inline float Square(float value)
{
    return value*value;
}

float SquaredDifferenceSum(const float * a, const float * b, size_t size)
{
    float sum = 0;
    for(size_t i = 0; i < size; ++i)
        sum += Square(a[i] - b[i]);
    return sum;
}

So I performed optimization with using of SSE instructions of CPU:
inline void SquaredDifferenceSum(const float * a, const float * b, size_t i, __m128 & sum)
{
    __m128 _a = _mm_loadu_ps(a + i);
    __m128 _b = _mm_loadu_ps(b + i);
    __m128 _d = _mm_sub_ps(_a, _b);
    sum = _mm_add_ps(sum, _mm_mul_ps(_d, _d));
}

inline float ExtractSum(__m128 a)
{
    float _a[4];
    _mm_storeu_ps(_a, a);
    return _a[0] + _a[1] + _a[2] + _a[3];
}

float SquaredDifferenceSum(const float * a, const float * b, size_t size)
{
    size_t i = 0, alignedSize = size/4*4;
    __m128 sums = _mm_setzero_ps();
    for(; i < alignedSize; i += 4)
        SquaredDifferenceSum(a, b, i, sums);
    float sum = ExtractSum(sums);
    for(; i < size; ++i)
        sum += Square(a[i] - b[i]);
    return sum;
}

This code works fine if the size of the arrays is not too large.
But if the size is big enough then there is a large computing error between results given by base function and its optimized version.
And so I have a question: Where is here a bug in SSE optimized code, which leads to the computing error.

A: The error follows from finite precision floating point numbers.
Each addition of two floating point numbers is has an computing error proportional to difference between them.
In your scalar version of algorithm the resulting sum is much greater then each term (if size of arrays is big enough of course).
So it leads to accumulation of big computing error.
In the SSE version of algorithm actually there is four sums for results accumulation. And difference between these sums and each term is lesser in four times relative to scalar code.
So this leads to the lesser computing error.
There are two ways to solve this error:
1) Using of floating point numbers of double precision for accumulating sum.
2) Using of the the Kahan summation algorithm (also known as compensated summation) which significantly reduces the numerical error in the total obtained by adding a sequence of finite precision floating point numbers, compared to the obvious approach.
https://en.wikipedia.org/wiki/Kahan_summation_algorithm
With using of Kahan summation algorithm your scalar code will look like:
inline void KahanSum(float value, float & sum, float & correction)
{
    float term = value - correction;
    float temp = sum + term;
    correction = (temp - sum) - term;
    sum = temp;
}

float SquaredDifferenceKahanSum(const float * a, const float * b, size_t size)
{
    float sum = 0, correction = 0;
    for(size_t i = 0; i < size; ++i)
        KahanSum(Square(a[i] - b[i]), sum, correction);
    return sum;
}

And SSE optimized code will look as follow:
inline void SquaredDifferenceKahanSum(const float * a, const float * b, size_t i,
                                      __m128 & sum, __m128 & correction)
{
    __m128 _a = _mm_loadu_ps(a + i);
    __m128 _b = _mm_loadu_ps(b + i);
    __m128 _d = _mm_sub_ps(_a, _b);
    __m128 term = _mm_sub_ps(_mm_mul_ps(_d, _d), correction);
    __m128 temp = _mm_add_ps(sum, term);
    correction = _mm_sub_ps(_mm_sub_ps(temp, sum), term);
    sum = temp;
}

float SquaredDifferenceKahanSum(const float * a, const float * b, size_t size)
{
    size_t i = 0, alignedSize = size/4*4;
    __m128 sums = _mm_setzero_ps(), corrections = _mm_setzero_ps();
    for(; i < alignedSize; i += 4)
        SquaredDifferenceKahanSum(a, b, i, sums, corrections);
    float sum = ExtractSum(sums), correction = 0;
    for(; i < size; ++i)
        KahanSum(Square(a[i] - b[i]), sum, correction);
    return sum;
}


text:
Q: Python Multiprocessing function not working I am currently learning how to use multiprocessing from Corey Schafer's YouTube video: https://www.youtube.com/watch?v=fKl2JW_qrso&ab_channel=CoreySchafer
I am at the 10-minute mark on the video and I had copied my codes exactly like what was shown in the video but the results I have gotten are frustratingly different.
import time
import multiprocessing

def do_something():
    print('Sleeping 1 second....')
    time.sleep(1)
    print('Done Sleeping...')

start = time.perf_counter()

p1 = multiprocessing.Process(target=do_something)
p2 = multiprocessing.Process(target=do_something)

p1.start()
p2.start()

p1.join()
p2.join()

finish = time.perf_counter()

print(f'Finished in {round(finish-start, 2)} second(s)')

The result should've been:
Sleeping 1 second...
Sleeping 1 second...
Done Sleeping...
Done Sleeping...
Finished in 1.01 second(s)

But what I've gotten instead is:
Finished in 0.48 second(s)

It did not even print the 'Sleeping 1 second...' and 'Done Sleeping...' thing. So I'm guessing the function in the multiprocessing thing didn't even run?? Does anyone know the reason why my python code is behaving this way? Any help is much appreciated. Thanks

A: that's because it crashed ... because on windows you should put all "command" code inside an if __name__ == "__main__": block as follows, function definitions and imports should be before this line.
import time
import multiprocessing

def do_something():
    print('Sleeping 1 second....')
    time.sleep(1)
    print('Done Sleeping...')

if __name__ == "__main__":
    start = time.perf_counter()

    p1 = multiprocessing.Process(target=do_something)
    p2 = multiprocessing.Process(target=do_something)

    p1.start()
    p2.start()

    p1.join()
    p2.join()

    finish = time.perf_counter()

    print(f'Finished in {round(finish-start, 2)} second(s)')

Edit: when working in IDLE it is printing the output correctly ... just not to the correct screen, you should use VSCode or Pycharm instead ... or maybe run the code from terminal or any other IDE.


text:
Q: Create script taking output from another Basically I want to have a (generated) playlist in every folder containing music, sorted in order and has the same name as the folder.
I have a script that takes the information from music files and creates a playlist in a specific format.
1) I can run the script on single folder by
$ ./playlist.sh ~/Path/To/Music > output.xwaxpls

2) Put the playlist in a way that increases numerically (all my music is formatted %track% - %artist% - %title%)
$ sort -o output.xwaxpls output.xwaxpls

3) Change the name of output.xwaxpls to parent directory name
Unable to get this far yet.
Obviously I would love a script that would do all this.
I'm trying to learn and do each step one at a time but sadly I'm falling at the first hurdle. I can't even work out how to run the playlist.sh on all subdirectories. It's putting me off as I'm stuck before I can try the other two.
I would love some help....
Edit:
Another few hours and I'm getting somewhere !!
`#!/bin/sh

curdir=$(pwd)
for folder in ~/Music/*; do
  [ -d "$folder" ] && cd "$folder" && ~/Desktop/./playlist.sh "$folder" > "$folder".xwaxpls && sort -o "$folder".xwaxpls "$folder".xwaxpls
done

`
This creates the playlists that I want, in the format that I want.......but the playlists are saved in ~/Music, not in the folder that contain the files.
I have tried to change the ~/Desktop/./playlist.sh "$folder" > "$folder".xwaxpls part to ~/Desktop/./playlist.sh "$folder" > "$folder"/"$folder".xwaxpls but an error is kicked out saying cannot create /home/user/Music/Singles//home/user/Music/Singles.xwaxpls: Directory nonexistent.
I have also tried to add && mv $playlist.xwaxpls $playlist/$playlist.xwaxpls which results in the same // error.
The // I understand, as I am forcing a double path but why is the xwaxpls file not written to the $folder in the first place ? I presume it's because I have specified the ~/Music/* in the for line ?

A: You might want something like
#!/bin/bash

for folder in ~/Music/*; do
  [ -d "$folder" ] || continue
  cd "$folder" || continue
  ~/Desktop/playlist.sh "$folder" | sort -n > "$folder"/"${folder##*/}".xwaxpls
done

Remember that you do not try sort -o file file, most unix commands don't like to write to an output file that is input at the same time.


text:
Q: Application Error on heroku app after deployment I have my rails application deployed on heroku. When I tried to push new changes on heroku they asked me to upgrade cedar -14.
Then, I ran this command
 heroku stack:set cedar-14 -a <app name>

after running this command  I deployed my app to heroku.After successful deployment when I try to run app through url. It shows Application Error and log says something like this...
: at=error code=H10 desc="App crashed" method=GET path="/"


text:
Q: .Net mail attachment attaching to wrong email I have a problem I've not run into before, and can't seem to find any similar issues when I search.
My issue is this.
I have an email method which attaches a PDF using a memory stream, then sends the email using the SendAsync method. Very rarely though, the attachment is attached to a different users email.
This has only happened on extremely rare occasions, and seems to be caused when two emails are sent at exactly the same moment, and even then it's rare that it happens.
The problem is that, no matter how rare, it should not be happening so I'd like to fix it.
The PDF is generated by downloading the results of a URL which returns a PDF, into a WebClient object, then using reading the results of the WebClient.DownloadData method into a memory stream.
The memory stream is then attached to an MailMessage object and sent using an SMTPClient object's SendAsync method.
As I said, the problem occurs very infrequently, unfortunately making it very difficult to test.
Here is an example of my code (no actual values, just an example of how it is created, in a cut down way, ie no error trapping etc):
var mailMessage = new MailMessage("fromaddress@test.com", "toaddress@test.com", "Subject");
var smtpClient = new SmtpClient();

mailMessage.Body = "Test";
var stream = new MemoryStream(new WebClient().DownloadData("test.com"));
var attachment = new Attachment(stream, "filename.pdf", System.Net.Mime.MediaTypeNames.Application.Pdf);

mailMessage.Attachments.Add(attachment);

smtpClient.SendCompleted += new SendCompletedEventHandler(SendCompleteCallback); // this is a method for logging errors etc
smtpClient.SendAsync(mailMessage, "randomGuidToken");

When the problem does happen, only the user who receives both attachments actually gets an email. The other user gets nothing, no email or attachment.
All help is appreciated.

A: I've managed to solve my issue.
It was down to how the SmtpClient and MailMessage classes were being instantiated and disposed of (or not, in this case).
I found out that the original code was creating the SmtpClient and MailMessage objects as a class wide variable, which was initialised in the class constructor, and the only code which handled the disposing of the objects was in the SendAsynCompleted callback method.
I have now changed the code so that the SmtpClient and MailMessage objects are instantiated within each method which needs them within the class, and made sure the objects are disposed of explicitly.
I've also moved away from using the SendAsync method for now and just use the standard Send method (I may look at moving back to the async method but will need to do a lot more testing and refactoring I think).


text:
Q: Unable to access user token in Directus I am trying to get directus user token. For this purpose I am using Postman. But when I send a POST request to the api with user login credentials. I get this error:
We're sorry but Directus doesn't work without JavaScript enabled. Please enable it to continue.
I want to access the (user token). Is there any alternative way to get user token in Directus CMS. Any help will be appreciated.
Thank you.

A:
We're sorry but Directus doesn't work without JavaScript enabled. Please enable it to continue.

If you're seeing the above error, I would imagine you're sending a post request to the Javascript frontend and not the API.
I would expect you to send a request to something like:
https://demo-api.directus.app/_/auth/authenticate
With post JSON body like:
{ "email" : "admin@example.com", "password" : "password" }
Docs: https://docs.directus.io/api/reference.html#get-auth-token

A: You could try the static token. It is generated for each user on directus_users.token. It's a little less-secure (depending on how you're using it) since it doesn't change, but should be much easier:
https://docs.directus.io/api/reference.html#static-tokens


text: Q: jquery space invaders project, what should i do to kill the aliens? i'm writing a space-invaders-game code, and i don't know how to kill the aliens with the bullets. i tried removing the element when both the ship and the bullet reach the same position from the top and the left, but it didn't work with me, and i don't know if the implementation of it was wrong or the idea itself.(long and ugly code, i know, but please tell me if you have any suggestions that might improve it, i'm still a beginner :D)


text:
Q: Unable to remove everything else in a folder except FileA How can I remove everything else in a folder except FileA, even hidden files?
I use Ubuntu.
I tried the following unsuccessfully
rm [^fileA]

A: find . -not -name fileA -exec rm {} \;

Note that this will only delete files, not folders. Believe me, you don't want to delete folders like that.

A: Use extglob.  Assuming that FileA is a regular file (i.e. does not begin with a .), then you can do:
shopt -s extglob  # Enable extglob
rm !(FileA) .*  # Remove all regular files not named FileA and all hidden files

If instead FileA is a hidden file, this won't work, since the !(pattern) construct only creates a list of all regular files not matching pattern.

A: You also could do it interactively,
rm -i * .*

The * is for all files (except hidden files).
The .* is for all hidden files
gene@vmware:/tmp/test$ ls -al
total 8
drwxr-xr-x  2 gene    gene    4096 2009-03-11 12:51 .
drwxrwxrwt 12 root    root    4096 2009-03-11 12:51 ..
-rw-r--r--  1 gene    gene       0 2009-03-11 12:51 fileA
-rw-r--r--  1 gene    gene       0 2009-03-11 12:51 .fileB
gene@vmware:/tmp/test$ rm -i * .*
rm: remove regular empty file `fileA'? n
rm: cannot remove directory `.'
rm: cannot remove directory `..'
rm: remove regular empty file `.fileB'? y
gene@vmware:/tmp/test$ ls -al
total 8
drwxr-xr-x  2 gene    gene    4096 2009-03-11 12:51 .
drwxrwxrwt 12 root    root    4096 2009-03-11 12:51 ..
-rw-r--r--  1 gene    gene       0 2009-03-11 12:51 fileA

A: For multiple files, the following will remove all files apart from those that have FileA or FileB in the name.
for file in *
do
  if [ x`echo $file | grep -ve "\(FileA\|FileB\)"` == x ]; then
    rm $file
  fi
done

It's more useful in a long list of files. If it's only a short list, I'd go with CoverosGene's response.

A: Most ways of doing this based on parsing the directory list are likely to be error prone.
If you have write access to the parent directory, and your necessary file is in sub-directory foo, how about:
% mkdir bar
% mv foo/fileA bar
% rm -rf foo
% mv bar foo

i.e. get your essential file(s) the hell out of the way first!


text:
Q: pyparsing verilog module pins info I am trying to get the following info from a Verilog file:

*

*module name

*pinslist

*pins info (pinName or busName (and vector range), direction)

For example, below a Verilog file:
module DMU  (
       A, B, C,
       vdd, Z, Q, QN );

output Z;
input  A, B,
       C, D;

inout vdd;

output [127:0] Q;
output [18:0] QN;  //my comment

endmodule

The code I have implemented:
range = LBRACK + Word(nums) + COLON + Word(nums) + RBRACK
inputDecl = Group("input" + Optional(range) + Group(OneOrMore(Word(alphanums+","), stopOn=SEMI))).setResultsName("inputPins")
inoutDecl = Group("inout" + Optional(range) + Group(OneOrMore(Word(alphanums+","), stopOn=SEMI))).setResultsName("inoutPins")
outputDecl = Group("output" + Optional(range) + Group(OneOrMore(Word(alphanums+","), stopOn=SEMI))).setResultsName("outputPins")

pinsDecl = ~Keyword("endmodule") + (
            inputDecl |
            inoutDecl |
            outputDecl
            )

token_module = Keyword("module") + Word(alphanums).setResultsName("moduleName") + LPAR + \
               Group(OneOrMore(Word(alphanums+","), stopOn=RPAR).setResultsName("pinsList")) + SEMI + pinsDecl

I have the following error I cannot solve:
File "/sw/freetools/python/3.7.2/rh60_64/modules_base/lib/python3.7/site-packages/pyparsing.py", line 2625, in parseImpl
    raise ParseException(instring, loc, self.errmsg, self)
pyparsing.ParseException: Expected ";" (at char 52), (line:3, col:22)

Can anyone help me ?


text:
Q: Powershell: split string with newline, then use -contains $a = {aa
bb
cc}
$a = $a -split "`n"
$a -contains "aa"

This returns false, when the string "aa" is seemingly part of the list. Why is this?

A: a solution cross Platform:
$a = $a -split [System.Environment]::NewLine

A: Every time I see a `n in code, I always question whether it should be `r`n on Windows.
Change your code to this:
$a = $a -split "`r`n"

A: To complement Kory Gill's helpful answer, which suggests that the problem may be that the input has CRLF ("`r`n") line endings, in which case -split "`n" (splitting by LF only) would leave the resulting array elements with a trailing CR ("`r"), causing "aa" not to be found with -contains, because the actual value is "aa`r".
The generic way to handle input with Windows- or Unix-style line endings is to use:
$a -split '\r?\n' # split $a into lines, whether it has CRLF or LF-only line endings

The -split operator uses regexes (regular expressions), and regex \r?\n matches any LF (\n) possibly (?) preceded by a CR (\r). To also match (rare) CR-only newlines, use \r?\n|\r
Regex escape sequences \r and \n correspond to PowerShell escape sequences `r and `n (which work in double-quoted strings only).
Note that PowerShell itself is quite flexible when it comes to line endings:

*

*Even on Windows interactive input in the regular console uses LF-only line endings (\n) (except in the obsolescent ISE).

*Scripts are allowed to have CRLF (\r\n) or LF (\n) line endings, and PowerShell preserves the source file's line endings in any multi-line string literals defined in the file.

*

*Note that this applies even to multi-line script blocks, as in the question: when you convert such a script block to a string later - which simply returns everything between the script-block delimiters, { and } - the source file's line endings are reflected in the resulting string.

As an aside: [Environment]::NewLine contains the platform-appropriate newline (line-ending) sequence: "`r`n" on Windows, "`n" on Unix-like platforms, but, as discussed above, there's no guarantee that all input encountered will have platform-appropriate newlines.


text:
Q: Writing video + generated audio to AVAssetWriterInput, audio stuttering I'm generating a video from a Unity app on iOS. I'm using iVidCap, which uses AVFoundation to do this. That side is all working fine. Essentially the video is rendered by using a texture render target and passing the frames to an Obj-C plugin.
Now I need to add audio to the video. The audio is going to be sound effects that occur at specific times and maybe some background sound. The files being used are actually assets internal to the Unity app. I could potentially write these to phone storage and then generate an AVComposition, but my plan was to avoid this and composite the audio in floating point format buffers (obtaining audio from audio clips is in float format). I might be doing some on the fly audio effects later on.
After several hours I managed to get audio to be recorded and play back with the video... but it stutters.
Currently I'm just generating a square wave for the duration of each frame of video and writing it to an AVAssetWriterInput. Later, I'll generate the audio I actually want.
If I generate one massive sample, I don't get the stuttering. If I write it in blocks (which I'd much prefer over allocating a massive array), then the blocks of audio seem to clip each other:

I can't seem to figure out why this is.  I am pretty sure I am getting the timestamp for the audio buffers correct, but maybe I'm doing this whole part incorrectly.  Or do I need some flags to get the video to sync to the audio?  I cant see that this is the problem, since I can see the problem in a wave editor after extracting the audio data to a wav.
Relevant code for writing audio:
- (id)init {
    self = [super init];

    if (self) {
        // [snip]

        rateDenominator = 44100;
        rateMultiplier = rateDenominator / frameRate;

        sample_position_ = 0;
        audio_fmt_desc_ = nil;
        int nchannels = 2;
        AudioStreamBasicDescription audioFormat;
        bzero(&audioFormat, sizeof(audioFormat));
        audioFormat.mSampleRate = 44100;
        audioFormat.mFormatID   = kAudioFormatLinearPCM;
        audioFormat.mFramesPerPacket = 1;
        audioFormat.mChannelsPerFrame = nchannels;
        int bytes_per_sample = sizeof(float);
        audioFormat.mFormatFlags = kAudioFormatFlagIsFloat | kAudioFormatFlagIsAlignedHigh;
        audioFormat.mBitsPerChannel = bytes_per_sample * 8;
        audioFormat.mBytesPerPacket = bytes_per_sample * nchannels;
        audioFormat.mBytesPerFrame = bytes_per_sample * nchannels;

        CMAudioFormatDescriptionCreate(kCFAllocatorDefault,
                                       &audioFormat,
                                       0,
                                       NULL,
                                       0,
                                       NULL,
                                       NULL,
                                       &audio_fmt_desc_
        );
    }

    return self;
}

- (BOOL)beginRecordingSession {
    NSError* error = nil;

    isAborted = false;
    abortCode = No_Abort;

    // Allocate the video writer object.
    videoWriter = [[AVAssetWriter alloc] initWithURL:[self getVideoFileURLAndRemoveExisting:
                   recordingPath] fileType:AVFileTypeMPEG4 error:&error];

    if (error) {
        NSLog(@"Start recording error: %@", error);
    }

    // Configure video compression settings.
    NSDictionary* videoCompressionProps = [NSDictionary dictionaryWithObjectsAndKeys:
                                           [NSNumber numberWithDouble:1024.0 * 1024.0], AVVideoAverageBitRateKey,
                                           [NSNumber numberWithInt:10],AVVideoMaxKeyFrameIntervalKey,
                                           nil];

    // Configure video settings.
    NSDictionary* videoSettings = [NSDictionary dictionaryWithObjectsAndKeys:
    AVVideoCodecH264, AVVideoCodecKey,
    [NSNumber numberWithInt:frameSize.width], AVVideoWidthKey,
    [NSNumber numberWithInt:frameSize.height], AVVideoHeightKey,
    videoCompressionProps, AVVideoCompressionPropertiesKey,
    nil];

    // Create the video writer that is used to append video frames to the output video
    // stream being written by videoWriter.
    videoWriterInput = [[AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:videoSettings] retain];
    //NSParameterAssert(videoWriterInput);
    videoWriterInput.expectsMediaDataInRealTime = YES;

    // Configure settings for the pixel buffer adaptor.
    NSDictionary* bufferAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
    [NSNumber numberWithInt:kCVPixelFormatType_32ARGB], kCVPixelBufferPixelFormatTypeKey, nil];

    // Create the pixel buffer adaptor, used to convert the incoming video frames and
    // append them to videoWriterInput.
    avAdaptor = [[AVAssetWriterInputPixelBufferAdaptor assetWriterInputPixelBufferAdaptorWithAssetWriterInput:videoWriterInput sourcePixelBufferAttributes:bufferAttributes] retain];

    [videoWriter addInput:videoWriterInput];

    // <pb> Added audio input.
    sample_position_ = 0;
    AudioChannelLayout acl;
    bzero( &acl, sizeof(acl));
    acl.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;

    NSDictionary* audioOutputSettings = nil;

    audioOutputSettings = [NSDictionary dictionaryWithObjectsAndKeys:
    [ NSNumber numberWithInt: kAudioFormatMPEG4AAC ], AVFormatIDKey,
    [ NSNumber numberWithInt: 2 ], AVNumberOfChannelsKey,
    [ NSNumber numberWithFloat: 44100.0 ], AVSampleRateKey,
    [ NSNumber numberWithInt: 64000 ], AVEncoderBitRateKey,
    [ NSData dataWithBytes: &acl length: sizeof( acl ) ], AVChannelLayoutKey,
    nil];

    audioWriterInput = [[AVAssetWriterInput
    assetWriterInputWithMediaType: AVMediaTypeAudio
    outputSettings: audioOutputSettings ] retain];

    //audioWriterInput.expectsMediaDataInRealTime = YES;
    audioWriterInput.expectsMediaDataInRealTime = NO; // seems to work slightly better

    [videoWriter addInput:audioWriterInput];

    rateDenominator = 44100;
    rateMultiplier = rateDenominator / frameRate;

    // Add our video input stream source to the video writer and start it.
    [videoWriter startWriting];
    [videoWriter startSessionAtSourceTime:CMTimeMake(0, rateDenominator)];

    isRecording = true;
    return YES;
}

- (int) writeAudioBuffer:(float *)samples sampleCount:(size_t)n channelCount:(size_t)nchans {
    if (![self waitForAudioWriterReadiness]) {
        NSLog(@"WARNING: writeAudioBuffer dropped frame after wait limit reached.");
        return 0;
    }

    //NSLog(@"writeAudioBuffer");
    OSStatus status;
    CMBlockBufferRef bbuf = NULL;
    CMSampleBufferRef sbuf = NULL;

    size_t buflen = n * nchans * sizeof(float);
    // Create sample buffer for adding to the audio input.
    status = CMBlockBufferCreateWithMemoryBlock(
        kCFAllocatorDefault,
        samples,
        buflen,
        kCFAllocatorNull,
        NULL,
        0,
        buflen,
        0,
        &bbuf);

    if (status != noErr) {
        NSLog(@"CMBlockBufferCreateWithMemoryBlock error");
        return -1;
    }

    CMTime timestamp = CMTimeMake(sample_position_, 44100);
    sample_position_ += n;

    status = CMAudioSampleBufferCreateWithPacketDescriptions(kCFAllocatorDefault, bbuf, TRUE, 0, NULL, audio_fmt_desc_, 1, timestamp, NULL, &sbuf);
    if (status != noErr) {
        NSLog(@"CMSampleBufferCreate error");
        return -1;
    }
    BOOL r = [audioWriterInput appendSampleBuffer:sbuf];
    if (!r) {
        NSLog(@"appendSampleBuffer error");
    }
    CFRelease(bbuf);
    CFRelease(sbuf);

    return 0;
}

Any ideas on what's going on?
Should I be creating/appending samples in a different way?
Is it something to do with the AAC compression? It doesn't work if I try to use uncompressed audio (it throws).
As far as I can tell, I'm calculating the PTS correctly. Why is this even required for the audio channel? Shouldn't the video be synced to the audio clock?

UPDATE
I've tried providing the audio in fixed blocks of 1024 samples, since this is the size of the DCT used by the AAC compressor.  Doesn't make any difference.
I've tried pushing all the blocks in one go before writing any video.  Doesn't work.
I've tried using CMSampleBufferCreate for the remaining blocks and CMAudioSampleBufferCreateWithPacketDescriptions for the first block only.  No change.
And I've tried combinations of these.  Still not right.

SOLUTION
It appears that:
audioWriterInput.expectsMediaDataInRealTime = YES;

is essential otherwise it messes with its mind.  Perhaps this is because the video was set up with this flag.  Additionally, CMBlockBufferCreateWithMemoryBlock does NOT copy sample data, even if you pass the flag kCMBlockBufferAlwaysCopyDataFlag to it.
So, a buffer can be created with this and then copied using CMBlockBufferCreateContiguous to ensure that it you get a block buffer with a copy of the audio data.  Otherwise it will reference the memory you passed in originally and things will get messed up.

A: It looks ok, although I would use CMBlockBufferCreateWithMemoryBlock because it copies the samples. Is your code ok with not knowing when audioWriterInput has finished with them?
Shouldn't kAudioFormatFlagIsAlignedHigh be kAudioFormatFlagIsPacked?

A: CMAudioSampleBufferCreateWithPacketDescriptions(kCFAllocatorDefault, bbuf, TRUE, 0, NULL, audio_fmt_desc_, 1, timestamp, NULL, &sbuf);

should be
CMAudioSampleBufferCreateWithPacketDescriptions(kCFAllocatorDefault, bbuf, TRUE, 0, NULL, audio_fmt_desc_, n, timestamp, NULL, &sbuf);i made it.


text:
Q: Wordpress Multi Site Image Issue I'm running a WP 3.5.1 multisite install and the images on my site suddenly stopped showing up; I think I've traced it to a .htaccess issue but now I'm stuck.
Using the default .htaccess code displays only broken images on my site:
# BEGIN WordPress

<IfModule mod_rewrite.c>

RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]

# uploaded files
RewriteRule ^([_0-9a-zA-Z-]+/)?files/(.+) wp-includes/ms-files.php?file=$2 [L]

# add a trailing slash to /wp-admin
RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L]
RewriteRule . index.php [L]
</IfModule>

# END WordPress

... but if I replace the RewriteRule ^([_0-9a-zA-Z-]+/)?files/(.+) wp-includes/ms-files.php?file=$2 [L] line with this, it ALMOST works; regular images show up fine, but timthumb-returned files (using the same image URL) DON'T work:
RewriteRule ^([_0-9a-zA-Z-]+/)?files/(.+) wp-content/blogs.dir/3/files/$2 [L]
... the only trouble is, my theme uses timthumb pretty extensively and it's still showing broken images through timthumb and I don't particularly want to edit the .htaccess file for every site I maintain.  How can I fix this?


text:
Q: How can I get bower and grunt to add angular-bootstrap ui dependency? I am learning node.js, and a trying to use automated tools to manage AngularJS apps.  Towards that end, I have nodejs, grunt, yeoman, and bower installed in a centos 7 devbox and am experimenting with an AngularJS app that I have created in the new environment.  How can I get bower to add the angular-bootstrap ui dependency to an AngularJS app that I am building in this environment?
bower.json and Gruntfile.js in my app both look auto-generated, so I hesitate to edit them without some guidance.

WHAT I HAVE TRIED SO FAR:
So far, I navigated to /path/to/workspace/client and typed bower install angular-bootstrap.  This command ran successfully.
But the bower-generated dependencies list inside index.html for the app does not contain the angular-bootstrap ui dependency, even after I closed index.html in the editor, typed Ctrl-C to stop the server and then typed grunt serve to start the server again and re-load index.html in the editor.
The bower-generated dependency list in index.html looks like the following:
<!doctype html>

    <meta charset="utf-8">
    <title></title>
    <base href="/" />
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">

    <link rel="stylesheet" href="styles/main.css">

    //HTML and AngularJS code omitted because it is not relevant to OP

I am also including bower.json as follows, but since it looks auto-generated, I hesitate to alter it manually:
{
  "name": "client",
  "version": "0.0.0",
  "dependencies": {
    "angular": "^1.4.0",
    "bootstrap-sass-official": "^3.2.0",
    "angular-animate": "^1.4.0",
    "angular-aria": "^1.4.0",
    "angular-cookies": "^1.4.0",
    "angular-messages": "^1.4.0",
    "angular-resource": "^1.4.0",
    "angular-route": "^1.4.0",
    "angular-sanitize": "^1.4.0",
    "angular-touch": "^1.4.0"
  },
  "devDependencies": {
    "angular-mocks": "^1.4.0"
  },
  "appPath": "app",
  "moduleName": "clientApp",
  "overrides": {
    "bootstrap": {
      "main": [
        "less/bootstrap.less",
        "dist/css/bootstrap.css",
        "dist/js/bootstrap.js"
      ]
    }
  }
}

I am also including Gruntfile.js, as follows, which seems to indicate that it automatically uses parameters from bower.json to update the dependencies in index.html. but you can see that Gruntfile.js begins with a statement that it was autogenerated, as follows:
// Generated on 2016-02-24 using generator-angular 0.15.1
'use strict';

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

module.exports = function (grunt) {

  // Time how long tasks take. Can help when optimizing build times
  require('time-grunt')(grunt);

  // Automatically load required Grunt tasks
  require('jit-grunt')(grunt, {
    useminPrepare: 'grunt-usemin',
    ngtemplates: 'grunt-angular-templates',
    cdnify: 'grunt-google-cdn'
  });

  // Configurable paths for the application
  var appConfig = {
    app: require('./bower.json').appPath || 'app',
    dist: '../server/dist'
  };

  // Define the configuration for all the tasks
  grunt.initConfig({

    // Project settings
    yeoman: appConfig,

    // Watches files for changes and runs tasks based on the changed files
    watch: {
      bower: {
        files: ['bower.json'],
        tasks: ['wiredep']
      },
      js: {
        files: ['<%= yeoman.app %>/scripts/{,*/}*.js'],
        tasks: ['newer:jshint:all', 'newer:jscs:all'],
        options: {
          livereload: '<%= connect.options.livereload %>'
        }
      },
      jsTest: {
        files: ['test/spec/{,*/}*.js'],
        tasks: ['newer:jshint:test', 'newer:jscs:test', 'karma']
      },
      compass: {
        files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        tasks: ['compass:server', 'postcss:server']
      },
      gruntfile: {
        files: ['Gruntfile.js']
      },
      livereload: {
        options: {
          livereload: '<%= connect.options.livereload %>'
        },
        files: [
          '<%= yeoman.app %>/{,*/}*.html',
          '.tmp/styles/{,*/}*.css',
          '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
        ]
      }
    },

    // The actual grunt server settings
    connect: {
      options: {
        port: 9000,
        // Change this to '0.0.0.0' to access the server from outside.
        hostname: 'localhost',
        livereload: 35729
      },
      livereload: {
        options: {
          open: true,
          middleware: function (connect) {
            return [
              connect.static('.tmp'),
              connect().use(
                '/bower_components',
                connect.static('./bower_components')
              ),
              connect().use(
                '/app/styles',
                connect.static('./app/styles')
              ),
              connect.static(appConfig.app)
            ];
          }
        }
      },
      test: {
        options: {
          port: 9001,
          middleware: function (connect) {
            return [
              connect.static('.tmp'),
              connect.static('test'),
              connect().use(
                '/bower_components',
                connect.static('./bower_components')
              ),
              connect.static(appConfig.app)
            ];
          }
        }
      },
      dist: {
        options: {
          open: true,
          base: '<%= yeoman.dist %>'
        }
      }
    },

    // Make sure there are no obvious mistakes
    jshint: {
      options: {
        jshintrc: '.jshintrc',
        reporter: require('jshint-stylish')
      },
      all: {
        src: [
          'Gruntfile.js',
          '<%= yeoman.app %>/scripts/{,*/}*.js'
        ]
      },
      test: {
        options: {
          jshintrc: 'test/.jshintrc'
        },
        src: ['test/spec/{,*/}*.js']
      }
    },

    // Make sure code styles are up to par
    jscs: {
      options: {
        config: '.jscsrc',
        verbose: true
      },
      all: {
        src: [
          'Gruntfile.js',
          '<%= yeoman.app %>/scripts/{,*/}*.js'
        ]
      },
      test: {
        src: ['test/spec/{,*/}*.js']
      }
    },

    // Empties folders to start fresh
    clean: {
      dist: {
        files: [{
          dot: true,
          src: [
            '.tmp',
            '<%= yeoman.dist %>/{,*/}*',
            '!<%= yeoman.dist %>/.git{,*/}*'
          ]
        }]
      },
      server: '.tmp'
    },

    // Add vendor prefixed styles
    postcss: {
      options: {
        processors: [
          require('autoprefixer-core')({browsers: ['last 1 version']})
        ]
      },
      server: {
        options: {
          map: true
        },
        files: [{
          expand: true,
          cwd: '.tmp/styles/',
          src: '{,*/}*.css',
          dest: '.tmp/styles/'
        }]
      },
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/styles/',
          src: '{,*/}*.css',
          dest: '.tmp/styles/'
        }]
      }
    },

    // Automatically inject Bower components into the app
    wiredep: {
      app: {
        src: ['<%= yeoman.app %>/index.html'],
        ignorePath:  /\.\.\//
      },
      test: {
        devDependencies: true,
        src: '<%= karma.unit.configFile %>',
        ignorePath:  /\.\.\//,
        fileTypes:{
          js: {
            block: /(([\s\t]*)\/{2}\s*?bower:\s*?(\S*))(\n|\r|.)*?(\/{2}\s*endbower)/gi,
              detect: {
                js: /'(.*\.js)'/gi
              },
              replace: {
                js: '\'{{filePath}}\','
              }
            }
          }
      },
      sass: {
        src: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        ignorePath: /(\.\.\/){1,2}bower_components\//
      }
    },

    // Compiles Sass to CSS and generates necessary files if requested
    compass: {
      options: {
        sassDir: '<%= yeoman.app %>/styles',
        cssDir: '.tmp/styles',
        generatedImagesDir: '.tmp/images/generated',
        imagesDir: '<%= yeoman.app %>/images',
        javascriptsDir: '<%= yeoman.app %>/scripts',
        fontsDir: '<%= yeoman.app %>/styles/fonts',
        importPath: './bower_components',
        httpImagesPath: '/images',
        httpGeneratedImagesPath: '/images/generated',
        httpFontsPath: '/styles/fonts',
        relativeAssets: false,
        assetCacheBuster: false,
        raw: 'Sass::Script::Number.precision = 10\n'
      },
      dist: {
        options: {
          generatedImagesDir: '<%= yeoman.dist %>/images/generated'
        }
      },
      server: {
        options: {
          sourcemap: true
        }
      }
    },

    // Renames files for browser caching purposes
    filerev: {
      dist: {
        src: [
          '<%= yeoman.dist %>/scripts/{,*/}*.js',
          '<%= yeoman.dist %>/styles/{,*/}*.css',
          '<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
          '<%= yeoman.dist %>/styles/fonts/*'
        ]
      }
    },

    // Reads HTML for usemin blocks to enable smart builds that automatically
    // concat, minify and revision files. Creates configurations in memory so
    // additional tasks can operate on them
    useminPrepare: {
      html: '<%= yeoman.app %>/index.html',
      options: {
        dest: '<%= yeoman.dist %>',
        flow: {
          html: {
            steps: {
              js: ['concat', 'uglifyjs'],
              css: ['cssmin']
            },
            post: {}
          }
        }
      }
    },

    // Performs rewrites based on filerev and the useminPrepare configuration
    usemin: {
      html: ['<%= yeoman.dist %>/{,*/}*.html'],
      css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
      js: ['<%= yeoman.dist %>/scripts/{,*/}*.js'],
      options: {
        assetsDirs: [
          '<%= yeoman.dist %>',
          '<%= yeoman.dist %>/images',
          '<%= yeoman.dist %>/styles'
        ],
        patterns: {
          js: [[/(images\/[^''""]*\.(png|jpg|jpeg|gif|webp|svg))/g, 'Replacing references to images']]
        }
      }
    },

    // The following *-min tasks will produce minified files in the dist folder
    // By default, your `index.html`'s  will take care of
    // minification. These next options are pre-configured if you do not wish
    // to use the Usemin blocks.
    // cssmin: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/styles/main.css': [
    //         '.tmp/styles/{,*/}*.css'
    //       ]
    //     }
    //   }
    // },
    // uglify: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/scripts/scripts.js': [
    //         '<%= yeoman.dist %>/scripts/scripts.js'
    //       ]
    //     }
    //   }
    // },
    // concat: {
    //   dist: {}
    // },

    imagemin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.{png,jpg,jpeg,gif}',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },

    svgmin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.svg',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },

    htmlmin: {
      dist: {
        options: {
          collapseWhitespace: true,
          conservativeCollapse: true,
          collapseBooleanAttributes: true,
          removeCommentsFromCDATA: true
        },
        files: [{
          expand: true,
          cwd: '<%= yeoman.dist %>',
          src: ['*.html'],
          dest: '<%= yeoman.dist %>'
        }]
      }
    },

    ngtemplates: {
      dist: {
        options: {
          module: 'clientApp',
          htmlmin: '<%= htmlmin.dist.options %>',
          usemin: 'scripts/scripts.js'
        },
        cwd: '<%= yeoman.app %>',
        src: 'views/{,*/}*.html',
        dest: '.tmp/templateCache.js'
      }
    },

    // ng-annotate tries to make the code safe for minification automatically
    // by using the Angular long form for dependency injection.
    ngAnnotate: {
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/concat/scripts',
          src: '*.js',
          dest: '.tmp/concat/scripts'
        }]
      }
    },

    // Replace Google CDN references
    cdnify: {
      dist: {
        html: ['<%= yeoman.dist %>/*.html']
      }
    },

    // Copies remaining files to places other tasks can use
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= yeoman.app %>',
          dest: '<%= yeoman.dist %>',
          src: [
            '*.{ico,png,txt}',
            '*.html',
            'images/{,*/}*.{webp}',
            'styles/fonts/{,*/}*.*'
          ]
        }, {
          expand: true,
          cwd: '.tmp/images',
          dest: '<%= yeoman.dist %>/images',
          src: ['generated/*']
        }, {
          expand: true,
          cwd: '.',
          src: 'bower_components/bootstrap-sass-official/assets/fonts/bootstrap/*',
          dest: '<%= yeoman.dist %>'
        }]
      },
      styles: {
        expand: true,
        cwd: '<%= yeoman.app %>/styles',
        dest: '.tmp/styles/',
        src: '{,*/}*.css'
      }
    },

    // Run some tasks in parallel to speed up the build process
    concurrent: {
      server: [
        'compass:server'
      ],
      test: [
        'compass'
      ],
      dist: [
        'compass:dist',
        'imagemin',
        'svgmin'
      ]
    },

    // Test settings
    karma: {
      unit: {
        configFile: 'test/karma.conf.js',
        singleRun: true
      }
    }
  });

  grunt.registerTask('serve', 'Compile then start a connect web server', function (target) {
    if (target === 'dist') {
      return grunt.task.run(['build', 'connect:dist:keepalive']);
    }

    grunt.task.run([
      'clean:server',
      'wiredep',
      'concurrent:server',
      'postcss:server',
      'connect:livereload',
      'watch'
    ]);
  });

  grunt.registerTask('server', 'DEPRECATED TASK. Use the "serve" task instead', function (target) {
    grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
    grunt.task.run(['serve:' + target]);
  });

  grunt.registerTask('test', [
    'clean:server',
    'wiredep',
    'concurrent:test',
    'postcss',
    'connect:test',
    'karma'
  ]);

  grunt.registerTask('build', [
    'clean:dist',
    'wiredep',
    'useminPrepare',
    'concurrent:dist',
    'postcss',
    'ngtemplates',
    'concat',
    'ngAnnotate',
    'copy:dist',
    'cdnify',
    'cssmin',
    'uglify',
    'filerev',
    'usemin',
    'htmlmin'
  ]);

  grunt.registerTask('default', [
    'newer:jshint',
    'newer:jscs',
    'test',
    'build'
  ]);
};

A: Note: this answer uses Gulp and, I know you are afraid of the UNMAINTAINED mention on wiredep github repository. But this is to give you a starting point, and I'm sure you can find the equivalent in Grunt:
You could use wiredep (in conjunction with Gulp):
npm -i --save-dev wiredep gulp

Add this to the .bowerrc file :
{
  "scripts": {
    "postinstall":"gulp wiredep"
  }
}

and in your Gulpfile.js:
gulp.task('wiredep', function() {
    // see wiredep website for the full options list
    var options = {
        bowerJson  : require('./bower.json'),
        directory  : './bower_components/',
      }, wiredep = require('wiredep').stream;

    console.log('Wiring bower dependencies');
    gulp.src('./index.html')
        .pipe(wiredep(options))
        .pipe($.inject(gulp.src('./app/**/*.js', {
            read: false
         })))
        .pipe(gulp.dest('./'));
});

And your index.html file:

Running gulp wiredep in your terminal will inject every libraries in the ./bower_components folder into your index.html file, between the bower:js and bower:css tags.

A: You forgot the save flag.
Run it again as:
bower install angular-bootstrap --save

then look at bower.json and it should have the added dependency


text:
Q: Could someone explain bizarre behavior executing millions of UPDATES? Could someone explain this behavior to me? I ran the following query on Postgres 9.3 running natively on OS X. I was trying to simulate some behavior where the index size could grow much larger than the table size, and instead found something even more bizarre.
CREATE TABLE test(id int);
CREATE INDEX test_idx ON test(id);

CREATE FUNCTION test_index(batch_size integer, total_batches integer) RETURNS void AS $$
DECLARE
  current_id integer := 1;
BEGIN
FOR i IN 1..total_batches LOOP
  INSERT INTO test VALUES (current_id);
  FOR j IN 1..batch_size LOOP
    UPDATE test SET id = current_id + 1 WHERE id = current_id;
    current_id := current_id + 1;
  END LOOP;
END LOOP;
END;
$$ LANGUAGE plpgsql;

SELECT test_index(500, 10000);

I let this run for about an hour on my local machine, before I started getting disk issue warnings from OS X. I noticed that Postgres was sucking up about 10MB/s from my local disk, and that the Postgres database was consuming a grand total of 30GB from my machine. I ended up cancelling the query. Regardless, Postgres did not return the disk space to me and I queried the database for usage statistics with the following result:
test=# SELECT nspname || '.' || relname AS "relation",
    pg_size_pretty(pg_relation_size(C.oid)) AS "size"
  FROM pg_class C
  LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace)
  WHERE nspname NOT IN ('pg_catalog', 'information_schema')
  ORDER BY pg_relation_size(C.oid) DESC
  LIMIT 20;

           relation            |    size
-------------------------------+------------
 public.test                   | 17 GB
 public.test_idx               | 14 GB

However, selecting from the table yielded no results.
test=# select * from test limit 1;
 id
----
(0 rows)

Running 10000 batches of 500 is 5,000,000 rows, which should yield a pretty small table/index size (on the scale of MB). I suspect that Postgres is creating a new version of the table/index for each INSERT/UPDATE that's happening with function, but this seems strange. The entire function is run transactionally, and the table was empty to start.
Any thoughts on why I'm seeing this behavior?
Specifically, the two questions I have are: why has this space not yet been reclaimed by the database and the second is why did the database require this much space in the first place? 30GB seems like a lot even when accounting for MVCC

A: Short version
Your algorithm looks O(n*m) on first glance, but effectively grows O(n * m^2), because all rows have the same ID. Instead of 5M rows, you are getting >1.25G rows
Long version
Your function is inside an implicit transaction. That's why you see no data after cancelling your query, and also why it needs to maintain distinct versions of the updated/inserted tuples for both loops.
Additionally, I suspect you have a bug in your logic or underestimating the number of updates made.
First iteration of the outer loop - current_id starts at 1, inserts 1 row, then the inner loop performs an update 10000 times for the same row, finalizing with the only row showing an ID of 10001, and current_id with a value of 10001. 10001 versions of the row are still kept, as the transaction is not finished.
Second iteration of the outer loop - as current_id is 10001, a new row is inserted with ID 10001. Now you have 2 rows with the same "ID", and 10003 versions in total of both rows (10002 of the first one, 1 of the second one). Then the inner loop updates 10000 times BOTH rows, creating 20000 new versions, getting to 30003 tuples so far...
Third iteration of the outer loop: current ID is 20001, a new row is inserted with ID 20001. You have 3 rows, all with same "ID" 20001, 30006 row/tuples versions so far. Then you perform 10000 updates of 3 rows, creating 30000 new versions, now 60006...
...
(If your space had allowed) - 500th iteration of the outer loop, creates 5M updates of 500 rows, just in this iteration
As you see, instead of your expected 5M updates, you got 1000 + 2000 + 3000 + ... + 4990000 + 5000000 updates (plus change), which would be 10000 * (1+2+3+...+499+500), over 1.25G updates. And of course a row is not just the size of your int, it needs some additional structure, so your table and index gets over ten gigabytes size.
Related Q & A:

*

*set isolation level for postgresql stored procedures

*Making sense of Postgres row sizes

A: PostgreSQL only returns disk space after VACUUM FULL, not after a DELETE or ROLLBACK (as a result of cancellation)

The standard form of VACUUM removes dead row versions in tables and indexes and marks the space available for future reuse. However, it will not return the space to the operating system, except in the special case where one or more pages at the end of a table become entirely free and an exclusive table lock can be easily obtained. In contrast, VACUUM FULL actively compacts tables by writing a complete new version of the table file with no dead space. This minimizes the size of the table, but can take a long time. It also requires extra disk space for the new copy of the table, until the operation completes.

As a side note your whole function seems questionable. I'm not sure what you're trying to test, but if you want to create data, you can use generate_series
INSERT INTO test
SELECT x FROM generate_series(1, batch_size*total_batches) AS t(x);

A: The actual numbers after analyzing the function are much bigger because all the rows of the table get the same value which is updated multiple times in each iteration.
When we run it with parameters n and m:
SELECT test_index(n, m);

there are m row inserts and n * (m^2 + m) / 2 updates. So, for n = 500 and m = 10000, Postgres will need to insert only 10K rows but perform ~25G (25 billion) tuple updates.
Considering that a row in Postgres has some 24 bytes overhead, a table with just a single int column will need 28 bytes per row plus the page overhead. So, for the operation to finish, we'd need about 700GB plus the space for the index (which would be a few hundred GB as well).

Testing
To test the theory, we created another table test_test with a single row.
CREATE TABLE test_test (i int not null) ;
INSERT INTO test_test (i) VALUES (0);

Then we add a trigger on test so every update will increase the counter by 1. (Code omitted). Then we we run the function, with smaller values, n = 50 and m = 100.
Our theory predicts:

*

*100 row inserts,

*250K tuple updates (252500 = 50*100*101/2)

*at least 7MB for the table on disk

*(+ space for the index)

Test 1 (original test table, with index)
    SELECT test_index(50, 100) ;

After completion, we check table contents:
x=# SELECT COUNT(*) FROM test ;
 count
-------
   100
(1 row)

x=# SELECT i FROM test_test ;
   i
--------
 252500
(1 row)

And disk usage (query under Index size/usage statistics in Index Maintenance):
tablename | indexname | num_rows | table_size | index_size | unique | number_of_scans | tuples_read
----------+-----------+----------+------------+------------+--------+-----------------+-------------
test      | test_idx  |      100 | 8944 kB    | 5440 kB    | N      |           10001 |      505003
test_test |           |        1 | 8944 kB    |            | N      |                 |

The test table has used almost 9MB for the table and 5MB for the index. Note that the test_test table has used another 9MB! That's expected as it also went through 250K updates (our second trigger updated the single row of test_test for each update of a row in test.)
Note also the number of scan on table test (10K) and the tuples reads (500K).
Test 2 (test table without index)
Exactly the same as above, except that the table has no index.
tablename | indexname | num_rows | table_size | index_size | unique | number_of_scans | tuples_read
----------+-----------+----------+------------+------------+--------+-----------------+-------------
 test        |        |      100 | 8944 kB    |            | N      |                 |
 test_test   |        |        1 | 8944 kB    |            | N      |                 |

We get the same size for disk usage of the table and of course no disk usage for indexes. The number of scans on table test is zero though and the tuples reads as well.
Test 3 (with lower fillfactor)
Tried with fillfactor 50 and the lowest possible, 10. No improvement at all. Disk usage was almost identical to the previous tests (which used the default fillfactor, 100 percent)


text:
Q: Moving back webpages with Javascript Ok this is the issue. I am working in a popup. We go from Page 1 to Page 2. Page 2 has frames set up on it. I know it's bad but it was not my decisions. Now on Page 2 in one frame we continue onto Page 3. If I click the back button on Page 2 with javascript history.go(-1) we can get to Page 1. But if the user goes from Page 2 to Page 3 then back to Page 2 a user can not simple go back to Page 1 unless the javascript is history.go(-3). Is there a way I can tell where I am coming from so I can determine which go to use?
FYI URLRefferrer does not work but it only gives me the page holding all the frames. Any suggestions welcomed.

A: An easy way is to link to the page you want directly instead of using history.go. Alternatively, you can try to use parent.history.go(-1).
A third thing you may try, if you have complete control over all the links in the inner frame is to always use location.replace from the inner frame, which will not add an entry into the history, something like the following script
$(function() {
    $('a').click(function(e) {
        e.preventDefault();
        location.replace(this.href);
    });
});


text:
Q: How can I change the developer name in Huawei AppGallery? I registered alone using my real name just to upload the app, but I'd like the developer name be accredited to the team I belong to..

A: To change the developer name, please execute the following steps.
After logging into your Huawei developer account,  go to Developer center->Settings-> My profile and then change the developer name there.


text:
Q: Completely separated sets, Stone–Čech compactification This is a problem I'm confused with:
Definition:
We say two subsets $A$ and $B$ of a topological space $X$ are completely separated if there exists a continuous map $f: X \rightarrow \mathbb{R}$ such that $f(A) \subseteq \{0\}$ and $f(B) \subseteq \{1\}$.
i.e we are not given that $A=f^{-1}(\{0\})$ but just that $f(A) \subseteq \{0\}$.
Prove that every pair of completely separated sets in a completely regular space have disjoint closures in their Stone–Čech compactification.
Right so we need to find a bounded continuous map $f: X \rightarrow \mathbb{R}$ and then extend this to $\beta(X)$. The problem is that how can we bound $f$ ? all we know is that there is a continuous map $f: X \rightarrow \mathbb{R}$ such that $f(x)=0$ if $x \in A$ and 1 if $x \in B$. But what if $f$ is unbounded in the points outside of $A$ and $B$. We are not given that $X = A \cup B$ so how can we bound $f$ ? can we simply define a new function say $g: X \rightarrow \mathbb{R}$ by $g(x) = min \{1,f(x)\}$ or something like that?
Thanks in advance.

A: CW answer to push it from unanswered queue:
Let $g(x)=\min\{1,f(x)\}$, and check that $g$ is continuous. Then let $h(x)=\max\{0,g(x)\}$, and check that $h$ is continuous.
$0\le h\le1$ and then we extend it.
Then observe $A\subseteq h^{−1}(\{0\})$ and similarly $B\subseteq h^{−1}(\{1\})$.
But singletons are closed in $\mathbb R$ and $h$ is continuous so taking closures we get the result.
The proof of continuity for $h$ is the same as for $g$
(Answer is taken from comments and looks incomplete though gives an outline to proof, feel free to edit it)


text:
Q: How is BigQuery slot quota calculated? We are considering moving to flat rate pricing for BigQuery, but it is unclear from the documentation how slot utilization is computed.
You pay for flat rate with a monthly rate, and if I look at out our slot utlization over a month in Stack driver it is consistently reported under 500 slots. But if I change to graphing out the daily utilization we sometimes peak over 2000 slots.
So is the allocated slots we are allowed to use measured against average or peak usage?

A: Allocated slots are counted against peak usage. With a 500 slot quota you can never utilize more than 500 slots at the same time. The result is that your query takes longer to run.


text:
Q: Fix Kendo UI Grid Pagination style I have recently updated my Kendo UI DLLs on my project, and now on all my grids, the pagination style has changed dramatically.
BEFORE:

AFTER:

What can I do to regain the old pagination style?


text:
Q: How to import website to WordPress I have a website written in HTML5 and CSS3 and I want to use this site in WordPress. I tried to upload it like template, but it didn't work. How can I solve this issue?

A: Sirko pointed you in the right direction. WordPress relies on PHP processing and MySQL database so you cannot simply upload it to the theme folder and activate. The HTML and CSS theme will need to be modified to incorporate the core WordPress theme development, at least. It isn't that difficult if you understand how WordPress works.
If you simply want to start with converting the theme to WordPress to support pages and menus alone, it isn't so complicated. If you are very new to this, it might be a stumbling block. You really should learn the core components to making a WP theme. Good luck!
Elegant themes walkthrough - HTML converted to WordPress

A: Your question is far too general to answer without you narrowing the scope; start with https://codex.wordpress.org/Main_Page to find out how to install and run WordPress, read https://codex.wordpress.org/Theme_Development if you want to adapt your current design to a WordPress theme. And you will need to import content, either by the database or manual entry with the WordPress editor. Read up and then come back to SO with more specific questions.

A: There is a reason why people sell themes either with HTML5 and Wordpress, though seperate in nature but structural in bound.
It is a long process but simple if you have knowledge of websites:
https://www.elegantthemes.com/blog/tips-tricks/converting-html-sites-to-wordpress-sites
Same as Markatledge said previously, by following the link above it can help you.


text:
Q: Determine interior and boundary of $A\times B$ Let $(X,\mathcal{O}_X)$ and $(Y,\mathcal{O}_Y)$ be topological spaces and $A,B$ subset of $X,Y$ respectively. I have to find the interior $(A\times B)^\circ$ and the boundary $\partial(A\times B)$. Furthermore, it is that the open sets are given by the product topology on $A\times B$.
This sounds pretty easy, nevertheless I am not quite sure what exactly I should show. The interior and boundary both depend on the topology itself. Is this context to general to actually "show" something?

A: (To remove the question from unanswered).
According to Exercise 2.3.B from [Eng], $(A\times B)^\circ=A^\circ\times B^\circ$ and $\partial(A\times B)=\partial A\times \overline{B}\cup \overline{A}\times \partial B$. Prove this.
By Proposition 2.3.1 from [Eng], the set $A^\circ\times B^\circ$ is open, so $A^\circ\times B^\circ\subset (A\times B)^\circ$. On the other hand, let $(x,y)\in (A\times B)^\circ$ be any point. Then there exists an element $U\times V$ of the canonical base at $X\times Y$ such that $(x,y)\in U\times V\subset  A\times B$. Then $U\subset A$ and $V\subset B$. Since $U$ and $V$ are open in $X$ and $Y$, respectively, we have $U\subset A^\circ$ and  $V\subset B^\circ$. Then $(x,y)\in A^\circ\times B^\circ$.
By Proposition 2.3.3 from [Eng], $\overline{A\times B}=\overline A\times \overline B$, so
$$\partial(A\times B)=$$ $$\overline{A\times B}\setminus (A\times B)^\circ=$$
$$\overline A\times \overline B \setminus A^\circ\times B^\circ =$$ $$
((\partial A\cup A^\circ)\times (\partial B\cup B^\circ)) \setminus A^\circ\times B^\circ=$$ $$\partial A\times \partial B\cup \partial A\times B^\circ \cup A^\circ \times \partial B=$$ $$(\partial A\times \partial B\cup \partial A\times B^\circ)\cup
(\partial A\times \partial B\cup A^\circ \times \partial B)=$$ $$ \partial A\times \overline{B}\cup \overline{A}\times \partial B.$$
References
[Eng]  Ryszard Engelking, General Topology, 2nd ed., Heldermann, Berlin, 1989.


text:
Q: How do Permanent Magnet Generators Work? Why we don't use this in our houses to generate the electricity? Isn't the electricity generated by the magnets strong enough? Why do we have to pay for electricity if we can just create it by pushing the magnets attached to a rotor of the generator?

A: You can't get 'free' energy, as energy cannot be created or destroyed. All 'free energy' devices are scams.
In order to generate electricity with a generator, you have to provide energy. If you turn the crank manually, that energy comes from your food, which comes from plants, who get their energy from the sun, which gets its energy from nuclear fusion.
If you are curious about how generators work, you can read about it here.

A: And to expand on Kvothe's answer, the cost of the extra food you would need would exceed the cost of the regular fuel that you save.  In addition, who wants to spend their life turning a generator?


text:
Q: Streamlining Parameter Passing I am reading through Code Complete and had a question about "Streamlining parameter passing". The author says that if you are passing a parameter among several routines, that might indicate a need to factor those routines into a class that share the parameter as class data.
Does this mean that if I have several separate class that use the same data I should create one new class that uses that data and then inherit to make new classes?
Or
Does this mean that if I have a bunch of loose routines in my program I should go ahead and put them into a class and get the benefits of encapsulation, etc.

A: The latter. It looks like they're talking about a case like this:
void function_1(std::string& my_data);
void function_2(std::string& my_data);

void main() {
    std::string my_data = "SomeString";
    function_1(my_data);
    function_2(my_data);
}

Which could be changed to:
class MyClass {
    std::string my_data;
public:
    MyClass(const std::string& str) : my_data(str) {}
    void function_1();
    void function_2();
}

void main() {
    MyClass obj("SomeString");
    obj.function_1();
    obj.function_2();
}

Where function_1 and function_2 use the my_data field, instead of having to be passed the string every time.


text:
Q: Text on one line I really have very little programming experience, but, I'm willing to learn - I found code for a countdown clock, but the text is not arranged the way I want it. I'd like it to be:
         Only
       **1905**
Days Until June 1, 2018

and then have it all centered. It's centered, but the last part of the counter stacks itself. Here is the code I am using:

    Only

    Days Until

June 1, 2018

A: That code you found it is obviously ancient, but the problem is the
 tag at the line:

June 1, 2018

This is an HTML line break.  Remove it and the line will not break.

A: Try this:

Only

****

Days Until


text:
Q: Decomposition of Modules Every finitely generated module $M$ over a principal ideal domain $R$ is isomorphic to a direct sum of cyclic modules. If $M=M_n(\mathbb Z)$, the matrices of order $n$ over the integers. What is the  decomposition in sum of cyclic modules of $M_n(\mathbb Z)$?

A: As was suggested above, the additive group on the $n\times n$ matrices is just a sum of $n^2$ copies of $\mathbb{Z}$, as isn't hard to see: it's torsion-free, in particular. I could imagine you were thinking about how to make the multiplicative structure work, but the theorem only applies to modules, not algebras. The algebra $M_n$ is not a sum of cyclic $\mathbb{Z}$-algebras, since all of the latter are commutative.