text:
Q: SQL Execute Task partially works I have a SQL Execute Task in my SSIS template that will either TRUNCATE or CREATE based on whether the table exists but the problem I'm encountering is if the script runs in sequence w/ all the other tasks in the Control Flow, it will not create the table if it doesn't exist. If I stop the package, and execute the SQL script by itself, it works just fine. Any pointers would be appreciated.
SQL Script:
IF object_id('[RAW].[TABLE_NAME]') is not null
    TRUNCATE TABLE [RAW].[TABLE_NAME];
ELSE
    BEGIN
        CREATE TABLE RAW.TABLE_NAME
        (
            [Sys_ID] BIGINT NOT NULL,
            [Report_Date] DATE,
            [Ingestion_Date] DATE
        PRIMARY KEY CLUSTERED
        (
            [Sys_ID] ASC
        )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
        ) ON [PRIMARY]

        ALTER TABLE [RAW].[TABLE_NAME] ADD  DEFAULT (NEXT VALUE FOR [dbo].[TABLE_SEQUENCE]) FOR [Sys_ID]
    END

A: This answer aims to resolve session conflicts. It is more of a suggestion than a solution..
A couple remarks first:

*

*There is [Primary] on the creation of the table

*You are using two different schemas dbo & raw

Regarding what I mentioned on the comment about dynamic code:
DECLARE @SQL NVARCHAR(MAX)

IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[RAW].[TABLE_NAME]') AND type in (N'U'))
BEGIN
    SET @SQL = 'TRUNCATE TABLE [RAW].[TABLE_NAME]'
    EXEC (@SQL)
END
ELSE
BEGIN
    SET @SQL = ' CREATE TABLE RAW.TABLE_NAME
                (
                    [Sys_ID] BIGINT NOT NULL,
            [Report_Date] DATE,
                [Ingestion_Date] DATE
            PRIMARY KEY CLUSTERED
            (
                [Sys_ID] ASC
            )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
            ) ON [PRIMARY]'
EXEC (@SQL)
SET @SQL = 'ALTER TABLE [RAW].[TABLE_NAME] ADD  DEFAULT (NEXT VALUE FOR [dbo].[TABLE_SEQUENCE]) FOR [Sys_ID]'
EXEC(@SQL)
END

A: Thank you to everyone who contributed to helping me resolve this issue. However, this was a major oversight on my part! I failed to set "ValidateExternalMetadata" for my OLE DB Destination to "False". The package was attempting to locate the table and failed in the event that it did not exist before reaching my SQL script to create the table.

A: Change truncate to drop
IF object_id('[RAW].[TABLE_NAME]') is not null
TRUNCATE TABLE [RAW].[TABLE_NAME];   -->> DROP TABLE [RAW].[TABLE_NAME];


text:
Q: collectionViewLayout.collectionViewContentSize getting SIGABRT I tried following this solution (How to determine height of UICollectionView with FlowLayout) to determine the size of my UICollectionViewLayout in order to size cells accordingly. My code below calls the collectionViewContentSize, which throws an error upon being called:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let frameWidth  = collectionViewLayout.collectionViewContentSize.width
    let maxCellWidth = (frameWidth) / (7.0/6.0 + 6.0)
    let frameHeight  = collectionViewLayout.collectionViewContentSize.height
    let maxCellHeight = frameHeight

    let cellEdge = maxCellWidth < maxCellHeight ? maxCellWidth : maxCellHeight

    return CGSize(width: cellEdge, height: cellEdge)
}

The error is the Thread 1 SIGABRT.
Any idea why this does not work?

A: You are probably getting infinite recursion because in order to know the content size of the collection view, it needs to know the size of each item. The whole reason the collection view is calling sizeForItemAt is to determine the content size of the collection view.
The good news is that there is no reason for you to ask for the collection view's content size. Instead, base your item's size on the size of the collection view itself, not its content size.
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let frameWidth  = collectionView.frame.width
    let maxCellWidth = (frameWidth) / (7.0/6.0 + 6.0)
    let frameHeight  = collectionView.frame.height
    let maxCellHeight = frameHeight

    let cellEdge = maxCellWidth < maxCellHeight ? maxCellWidth : maxCellHeight

    return CGSize(width: cellEdge, height: cellEdge)
}

redpajama_set_name: RedPajamaStackExchange


text: Q: How to expand one row at a time in nested PrimeFaces datatable I am using PrimeFaces 4.0 and I want to expand one row at a time and other rows should be collapsed.  I have a requirement to open a single row at a time. I have seen solution for the same question but when I am trying to implement that on a data table inside a data table , it is collapsing the parent datable also....I need to collapse only child table inside parent data table.


text:
Q: CSS 3 Transitions with Opacity - Chrome and Firefox I've been playing around with CSS3 transitions to fade in an overlay div when I came a cross an odd problem.
Basically I have a div element that has styles set on it's id - i.e. background-color: #000, opacity: 0, etc. As well as the browser-specific transition styles.  By default the overlay element has a "hiddenElement" class on it, setting it's display to none.
When the overlay is to be displayed the hiddenElement class is removed, and another class is added "Initialised", this class sets the elements opacity to 0.6.
What I expected to happen was for the element to be animated in smoothly, which does happen in Opera, but in firefox and chrome it doesn't work exactly like that.
I've built an isolated case here: http://jsbin.com/obojet/27/.
As you can see when the "addClass('Initialised')" is wrapped in a setTimeout(), even with a timeout of 0ms in chrome, it animates correctly. Just doing addClass outside a timeout, wont do the animation.  In firefox, the timeout has to be longer - 50ms.  In opera it just works.
It's probably down to the UI/Javascript contending for the single thread, but I was just curious if anyone else had experience similar issues.

A: I've had all sorts of issues with this.  It's a really bad part of the CSS3 transitions specification because the spec says nothing about this type of behavior.
The predictable way to do this is:

*

*Set initial state of object.

*Set transition related CSS3 on the object.

*Object must not be display: none at this point.

*Let browser return to event loop and repaint anything that needs repainting to establish pre-animation state.

*Then add a class to the object that sets the final state and triggers the animation.

*Return to browser event loop for the animation to take place.

The unpredictable way to do this is:

*

*Anything involving display: none in any of the states.

*Set intital state and CSS3 transition rules

*Set final state without letting browser go back to the event loop.

*Go back to event loop (often times the CSS3 transition will not go).

I see value in being able to change a whole bunch of properties at once programmatically without triggering the start of the CSS3 transition.  But, it is not unusual that you want to establish the initial state with a bunch of code, programmatically set up the transition you want to have happen and then set the final state all in one piece of code.  Today, you can't do that and get reliable behavior.   You will have to insert some setTimeout calls in the middle.  What would be nice would be to have a synchronous function call for setting the initial state that would say to the browser: OK, I'm doing setting the initial state of this object.  Any changes I make from now on, I want you to include in the CSS3 transitions I have set.  Then, you wouldn't need the extra setTimeout non-sense.
Your example shows this type of thing.  You could make it work without the setTimeout by having your initial state be opacity: 0; instead of display: none;, though I realize that may not be what you want.  Then, the initial state (without display: none) would be seen by the browser before you establish the final state and the transition should work.


text:
Q: img is not loading when change the image by using javascript This is my code i can't understand what is wrong with in this.

Click the light bulb to turn on/off the light

Default image is Displaying when page come in browser but when I click the image changing image is not loading

A: You aren't using valid file protocols (file:///C:/mydir/index.html) to access the files. As others have said, move them "next" to your html file and just use the file name without a path (e.g. light_bulb_off3.jpg), or change your paths to something valid (e.g. file:///C:/Users/ashokch/Desktop/light_bulb_off3.jpg)

A: Try this:

Please notice the file:/// protocol handler. And / (slash) instead off \(backslash).
It is used to show local files in your browser.
But this only works for local files.
If you want the webserver to serve these images, create a folder in your webserver root folder.
Example
/images

And store your images in that folder.
Then point your image src or javascript attribs to the absolute path.

This will take your current url, strip out the hostname and protocol and append the src.
Example
http://www.example.org/folder/test.html

Absolute means, with protocol and hostname/path.
Relative means, relative to the root of your current domain (without any path).

A: Upload your images to a free image hosting website like  :-
http://photobucket.com/   or
https://imageshack.com/
Use the new weblinks to the images & check if it works.
"bulbon" ???  What's it ?

A: Your image path should be relative to your project/code directory instead of the file system. Either copy the images into the project directory or give a relative path. That would solve the issue.


text:
Q: Spliting database according to user's ID I have a database of 5m rows and it grows and it's getting harder and harder to do operations with it.
Is it a good idea to split the table in 10 tables (v0_table, v1_table... v9_table), where the number(v*) is the first number of the user's id?
The user's id in my case are not auto-increment so it would sort the data evenly across those 10 tables.
The problem is I have never done similar things....
Can anyone spot any disadvantages?
EDIT:
I would appreciate any help with tuning the structure or the query.
So the slowest query is the following one:
SELECT logos.user,
       logos.date,
       logos.level,
       logos.title,
       Count(guesses.id),
       Sum(guesses.points)
FROM   logos
       LEFT JOIN guesses
              ON guesses.user = '".$user['uid']."'
                 AND guesses.done = '1'
                 AND guesses.logo = logos.id
WHERE  open = '1'
GROUP  BY level

Where guesses table:
+--------+------------+------+-----+-------------------+----------------+
| Field  | Type       | Null | Key | Default           | Extra          |
+--------+------------+------+-----+-------------------+----------------+
| id     | int(11)    | NO   | PRI | NULL              | auto_increment |
| logo   | int(11)    | NO   | MUL | NULL              |                |
| user   | int(11)    | NO   | MUL | NULL              |                |
| date   | timestamp  | NO   |     | CURRENT_TIMESTAMP |                |
| points | int(4)     | YES  | MUL | 100               |                |
| done   | tinyint(1) | NO   | MUL | 0                 |                |
+--------+------------+------+-----+-------------------+----------------+

LOGOS table:
+-------+--------------+------+-----+-------------------+----------------+
| Field | Type         | Null | Key | Default           | Extra          |
+-------+--------------+------+-----+-------------------+----------------+
| id    | int(11)      | NO   | PRI | NULL              | auto_increment |
| name  | varchar(100) | NO   |     | NULL              |                |
| img   | varchar(222) | NO   | MUL | NULL              |                |
| level | int(3)       | NO   | MUL | NULL              |                |
| date  | timestamp    | NO   | MUL | CURRENT_TIMESTAMP |                |
| user  | int(11)      | NO   | MUL | NULL              |                |
| open  | tinyint(1)   | NO   | MUL | 0                 |                |
+-------+--------------+------+-----+-------------------+----------------+

EXPLAIN:
+----+-------------+---------+------+----------------+------+---------+-------+------+----------------------------------------------+
| id | select_type | table   | type | possible_keys  | key  | key_len | ref   | rows | Extra                                        |
+----+-------------+---------+------+----------------+------+---------+-------+------+----------------------------------------------+
|  1 | SIMPLE      | logos   | ref  | open           | open | 1       | const |  521 | Using where; Using temporary; Using filesort |
|  1 | SIMPLE      | guesses | ref  | done,user,logo | user | 4       | const |   87 |                                              |
+----+-------------+---------+------+----------------+------+---------+-------+------+----------------------------------------------+

A: Short and sweet:  No.  This is never a good idea.  Is your table properly indexed?  Is MySQL properly tuned?  Are your queries efficient?  Are you using any caching?

A: Instead of sharding your table, you may want to examine other tables in your database to see if they can be split off into other dbs. For example tables, that are never joined to are great candidates for this type of vertical partitioning.
This allows you to optimize hardware for smaller sets of data.

A: Your problem isn't that you have too much data, it's that this data is not properly indexed. Try adding an index:
CREATE INDEX open_level ON logos(open, level)

This should eliminate Using temporary; Using filesort on logos.
Basically, you need an index on this table for this query to cover two things: open - for WHERE  open = '1' and level - for GROUP  BY level in this order, as MySQL will first filter by open, then will group the results by level (implicitly sorting by it in process).


text:
Q: Complete blanks by last non-blank value in R I'm struggling to solve this apparently simple question in R, but no suceess until now.
I have a data.frame with a char variable having some blanks and some non-blank values. I'm trying to complete those blanks with the last non-blank found into the same variable from top-down as in the following example related do variable 'Species' in data.frame 'want' vs 'have'.
If someone could help, I thanks in advance!
set.seed(12346)
foi <- split(iris, iris$Species)
want <- do.call("rbind", lapply(foi, function(x){
  x[1:sample(1:10, 1), ]
}))
row.names(want) <- NULL
want$Species <- as.character(want$Species)

have <- want
have$Species[2:10] <- ""
have$Species[12:16] <- ""
have$Species[18:21] <- ""

head(have, 20)
head(want, 20)

A: A simple for loop assuming the first value is non missing:
for(i in which(have$Species=="")) have$Species[i]=have$Species[i-1]

You could split your variable by block of consecutive blank values and fill each block with the first previous non blank value if speed is an issue and your file is huge.


text:
Q: no recomposition (Jetpack Compose) How can I start recomposition in my buttons?
As far as I understand something in the list itself needs to be changed, how can I go about this?
data class KeyData(var text: String, val size: Int, var colour: Color)

val firstRowKeyboard = listOf("Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P")
    .map { text: String -> KeyData(text, 35, Color.White) }.toMutableStateList()

// I tried both ways, but nothing changes

val secondRowKeyboard = "ASDFGHJKL".toCharArray()
    .map { text: Char -> KeyData(text.toString(), 35, Color.White) }.toMutableStateList()

and the trigger:
    fun checkKeyboard() {
    for (i in 0..9){
        val letter = firstRowKeyboard[i]
        if (letter.text in yellowLetterList){
            firstRowKeyboard[i] = letter.copy(colour = Color.Yellow)
        }
    }
}

and my composables:
@Composable
fun Keyboard() {
    Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly) {
        viewModel.firstRowKeyboard.forEach {
            MyKeyboardButton(it.text, it.size, it.colour)
        }
    }
}

@Composable
fun MyKeyboardButton(text: String, width: Int, colour: Color) {

    val buttonColour by remember {
        mutableStateOf(colour)
    }

    Button(
        onClick = {
            viewModel.addLettersToGrid(text)
        },
        modifier = Modifier
            .width(width.dp)
            .height(60.dp)
            .padding(0.dp, 2.dp),
        colors = ButtonDefaults.buttonColors(backgroundColor = buttonColour),
        border = BorderStroke(2.dp, Color.LightGray)
    ) {
        Text(text = text, textAlign = TextAlign.Center)
    }
}

the colour is changing in the list, so something is working, however recomposition is never triggered.
If the colour of the KeyData changing isnt enough then would I need to change the text within the list? What is a good alternative?

A: You are not setting
val buttonColour by remember {
    mutableStateOf(colour)
}

other than in composition.
Thera are few options you can take
First one is not that good but it still will work
  val buttonColour by remember {
        mutableStateOf(colour)
    }

   buttonColour = colour

or
  val buttonColour by remember(colour) {
        mutableStateOf(colour)
    }

And better option is to remove
 val buttonColour by remember(colour) {
        mutableStateOf(colour)
    }

from MyKeyboardButton
@Composable
fun MyKeyboardButton(text: String, width: Int, colour: Color) {

    Button(
        onClick = {
            viewModel.addLettersToGrid(text)
        },
        modifier = Modifier
            .width(width.dp)
            .height(60.dp)
            .padding(0.dp, 2.dp),
        colors = ButtonDefaults.buttonColors(backgroundColor = colour),
        border = BorderStroke(2.dp, Color.LightGray)
    ) {
        Text(text = text, textAlign = TextAlign.Center)
    }
}

and change it to a stateless Composable since you pass color from ViewModel.


text:
Q: Get the value from a default constraint I need to change a default constraint value from 0 to 1. This is done easy with:
ALTER TABLE table DROP CONSTRAINT X
ALTER TABLE table ADD CONSTRAINT X default (1) for table.column

The problem is that I don't want to drop and create a new constraint every time I run modelupdate on my database. That's why I want to run this code IF the value of the constraint is 0.
Is it possible to check the value of a default constraint in SQL, if yes, how?

A: You can find the "definition" of the default constraint like this:
SELECT
    DefaultConstraintName = df.name,
    df.definition
FROM
    sys.default_constraints df
INNER JOIN
    sys.tables t ON df.parent_object_id = t.object_id
INNER JOIN
    sys.columns c ON c.object_id = df.parent_object_id AND df.parent_column_id = c.column_id
WHERE
    t.Name = N'YourTableNameHere'
    AND c.Name = N'YourColumnNameHere'

That however will be returning a string representation of your default value - not the actual value itself (in whatever datatype it is). But that might help you find what you need

A: You can see the default value for the column from the below information_schema view.
SELECT COLUMN_DEFAULT FROM INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'TableName' and COLUMN_NAME = 'ColumnName'


text:
Q: Trouble Turning Computer On Basically - once my PC is 'ON' it stays on for hours or even days with no trouble.  When I shut it down (none of that hibernate stuff - 100% off)...it won't turn back on when I hit the 'power' button.
It seems like the way to fix this is to give the computer a good smack...after a few hits, the power button will once again turn on the PC.
I've had this problem for a while now and it seems to be getting worse.  I've replaced cases and the problem remains - so I'm fairly confident it's not a bad power-on button.
I want to fix this - but I don't know what is really going on.  My guess is that it is a bad power supply.  I've completely taken apart and reassembled my computer - it didn't help (so I don't think it is simply a loose cable somewhere).
Does this sound like a PS issue?  Is it possible my motherboard is at fault?  Is there any way for me to test these things without purchasing new hardware?

A: It sounds like a discipline problem ... give it a really good smack.
No, no, more seriously, it may be a faulty connection (a dry solder joint?) caused by cooling from operating temperature to room temperature. What's the ambient temperatue there?
This kind of fault may be diagnosed if you apply a electronic 'freeze spray' to selected parts of the PC one at a time, while it's running, so the faulty component or connection is cooled and behaves as if the PC has been switched off for a while.
All the parts you mentioned would be potential candidates. Either take the PC to a repair person or try yourself with 'freeze spray' from an electronics DIY retailer.

A: Do you know how hot your computer runs on average?  I've seen cases where someone wasn't careful when processing video on their laptop and ended up sustaining 200°F for a minute or two, causing erratic behavior from then on until it finally died 3 months later.


text:
Q: Efficient way to construct datetime64 and pandas time series? The time series index in pandas uses numpy datetime64 type.
Is there any efficient way to construct datetime64 objects?
The only ways I have seen on documents are either from a string or from a python datetime object.
If I have a large number of time stamps (millions), represented in epoch time (in terms of seconds from 1970-01-01), or nano sec epoch time (number of ns from 1970-01-01), is there any fast way to convert the integer to numpy datetime64?
Internally numpy.datetime64 is also represented in integers.
I do not want to convert epoch time to string or python datetime object then convert to numpy.datetime64, since it is too inefficient for large amount of data.

A: pd.to_datetime will convert epoch timestamps as documented in the link:
dt = pd.to_datetime([1349720105, 1349806505, 1349892905,
         1349979305, 1350065705], unit='s')

print(dt)
DatetimeIndex(['2012-10-08 18:15:05', '2012-10-09 18:15:05',
           '2012-10-10 18:15:05', '2012-10-11 18:15:05',
           '2012-10-12 18:15:05'],
          dtype='datetime64[ns]', freq=None, tz=None)

A: Yes there is one. However I haven't measure the performance. According to http://docs.scipy.org/doc/numpy-dev/reference/arrays.datetime.html
import numpy as np
a = np.datetime64('1970-01-01') + np.timedelta64(1, 's')

or
a = np.datetime64('1970-01-01') + np.timedelta64(100, 'ns')


text:
Q: yii2 checkbox not working its always submit 0 in POST I have a simple field is_active in form tinyint in db also defined as integer in rules when I submit form checkbox checked or unchecked it's always submitting 0.
echo $form->field($model, 'is_active')->checkbox();

A: I use this when dealing with my form's checkboxes:
$model= (isset($_POST['is_active'])) ? 1 : 0;
Also make sure you don't set a specific value for the checkbox. Otherwise you will get strange results.

A: This patch worked for me, but I am still wondering why this issue has not been reported yet on yii2 platform or I am doing something wrong here
diff --git a/vendor/yiisoft/yii2/helpers/BaseHtml.php b/vendor/yiisoft/yii2/helpers/BaseHtml.php
index 66a5730..d2bd49c 100644
--- a/vendor/yiisoft/yii2/helpers/BaseHtml.php
+++ b/vendor/yiisoft/yii2/helpers/BaseHtml.php
@@ -706,10 +706,10 @@ class BaseHtml
      *
      * @return string the generated checkbox tag
      */
-    public static function checkbox($name, $checked = false, $options = [])
+    public static function checkbox($name, $value, $checked = false, $options = [])
     {
         $options['checked'] = (bool) $checked;
-        $value = array_key_exists('value', $options) ? $options['value'] : '1';
+        //$value = array_key_exists('value', $options) ? $options['value'] : '1';
         if (isset($options['uncheck'])) {
             // add a hidden field so that if the checkbox is not selected, it still submits a value
             $hidden = static::hiddenInput($name, $options['uncheck']);
@@ -892,7 +892,7 @@ class BaseHtml
             if ($formatter !== null) {
                 $lines[] = call_user_func($formatter, $index, $label, $name, $checked, $value);
             } else {
-                $lines[] = static::checkbox($name, $checked, array_merge($itemOptions, [
+                $lines[] = static::checkbox($name, $value, $checked, array_merge($itemOptions, [
                     'value' => $value,
                     'label' => $encode ? static::encode($label) : $label,
                 ]));
@@ -1446,7 +1446,7 @@ class BaseHtml
             $options['id'] = static::getInputId($model, $attribute);
         }

-        return static::checkbox($name, $checked, $options);
+        return static::checkbox($name, $value, $checked, $options);
     }

     /**


text:
Q: Solaris pstack output: what does "SYS#0" mean? I encountered "SYS#0" at the top of a stack and cannot find any documentation as to what that means.

*

*Compiler: g++

*OS: Solaris 9

*Arch: SPARC

*Memory Manager libhoard_32.so from Hoard 3.5.1
We used "gcore" to generate a core file. Looking at the output of running the "pstack" command against the core file, the only thread that was doing anything interesting had the following at the very top of its call stack:
ff309858 SYS#0    ()
ff309848 void MyHashMap<const void*,unsigned,AlignedMmapInstance<65536U>::SourceHeap>::set(const void*,unsigned) (ff31eed4, 9bf20000, 10000, 40, 9bf1fff0, ff31e738) + 134
...

pflags for that LWP shows:
/8:   flags = PR_STOPPED|PR_ISTOP|PR_ASLEEP
why = PR_REQUESTED
sigmask = 0xfffffeff,0x00003fff

I could not find any mention of this syntax in the Sun documentation.
Edit: The process appears to have hung sometime prior to doing the gcore. Is "SYS#0" somehow interrelated with process hangs?
Edit: Added next stack frame and link to Hoard, pflags output
Edit: The accepted answer is correct. In addition, at least on SPARC, the g1 register should contain the system call number, but this did not appear to be the case in our core file.
The topic "what is an indirect system call?" is probably good material for another question.

A: Try this:
$ cat foo.c
#include <stdio.h>

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

    char buf[1024];
    proc_sysname(0, buf, 1024);
    printf("%s\n", buf);

}
$ gcc -ofoo -lproc foo.c
$ ./foo
SYS#0
$

SYS#0 is therefore the string that represents system call zero. If you look in <sys/syscall.h> (the system call table) you will find the following:
/* syscall enumeration MUST begin with 1 */

/*
 * SunOS/SPARC uses 0 for the indirect system call SYS_syscall
 * but this doesn't count because it is just another way
 * to specify the real system call number.
 */

#define SYS_syscall 0

The indirect system call syscall(SYS_syscall, foo, bar, ...) is equivalent to the direct call syscall(foo, bar, ...).


text:
Q: insert into database having large number of parameter i have to insert data into database .Because sql statement VALUES(......) have 8 parameters . Is it proficient way to use insert statement ?
    Class UserRegistration {
public void insertToDatabase(){
       String sql=" INSERT INTO db1(......) Values(id,fname,lastname,username,password,usertype,email,contact,address )"
}

}

A: The correct way to do it in Java, assuming you're using JDBC, is to use a PreparedStatement.
String sql = "INSERT INTO db1" +
            " (id,fname,lastname,username,password,usertype,email,contact,address)" +
            " VALUES (?,?,?,?,?,?,?,?,?)";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
    stmt.setInt   (1, id);
    stmt.setString(2, fname);
    stmt.setString(3, lastname);
    stmt.setString(4, username);
    stmt.setString(5, password);
    stmt.setString(6, usertype);
    stmt.setString(7, email);
    stmt.setString(8, contact);
    stmt.setString(9, address);
    stmt.executeUpdate();
}


text:
Q: Issue with xarray.open_raterio() img file and multiprocessing Pool I am trying to use mutliprocessing Pool.map() to speed up my code. In the function where I have computation occurring for each process I reference an xarray.DataArray that was opened using xarray.open_rasterio(). However, I receive errors similar to this:
rasterio.errors.RasterioIOError: Read or write failed. /net/home_stu/cfite/data/CDL/2019/2019_30m_cdls.img, band 1: IReadBlock failed at X offset 190, Y offset 115: Unable to open external data file: /net/home_stu/cfite/data/CDL/2019/
I assume this is some issue related to the same file being referenced simultaneously while another worker is opening it too? I use DataArray.sel() to select small portions of the raster grid that I work with since the entire .img file is way to big to load all at once.  I have tried opening the .img file in the main code and then just referencing to it in my function, and I've tried opening/closing it in the function that is being passed to Pool.map() - and receive errors like this regardless. Is my file corrupted, or will I just not be able to work with this file using multiprocessing Pool? I am very new to working with multiprocessing, so any advice is appreciated. Here is an example of my code:
import pandas as pd
import xarray as xr
import numpy as np
from multiprocessing import Pool

def select_grid(x,y):
    ds = xr.open_rasterio('myrasterfile.img') #opening large file with xarray
    grid = ds.sel(x=slice(x,x+50), y=slice(y,y+50))
    ds.close()
    return grid

def myfunction(row):
    x = row.x
    y = row.y
    mygrid = select_grid(x,y)
    my_calculation = mygrid.sum() #example calculation, but really I am doing multiple calculations
    my_calculation.to_csv('filename.csv')

with Pool(30) as p:
    p.map(myfunction, list_of_df_rows)


text:
Q: Impala raise " AnalysisException: Syntax error" when using ROW_NUMBER() OVER I have a query like this:
SELECT MONTH_ID, 'Total' AS cola, colb
FROM
(
    SELECT A.*, ROW_NUMBER()OVER(PARTITION BY MONTH_ID,col3 ORDER BY col4 DESC) AS ROWN
    FROM
        (
            SELECT A.*, B.col3
            FROM table1 A
            LEFT JOIN table2 B
            ON A.col1 = B.col1
        ) A
)
WHERE ROWN=1
GROUP BY MONTH_ID

If I create a intermediate table with the subqueries this query can work. But when I run entire thing Impala will raise: "AnalysisException: Syntax error in line 12:undefined: WHERE ROWN = 1 ^ Encountered: WHERE Expected: AS, DEFAULT, IDENTIFIER CAUSED BY: Exception: Syntax error"
I tried run this in Hive, different error shows: "Error while compiling statement: FAILED: ParseException line 20:4 cannot recognize input near 'WHERE' 'ROWN' '=' in subquery source"
Then I tried same query in oracle, it works...
Could anyone explain why this is happening and how to solve this?
Thank you for your help ;)

A: Subquery should have some alias like this (see comment in the code):
SELECT MONTH_ID, 'Total' AS cola, colb
FROM
(
    SELECT A.*, ROW_NUMBER()OVER(PARTITION BY MONTH_ID,col3 ORDER BY col4 DESC) AS ROWN
    FROM
        (
            SELECT A.*, B.col3
            FROM table1 A
            LEFT JOIN table2 B
            ON A.col1 = B.col1
        ) A
) B ----------------------------Alias is a must --------------
WHERE ROWN=1
GROUP BY MONTH_ID, colb -----All columns which are not aggregated and not constants should be in GROUP BY


text:
Q: How to obtain absolute img src url with Jquery I want to get all the absolute urls of a website's images to display them, but I need the absolute url of a $('img').
I tried:
$('img').attr('src')

but it only returned relative urls of a single one, I am using map to solve the problem of multiple images but still. How do I get the absolute url?

A: Use .prop instead of .attr. This accesses the dynamic property, which is after canonicalization, rather than the static DOM attribute.

alert($('img').prop('src'));

See .prop() vs .attr()

A: This should give the absolute url for the first picture, of course you can loop through all of them:
$('img')[0].src

for (var i = 0; i<$('img').length;i++) {
alert($('img')[i].src)
}


text:
Q: Add an active class to a filter link AngularJS I have set up my site using AngularJS so the data is looped and displays correctly. I also have a menu on the side that when you click each link will show only that category however I cannot seem to be able to add the active class on each link as they are clicked (and obviously removed when clicked on another category) I either have all the links with active or none. Unfortunately have tried to get this to work on js fiddle but the code that is working for me locally is not working. Hopefully someone can point me in the right direction.
Js file:
var myApp = angular.module('myApp', ['ngSanitize']);

myApp.factory('Videos', function () {
    var Videos = {};
    Videos.video = [{
        Title: "VIDEO TITLE",
        SubHeading: "SUBTITLE",
        Category: "CATEGORY 1",
        Version: "1",
        url: "asdfghjkl;",
        image: "IMAGE",
        alt: "Image alt",
        description: "Some Text",
        link: "LINK",
        link2: "LINK2"
    }, {
        Title: "VIDEO TITLE 2",
        SubHeading: "SUBTITLE",
        Category: "CATEGORY 2",
        Version: "1",
        url: "asdfghjkl;",
        image: "IMAGE",
        alt: "Image alt",
        description: "Some Text",
        link: "LINK",
        link2: "LINK2"
    }, {
        Title: "VIDEO TITLE 3",
        SubHeading: "SUBTITLE",
        Category: "CATEGORY 3",
        Version: "1",
        url: "asdfghjkl;",
        image: "IMAGE",
        alt: "Image alt",
        description: "Some Text",
        link: "LINK",
        link2: "LINK2"
    }, {
        Title: "VIDEO TITLE 4",
        SubHeading: "SUBTITLE",
        Category: "CATEGORY 1",
        Version: "1",
        url: "asdfghjkl;",
        image: "IMAGE",
        alt: "Image alt",
        description: "Some Text",
        link: "LINK",
        link2: "LINK2"
    }, {
        Title: "VIDEO TITLE 5",
        SubHeading: "SUBTITLE",
        Category: "CATEGORY 5",
        Version: "1",
        url: "asdfghjkl;",
        image: "IMAGE",
        alt: "Image alt",
        description: "Some Text",
        link: "LINK",
        link2: "LINK2"
    }, {
        Title: "VIDEO TITLE 6",
        SubHeading: "SUBTITLE",
        Category: "CATEGORY 6",
        Version: "1",
        url: "asdfghjkl;",
        image: "IMAGE",
        alt: "Image alt",
        description: "Some Text",
        link: "LINK",
        link2: "LINK2"
    }, {
        Title: "VIDEO TITLE 7",
        SubHeading: "SUBTITLE",
        Category: "CATEGORY 7",
        Version: "1",
        url: "asdfghjkl;",
        image: "IMAGE",
        alt: "Image alt",
        description: "Some Text",
        link: "LINK",
        link2: "LINK2"
    }, {
        Title: "VIDEO TITLE 8",
        SubHeading: "SUBTITLE",
        Category: "CATEGORY 2",
        Version: "1",
        url: "asdfghjkl;",
        image: "IMAGE",
        alt: "Image alt",
        description: "Some Text",
        link: "LINK",
        link2: "LINK2"
    }, {
        Title: "VIDEO TITLE 9",
        SubHeading: "SUBTITLE",
        Category: "CATEGORY 3",
        Version: "1",
        url: "asdfghjkl;",
        image: "IMAGE",
        alt: "Image alt",
        description: "Some Text",
        link: "LINK",
        link2: "LINK2"
    }, {
        Title: "VIDEO TITLE 10",
        SubHeading: "SUBTITLE",
        Category: "CATEGORY 4",
        Version: "1",
        url: "asdfghjkl;",
        image: "IMAGE",
        alt: "Image alt",
        description: "Some Text",
        link: "LINK",
        link2: "LINK2"
    }];
    return Videos;
});

function VideoCtrl($scope, Videos) {
    $scope.filters = {};
    $scope.videos = Videos;
}

HTML:

            PAGE TITLE

        {{video.Version}}

{{video.link}}

{{video.Category}}

                 Video Categories

                Category 1
                Category 2
                Category 3
                Category 4
                Category 5
                Category 6
                Category 7

As far as I can work out I need to add something like ng-class="{ active: clicked }" to each link but am unsure how to proceed on the js side as each example I have seen is either way more complex or much simpler. So basically I want when I click on Category 1 only the items that are in Category 1 are showing (which is working) and also the link for Category 1 to have an active class applied.
After that I would like to be able at the same time to change the page title to change to a heading specified for each Category.

A: You can use the fact that the currently selected category is on the scope.
ng-class="{active: filters.Category == 'Category 1'}"

Example: http://plnkr.co/edit/vcuJECCSM7KHJaU9eZKq?p=preview


text:
Q: Single switch to connect internal and external NICs? We have bunch of servers with two NICs, one is configured with internal IP and one with external IPs. Planning to use a single switch to connect them all together.
Here is the current setup:
--Router---Firewall--ExternalSwitch--NIC1
                     InternalSwitch--NIC2

Each of the server has dual NICs and we are connecting one NIC to 'external-switch'
and one NIC to 'internal-switch'.
Also there is no internal-router we are using one of the internal IPs as default gateway,
which i think can be left blank? The idea of using one switch came up since the external-switch was a 8-port one and was running out of ports. What is the best way to use the dual NICs in our scenario?

A: You don't tell us enough to really help you here, but I can tell you that your design as diagrammed is for all intents and purposes completely wrong (or vastly oversimplified, so as to lose all relevant information and thus be completely wrong).
As diagrammed you have no separation between internal and external networks (you're glomming everything into the same switch, presumably the same VLAN) which effectively negates any potential security benefits you might be hoping to gain - the only thing you might gain is performance if you routinely saturate one of the NICs (and that could be achieved through other methods).

To have any semblance of proper separation you need two switches (or two separate VLANs on a switch that supports VLANs).  Internal communication should be completely isolated from external communication, as shown here

Note that from a security standpoint even this illustrated configuration is still a terrible one. With a few rare exceptions you should never have a computer in the situation illustrated above (dual-homed with one NIC on the inside network and one NIC on the outside network) because it is a HUGE security risk: If someone compromises that machine they now have access to your internal network.
A better configuration would be a proper DMZ with restricted access through a firewall to internal resources.


text:
Q: Access 2007 using a DAO recordset to add record to the END of a table I have a report template in Word that pulls tables from an Access 2007 database.  The tables should be exactly structured as they should appear in the report since we want to do a minimal amount of post-processing a formatting after updating the fields in the template.
In one step I use some VBA and a DAO.RecordSet to add a TOTAL row to the bottom of the table.  The last bit there under "Add the total row" is where the row is added.
I want this row to be the LAST row in the table so when we update the fields in the Word report we don't have to move it around.  About 90% of the time it works all the time :) but occasionally it will put the Total row at the top.  I'm not sure how to force it to the bottom of the table.  Any hints or workarounds?
I've found a SQL statement is even worse, it almost always adds the total row to the top.
Thanks!
'Add the total row.
rs1.MoveLast
rs1.AddNew
rs1.Fields(fname) = "Total"
rs1.Fields("Frequency") = TotalSum
rs1.Fields("Percent") = "100.0%"
rs1.Update

rs1.Close

A: In a relational database, there is no such thing as first or last, only an order that you impose with a field on which to sort. This is often an ID or date. Add a suitable field and then sort by that field when extracting the data. When adding a record, make sure it fits in the sequence you want by updating the sort field.


text:
Q: Counting length of strings and "padding" it I'm doing an assignment which requires a method with a string and an int as parameters. The method should pad the parameter string with spaces until its length is the given length. For instance, padString("hello", 8 should return "hello___"(the _ represents the three spaces)) If the int is higher than the length of the string, then it would simply return the string. I'm having trouble getting the "padding" part of the program down.
As this assignment is early on in the book, I assume it can be done with beginner stuff such as forloops, parameters, and common string methods as I'm not supposed to use if/else statements yet.
Here's the—obviously flawed—code that I have currently:
public class Exercise11 {

public static final String word = "congratulations";
public static final int length = 10;

public static void main(String[] args) {
    padString();

}

public static String padString(String word, int length) {
    if (word.length() >= length) {
        return word.substring(0,length + 1);
    } else {
        String thing = word;
        return word + addSpaces(word, length);
    }

}

public static void addSpaces(String word, int length) {
    for (int i = 1; i <= length-word.length(); i++) {
            return (" ");
        }
}

}

By the way, is there a way to add something such as spaces onto a String variable with a for loop? Thanks for the help.

A: That's a reasonable start...
padString is expecting two parameters, a String and int, so this...
public static void main(String[] args) {
    padString();
}

Could be changed to...
public static void main(String[] args) {
    padString(word, length);
}

The next problem is in you addSpaces method.  The return statement in your loop means that the loop will only ever execute once and will only ever return a single space character.
Instead, you need to be concatenating the space on each loop to a temporary String, which you will pass back, for example...
public static String addSpaces(String word, int length) {
    StringBuilder sb = new StringBuilder(length);
    for (int i = 0; i < length - word.length(); i++) {
        sb.append(" ");
    }
    return sb.toString();
}

So, if I run...
System.out.println("[" + padString("hello", length) + "]");

I get [hello     ]

A: The immediate problem is that your for loop in addSpaces is immediately returning a single space, no matter how many spaces you need to add to it. A better approach would be for addSpaces to return String and to add spaces to an internal String variable until it was the correct length, then return that.
Also, in Java, it's customary to start loops from zero unless there's a particularly strong reason to start somewhere else. In your case, word.length() might be a good starting point, but 1 isn't.

A: Your add spaces returning  nothing.It's void.And internal logic also not fulfilling your requirements.
Your addSpaces  method should something like
public static String addSpaces(String word, int length) {
     String spaces="";
    for (int i = 1; i <= length-word.length(); i++) {
           spaces +=  " ";
        }
     return  spaces;
}

And prefer to use StringBuilder to append instead String for better performance.
With StringBuilder
 public static String addSpaces(String word, int length) {
         StringBuilder spaces=new StringBuilder();
        for (int i = 1; i <= length-word.length(); i++) {
               StringBuilder.append(" ");
            }
         return  spaces.toString();
    }

Then you return word + addSpaces(word, length);  works perfect.Assuming i did'nt miss anything else :).

A: Thanks guys, it finally works now.
Here's the final copy of the code:
public class Exercise11 {

public static final String WORD = "congratulations";
public static final int LENGTH = 10;

public static void main(String[] args) {
    System.out.println(padString(WORD, LENGTH));
}

private static String padString(String word, int length) {
    if (word.length() >= length) {
        return word.substring(0,word.length());
    } else {
        return word + addSpaces(word, length);
    }

}

public static String addSpaces(String word, int length) {
    StringBuilder sb = new StringBuilder(length);
    for (int i = 0; i < length - word.length(); i++) {
        sb.append("_"); // these are more visible than empty spaces
    }
    return sb.toString();
}

}

I still have a couple question however. What is the point of constructing the "Stringbuilder" and what is the "append" method?
Because the book doesn't have these things at this point, is there another method?


text:
Q: How to use mouse scroll as an event to simulate a click So, hello everyone, I am a python, sort of beginner, programmer and recently I have the problem that for some reasons, I wanna use the mouse scroll wheel as a left-click, basically, rotating the scroll wheel once simulates the left click(or any key/click) once, I have been having difficulty in doing this so any help would be appreciated!!!!!!!!!!!

A: You can install mouse package
pip install mouse

And then send custom mouse events to your program.
# scroll down
mouse.wheel(-1)

# scroll up
mouse.wheel(1)

# left click
mouse.click('left')

# right click
mouse.click('right')

# middle click
mouse.click('middle')

take a look at: https://pypi.org/project/mouse/


text:
Q: How to Add values in a table together using jQuery? I have an HTML table with number values. What I need to do is to get all these values and add them together using jQuery.
Any ideas?

Example table:
http://pastie.org/998759

A: You can call .each:
var sum = 0;

$('table td').each(function() {
    sum += parseFloat($(this).text());
});

A: I'm going to give you some pseudo-code of how I would do it (mainly because I can't be stuffed writing the whole thing).

*

*Create an object/array/variables to store the totals.

*jQuery select the table

*Use .each() to loop through each tr.

*Loop each td and add the value to the relevant total.

*Once all of the tr have been looped through, do whatever you want :)

Hope this helps you out :)
EDIT: I was writing the code as if you wanted to total each column, rather than all cells into a single total.

A: It's already been answered. So just as a fun exercise:
// Give all arrays the power of summation
Array.prototype.sum = function(){
    for( var i=0,sum=0;i<this.length;sum+=this[i++] );
    return sum;
}

// Use map for kicks
$(document).ready( function(){
    var result = $('table#mytable tr td').map( function(){
        return parseFloat( $(this).text() );
    }).get().sum();
});


text:
Q: IOS ABPerson is Member of ABGroup Is there a fast way in the Address Book framework on the iOS platform to determine which groups a particular address book record belongs too?  I have been slogging through the docs and it looks like the answer is no.
I need to quickly slap up a list of groups and a checkmark to indicate membership for a particular address book entry.  Right now it looks like I need to build the list of groups and group members then search it.  Since group membership can be changed in multiple places, I have no easy way of persisting the information between launches and ensuring its still valid.
Thanks for any help.
Rich

A: yes you are right. In iOS you can't fast and easy get group membership of contact.
you can iterate groups arrays only every time :(


text:
Q: Matplotlib code not executing due to labels? I'm using the salem_executions_data.csv, this is how it looks like:
year,month,accusations,executions
1962,1,0,0
1962,2,3,0
1962,3,4,0
1962,4,22,0
1962,5,39,0
1962,6,3,1
1962,7,12,5
1962,8,23,5
1962,9,33,9
1962,10,1,0
1962,11,3,0
1962,12,0,0
1963,1,0,0
1963,2,0,0
1963,3,0,0

Working with Python 2.7, what I wanted was to:

*

*Load the csv file

*Make a accusations vs executions using 3d scatter

And what I have so far is this:
import matplotlib.pyplot as plt
import csv

x = []
y = []

with open('data/salem_executions_data.csv','r') as csvfile:
    plots = csv.reader(csvfile, delimiter=',')
    from itertools import islice

    for row in islice(plots,1,None):

        for row in plots:
            temp=row[int(str(2))]
            x.append(temp)
            temp=row[int(str(3))]
            y.append(temp)

plt.plot(x,y)
plt.xlabel('Accusations')
plt.ylabel('Executions')
plt.title('Accusations vs Executions')
plt.legend()
plt.show()

Once I execute this cells I get no output code... Any help?
After adding %matplotlib inline this is the output I get, do you think its okay?
enter image description here
Update v3:
After changing plt.plot to plt.scatter:
enter image description here

A:
I get a scatter. I have not changed anything from your code.  The only change i have made is to make it a scatter plot by replacing your code plt.plot(x,y) with plt.plot(x,y,'.')


text:
Q: I need help developing a google script to generate a product list I am very green at google script but I am trying to build a project that will:

*

*take 2 inputs (a name and item #) on a list on sheet A (pink cells in image) and copy/paste them to specific 2 cell range (green cells in image) at the top of the sheet. These values generate an output on the first 4 rows of the sheet (blue cells) that is a template for my products. I did creat named ranges for those cells. I think...
Image ->Picture of My "SheetA"

*Insert 4 rows on the top of sheet B. *This is an image of Sheet B

*Copy these new values from the first 4 rows on sheet A and paste them into the newly inserted rows on sheet B.

*Repeat

I have been trying to build the function myself, but I am very inexperienced. I really do just want to learn though, so if you can help me understand anything that gets me closer to making this work, I would really appreciate it!
Here is my code so far:
function onOpen() {
  var spreadsheet = SpreadsheetApp.getActive();
  var menuItems = [
    {name: 'Prepare sheet...', functionName: 'prepareSheet_'},
    {name: 'Generate products...', functionName: 'generateProduct_'}
  ];
  spreadsheet.addMenu('Directions', menuItems);
}

function generateProduct_() {
    var i = 0
    var generatorCells = nameCell + ":" + numberCell;
    var nameCell = new String("A"+i);
    var numberCell = new String("B"+i);
    var generatorCells = nameCell + ":" + numberCell;
    var nameCellResults = new String("A"+(i*5));
    var numberCellResults = new String("B"+(i*5));
    for (var i=11;CELL_EMPTY = false; i++) {
  spreadsheet.getRange(generatorCells).copyTo(getRange(productGenCells)), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false;
  spreadsheet.getRange('2:5').copyTo(sheet.getRange(genResults),{contentsOnly:true}, spreadsheetApp.CopyPasteType.PASTE_VALUES, true);
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Results'), true);
   spreadsheet.getActiveSheet().insertRowsBefore(spreadsheet.getActiveRange().getRow(), 4);
  spreadsheet.getActiveRange().offset(0, 0, 1, spreadsheet.getActiveRange().getNumColumns()).activate();
  spreadsheet.getRange('productGen!2:5').copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('productGen'), true);
  spreadsheet.getRange('2:2').activate();
  }
};

A: If you run your code through https://jshint.com/ (or similar) it will pick up numerous issues. Some corrected code below. But the most glaring issue is the conditional test in the for loop.
1) Firstly a single = (assignment) operator is used instead of a double == (test)
2) The value that is supposedly tested for CELL_EMPTY is not set in the loop.
3) this should probably be a while loop anyway.
function onOpen() {
  var spreadsheet = SpreadsheetApp.getActive();
  var menuItems = [
    {name: 'Prepare sheet...', functionName: 'prepareSheet_'},
    {name: 'Generate products...', functionName: 'generateProduct_'}
  ];
  spreadsheet.addMenu('Directions', menuItems);
}

function generateProduct() {
    var i = 0;
    var nameCell = "A"+i;
    var numberCell = "B"+i;
    var generatorCells = nameCell + ":" + numberCell;
    var nameCellResults = "A"+(i*5);
    var numberCellResults = "B"+(i*5);
    for (i=11;CELL_EMPTY == false; i++) {
        spreadsheet.getRange(generatorCells.copyTo(getRange(productGenCells)), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
          spreadsheet.getRange('2:5').copyTo(sheet.getRange(genResults),{contentsOnly:true}, spreadsheetApp.CopyPasteType.PASTE_VALUES, true);
          spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Results'), true);
          spreadsheet.getActiveSheet().insertRowsBefore(spreadsheet.getActiveRange().getRow(), 4);
          spreadsheet.getActiveRange().offset(0, 0, 1, spreadsheet.getActiveRange().getNumColumns()).activate();
          spreadsheet.getRange('productGen!2:5').copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
          spreadsheet.setActiveSheet(spreadsheet.getSheetByName('productGen'), true);
          spreadsheet.getRange('2:2').activate();
        }
}


text:
Q: Remove lines from tab-delimited file with missing values I have a large (~900MB) tab-delimited text file that I will be processing in a downstream program.  I need to delete any line with a missing value.  The correct number of columns are on each line (so a missing value would correspond to 2 tabs).
Note: My actual data has ~2 million lines and 80-300 columns.  Possible characters are a-z A-Z 0-9 - (hyphen) _ (underscore) and tab (delimited).  No spaces or special characters are in the file.
I am new to this kind of scripting, so an explanation of any code provided would be appreciated. I normally use R, but my filesizes have outgrown the data manipulation functionality of R.
How can I at the terminal (or within a shell script) delete lines with missing values from a file (e.g. using sed)?
Example Input File:
Col1    Col2    Col3
A        B        C
D                 F
G        H        I
J        K

Example Output File:
Col1    Col2    Col3
A        B        C
G        H        I

A: With awk:
awk -F"\t" '$1!=""&&$2!=""&&$3!=""' file

Actually it is that simple.

*

*awk splits the input at the field separator tab \t specified with the -F flag. This could also be omitted, when your content has no spaces in the fields.

*$1!=""&&... is a condition. When this condition is true, awk simply prints the line. You could also write '$1!=""&&$2!=""&&$3!=""{print}', but that's not necessary. Awks default behavior is to print the line, when no action is given. Here, that condition is true when the fields $1, $2 and $3 all are not empty, hence when the first 3 fields have a value.

To write to another file use this:
awk -F"\t" '$1!=""&&$2!=""&&$3!=""' input_file >output_file

Edit: With an undefined number of columns you could use this awk, it check every field in the line:
awk -F"\t" '{for(i=1;i<=NF;i++){if($i==""){next}}}1' file

A: ...for any of the below to work you must first do...
t=$(printf \\t)          ### because it's hard to demo CTRL+V TAB

...now, with a POSIX grep...
grep -Ev "^$t+|$t($t|$)"     <in >out

grep will select lines which do not match the pattern - which uses the | or metacharacter to denote a ^head-of-line tab, or two consecutive tabs, or a $tail-of-line tab - which are the only possible fail cases as near as I can tell.
without the -vnegation switch it might be:
grep -E "([^$t]+$t){2}[^$t]" <in >out

...which specifies an {occurrence count} for the (pattern group) of + one or more chars in the [class] of characters which are ^ not tabs followed by a tab.

...or with a POSIX sed...
sed -ne"s/[^$t][^$t]*/&/3p"  <in >out

...or...
sed -ne"s/[^$t]\{1,\}/&/3p"  <in >out

...or w/ GNU or BSD seds...
sed -Ene"s/[^$t]+/&/3p"      <in >out

...where sed does -not print by default any line unless it can s///ubstitute for &itself the third occurrence on a line of the longest possible sequence of at least one [^not tab] character.

(using literal tabs should be preferred for portability. the original version of this answer used \backslash escapes and it was not helpful. definitely using \backslash escapes in a [character class] will limit the applicability of your code.)

A: If your fields can never contain whitespace, an empty field means either a tab as a first character (^\t), a tab as the last character (\t$) or two consecutive tabs (\t\t). You could therefore filter out lines containing any of those:
grep -Ev $'^\t|\t\t|\t$' file

If you can have whitespace, things get more complex. If your fields can begin with spaces, use this instead (it considers a field with only spaces to be empty):
grep -Pv '\t\s*(\t|$)|\t$|^\t' file

The change filters out lines matching a tab followed by 0 or more spaces and then either another tab or the end of the line.
That will also fail if the last field contains nothing but spaces. To avoid that too, use perl with the -F and -a options to split input into the @F array, telling it to print unless one of the fields is empty (/^$/):
perl -F'\t' -lane 'print unless grep{/^$/} @F' file

A: awk 'NF==3' file

Prints a line if number of fields equals 3. Pretty straightforward to change number of columns according to your data.
However as pointed out, this doesn't work with OP's requirement of variable number of fields.

A: You can try something like this:
grep "^[a-zA-Z0-9]\+[[:space:]][a-zA-Z0-9]\+[[:space:]][a-zA-Z0-9]\+$" input_file > output_file

The purpose of grep is to (or not to) find strings in one or more files that match a given pattern. Here, the pattern [a-zA-Z0-9]\+ matches one or more alphanumeric characters, which is followed by a whitespace or tab. The beginning of a line is matched by ^, whereas $ indicates the end of line. If other characters are used in the columns, they should be added to the character class above. Finally, > redirects the matched output to the output file.
Please also look at @terdon's comment below for potential pitfalls and an alternative solution. Note that if you are working in Linux/Unix environments, the usefulness of grep goes much beyond this particular solution.

A: I have more generic way to do this task
<$your_file perl -CASD -ne 'print if not grep { /^$/ } split "\t"'

@terdon: You are right, now it works as expected.

A: This is one perl can do quite neatly:
perl -lane 'print if @F==3';

autosplits into the array @F and if the number of fields is 3, it prints.
Edit: You can auto-configure the field number:
perl -lane '$cols //= @F; print if @F == $cols'

This will set the $cols variable to the number of columns on the first line (which from your example, is the header row).
Note - it doesn't work with white spaced fields (other examples above are more appropriate for that. Something like using -F"\t" to set the delimiter and grep to filter the empty fields)
Note //= is a conditional assignment - it assigns if no value is currently defined. It's also a newer perl feature, and I'm aware there's some quite old perl versions in circulation. (5.8.8 pops up fairly frequently).
If this doesn't work on your version, ||= should do the trick just fine - that's a conditional assignment too, that tests 'truth'. Which should work fine with your data set. (It handles '0' and '' differently to // but those shouldn't show up).


text:
Q: jquery - selecting by css class new to web.
I am trying to know if user has clicked on div with css a certain class
my class html element is as follows

my event target value is
$(event.target): jQuery.fn.init[1]
   0: div.icon arrowIcon arrowLight tagIcon

and the function
($(event.target).find('.tagIcon').length > 0)

returns false.
Any idea?

A: find searches the children. You should check if your element has the class you want:
$(event.target).hasClass("tagIcon")

A: find() finds matching element(s) inside the element it is called on. It does not matter if the element itself matches the selector.
Change your check to:
($(event.target).is('.tagIcon'))


text:
Q: C++11 : Atomic variable : lock_free property : What does it mean? I wanted to understand what does one mean by lock_free property of atomic variables in c++11. I did googled out and saw the other relevant questions on this forum but still having partial understanding. Appreciate if someone can explain it end-to-end and in simple way.

A: It's probably easiest to start by talking about what would happen if it was not lock-free.
The most obvious way to handle most atomic tasks is by locking. For example, to ensure that only one thread writes to a variable at a time, you can protect it with a mutex. Any code that's going to write to the variable needs obtain the mutex before doing the write (and release it afterwards). Only one thread can own the mutex at a time, so as long as all the threads follow the protocol, no more than one can write at any given time.
If you're not careful, however, this can be open to deadlock. For example, let's assume you need to write to two different variables (each protected by a mutex) as an atomic operation -- i.e., you need to ensure that when you write to one, you also write to the other). In such a case, if you aren't careful, you can cause a deadlock. For example, let's call the two mutexes A and B. Thread 1 obtains mutex A, then tries to get mutex B. At the same time, thread 2 obtains mutex B, and then tries to get mutex A. Since each is holding one mutex, neither can obtain both, and neither can progress toward its goal.
There are various strategies to avoid them (e.g., all threads always try to obtain the mutexes in the same order, or upon failure to obtain a mutex within a reasonable period of time, each thread releases the mutex it holds, waits some random amount of time, and then tries again).
With lock-free programming, however, we (obviously enough) don't use locks. This means that a deadlock like above simply cannot happen. When done properly, you can guarantee that all threads continuously progress toward their goal. Contrary to popular belief, it does not mean the code will necessarily run any faster than well written code using locks. It does, however, mean that deadlocks like the above (and some other types of problems like livelocks and some types of race conditions) are eliminated.
Now, as to exactly how you do that: the answer is short and simple: it varies -- widely. In a lot of cases, you're looking at specific hardware support for doing certain specific operations atomically. Your code either uses those directly, or extends them to give  higher level operations that are still atomic and lock free. It's even possible (though only rarely practical) to implement lock-free atomic operations without hardware support (but given its impracticality, I'll pass on trying to go into more detail about it, at least for now).

A: Jerry already mentioned common correctness problems with locks, i.e. they're hard to understand and program correctly.
Another danger with locks is that you lose determinism regarding your execution time: if a thread that has acquired a lock gets delayed (e.g. descheduled by the operating system, or "swapped out"), then it is possible that the entire program is delayed because it is waiting for the lock. By contrast, a lock-free algorithm is always guaranteed to make some progress, even if any number of threads are held up somewhere else.
By and large, lock-free programming is often slower (sometimes significantly so) than locked programming using non-atomic operations, because atomic operations cause a significant hit on caching and pipelining; however, it offers determinism and upper bounds on latency (at least overall latency of your process; as @J99 observed, individual threads may still be starved as long as enough other threads are making progress). Your program may get a lot slower, but it never locks up entirely and always makes some progress.
The very nature of hardware architectures allows for certain small operations to be intrinsically atomic. In fact, this is a very necessity of any hardware that supports multitasking and multithreading. At the very heart of any synchronisation primitive, such as a mutex, you need some sort of atomic instruction that guarantees correct locking behaviour.
So, with that in mind, we now know that it is possible for certain types like booleans and machine-sized integers to be loaded, stored and exchanged atomically. Thus when we wrap such a type into an std::atomic template, we can expect that the resulting data type will indeed offer load, store and exchange operations that do not use locks. By contrast, your library implementation is always allowed to implement an atomic Foo as an ordinary Foo guarded by a lock.
To test whether an atomic object is lock-free, you can use the is_lock_free member function. Additionally, there are ATOMIC_*_LOCK_FREE macros that tell you whether atomic primitive types potentially have a lock-free instantiation. If you are writing concurrent algorithms that you want to be lock-free, you should thus include an assertion that your atomic objects are indeed lock-free, or a static assertion on the macro to have value 2 (meaning that every object of the corresponding type is always lock-free).

A: Lock-free is one of the non-blocking techniques. For an algorithm, it involves a global progress property: whenever a thread of the program is active, it can make a forward step in its action, for itself or eventually for the other.
Lock-free algorithms are supposed to have a better behavior under heavy contentions where threads acting on a shared resources may spent a lot of time waiting for their next active time slice. They are also almost mandatory in context where you can't lock, like interrupt handlers.
Implementations of lock-free algorithms almost always rely on Compare-and-Swap (some may used things like ll/sc) and strategy where visible modification can be simplified to one value (mostly pointer) change, making it a linearization point, and looping over this modification if the value has change. Most of the time, these algorithms try to complete jobs of other threads when possible. A good example is the lock-free queue of Micheal&Scott (http://www.cs.rochester.edu/research/synchronization/pseudocode/queues.html).
For lower-level instructions like Compare-and-Swap, it means that the implementation (probably the micro-code of the corresponding instruction) is wait-free (see http://www.diku.dk/OLD/undervisning/2005f/dat-os/skrifter/lockfree.pdf)
For the sake of completeness, wait-free algorithm enforces progression for each threads: each operations are guaranteed to terminate in a finite number of steps.


text:
Q: Need help on determining the time complexity of a square grid So I am currently learning time complexity on my Data Structures class and I kind of got lost while doing an exercise. In the exercise I have a grid of 16 vertices so I have that T(n)=T(16), so I would have that the total of edges equals 24. For the exercise I had to do a general formula for T(n). The formula I used was T(n)=[sqrt(n)*(sqrt(n)-1)]*2 = 2(n - sqrt(n)). Now the part I got stuck is that the exercise  also asks me to prove that T(n) ϵ θ(n) by determining C1,C2 and n0. For that part I have done the following: c1n <= 2n - 2sqrt(n) <= c2n
                *Dividing by n: *
c1 <= 2 - 2/[sqrt(n)] <= c2

However I do not know how to proceed from there or if this is even the correct aproach to answering that part of the exercise. Any help on how to proceed would be greatly apreciated. Thanks in advance.

A: sqrt(n)*sqrt(n) - 1 == n - 1
Thus distributing the 2 gives T(n)=2*n - 2 not 2(n - sqrt(n)). I believe you have an arithmetic error.


text:
Q: Core Data : Post migration, additional migration code I wish to migrate from my version1 data model to version2, but once the migration is complete I wish to perform some custom migration code. How will I know if/when the migration occurs? Is there a migrationHasCompleed delegate method or notification?
For interests sake: The custom migration code I wish to perform resizes png's in the database.

A: For reference, you can also test in advance whether a migration is necessary, which would probably be cleaner.
NSError *error;
NSDictionary *sourceMetadata = [NSPersistentStoreCoordinator metadataForPersistentStoreOfType:NSSQLiteStoreType
                                                                                URL:storeURL
                                                                                error:&error];
NSManagedObjectModel *destinationModel = [persistentStoreCoordinator managedObjectModel];
BOOL migrationRequired = ![destinationModel isConfiguration:nil compatibleWithStoreMetadata:sourceMetadata];

// Now add persistent store with auto migration, and do the custom processing after

A: Well, you could run this code right after the migration happen, on your persistent store coordinator setup:
+ (NSPersistentStoreCoordinator *)persistentStoreCoordinatorForStore:(NSString *)store {
    NSURL *storeUrl = [NSURL fileURLWithPath:[[[self class] applicationDocumentsDirectory] stringByAppendingPathComponent:store]];

    NSError *error = nil;
    NSPersistentStoreCoordinator *persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[[self class] managedObjectModel]];

    // Check for model changes without trying to update
    if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]) {
        // Set the automatic update options for the current model
        NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                                 [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
                                 [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,
                                 nil];

        if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error]) {

            NSLog(@"Error opening the database. Deleting the file and trying again.");

            //delete the sqlite file and try again
            [[NSFileManager defaultManager] removeItemAtPath:storeUrl.path error:nil];
            if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error])
            {
                /*
                 Replace this implementation with code to handle the error appropriately.

                 abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.

                 Typical reasons for an error here include:
                 * The persistent store is not accessible
                 * The schema for the persistent store is incompatible with current managed object model
                 Check the error message to determine what the actual problem was.
                 */
                NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
                abort();
            }
        } else { // The model was updates successfuly
            // Implement here your custom migration code
        }

    }

    return [persistentStoreCoordinator autorelease];
}

Cheers,
vfn


text:
Q: Google Scripts Chart syntax and how do I colour a candlestick chart I am using Google Scripts to create a chart in Google Sheets however I have been having difficulties for a couple days now and I think it comes down to my lack of understanding of the syntax used by Google Scripts and its embedded chart object.
From my understand - and according to the syntax below:

To set the candlesticks rising colour to green I would do the following:
.setOption('candlestick', {risingColor: {fill: '#31d831'}})

However this doesn't work! I'd assume the syntax works like this:
candlestick.risingColor.fill
└────┬────┘ └────┬────┘ └──┴──────────────┐
     └───────┐   └──────────┐             │
.setOption('candlestick', {risingColor: {fill: '#31d831'}})

I made this assumption because this code here works:
.setOption('vAxes', {0: {viewWindow: {min: 1}}})

The documentation is similar:

vAxis.viewWindow.min
└─┬─┘ └────────┬┘└─┴───────────────────┐
  └──────────┐ └──────────┐            │
.setOption('vAxes', {0: {viewWindow: {min: 1}}})
                     |
┌────────────────────┴──────────────────────────────┐
This zero refers to the data set I would like to edit

Sidenote: While typing this I have also realised that I've spelt Axis wrong as Axes however this works Even through the documentation says Axis
I am thoroughly confused and I cannot find an answer anywhere my google-fu might of just been weak but I just cannot figure this out.
This is a similar question however they are not using embedded sheets and even when I copy their syntax it doesn't work!
Thank you in advance any help would be greatly appreciated!
Edit:
Here is the code I am using to generate my chart:
const chart = data.newChart()
    .setChartType(Charts.ChartType.CANDLESTICK)
    .addRange(candle.getRange("a:e"))
    .setOption('vAxes', {0: {viewWindow: {min: smallestValue-1, max: largestValue+1}}})
    .setOption('candlestick', {risingColor: {stroke: '#31d831'}, fallingColor: {stroke: '#d83131', fill: '#ffffff'}}) // This is the line that doesn't work because I am unsure of the syntax!
    .setOption('height', 735)
    .setOption('width', 1175)
    .setPosition(1, 1, 0, 0)
    .build()

candle.insertChart(chart)

This syntax is different to the syntax in the second answer in the possible duplicate.
The accepted answer in that possible duplicate asks the user to export the chart and grab the options from there after creating it with the charts GUI in Google Sheets. However you cannot edit the colours in google sheets GUI for the Candlestick chart!
I know colouring is possible for the candlestick chart as the example in the documentation does it (This syntax here does not work when using .setOption() as explained in my original question)
I have also tried this syntax which is seen in this question:
var chart = data.newChart()
    .setChartType(Charts.ChartType.CANDLESTICK)
    .addRange(candle.getRange("a:e"))
    .setOption('vAxes', {0: {viewWindow: {min: smallestValue-1, max: largestValue+1}}})
    .setOption('candlestick.risingColor.stroke', '#31d831')
    .setOption('candlestick.fallingColor.stroke', '#d83131')
    .setOption('candlestick.fallingColor.fill', '#ffffff')
    .setOption('height', 735)
    .setOption('width', 1175)
    .setPosition(1, 1, 0, 0)
    .build()

candle.insertChart(chart)

However this doesn't work either
Final edit for anyone else:
I have come to the conclusion that it is not possible to do what I am trying to do and with the help of TheMaster he has pointed me in the direction of using and taking advantage of the sidebar I have added this as an edit instead of the answer as maybe this might become possible one day and if it does It'd be nice to get this properly answered.
Good luck to anyone else looking into this in the future, keep me updated on its possibility!


text:
Q: How to exclude multiple ranges from the X-axis in ListPlot Here I have the codes for my Listplot.
α[δ_, s13_, s12_, θ12_,
   c13_] := (-180/2 π  ) ArcTan[
    s13^2 s12^2 Sin[
       2 δ Degree]/(c13^2 Cos[2 θ12 Degree] s12^2 +
        s13^2 s12^2 Sin[2 δ Degree])];

Tab1 = Table[{δ, α[δ,
     Random[Real, {0.1363, 0.157}], Random[Real, {0.5, 0.595}],
     Random[Real, {30.002, 36.6}],
     Random[Real, {0.9906, 0.9875}]]}, {δ, 0, 190, 1 Degree}];

P1 = ListPlot[Tab1, PlotRange -> {-25, 25},
  FrameLabel -> {δ, α}, Frame -> True,  PlotStyle -> Red,]

Here I want to omit the points from the plot obtained for the ranges of delta {20,50} and {125,150}. Please suggest how do I do that.

A: thorimur's answer explains various ways to remove parts of input data before plotting.
An alternative approach is to hide (rather than remove) parts of the data. This can be done by constructing white rectangles with appropriate coordinates and combine them with the  original plot using Show:
listplot = ListPlot[Tab1, PlotStyle -> Red, PlotRange -> {-25, 25},
   FrameLabel -> {δ, α}, Frame -> True];

hiddenranges = {{20, 50}, {125, 150}};

Show[listplot, Graphics @ {White,
  Rectangle[Scaled[{0, -1}, {#, 0}], Scaled[{0, 1}, {#2, 0}]] & @@@ hiddenranges}]

A: One way is to change the construction of Tab1 in the first place, and simply Join together the ranges that you are going to keep.
Another is to use Select, Cases, or DeleteCases to modify Tab1. With Select, one could do that as
Select[Tab1, Not[20 <= #[[1]] <= 50] && Not[125 <= #[[1]] <= 150] &]

This applies the function in the second argument to each element of the list, and throws away the ones that give False, keeping ("selecting") only those that give True.
As @Louis B mentioned in a comment, you can also represent the interval as Interval[{20, 50}, {125, 150}], and test for membership via IntervalMemberQ. As @Louis B says, the corresponding function to use in the second argument would be Not @ IntervalMemberQ[Interval[{20,50}, {125,150}], First[#]] &.
With DeleteCases, one could do that as
DeleteCases[Tab1, {_?(20 <= # <= 50 || 125 <= # <= 150 &), _}]

This deletes all parts of the expression that match the pattern in the second argument, which matches any list of two expressions, the first of which yields true under the function enclosed in parentheses after ?. Another way to write that pattern is
DeleteCases[Tab1, {x_, _} /; (20 <= x <= 50 || 125 <= x <= 150)]

where x now names the first blank pattern, and /; can be read as "on the condition that".
Hope this helps; let me know if anything is unclear or mysterious!


text:
Q: htmx: onLoad: "on full page load" and "on after swap" I would like to initialize a select element like in the tom-select Example with my own method:
<select id="select-repo" placeholder="Pick a repository..." multiple></select>

function my_select_init(el) {
  new TomSelect(el, {
    persist: false,
    createOnBlur: true,
    create: true
  })
}

There two different ways:
Case 1: The full page gets loaded
In this case you can use one of the modern onLoad methods.
For example:
document.addEventListener('DOMContentLoaded', function () {
  // do something here ...
}, false);

Case 2: the fragment get inserted into the DOM via htmx
How to initialize the snippet?
Preferred solution
I want the HTML and the on-load code to be in one place (Locality of Behaviour) and I want this html fragment to be the same for both cases.
Up to now I don't use Hyperscript or Alpine.js, but I am open to use one of these libraries, if this makes the solution simpler.

A: What you want to use is the htmx.onLoad callback:
  htmx.onLoad(function(elt) {
    // look up all elements with the tomselect class on it within the element
    var allSelects = htmx.findAll(elt, ".tomselect")
    for( select of allSelects ) {
      new TomSelect(select, {
                    persist: false,
                    createOnBlur: true,
                    create: true
                   });
    }
  })

This javascript will execute initially when the page is loaded on the body element, and then for all new content added by htmx to the page.
See https://htmx.org/docs/#3rd-party


text:
Q: libpng ndk-build internal compiler error in debug mode I use ndk-build to compile libpng source code in debug mode, then it shows "internal compiler error" in pngrtran.c. But when I compile in release mode, it can success. Is this a bug in libpng? How I can resolve this?

A: It's not a bug in libpng; anything a program describes as an "internal error" is a bug in the program (libpng does this, but then it shows "libpng: internal error"!)  So it's a bug in the compiler.
You should report it to the ndk guys or you could go directly to the compiler vendor (probably GNU) because they would likely to be more responsive.
You can't resolve the problem - it needs a compiler fix (maybe only to output a message that doesn't claim it's an internal error, but at least that.)  You can avoid the problem by simply not compiling libpng in debug mode.  Since I assume this is for Android so you can (I believe) mix-and-match debug and now debug code (this does NOT work on Windows with at least one compiler!)
You can also try working out which compiler option reveals the problem; compare the options being passed to the compiler in both release and debug, then bisect the differences to see if you can narrow the issue down to one setting.
John Bowler jbowler 2 acm.org

A: The android team should know about the bug. As Its a resurface of an old one:
http://code.google.com/p/android/issues/detail?id=20862


text:
Q: Mongoose doesn't update db entries I use express.js with mongoose as ODM.
I know mentioned that when other serives do an update to mongoDB, mongoose doesn't recognize this. So still shows the old state of the database.
I think this is because mongoose uses a callback to get updated after creating, updating a new document but this callback doesn't get fired when another service interacts with mongoDB.
So how can I manuelly say mongoose to look after not own created documents?
routes/user.js
var User = require('../models/user.js')
, requirements = { enabled: true, expired: false, locked: false };

exports.list = function(req, res){
    User.find(requirements, function(err, users){
        res.send(users);
    });
};

app.js
app.get('/users', user.list);

When I now access /users with curl or with the browser I am getting an array of all users in mongodb. Thats right until now. Now I register a new user over my PHP environment. When I now request /users again I still get the same array as before without the over php created user!
When I now restart the node service and request /users again the by php created user is there....

A: The express.js framework includes view caching which is enabled by default for production sites).  I suspect your results are getting cached because you have included a function reference (user.list) rather than a closure, eg:
app.get('/users', function(req, res){
    User.find(requirements, function(err, users){
        res.send(users);
    });
});

The view caching is a global setting and should only be caching the view template, not the contents of the view.  There was a request for more granular caching but it looks like this isn't required.
You can try disabling the view caching using:
app.disable('view cache');

A good resource to search or ask for clarification would be the Express.js Google Group.


text:
Q: HP DL180G6 - Getting a SATA HBA that works with the backplane I've got the above mentioned server in a particularly strange configuration right now. This is the 12x3.5" drive configuration model of the 180. From the backplane, the drives go into an HP Smart Array controller.
Problem: I'm not interested in the hardware RAID provided by this controller. I just want the drives to be passed through, raw, to the operating system for me to manage there.
This doesn't appear to be possible, from looking at some other questions. There's no JBOD mode on these controllers, and the workaround of just setting each individual volume to a single logical raid0 works, but means downtime for failures as the drives can't be swapped online.
So there are no doubt a boatload of SATA HBA's out there. I don't dare ask for recommendations at the risk of getting this question closed (but if the answer to this question is affirmative, feel free to throw a model number or two at me..), rather, I'm a bit more interested in if the backplane and system board support arbitrary HBAs. Can I plug any random SATA HBA in and have it work with this machine, or is there some special HP sauce that limits me to a tiny handful of first party controllers. Do these even exist?

A: There may be more to the design of the solution you're trying to build. But for your use case, if you are trying to use a software-defined-storage solution like ZFS or a software RAID setup, buy a simple SAS HBA.
The LSI 9211-8i will work well for this server chassis.

A: HP recently got a HP H240 Smart Host Bus Adapter, which is what was lacking for a long time - a HP branded HBA with ability to connect the HP server enclosures and get all sorts of software raids, including ZFS. Though H240 is PCIe 3.0, and HP DL180G6 has only 2.0 x8 slots, H240 should work in backwards compatibility mode.


text:
Q: Is there a way to make binding happen in a Silverlight control that is created in code? I'm wanting to print a UserControl that binds to a view model.  I create the control in code because if I don't it prints off the edge of the page.  Apparently, there is no way to control the size or scale of a printed UIElement without screwing up the element that is on the Silverlight page.  So I create the 'UserControl' with the following code in the PrintPage event of a PrintDocument:
    private void OnPrintPage(object sender, PrintPageEventArgs e)
    {
        PurchaseReceipt purchaseReceipt = new PurchaseReceipt();

        purchaseReceipt.DataContext = _receiptData;
        purchaseReceipt.Visibility = System.Windows.Visibility.Visible;

        purchaseReceipt.Margin = new Thickness(25.0);
        purchaseReceipt.Width = e.PrintableArea.Width - 50.0;

        e.PageVisual = purchaseReceipt;
    }

The problem is that binding doesn't work, or doesn't work in time. Is there a way to force an element to bind?


text:
Q: Check if applied migrations match the DbContext? I want to create a unit test to ensure no developer will commit model changes without the corresponding migration.
How do I test that the database matches the DbContext?

A: You can leverage some of the lower-level Migrations components to do that:
var migrationsAssembly = db.GetService<IMigrationsAssembly>();
var differ = db.GetService<IMigrationsModelDiffer>();

var hasDifferences = differ.HasDifferences(
    migrationsAssembly.ModelSnapshot.Model,
    db.Model);

Assert.False(hasDifferences, "You forgot to add a migration!");

A: Based on @bricelam's answer I created a generic method to test for applied migrations.
private static void ShouldMatchContext<T>()
  where T : DbContext
{
  using (var connection = new SqliteConnection("DataSource=:memory:"))
  {
    connection.Open();
    var builder = new DbContextOptionsBuilder<T>();
    var db = Activator.CreateInstance(typeof(T), builder.UseSqlite(connection).Options) as T;

    db.Database.EnsureCreated();

    var migrationsAssembly = db.GetService<IMigrationsAssembly>();
    var differ = db.GetService<IMigrationsModelDiffer>();

    bool hasDifferences = differ.HasDifferences(migrationsAssembly.ModelSnapshot?.Model, db.Model);

    Assert.False(hasDifferences);
  }
}


text:
Q: Calculation of a derivation $X\in \mathbb R^{m\times n}$ and $\|X\|_F$ be the Frobenius norm of $X$. How to calculate $\frac{\partial g(X)}{\partial X}$,
where
$g(X)=\frac{1}{2}\|X-X_k\|_F^2$,   $X = U\Sigma V^T = \sum_{i = 1}^{\min\{m,n\}}\sigma_iu_iv_i^T$ be the SVD of X, $\Sigma = diag(\sigma_1,\sigma_2,\ldots,\sigma_{\min{\{m,n\}}})$ and $\sigma_1,\sigma_2,\ldots $ are in noincreasing order, $X_k=\sum_{j = 1}^{k}\sigma_ju_jv_j^T$.


text:
Q: Custom Task Process I am trying to create a custom task process using SharePoint Designer. Once the approver approves the task, the approver should be able to select a person/group that will be notified of this outcome.
I tried creating a task form field so that it is available in the task completion form. I am successful up to this point because the form recognizes this field. I am able to add it to the canvas of the task form.
However, when I try to use this field on the workflow, and I presume this is treated as a parameter, I cannot find it. Thus, I cannot use the parameter in an action to send the notification email.

A: Adding a taskform field inside a custom task only makes it available inside this custom task, to get the value out to your main workflow do the following:

*

*In the main workflow start the task editor by clicking TaskName in Start Taskname process on ...

*In the customization section click Change the behavior of a single task

*Down in the When a Task Completes add a Set Variable where you set some new task variable to Current Task: FieldName

*Now you can go back to the main workflow which now has the value from the last task in the variable.


text:
Q: Evaluate the following: $(1-i)^{1+i}$ My progression:
$(1-i)^{i+1} = e^{(i+1) * \ln(1-i)}$. I get stuck after this point.

A: The expression $z^w$ where $z, w \in \mathbb{C}$ is not uniquely determined. In fact, we define
$$z^w = e^{w\log z}$$
where $\log z$ is any logarithm of $z$. There are infinitely many choices of $\log z$, and for most values of $z$ and $w$ there will be infinitely many possible values for $z^w$.
To get something unique, you will have to specify a particular branch of the complex logarithm, but when you do so. $z^w$ won't be defined for all $z$ (or at the very least $z^w$ won't be continuous in $z$, depending on what your conventions with branches are).
In your particular case $\log(1-i) = \ln \sqrt 2 - \dfrac{i\pi}4 + 2\pi i k$ for some arbitrary integer $k$, and
\begin{align}
(1-i)^{1+i} &= e^{(1+i)\log(1-i)} \\
&= e^{(1+i)(\ln \sqrt 2 - \frac{i\pi}4 + 2\pi i k)} \\
&= e^{ \ln \sqrt 2 + \frac\pi4-2\pi k + i(\ln\sqrt 2 - i\frac{\pi}4 + 2\pi k)} \\
&= \sqrt 2 e^{\frac\pi4-2\pi k\pi}\cdot e^{i(\ln\sqrt2-\frac\pi4)} \\
&= \sqrt 2 e^{\frac\pi4-2\pi k\pi}\cdot \big( \cos (\ln\sqrt2-\frac\pi4) + i \sin(\ln\sqrt2-\frac\pi4) \big) \\
\end{align}

A: $$\ln\left((1-i)^{(1+i)}\right)=(1+i)\ln(1-i)=(1+i)\left[\frac{1}{2}\ln(2)-\frac{1}{4}i\pi\right]$$
So:
$$\ln[(1-i)^{(1+i)}]=F=\frac{1}{2}\ln(2)(1+i)+\frac{1}{4}\pi(1-i)$$
and:
$$(1-i)^{(1+i)}=\exp(F)$$
and then:
$$(1-i)^{(1+i)}=(1+i)\left(\sin\left(\frac{1}{2}\ln(2)\right)-i\cos\left(\frac{1}{2}\ln(2)\right)\right)\exp\left(\frac{1}{4}\pi\right)$$

A: $n \in {\mathbb Z}$.
\begin{align}
\left(1 - {\rm i}\right)^{1 + {\rm i}}
&=
\left[\sqrt{2\,}\,{\rm e}^{{\rm i}\left(-\pi/4 + 2n\pi\right)}\right]
^{1 + {\rm i}}
=
\left(\sqrt{2\,}\,\right)^{1 + {\rm i}}
{\rm e}^{{\rm i}\left(-\pi/4 + 2n\pi\right) - \left(-\pi/4 + 2n\pi\right)}
\\[3mm]&=
\sqrt{2\,}\,{\rm e}^{\pi/4 - 2n\pi}\,
\left(\sqrt{2\,}\,\right)^{\rm i}
{\rm e}^{{\rm i}\left(-\pi/4 + 2n\pi\right)}
=
\left(1 - {\rm i}\right){\rm e}^{\pi/4 - 2n\pi}\,
2^{{\rm i}/2}
\\[3mm]&=
{\rm e}^{\pi/4 - 2n\pi}\,
{\rm e}^{{\rm i}\ln\left(2\right)/2}\left(1 - {\rm i}\right)
=
{\rm e}^{\pi/4 - 2n\pi}\,
\left[%
\cos\left({1 \over 2}\ln\left(2\right)\right)
+
{\rm i}\sin\left({1 \over 2}\ln\left(2\right)\right)
\right]\left(1 - {\rm i}\right)
\\
----&------------------------------------
\end{align}
\begin{align}
&n \in {\mathbb Z}\,,
\\[5mm]
&\color{#ff0000}{\left(1 - {\rm i}\right)^{1 + {\rm i}}}
\\&=
\color{#ff0000}{{\rm e}^{\pi/4 - 2n\pi}\times
\left\{%
\left[
\cos\left({1 \over 2}\ln\left(2\right)\right)
+
\sin\left({1 \over 2}\ln\left(2\right)\right)\right]
+
{\rm i}\left[%
-\cos\left({1 \over 2}\ln\left(2\right)\right)
+
\sin\left({1 \over 2}\ln\left(2\right)\right)\right]
\right\}}
\end{align}


text:
Q: Perfect example document (template) for English, Greek and Hebrew (XeLaTeX) EDIT 2 (23-2-2017): Changed the title and added that the example file in this post specifically works with XeLaTeX.
EDIT 1 (20-2-2017): Due to cfr's request, I have added a file. This is not the original, but a progress file, so to speak, based on cfr's example file. This one works with XeLaTeX:
\documentclass[12pt, a4paper, titlepage]{article}

\usepackage[hidelinks]{hyperref}
\usepackage{amssymb}
\usepackage{amsmath}
\usepackage{verbatim}
\usepackage{afterpage}
\usepackage[top=1.00in, bottom=1.00in, left=1.00in, right=1.00in]{geometry}
\usepackage{setspace}

%% for centering section titles
\usepackage[center]{titlesec}

\usepackage{polyglossia}

\setmainlanguage[variant=british]{english}
\setotherlanguage{hebrew}
\setotherlanguage{greek}
\newfontfamily\hebrewfont{SBL Hebrew}
\newfontfamily\greekfont{SBL Greek}

\title{Title}

%%   BEGIN DOCUMENT
\begin{document}
    \begin{titlepage}
        \maketitle
        \thispagestyle{empty}
    \end{titlepage}
    \pagenumbering{arabic}

\section{First}
\textgreek{αταραξία}. That was in Greek using SBL Greek.

\texthebrew{קֹהֶלֶת}. That was in Hebrew using SBL Hebrew.

\end{document}

OLD ORIGINAL POST:
Perhaps I am foolish in this regard, but I could not---after having tried to figure it out for a long time---manage to get a basic working file with English as the main language and Greek and Hebrew as the ones thrown in every now and then.
First I tried to add Hebrew to my existing working PdfLaTex document (that accepts English and Greek), but this is a very annoying and soul-killing process. Then, since many seem to recommend XeLaTex or LuaLatex, I tried these, but to no avail either (and also a soul-killing process; in fact, do I even have a soul left after all this? Is not the point of technology for the user that it serves him and not the other way around?).
I also followed the instructions in version 5.06 of The Not So Short Introduction to LaTeX 2ε. It is the part on XeLaTeX (starting on p. 34) in section 2.5.8 The Unicode option. Well, it didn't help me at all, even though I followed it.
So will someone please provide a basic working file for PdfLaTeX, XeLaTeX or LuaLaTeX (preferrably the best option) where English is the main language and Greek and Hebrew are the others?
I have installed, by the way, the Hebrew font called SBL Hebrew. For English and Greek I would simply use Computer Modern or something similar.

A: Update
babel's BIDI support is coming along nicely, and it's now possible to do this relatively painlessly. babel seems to be being more actively developed than polyglossia, so this is likely to be increasingly the way to go. It also works with both xelatex and lualatex.
\documentclass{article}
\usepackage[nil,bidi=default]{babel}
\babelprovide[import=en-GB,main]{british}
\babelprovide[import=he]{hebrew}
\babelprovide[import=el]{polutonikogreek}
\babelfont[british]{rm}{Latin Modern Roman}
\babelfont[hebrew]{rm}[Contextuals=Alternate]{SBL BibLit}
\babelfont[polutonikogreek]{rm}[Contextuals=Alternate]{SBL BibLit}
\usepackage{parskip}
\pagestyle{empty}
\begin{document}

\textsuperscript{1}In the beginning was the Word, and the Word was with God,
and the Word was God. \textsuperscript{2}He was with God in the beginning.
(John 1:1–2)

\selectlanguage{polutonikogreek}

\textsuperscript{1} Ἐν ἀρχῇ ἦν ὁ λόγος, καὶ ὁ λόγος ἦν πρὸς τὸν θεόν, καὶ θεὸς
ἦν ὁ λόγος. \textsuperscript{2}Οὗτος ἦν ἐν ἀρχῇ πρὸς τὸν θεόν.
\foreignlanguage{british}{(John 1:1–2)}

\selectlanguage{hebrew}

\textsuperscript{1}בְּרֵאשִׁ֖ית בָּרָ֣א אֱלֹהִ֑ים אֵ֥ת הַשָּׁמַ֖יִם וְאֵ֥ת הָאָֽרֶץ׃
\textsuperscript{2}וְהָאָ֗רֶץ הָיְתָ֥ה תֹ֨הוּ֙ וָבֹ֔הוּ וְחֹ֖שֶׁךְ עַל־פְּנֵ֣י תְהֹ֑ום וְר֣וּחַ אֱלֹהִ֔ים מְרַחֶ֖פֶת
עַל־פְּנֵ֥י הַמָּֽיִם׃ \foreignlanguage{british}{(Genesis 1:1–2)}

\selectlanguage{british}

Inline Greek (\foreignlanguage{polutonikogreek}{Ἐν ἀρχῇ ἦν ὁ λόγος} [John 1:1]) and
Hebrew (\foreignlanguage{hebrew}{בְּרֵאשִׁ֖ית בָּרָ֣א אֱלֹהִ֑ים אֵ֥ת הַשָּׁמַ֖יִם וְאֵ֥ת הָאָֽרֶץ} [Genesis
1:1]) also
must work.

\end{document}

Original answer
Here's a slightly extended example, which also works for lualatex (@cfr's answer will not compile with lualatex — My guess is it ought to, but there are bugs in luabidi.sty).
I've also found problems with \raggedright under xelatex which is worked around in this example (bug in bidi.sty?).
Finally, this shows how to use the SBL BibLit font correctly, specifying the Script and Contextual Alternates needed particularly for Hebrew.
\documentclass{article}
\usepackage{polyglossia}
\setmainlanguage[variant=british]{english}
\setotherlanguage{hebrew}
\setotherlanguage[variant=ancient]{greek}
\newfontfamily\greekfont{SBL BibLit}%
  [Script=Greek,Contextuals=Alternate,Ligatures=Required]
\newfontfamily\hebrewfont{SBL BibLit}%
  [Script=Hebrew,Contextuals=Alternate,Ligatures=Required,Scale=1.2]
\pagestyle{empty}
\ifluatex
  \let\luatexpardir\pardir % luabidi needs this
  \let\luatextextdir\textdir % luabidi needs this
  % text direction gets stuffed up without these workarounds
  \let\luatextextgreek\textgreek
  \let\luatextextenglish\textenglish
  \AtBeginDocument{%
    \renewcommand{\textgreek}[1]{\bgroup\textdir TLT\luatextextgreek{#1}\egroup}
    \renewcommand{\textenglish}[1]{\bgroup\textdir TLT\luatextextenglish{#1}\egroup}
  }
\fi
% \raggedright stuffs up under xelatex
\let\origraggedright\raggedright
\renewcommand{\raggedright}{%
  \origraggedright
  \ifxetex
    \renewenvironment{hebrew}[1][]{%
      \par
      \raggedleft % add to right align paragraphs
      \begin{otherlanguage}[##1]{hebrew}}%
      {\end{otherlanguage}\par}%
  \fi}
\begin{document}

In the beginning was the Word, and the Word was with God, and the Word was
God. (John 1:1)

\begin{greek}
  Ἐν ἀρχῇ ἦν ὁ λόγος, καὶ ὁ λόγος ἦν πρὸς τὸν θεόν, καὶ θεὸς ἦν ὁ λόγος.
  \textenglish{(John 1:1)}
\end{greek}

\begin{hebrew}
  בְּרֵאשִׁית בָּרָא אֱלֹהִים אֵת הַשָּׁמַיִם וְאֵת הָאָרֶץ. \textenglish{(Genesis 1:1)}
\end{hebrew}

Inline Greek (\textgreek{Ἐν ἀρχῇ}) and Hebrew (\texthebrew{בראשית}) also must
work.

\section*{With \texttt{\textbackslash raggedright}}
\raggedright

In the beginning was the Word, and the Word was with God, and the Word was
God. (John 1:1)

\begin{greek}
  Ἐν ἀρχῇ ἦν ὁ λόγος, καὶ ὁ λόγος ἦν πρὸς τὸν θεόν, καὶ θεὸς ἦν ὁ λόγος.
  \textenglish{(John 1:1)}
\end{greek}

\begin{hebrew}
  בְּרֵאשִׁית בָּרָא אֱלֹהִים אֵת הַשָּׁמַיִם וְאֵת הָאָרֶץ. \textenglish{(Genesis 1:1)}
\end{hebrew}

Inline Greek (\textgreek{Ἐν ἀρχῇ}) and Hebrew (\texthebrew{בראשית}) also must
work.

\end{document}

A: Something like this?
\documentclass{article}
\usepackage{polyglossia}
\setmainfont{Noto Serif}
\setsansfont{Noto Sans}
\setmainlanguage[variant=british]{english}
\setotherlanguage{hebrew}
\setotherlanguage{greek}
\newfontfamily\hebrewfont{Noto Sans Hebrew}[Script=Hebrew]
\newfontfamily\greekfont{Noto Serif}
\begin{document}

This is the main language.

\begin{hebrew}
  עברית
\end{hebrew}

\begin{greek}
  εὐδαιμονία
\end{greek}

\end{document}

Compile with XeLaTeX.