text:
Q: npm start gives weird error 8 with Unexpected token ILLEGAL I am getting weird error 8 with below output while doing $ npm start
SyntaxError: Unexpected token ILLEGAL
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
npm ERR! weird error 8
npm WARN This failure might be due to the use of legacy binary "node"
npm WARN For further explanations, please read
/usr/share/doc/nodejs/README.Debian

npm ERR! not ok code 0

npm -v
1.3.10
node -v
v0.10.25
I have installed nodejs-legacy
$ which node
/usr/bin/node

$ which nodejs
/usr/bin/nodejs

Can somebody please help with it.
I am trying to run react-jsonschema-form or word-finder (https://github.com/amirrajan/word-finder) on ubuntu 14.04

A: You are using Node 0.10 - currently the LTS version is 4.5.0 and the Current version is 6.6.0. Consider upgrading Node because you are using a very outdated version. Node 0.10 was released on March 2013, its maintainence period ends in a week (on October 1, 2016) and then it will no longer get any updates, see: https://github.com/nodejs/LTS#lts_schedule
According to package.json in github.com/mozilla-services/react-jsonschema-form the required Node version is at least 6.x and npm 2.14.7. You are trying to run it on Node v0.10.25 and npm 1.3.10. You shouldn't expect it to work.
To install a modern version of Node, you can either download a binary version from https://nodejs.org/ or you can build it from source, for example with a procedure similar to this one:
If you want to have node installed in /usr/local and available as /usr/local/bin/node you can do this:
# change dir to your home:
cd ~
# download the source:
curl -O https://nodejs.org/dist/v6.6.0/node-v6.6.0.tar.gz
# extract the archive:
tar xzvf node-v6.6.0.tar.gz
# go into the extracted dir:
cd node-v6.6.0
# configure for installation:
./configure --prefix=/usr/local
# build and test:
make && make test
# install:
sudo make install
# make sure you have /usr/local/bin in your $PATH before /usr/bin:
# add this to your .profile or .bashrc:
PATH="/usr/local/bin:$PATH"

Or if you want to be able to have few versions installed at the same time, with a symlink to the default one to use:
# change dir to your home:
cd ~
# download the source:
curl -O https://nodejs.org/dist/v6.6.0/node-v6.6.0.tar.gz
# extract the archive:
tar xzvf node-v6.6.0.tar.gz
# go into the extracted dir:
cd node-v6.6.0
# configure for installation:
./configure --prefix=/opt/node-v6.6.0
# build and test:
make && make test
# install:
sudo make install
# make a symlink to that version:
sudo ln -svf /opt/node-v6.6.0 /opt/node
# make sure you have /opt/node/bin in your $PATH before /usr/bin
# add this to your .profile or .bashrc:
PATH="/opt/node/bin:$PATH"

See this answer for more info.


text:
Q: How to use find.byType matching of List in Flutter widget testing I want to do widget testing for a Stack. Here is the sample code
final List<Widget> children = [];
final stack = Stack(children: children);
await tester.pumpWidget(Container(child: stack));
...

final stackFinder = find.byWidget(stack);
expect(stackFinder, findsOneWidget);

// children should be in Stack
final childrenFinder = find.descendant(
  of: stackFinder,
  matching: find.byType(children.runtimeType),
);
expect(childrenFinder, findsWidgets);

but get error:
Expected: at least one matching node in the widget tree
  Actual: ?:<zero widgets with type "List<Widget>" that has ancestor(s) with type "Stack"

I try to change matching to matching: find.byType([].runtimeType), or matching: find.byType(List<Widget>), but it doesn't work too.
Do you know how to fix it? Or, in case it's impossible, which method you use to verify the number of children inside?

A: List<Widgets> is not a widget. Therefore you cannot create a finder that will look for that type.
You could instead look for Widget and check if you find the correct number of widget that you are expecting.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What does JSON.stringify data look like in the url I use JSON.stringify to send jQuery arrays to $_POST data to a PHP file through an .ajax() call. The call works fine and the desired data is returned, but:
If I was going to debug and type in variables manually, what does this data look like in url format?
http://domain.com/ajax.php?foo=1,2&bar=3,4 or something else?
MY SOLUTION:
URL is http://domain.com/ajax.php?foo=[1,2]&bar=[3,4]

A: I would recommend using fiddler and use the Composer therefore you dont have to use separate code for debugging. You can also test what the result would look like by using the console in IE. Generally json.stringy turns your json into a string so it would look like
[1,2,3,4,5,6,7]

A: You will not be able to post the JSON data as a URL. You are mixing apples and pears. But you could do a few methods.
1) if the JSON is very simple you could actually do a url with the JSON data in it like this http://urdomain/ajax.php?data=[4,5,7] and use $_REQUEST['data'] instead of $_POST['data'] . but this could create more problems than it is worth.
2) best option is to use a browser plugin like this. You can do proper json posts and get the feedback.
3) or if u just want see what is happening you can just look at the browsers NET log in its development panel.


text:
Q: How to load MVC Partial View and keep Angular JS working How should I load mvc partial views and keep Angular JS working.
Angular JS is working fine after I render the layout, but if I load partial views in the layout, Angular JS is not working anymore in the partials.
I guess that Angular engine is not compiling the ng- directives after I inject the HTML in the DOM.

A: Instead of inject your HTML manually. Be it through angular.element.html or $().html. Try using one of the following, angular approved, options:

*

*A routing engine like ngRoute or ui-router. The engine can include a template which is rendered by the backend.

*The ngInclude directive. This way you can include HTML templates directly.

*Write a custom directive which injects your HTML.

Because these are AngularJS friendly methods, Angular will actually parse the HTML and bind any values within the newly loaded HTML.

A: From an answer from here
I think you may need to compile HTML string or DOM into a template.
More information, please refer to:
$compile
https://docs.angularjs.org/api/ng/service/$compile
There are some threads that may help you:
AngularJS - Dynamically creating elements that specify directives
AngularJS - Dynamically creating elements that specify directives
Bind Angularjs to newly created html element dynamically
Bind Angularjs to newly created html element dynamically


text:
Q: can't append multiline html with jquery I'm trying to append a multilined HTML code to a div using jquery, but it keeps giving me error "Unexpected token ILLEGAL"
Here is a line I'm trying to append:
$('.irbiswindow').append('

Rare and gorgeous "irbis" snow leopards observe the surroundings ready to hunt.

3Ds Max, Photoshop, Vray, Zbrush

');

A: Try to do a multiline concatenation with this trick 'text'+ newline 'text'
$('.irbiswindow').append('

' +
    '	' +
    '
Rare and gorgeous "irbis" snow leopards observe the surroundings ready to hunt.

3Ds Max, Photoshop, Vray, Zbrush

' +
    '

');

A: You could store the html in a js variable as such:
var html;
html += '
';
html += '
';
html += '      ';
...
html += '      	';
html += '
';
html += '
';

$('.screencontainer').delay(0).animate({height:"2560px",width:"1000px"},0, function(){$('.irbiswindow').append(html)});

A: Far better to put your static HTML in actual HTML and then clone the content to append it:

$('.irbiswindow').append( $("#tableToClone").clone() );

Rare and gorgeous "irbis" snow leopards observe the surroundings ready to hunt.

3Ds Max, Photoshop, Vray, Zbrush

A: By default, the HTML code containing line-breaks cannot be used with append/prependdirectly. But fortunately, currently there are following effective methods:

*

*Use "+" to join HTML code pieces.

*Use "\" to escape.

*Use "`" (back-tick, grave accent), do not need any extra operations.
This method is supported from ES2015/ES6 (Template literals).

*Add a hidden tag containing the same HTML code you need, e.g.
, then use.append($('#foo').html());.
Now post some use scenarios to the first three methods metioned above (just run them in the console of Chrome browser.):

We can see their differences clearly.


text:
Q: In Access 2003, problem with a memo field if and only if there is a filter on the PK and a sub query is joined I have a problem in a query in Acess 2003 (SP3).
I have a query that includes some tables and a sub query. The sub query and tables are all joined to a main table. The query uses some aggregate functions and there is a HAVING clause that filters the result on the primary key (PK).
Under these conditions, a memo field of the main table is not displayed properly. Two garbage characters, never the same, are displayed instead of the content of the field.
Now what is weird is that if I remove the HAVING clause, or if I use it to filter on something else other than the PK, the field is displayed correctly. If I remove the sub query from the query the field is also displayed correctly even if there is still a filter (HAVING clause) on the PK.
Is this a bug in Access (I think it is)? If so, does someone know of a workaround for this bug?

A: MSAccess Memo fields truncated to 255 characters (before Access 2000, wouldn't work at all) in GROUP BY queries. However, to take care of the apparent bug try this:
Instead of MemoField  use  Left([MemoField,255)


text:
Q: Does windows have some inbuilt database engine? So far, in my applications, I stored all my data via serialization, so I never really needed anything else. But now I am working with more complicated data and I need more than a simple file to store them. Is there some inbuilt storage engine in Windows I can use, which will allow me to pull and edit data with SQL queries? (Since I doubt the user will be willing to install and configure standalone MySQL server just for my application and I don't really want to use 3rd party solutions)
And if there is, how can I access such database engine?

A: Yes, Windows does have an embedded database engine, which has been there since Windows 2000. It is called Esent.
There is a project called Managed Esent to expose the features of Esent to managed code. There is a NuGet package for it.
I do not know whether it fits your exact need of updates via SQL queries but it does boast a number of features:

*

*ACID transactions with savepoints, lazy commits, and robust crash recovery.

*Snapshot isolation.

*Highly concurrent database access.

*Flexible meta-data (tens of thousands of columns, tables, and indexes are possible).

*Indexing support for integer, floating point, ASCII, Unicode, and binary columns.

Update
I have since had some experience with Esent in C# via the nuget package. It does NOT have SQL query capabilities. There is support for indices and basic cursors over them but nothing like the power of SQL. My suggestion if you need a light-weight SQL is definitely SQLite.

A: SQLite is a software library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine.
http://www.sqlite.org
SQLite will work without requiring your App User to install SQLExpress or any other database engine, making it a good option for desktop applications.

A: Use SQLite as standalone database and integrated part of your applications.
Main benefits:

*

*data is stored inside a single file, easy to pull/edit

*ships as part of your application as dll, no separate
installation/configuration needed

A: i found some info about the database on the Microsoft website database info
there is a embedded database engine. Esent

A: If it is small set of user specific data, storing at windows registry is a good option.

A: No, there is no inbuilt database available.
But there are good alternatives, like the mqsql express server or a SQLITE database, which is basically a single database file which is accessed through a library in your project. So if you use SQLITE, you do not need to instal anything.


text:
Q: how to draw a circular arc using 2 extreme points, radius and center in OpenCV I have the extreme/corner points of an arc, along with its radius and center coordinates. How to draw an arc using opencv using what I have?
I need to draw an arc with a different color between these two points


text:
Q: NGINX - URL rewriting I can't seem to be able to rewrite the following url :

https://website.org/urlCNX/Files/software/software.application?CNX=CNX&UUID=66A6DUZS7Z4L742VHZ594ZAPM9P06

to

https://website.org/url/Files/software/software.application?CNX=CNX&UUID=66A6DUZS7Z4L742VHZ594ZAPM9P06

(Note the missing "CNX" after /url)
I've currently set the following rule in NGINX but it does nothing :

   location ~* /iComptaCNX/ {
       rewrite ^/iCompta/(.+) $1 permanent;
   }

Thanks.

A: The regular expression in the rewrite statement needs to match the URI you are attempting to change. It needs to match URIs that begin with /iComptaCNX/.... Your current attempt will not match that URI.
Try:
rewrite ^/iComptaCNX/(.+)$ /iCompta/$1 permanent;

See this document for details.

If you want a general solution that will remove CNX from the end of the first element in any URI, use:
rewrite ^/([^/]+)CNX/(.+)$ /$1/$2 permanent;


text:
Q: ReactJS: How to autofocus inputs in a slider I have an application like quiz. Every single slider has one input. I want to autofocus the related input when the user clicks on the next button or press on the enter.
I tried to achieve it by using useEffect. However, it doesn't work.
This is the related function which includes the next function of slick and focus attribute of inputs:
const inputRef = useRef([]);

const handleEnter = (event, index) => {
      if (event.key.toLowerCase() === "enter") {
          sliderRef.current.slickNext(); // The next slider function of the react-slick package
          inputRef.current[index].focus()
      }
}

Here are my inputs in map function:
{data.map((post, index) => (
  <Input
     id={post.question_uuid}
     name={post.question_uuid}
     onKeyDown={e => {handleEnter(e, index)}}
     autoComplete="off
     ref={el => inputRef.current[index] = el}
  />
))}

A: Use useRef for every input and store them on an array with the index that came from your map then after changing every slide you can get the input ref from the array based on the current index and call
array[index].current.focus()


text:
Q: Hold border and Resize two or more DIV simultaneously in the same container Code :

this is the part

of the genial

and good widget

Let's say that div#widget1 is 99px width and div.part are 33px by default.
How can I easily resize div.blue by increasing its width and deacreasing width of other div.part proportionnaly ?
http://jqueryui.com/demos/resizable/#synchronous-resize : give an example which show element increase in the same time.

A: possible duplicate of resizing div panel
Testing my solution here : http://jsfiddle.net/lnplnp/MxKLH/
But this do perfectly what I need :
JAVASCRIPT :
$(document).ready(function() {

  // init
  var containerWidth = $("#container").width();
  var nbpanels = $(".panel").size();
  var padding = 2.5;

  $(".panel").width( (containerWidth / nbpanels) - (nbpanels * padding - 2 * padding));

  $(".panel").resizable({
    handles: 'e',
    maxWidth: 450,
    minWidth: 120,
    resize: function(event, ui){
      var currentWidth = ui.size.width;
      // set the content panel width
      $(".panel").width( ( (containerWidth - currentWidth + padding ) / (nbpanels - 1) ) - ((nbpanels - 1) * padding) );
      $(this).width(currentWidth);
    }
  });

});

HTML :

    some text, lorem ipsum. some text, lorem ipsum. some text, lorem ipsum.

    some more text, lorem ipsum. some text, lorem ipsum. some text, lorem ipsum.

    some text, lorem ipsum. some text, lorem ipsum. some text, lorem ipsum.

    some text, lorem ipsum. some text, lorem ipsum. some text, lorem ipsum.

CSS :
.clear{
  clear:both;
}

#container{
  border: 1px red solid;
  margin: 0 auto;
  width: 900px;
}

.panel{
  background-color: #9999FF;
  float: left;
  height: 200px;
  padding: 2.5px;
}

#panel1{
  background-color: #FF0000;
}

I think the JS can be improve... but it's working !

A: $('.part').attr('width',10);
$('.blue').attr('width',50);

Using this the width of all divs named part will be decreased and the width of only blue increased.


text:
Q: PHP reference full path to Class Variable I need to easily reference a specific path to a class variable that I can use later (like arrays). Is this possible?
echo $contract[0]->personnel_requirements->m->day->d7 // This works like expected

$p = "personnel_requirements->m->day->d7";

echo $contract[0]->$p; // This doesn't work :(

A: I am not sure why you want to do this, but here is an idea:
$p = "A->B->C";
$pl = explode("->", $p);
$X = $contract[0];
foreach($pl as $v) {
    $X = $X->{$v};
}
echo $X;


text:
Q: Erro Postgresql com Spring boot - api Opa pessoal
Esto fazendo uma aplicação bem simples mesmo, para ver como funciona o postgresql.
Estou fazendo uma aplicação Spring Api.
Minha classe
@Entity

public class Produto implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String nome;
private BigDecimal valor;
private int quantidade;

restante do codigo
Meu build.gradle:
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'org.postgresql:postgresql'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
    exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}

}
Application.properties
spring.datasource.url = jdbc:postgresql://localhost:5432/product
spring.datasource.username = postgres
spring.datasource.password = 123
spring.jpa.database-platform = org.hibernate.dialect.PostgreSQL94Dialect
spring.jpa.show-sql = false
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.format_sql=true

Seguinte erros:
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.exception.GenericJDBCException: Unable to open JDBC Connection for DDL execution

A: O problema está na sua URL de conexão:
jdbc:postgresql://localhost:5432/product

A exceção apresentada mais abaixo da sua stacktrace (na sua imagem) deixa isso bem claro: database product does not exist
Verifique se a base product se encontra criada antes da execução da aplicação, isso não é problema de dependências, ou configuração de entidade.


text:
Q: How to know when and by whom last publish was made? For example we have 2 teams which share one demo server. They make publish several times a day. How can I know when (date and time) and by whom (member name) the last publish was made? May be there is some Visual Studio option or TFS setting to get publish notifications?

A: You can use the following code to get a build timestamp.
    /// <summary>
    /// Read the linker timestamp from an executable.
    /// </summary>
    private DateTime RetrieveLinkerTimestamp(String strFileName)
    {
        try
        {
            //Open file
            string filePath = strFileName;
            const int c_PeHeaderOffset = 60;
            const int c_LinkerTimestampOffset = 8;
            byte[] b = new byte[2048];
            System.IO.Stream s = null;

            try
            {
                s = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                s.Read(b, 0, 2048);
            }
            finally
            {
                if (s != null)
                {
                    s.Close();
                }
            }

            //Get timestamp
            int i = System.BitConverter.ToInt32(b, c_PeHeaderOffset);
            int secondsSince1970 = System.BitConverter.ToInt32(b, i + c_LinkerTimestampOffset);

            //Convert to date/time
            DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0);
            dt = dt.AddSeconds(secondsSince1970);
            dt = dt.AddHours(TimeZone.CurrentTimeZone.GetUtcOffset(dt).Hours);
            return dt;
        }
        catch (Exception ex)
        {
            throw new Exception("Error in RetrieveLinkerTimestamp", ex);
        }
    }


text:
Q: How to pass from Activity to BroadcastReceiver() using pendingIntent Kotlin Hi I am trying to display my temperature value and weather description notification from my WeatherBroadcater BroadcastReceiver using the values from my WeatherNotification activity. However, I was not able to retrieve the values as it was presented null on the BroadcastReceiver. Check how do I do this and thanks in advance
WeatherNotification.kt
private fun setIntent() {
    val intent = Intent(this, WeatherBroadcaster::class.java)

    Log.d("Broadcast", "sending to broadcast Temp: ${weatherResult.temp}, Desc: ${weatherResult.weatherDescription}")
    intent.putExtra("Temp", weatherResult.temp.toString())
    intent.putExtra("WeatherDes", weatherResult.weatherDescription.toString())
    val pendingIntent: PendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
    alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager

    val timeStart = System.currentTimeMillis()
    val interval = 1000

    alarmManager.setRepeating(
        AlarmManager.RTC_WAKEUP,
        timeStart,interval.toLong(), pendingIntent
    )
}

WeatherBroadcaster.kt
    override fun onReceive(context: Context?, intent: Intent?) {
    val intent = Intent(context, WeatherNotification::class.java)

    val temp: String? = intent.getStringExtra("Temp")
    val desc: String? = intent.getStringExtra("WeatherDes")
    Log.d("Broadcast", "sending to broadcast Temp: $temp, Desc: $desc")

    val pendingIntent: PendingIntent = PendingIntent.getActivity(context, 0, intent, 0)

    var bitmap = BitmapFactory.decodeResource(context?.resources, R.drawable.pressure)
    var bitmapSun =
        BitmapFactory.decodeResource(context?.resources, R.drawable.sunrise)

    val builder = NotificationCompat.Builder(context!!, CHANNEL_ID)
        .setSmallIcon(R.drawable.ic_launcher_foreground)
        .setContentTitle(temp)
        .setContentText(desc)
        .setLargeIcon(bitmapSun)
        .setStyle(NotificationCompat.BigPictureStyle().bigPicture(bitmap))
        .setContentIntent(pendingIntent)
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)

    with(NotificationManagerCompat.from(context)) {
        notify(notificationId, builder.build())
    }
}

LogCat
2020-10-08 16:56:13.774 6462-18591/com.sgtech.ict3104.racecar D/Broadcast: sending to broadcast Temp: 30.97°C, Desc: light rain

2020-10-08 16:56:33.227 6462-6462/com.sgtech.ict3104.racecar D/Broadcast: sending to broadcast Temp: null, Desc: null

A: There is typo on the key for the temperature and you are initialization a new intent on the receiver
override fun onReceive(context: Context?, intent: Intent?) {
    val intent = Intent(context, WeatherNotification::class.java)
    //...
}

That val intent is a new Intent you are creating from the context argument on the method signature. What you need is to examine the intent argument instead.
override fun onReceive(context: Context?, intent: Intent?) {
    //the intent is now the same as in the argument, the same received
    intent ?: return
    val temp: String? = intent.getStringExtra("temp")
    val desc: String? = intent.getStringExtra("WeatherDes")
    Log.d("Broadcast", "sending to broadcast Temp: $temp, Desc: $desc")
    //...
}


text:
Q: Stack rows under one another My dataset looks like this
Col1 Col2 Col3
 AA   BB   NA
 DD   EE   NA
 FF   NA   GG

I would like to stack rows under one another so that the final product looks like this
Col1
AA
BB
DD
EE
FF
GG

I really struggle finding an easy way to do this. Any help would be great!

A: We can do
data.frame(col1 = na.omit(c(t(dat))), stringsAsFactors = FALSE)
#  col1
#1   AA
#2   BB
#3   DD
#4   EE
#5   FF
#6   GG

We first transpose your data using t() which returns a matrix, then we call c() to get vector, remove NAs with na.omit and finally create desired output using data.frame().
data
dat <- structure(list(Col1 = c("AA", "DD", "FF"), Col2 = c("BB", "EE",
NA), Col3 = c(NA, NA, "GG")), .Names = c("Col1", "Col2", "Col3"
), class = "data.frame", row.names = c(NA, -3L))


text:
Q: Does the multiplication by diagonal matrix preserve the signs of eigenvalues? My question is as follows:

Let $A$ be a real symmetric $n\times n$ matrix and $D=\mathrm{diag}(d_1,\ldots,d_n)$ be a diagonal matrix whose diagonal entries are all positive real numbers(denoted as $d_1,\ldots,d_n$). If $A$ has $k$ positive eigenvalues, $m$ zero eigenvalues(i.e. $0$ is an eigenvalue with multiplicity $m$) and $n-m-k$ negative eigenvalues. Then does $DA$ have the same number of positive, zero, negative eigenvalues?

Intuitively, I think this statement is true because, heuristically, if we assume that $A$ is also diagonal, its diagonal entries are exactly the eigenvalues of $A$, and the identity $\mathrm{diag}(d_1,\ldots,d_n)\cdot \mathrm{diag}(a_1,\ldots,a_n)=\mathrm{diag}(a_1d_1,\ldots,a_nd_n)$ directly gives the result. Also it is well-known that the statement is true if $A$ is positive semi-definite. However, I'm not sure that this is also true for the general cases where $A$ is not necessarily positive semi-definite. I tried to find a counterexample, but it also didn't work.
Does anyone have ideas?
Thanks in advance!

A: Yes. Since $B=D^{1/2}AD^{1/2}$ is congruent to $A$, they have the same inertia, by Sylvester's law of inertia. However, $B$ is similar to $D^{1/2}BD^{-1/2}=DA$. Therefore $DA$ also has the same number of positive/zero/negative eigenvalues as $A$.

A: Does Sylvester's law only work for symmetric $A$? I have a similar problem with blocked $A = \begin{bmatrix}L& B\\B& L\end{bmatrix}$ and $D = \begin{bmatrix}D_1& \\& D_2\end{bmatrix}$; where $L$ is symmetric but $B$ is not symmetric. I know $A$ has all nonnegative eigenvalues, does that hold for $DA$?


text:
Q: Textmate 2: How can increase font size of sections in the markup code? Now that TextMate 2 has gone open-source, I have a reason to move from TeXShop to TextMate 2.
There is a great feature in the markdown bundle (markdown.tmbundle), which makes the headings in code look like:

The very same thing in using the latex bundle (latex.tmbundle) results in:

Question: How can I implement the larger text size (perhaps even colors) in code for sections/subsections/subsubsections in the latex bundle?
The original question was posted on stackoverflow, where I have even put a bounty on it to no avail. Perhaps the community here will be more helpful.

A: The procedure to change the appearance of section in Texmate 2 is the following:
In the Bundle editor menu, select Edit bundles ....
Then select the bundle Themes.
From menu File, select New, and when prompted select Setting
Give a name to the setting.
In the Scope Selector field use meta.function.section.latex
Then you can edit the setting, for example:
{
    fontName = 'Courier';
    fontSize = 36;
}

Then save (in the usual way, e.g, command-s).
You can repeat for other sectioning command (to identify the scope, move the cursor on the appropriate place and then use the following key combination control-shift-P)

Update: There was a feature request to give the different kinds of section tags unique tags so that be given different sizes. The scopes are now:

*

*meta.function.section.section.latex

*meta.function.section.subsection.latex

*meta.function.section.subsubsection.latex

*meta.function.section.chapter.latex

*meta.function.section.part.latex

*meta.function.section.addpart.latex

*meta.function.section.addchap.latex

*meta.function.section.addsec.latex

*meta.function.section.minisec.latex

You can create multiple setting items to target different items, if you want multiple scopes to share the same size you can separate the scopes with a comma in the scope field.
The user that requested this feature has created a bundle that does this.


text:
Q: Windows 7 Aero Peek Click Desktop Is there a way to enable clicking your desktop icons when you have Windows 7 Aero Peek Desktop showing? The hotkey for this Im using is: WinKey+Space

A: No. The whole point of Aero Peek is that you're only peeking at the desktop, not interacting with it. If you want to be able to click on the icons, use Win+D to minimise all windows.


text:
Q: How to Set .env with JS I have this, from https://npm.io/package/node-calendly-sdk.
calendly_client = new Calendly("YOUR-API-TOKEN")

I'm confused on how to set .env varibles in js

A: Env variables are a set of values, generally to store sensitive data that shouldn't be in the code.
In nodejs, you can add the npm package dotenv with: npm i dotenv, then, you have to create a file named .env in the root directory of your project and define your variable like:
.env file:
API_KEY_TOKEN = "some value"

Then, at the very beginning of your nodejs file, write: require("dotenv").config(); and that's it, you can access your .env variables with process.env
Full example:
require("dotenv").config();
calendly_client = new Calendly(process.env.API_KEY_TOKEN );

For a complete documentation visit dotenv


text:
Q: Is it safe to resize my swap partition on a production system? I have a laptop with 4GB RAM, but when I first set it up, I had no plans to hibernate so I gave it 2GB swap. I don't want to use a swap file, so is it safe to resize the swap partition (and of course the main ext4 partition)?

A: Yeah, that should be just fine. Swap space is used when the system has too many applications running to hold all of their data in memory; it's a feature of the paging/virtual memory system. If you shut down the machine properly before repartitioning, there shouldn't be any data in the swap space and you should be able to expand it safely.

A: The problem you will encounter is that if you try to resize a partition it probably won't work as you are currently using it. In the computer system jargon we says the partition is "mounted", reflecting the fact that you can browse it and access its data.
So what you want to do is boot from a Live CD or USB and use the disk partition manager to resize your "home" partition for instance. As you would have started the computer from the Live device, your real home partition would not be "mounted", and as such you can edit it.
Though, in most cases you won't have problems resizing a partition you should always perform a complete backup of your data on your computer. And in addition, you should check the following, it will help avoiding problem:

*

*as you have a laptop, check that your battery is fully charged and that the power cable is plugged in. So you're reducing the risk of power failure during the resizing process

*you should check the partition for errors and correct them before resizing. You could check the Ubuntu wiki for fsck, or you can use the command sudo fsck -y /dev/sda<n> replacing  by the proper partition number. I advise you to do that from the Live CD/USB too.

*as you want to reduce a partition of 2GB, you should verify first that you have more than 2GB free on this partition.

*finally it's good practice to avoid having a file system too full (more than 80 or 90 %) as this helps keeping file fragmentation low. You should be aware that file fragmentation could raise the time and complexity necessary to resize a partition.

But don't be afraid, it's doable. I've done on a production development server at work. And everything worked fine.


text:
Q: C#: how to set version number of assembly I have written a DLL in C# using VS2005.
Currently the DLL is showing a version number of 1.0.0.0.
How do I set this version number to something different?

A: You can set the version number in AssemblyInfo.cs.
// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

Note that the assembly version is not the same as the assembly file version. From your brief description it sounds more like you are looking for the latter - AssemblyFileVersion.

A: Alter this line in AssemblyInfo.cs:
// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
[assembly: AssemblyVersion("1.9.10292.8")]

A: look in the AssemblyInfo.cs file for the following line, and set it to whatever version number you want:
[assembly: AssemblyVersion("1.0.0.0")]

A: You can either specify the file version using the AssemblyFileVersionAttribute directly...

Instructs a compiler to use a specific
  version number for the Win32 file
  version resource.

...or you can remove this attribute entirely which will mean that the file version defaults to the assembly version. This is probably good practice as having a file version that is different to the assembly version will cause confusion.

If the AssemblyFileVersionAttribute is
  not supplied, the
  AssemblyVersionAttribute is used for
  the Win32 file version that is
  displayed on the Version tab of the
  Windows file properties dialog.

You can set the assembly version using the AssemblyVersionAttribute.
Assembly attributes are usually applied in the AssemblyInfo.cs file as stated in the other answers.

A: Right click the project and click properties.
The properties window will appear. In that click Application tab.
It will show application information of the project. There will be a button named Assembly Information. click the button, it will show you a form containing assembly information of the project. You can specify the assembly version (contains four text boxes, i.e., Major Version, Minor Version, Build Number, Revision). It will store the assembly details in AssemblyInfo.cs of the corresponding project.

A: If you need to change it on visual studio open your solution file then right click and select properties then select Application on that select assembly information than change version on assembly.
enter image description here


text:
Q: Access to Wildfly  through JNDI is it possible to access Wildfly properties (defined in standalone.xml) through JNDI?
Like:
    <system-properties>
        <property name="MY_PROPERTY" value="some value"/>
...
    </system-properties>

and read it in java:
@Resource(lookup = "java:comp/env/MY_PROPERTY")
private String property;

A: <system-properties> are used to define environment variables and not JNDI variables. Define JNDI variables inside
<subsystem xmlns="urn:jboss:domain:naming:2.0">
<bindings>
...
<simple name="java:/env/MY_PROPERTY" value="some value"/>
</bindings>
</subsystem>

Now, you can read it as a JNDI.


text:
Q: Static image folder with google app engine There are already a lot of post dealing with this issue but I wasn't able to find a solution to my problem. I am using the Google App Engine Launcher to create a small web application using python. I need to display a picture (/images/chartname.png) on my page. I am using the following line of html code <img width=150 src="/images/chartname.png"> but the picture does not show up. Additionally when I open http://localhost:8080/images I get an error 404.
Here's the content of my .yaml file:
application: app
version: 1
runtime: python27
api_version: 1
threadsafe: false

handlers:
- url: /.*
  script: app.my_app

- url: /images
  static_dir: images

I don't understand why the picture doesn't show up and why http://localhost:8080/images returns an error 404.
I've tried the suggestion in this post: Google App Engine add image to page with static folder but it didn't do it for me.

A: Try reordering the handlers:
- url: /images
  static_dir: images

- url: /.*
  script: app.my_app

Patterns are evaluated in the order they appear in the app.yaml file, from top to bottom. The first mapping whose pattern matches the URL is the one used to handle the request.


text:
Q: C++ filling array with dereferenced pointers According to what I have found in this question an array of references is illegal. Im kinda new to C++ and was playing around with pointers and dereferencing and the following code seems to execute just fine.
#include <iostream>
#include <cstdlib>

using namespace std;

struct A
{
    int data1;
    int data2;

    A (void) : data1(0), data2(0) {}

    // many more datas
};

int main()
{
    cout << "test start" << endl;

    A *a = new A();
    A arr[100];

    for (int x=0; x<100; x++) arr[x] = *a;

    cout << "test done" << endl;
}

what happens here under the hood? is a copy of the a object being put in every location of the array? if so, when returning a object reference from a function like:
A &function (void) { return &A(); }

is it the same thins as this?:
A function (void) {return A();}

A: For your first question, arr[x] = *a; causes the program to copy all the data stored in the object to the specified array element.
For your second question, A &function (void) { return &A(); } appears to attempt to return the address of a function, but the format is incorrect.  Look up "pointer to function" for more information.  You could however, do this:
A test;

A &function(void)
{
    return test;
}

A &ref = function();

This way, you have an actual object in your program that can be used in a reference and your function returns the address to that object.  Which appears to be what you are trying to do with that particular function.
Edit:  Removed incorrect part of answer.  A function(void) { return A(); } does create an object and return the created object.
Edit2:  changed return &test; to return test; in A &function().


text:
Q: PowerShell : Divide Files by Line in Faster Way We're considering to divide huge file, over 25GB and to import into Redshift DWH.
So far, we can simply divide the file by 1000000 lines, but it took almost two hours to divide into 111 files.
$i=1; cat .\TRGET_FILE.csv -ReadCount 1000000 | % { $_ > TRGET_FILE_$i.csv;$i++ }

Also we'd like to escape the word '\' to '\\' in each files, so as not to prevent Redshift data load. But it consumes both of time and resources in this way.
Could you kindly let me know if you'll know any better solutions?
Thank you.

A: cat is an alias for Get-Content which is notoriously slow at reading files. I also suspect that using redirection may not be the best way to write the target file either.
Let's try using some .Net classes and methods instead:
$bigfile = '.\TRGET_FILE.csv'
$outfile = '.\TRGET_FILE{0:d5}.csv'
$linecount = 1000000
$i = 0
$outstream = $null

foreach ($line in [System.IO.File]::ReadLines($bigfile)) {
    if (($i % $linecount) -eq 0) {
        if ($null -ne $outstream) { $outstream.Close() }
        $outstream = [System.IO.StreamWriter]::new(($outfile -f ($i/$linecount)))
    }

    $outstream.WriteLine($line.Replace('\', '\\'))

    $i++
}
$outstream.Close()

The [System.IO.File]::ReadLines method is very fast, and we can iterate over it quickly with a foreach loop, without reading every line from the file first.
Since each iteration of the loop processes a single line, we'll write it out to the target file. But we don't want to use something like Out-File -Append because it will reopen and close the file every time.
So instead, when we calculate that we've reached the number of lines (or on the first iteration), we can open a new file as a [System.IO.File]::StreamWriter,  and that way we have it open already, and can write out each line.
When we write the line, we also replace a single backslash \ character with two backslashes.
When we reach the desired number of lines, we first check if the $outstream is $null (it will be $null the first time), and if it's not null, we close the stream (to close the output file), and then create a new one, with the new file name.
The output file name is templated to a 5 digit number via string templating.
{0:d5} -- 0 means the first item in the template, d is for a number, 5 tells it to ensure the number is at least 5 digits, so it will pad it with zeroes. That will help with file ordering.
Finally at the end of the loop, which will end before reaching the desired number of lines (the tail of the file), we close that last stream.
頑張ってね

A: Can you try to limit the chunk size to 1m ~ 2m by reducing the readcount? some thing  like this:
$i = 1; $j = 1
Get-Content .\TRGET_FILE.csv -ReadCount 10000 |
    ForEach-Object {
        $_ | Add-Content -Path TRGET_FILE_$i.csv
        $j++
        if ($j -eq 100) {
            j=1; i++
        }
    }

if this works better you can apply the replacement like this:
$i = 1; $j = 1
Get-Content .\TRGET_FILE.csv -ReadCount 10000 |
    ForEach-Object {
        $_.replace('\', '\\') | Add-Content -Path TRGET_FILE$i.csv
        $j++
        if ($j -eq 100) {
            j=1; i++
        }
    }

A lot of this depends the disk IO, so have a disk that is super fast on read and write block will help.

A: The linux shell command split is made to do this exact job.  It can split files by lines of any line count you wish.  See https://man7.org/linux/man-pages/man1/split.1.html
split -l 1000000 -da 4 file_in file_out


text:
Q: Removing DAL dependency from Service Layer using a C# n tier application we have a project where we are trying to remove the dependency of the DAL from our service layer. We have taken the using statement reference out of the project along with the reference out of the project.json.
Now we have something like the following in our Service Layer...
var stockItem= await _unitOfWork.StockRepo.FindOne(p => p.product == product && p.warehouse == warehouse).FirstOrDefaultAsync();

This is exactly the sort of thing we are after. The problem is when we hover over var stockItem the tooltip states DAL.entities.Stock so we still have a dependency.
So does this mean that our service layer still knows about our DAL. Anyone have any idea how to remove this problem.

A: There is a point where you have to bring the service layer and DAL together. But you can seperate that into different assemblies.
Definition of the ServiceLayer Foo.Services.Core.dll
namespace Foo.Services.Core.Models
{
    public class Foo
    {
       ...
    }
}

namespace Foo.Services.Core.DataServices
{
    public interface IFooService
    {
        Task<Foo> GetByIdAsync( int id );
    }
}

Next project will be more concrete with a UnitOfWork Foo.Services.Impl.UnitOfWork.dll
namespace Foo.Services.Impl.UnitOfWork
{
    public class UnitOfWorkFooService : IFooService
    {
        private readonly IUnitOfWork _uow;
        public UnitOfWorkFooService( IUnitOfWork uow )
        {
            _uow = uow;
        }

        public Task<Foo> GetByIdAsync( int id );
        {
            return await _uow.FooRepo.FindOne( ... ).FirstOrDefaultAsync();
        }
    }
}

Or maybe a total different in the future talking to a REST API Foo.Services.Impl.RestApi.dll
namespace Foo.Services.Impl.RestAPI
{
    public class RestApiFooService : IFooService
    {
        private readonly IRestApi _restapi;
        public RestApiFooService( IRestApi restapi )
        {
            _restapi = restapi;
        }

        public Task<Foo> GetByIdAsync( int id );
        {
            return await _restapi.FooEndpoint.GetAsync( id );
        }
    }
}


text:
Q: Salesforce Lightning: Dynamically Create Tabset/Tab I'm currently having an issue when trying to tabset with dynamic tabs. It appears that I need to use "aura:set" to set the label for each tab. When I do that though, I receive the oh so incredibly helpful "An internal server error has occurred Error ID: xxxxxxxxxxxxxxxx.
Exact Error Messages (Scroll right for error codes)
Error : [{"status":"SUCCESS","message":""},{"status":"SUCCESS","message":""},{"status":"ERROR","message":"An internal server error has occurred\nError ID: 2003145941-42295 (-1127739456)"},{"status":"SUCCESS","message":""},{"status":"ERROR","message":"An internal server error has occurred\nError ID: 2003145941-42296 (-1127739456)"},{"status":"SUCCESS","message":""},{"status":"ERROR","message":"An internal server error has occurred\nError ID: 2003145941-42297 (-1127739456)"}]

Here is a quick distillation of what I'm trying to do:
MyComponent.cmp
<aura:component description="TabSetExample">
    <aura:attribute name="horizontalTabs" type="Aura.Component[]" access="private"/>
    <aura:handler name="init" action="{!c.onInit}" value="this"/>
    {!v.horizontalTabs}
</aura:component>

MyComponentController.js
({
    onInit : function(component, event, helper) {
        helper.createTabset(component);
    }
})

MyComponentHelper.js
({
    createTabset: function(component) {
        var newComponents = [];
        newComponents.push(["lightning:tabset", {
            "aura:id" : "tabset",
            "variant" : "default"
        }]);
        newComponents.push(["lightning:tab", {
            "id" : "tab1"
        }]);
        newComponents.push(["aura:set", {
            "attribute": "label",
            "body": "Tab 1"
        }]);
        newComponents.push(["lightning:tab", {
            "id" : "tab2"
        }]);
        newComponents.push(["aura:set", {
            "attribute": "label",
            "body": "Tab 2"
        }]);
        newComponents.push(["lightning:tab", {
            "id" : "tab3"
        }]);
        newComponents.push(["aura:set", {
            "attribute": "label",
            "body": "Tab 3"
        }]);
        $A.createComponents(newComponents,
            function (components, status, errorMessage) {
                if (component.isValid() && status === "SUCCESS") {
                    var tabset = components[0];
                    var tabs = [];
                    for(var i = 1; i < components.length; i++) {
                        if(i % 2 === 0) {
                            components[i-1].set("v.label", components[i]);
                        } else {
                            tabs.push(components[i]);
                        }
                    }
                    tabset.set("v.body", tabs);
                    component.set("v.horizontalTabs", tabset);
                } else {
                    //log error
                }
            }
        );
    }
})

It appears as though the I'm unable to generate an "aura:set" component (is this actually a component?). If I can't generate the "aura:set" dynamically, does anyone know of a way to dynamically set the label of a "lightning:tab"? I've tried a String and an "aura:html" setup as a span, neither works.

A: You can't initialize an aura:set component. It causes Bad Things to happen. The label attribute is a Component[] value so you need to create an aura:text component and then assign it to the label after component generation.
The code should look something more like this:
({
    createTabset: function(component) {
        var newComponents = [];
        newComponents.push(["lightning:tab", {
            "id" : "tab1",
            "title": "Tab 1"
        }]);
        newComponents.push(["aura:text",{
            "value" : "Tab 1"
        }]);
        newComponents.push(["lightning:tab", {
            "id" : "tab2",
            "title": "Tab 2"
        }]);
        newComponents.push(["aura:text",{
            "value" : "Tab 2"
        }]);
        newComponents.push(["lightning:tab", {
            "id" : "tab3",
            "title": "Tab 3"
        }]);
        newComponents.push(["aura:text",{
            "value" : "Tab 3"
        }]);
        $A.createComponents(newComponents,
            function (components, status, errorMessage) {
                console.log(errorMessage);
                if (component.isValid() && status === "SUCCESS") {
                    var tabs = [];
                    for(var i = 0; i < components.length; i++) {
                        if(i % 2 === 0) {
                            tabs.push(components[i]);
                        } else {
                            components[i-1].set("v.label", components[i]);
                        }
                    }
                    component.set("v.horizontalTabs", tabs);
                } else {

                }
            }
        );
    }
})

It appears you have to set the tab bodies before they'll render, or perhaps I'm missing something else, but at minimum, this no longer errors.


text:
Q: What's the default JVM heap size of Java application launched by eclipse If I don't set -Xmx of the Java application in eclipse. Eclipse will launch it with a default heap size which is related to the physical memory. I want to know how to compute this default value.

A: You can use MemoryMXBean to get JVM init and max memory and RuntimeMXBean to get JVM arguments.


text:
Q: Show input elements hidden under keyboard Android PhoneGap I have a form in which one input element gets hidden under keyboard after focusing on it. I don't want my page to get resized.
Can this be handled using scroll, so that only the form div gets scrolled to that particular element?
Or any other approach to this?
I'm not using jquery-mobile and I have tried scrollToElement of iScroll 5, but to no use.

<input id="pac-input" class="controls" type="text" placeholder="Search Area" />

        <form id="booking_form" action="#" >

            <input type="tel" id="contact_no" placeholder="Contact Number*" maxlength="10"/>

                <textarea cols="10" id="pick_up_location" placeholder="Pickup Location*" ></textarea>

                <textarea cols="10" id="drop_off_location" placeholder="Drop off Location*" ></textarea>

            <input type="text" id="pick_up_time" placeholder="Pickup time*" />
            <input type="text" id="car_model" placeholder="Car*" />
            <input type="submit" id="confirm_booking" class="custom_button" value="Confirm Booking" />
        </form>

        <button id="create_booking" class="custom_button">Book Now</button>

The input field car_model gets hidden under keyboard. I have android:windowSoftInputMode="adjustPan" in my manifest file.
theScroll = new IScroll('form');
$('#car_model').focus(function(){
    theScroll.scrollTo($('#car_model'));
});


text:
Q: jQuery hide (and show) element within parent OK, maybe it's late in the day! I've tried most the related questions, I'm sure it's pretty simple but here goes:
Here's the HTML structure:

blah blah

Close div!

Show div!

There will be multiple instances of the above structure (Wordpress loop) so it should only show the div within that instance (not all of them). This is my jQuery so far:
$("a.info-show").click(function(){
     $(this).parent('article').find('.info-wrap').animate({ opacity: 'show' }, "slow");
    return false;
});

Not working. What am I missing here? Thanks!

A: Try this:
$(document).ready(function(){
    $("a.info-show").click(function(e){
        e.preventDefault();
        $(this).parents('article').find('div.info-wrap').animate({ opacity: 1 }, "slow");
        return false;
    });
});

Or use:
$(document).ready(function(){
    $("a.info-show").click(function(e){
        e.preventDefault();
        $(this).parents('article').find('div.info-wrap').fadeIn('slow');
        return false;
    });
});

Read http://api.jquery.com/fadeIn/ and http://api.jquery.com/animate/

A: you can use example created like
$("a.info-show").click(function(e){

$(this).parents('article').find('.info-wrap').fadeIn('slow');
    $("a.info-show").hide('slow');
    return false;
});

$("a.info-close").click(function(e){

$(this).parents('article').find('.info-wrap').fadeOut('slow');
 $("a.info-show").show('slow');
    return false;
});

and use fiddle link to test your question.

A: Make sure your script is running inside onready, other than that it seems fine.
$(function(){
    $("a.info-show").click(function(){
        $(this).siblings('.info-wrap').animate({ opacity: 'show' }, "slow");
        return false;
    });
})

Demo: Fiddle

A: TRY:
$("a.info-show").click(function(e){
    $(this).closest("article").find("div.info-wrap").fadeIn(500);
});

Also make sure that the classes are actually present when jquery initialises. If you are using ajax for this, it might be a good idea to bind these to a parent node

A: Your code looks fine to me. Only problem that i can think of is that you are not binding the click function to an event (like document.ready()). Here is a working JSFiddle for you.
JS
$(document).ready(function(){
    $('.info-show').click(function(){
        var info = $(this).parent().find('.info-wrap > p');
        info.animate({ opacity: 1 }, "slow");
    });
    $('.info-close').click(function(){
        var info = $(this).parent().find('p');
        info.animate({ opacity: 0 }, "slow");
    });
});

Also make sure you initially set the opacity to 0 for this to work.
CSS
article .info-wrap > p {
   opacity: 0;
}

A: Try with .prev():
$("a.info-show").click(function () {
   $(this).prev('.info-wrap').fadeIn();
   return false;
});

checkout the fiddle


text:
Q: How do I update a text label in SwiftUI? I have a SwiftUI text label and i want to write something in it after I press a button.
Here is my code:
Button(action: {
                registerRequest() // here is where the variable message changes its value
            }) {
                Text("SignUp")
            }
            Text(message) // this is the label that I want to change

How do I do this?

A: With only the code you shared it is hard to say exactly how you should do it but here are a couple good ways:
The first way is to put the string in a @State variable so that it can be mutated and any change to it will cause an update to the view. Here is an example that you can test with Live Previews:
import SwiftUI

struct UpdateTextView: View {
    @State var textToUpdate = "Update me!"
    var body: some View {
        VStack {
            Button(action: {
                self.textToUpdate = "I've been udpated!"
            }) {
                Text("SignUp")
            }
            Text(textToUpdate)
        }
    }
}

struct UpdateTextView_Previews: PreviewProvider {
    static var previews: some View {
        UpdateTextView()
    }
}

If your string is stored in a class that is external to the view you can use implement the ObservableObject protocol on your class and make the string variable @Published so that any change to it will cause an update to the view. In the view you need to make your class variable an @ObservedObject to finish hooking it all up. Here is an example you can play with in Live Previews:
import SwiftUI

class ExternalModel: ObservableObject {
    @Published var textToUpdate: String = "Update me!"
    func registerRequest() {
        // other functionality
        textToUpdate = "I've been updated!"
    }
}

struct UpdateTextViewExternal: View {
    @ObservedObject var viewModel: ExternalModel
    var body: some View {
        VStack {
            Button(action: {
                self.viewModel.registerRequest()
            }) {
                Text("SignUp")
            }
            Text(self.viewModel.textToUpdate)
        }
    }
}

struct UpdateTextViewExternal_Previews: PreviewProvider {
    static var previews: some View {
        UpdateTextViewExternal(viewModel: ExternalModel())
    }
}


text:
Q: Undo a checkout that has no activity attached to it Somehow one of my checkouts in UCM has no  activity attached to it and when i try to to undo checkout, it says that cleartool: Error: To operate on UCM branch, must be set to an activity and a UCM view. Has anyone come across this kind of scenario? Please advise.
According to IBM we could remove the view and all its references and then re-create it which should solve the issue of the checkout.
Is there a way to find what has gone wrong and any suggestions to fix the issue?

A:
According to IBM we could remove the view and all its references and then re-create it which should solve the issue of the checkout.

Yes, it is the nuke-view approach:
cleartool rmview -force -uuid (uuid_of_the_view) -vob \aVob

Keep it mind it will cancel any checkout produced by that view.

Is there a way to find what has gone wrong and any suggestions to fix the issue?

Maybe the activity was somehow deleted, leaving the checked out version "orphaned" (in term of activity, that is).
An cleartool lshistory -minor on the vob (vob:\avob) for instance, or the element of the file (path/to/file@@) might reveal some event which could shed light on this circumstance.


text:
Q: Analyzing cProcess output I have a python script that analyzes an output of a Perforce server. With this I have two different ways to output the what processes are running at a given time.
1.Matching process indents with start of process indent (P120 would have 119 indents)
+P1
     +P2
-P1
           +P3
           -P3
     -P2
2.Matching process indents with the number of processes running
+P1
     +P2
         +P3
         -P2
     -P3
-P1
For both of these functions the input is a list of process object that I have created.
Code for type 1: (SLOW)
def visual_output_match(processes):

output_string = ""
process_number = 1
indent_number = 0
running_processes = []

# Go through each process
for process in processes:
    # Assign a process number to the new process that is about to start
    process.set_process_number(process_number)

    # This will append the process onto a list of processes that are currently running
    running_processes.append(process)

    # Get a list of processes that have ended before the new process started
    ending_processes = check_ended_processes(running_processes, process)

    # Delete the processes that have ended from the running_processes list
    running_processes = remove_running_processes(running_processes, ending_processes)

    # Print all the processes that finished before the new process began
    for p in ending_processes:
        # Tabs over the correct amount depending on how many processes are running
        indent_number = p.get_process_number() - 1
        output_string += ('\t' * indent_number)
        output_string += ("-P" + str(p.get_process_number()) + "   " + p.short_srting_summary_end() + '\n')

    # Tabs over the correct amount depending on how many processes are running
    indent_number = process.get_process_number() - 1
    output_string += ('\t' * indent_number)
    output_string += ("+P" + str(process.get_process_number()) + "   " + process.short_srting_summary_start() + '\n')
    process_number += 1
return output_string`

Code for type 2: (FAST)
def visual_output_not_match(processes):

output_string = ""
number_tabs = 0
process_number = 1
running_processes = []

# Go through each process
for process in processes:
    # Assign a process number to the new process that is about to start
    process.set_process_number(process_number)

    # This will append the process onto a list of processes that are currently running
    running_processes.append(process)

    # Get a list of processes that have ended before the new process started
    ending_processes = check_ended_processes(running_processes, process)

    # Delete the processes that have ended from the running_processes list
    running_processes = remove_running_processes(running_processes, ending_processes)

    # Print all the processes that finished before the new process began
    for p in ending_processes:
        number_tabs -= 1
        # Tabs over the correct amount depending on how many processes are running
        output_string += ('\t' * number_tabs)
        output_string += ("-P" + str(p.get_process_number()) + "   " + p.short_srting_summary_end() + '\n')

    # Tabs over the correct amount depending on how many processes are running
    output_string += ("\t" * number_tabs)
    output_string += ("+P" + str(process.get_process_number()) + "   " + process.short_srting_summary_start() + '\n')
    number_tabs += 1
    process_number += 1
return output_string

For the exact some number of processes the 1st type will take upwards of 11 minutes while the other one will only take around 1 second. Now I realize that with type 1 if I have 11,000 processes then I will at some point have 11,000 tabs on a given line and with type 2 that is not true. Although would that be the only thing that is slowing my script down? Does anyone else see any other critical errors. Let me know if you need to see some of the other methods that I call in this script.
Now I did run a cProfiler on these two functions and this is what I get:
1: (SLOW)
     3381490 function calls in 681.195 seconds

     Ordered by: internal time

     ncalls  tottime  percall  cumtime  percall filename:lineno(function)
          1  679.175  679.175  681.182  681.182 visual_output.py:107(visual_output_match)
      13706    0.568    0.000    0.769    0.000 visual_output.py:147(check_ended_processes)
      13706    0.404    0.000    0.657    0.000 visual_output.py:162(remove_running_processes)
      13706    0.258    0.000    0.264    0.000 server_info.py:398(short_srting_summary_start)
      13702    0.257    0.000    0.264    0.000 server_info.py:402(short_srting_summary_end)
     787125    0.206    0.000    0.206    0.000 server_info.py:67(__eq__)
     800837    0.118    0.000    0.118    0.000 server_info.py:267(get_datetime_end)
     800837    0.080    0.000    0.080    0.000 server_info.py:264(get_datetime_start)
     800828    0.038    0.000    0.038    0.000 {len}
      54816    0.028    0.000    0.028    0.000 server_info.py:308(get_process_number)
      13706    0.018    0.000    0.018    0.000 server_info.py:406(set_process_number)
          1    0.013    0.013  681.195  681.195 <string>:1(<module>)
      27408    0.013    0.000    0.013    0.000 {method 'time' of 'datetime.datetime' objects}
      27408    0.011    0.000    0.011    0.000 {method 'append' of 'list' objects}
      13702    0.010    0.000    0.010    0.000 {method 'pop' of 'list' objects}
          1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

2: (FAST)
           3354269 function calls (3354219 primitive calls) in 1.981 seconds

     Ordered by: internal time

     ncalls  tottime  percall  cumtime  percall filename:lineno(function)
          1    0.688    0.688    1.981    1.981 visual_output.py:67(visual_output_not_match)
      13706    0.407    0.000    0.563    0.000 visual_output.py:147(check_ended_processes)
      13706    0.375    0.000    0.603    0.000 visual_output.py:162(remove_running_processes)
     787125    0.189    0.000    0.189    0.000 server_info.py:67(__eq__)
     800837    0.079    0.000    0.079    0.000 server_info.py:267(get_datetime_end)
     800837    0.075    0.000    0.075    0.000 server_info.py:264(get_datetime_start)
      13706    0.059    0.000    0.061    0.000 server_info.py:398(short_srting_summary_start)
      13702    0.053    0.000    0.055    0.000 server_info.py:402(short_srting_summary_end)
     800850    0.035    0.000    0.035    0.000 {len}
      13706    0.005    0.000    0.005    0.000 server_info.py:406(set_process_number)
      27408    0.005    0.000    0.005    0.000 server_info.py:308(get_process_number)
      13702    0.004    0.000    0.004    0.000 {method 'pop' of 'list' objects}
      27434    0.003    0.000    0.003    0.000 {method 'append' of 'list' objects}
      27408    0.003    0.000    0.003    0.000 {method 'time' of 'datetime.datetime' objects}
          1    0.000    0.000    1.981    1.981 <string>:1(<module>)
          2    0.000    0.000    0.000    0.000 {method 'send' of '_socket.socket' objects}
       24/2    0.000    0.000    0.000    0.000 brine.py:202(_dump)
       12/2    0.000    0.000    0.000    0.000 brine.py:179(_dump_tuple)
         10    0.000    0.000    0.000    0.000 brine.py:106(_dump_int)
       10/2    0.000    0.000    0.000    0.000 brine.py:360(dumpable)
          2    0.000    0.000    0.000    0.000 protocol.py:220(_send)
          2    0.000    0.000    0.000    0.000 protocol.py:227(_send_request)
          2    0.000    0.000    0.000    0.000 channel.py:56(send)
          2    0.000    0.000    0.000    0.000 <string>:531(write)
          2    0.000    0.000    0.000    0.000 stream.py:173(write)
          2    0.000    0.000    0.000    0.000 brine.py:332(dump)
       14/8    0.000    0.000    0.000    0.000 brine.py:369(<genexpr>)
          5    0.000    0.000    0.000    0.000 {method 'pack' of 'Struct' objects}
          2    0.000    0.000    0.000    0.000 protocol.py:438(_async_request)
          2    0.000    0.000    0.000    0.000 brine.py:150(_dump_str)
        6/2    0.000    0.000    0.000    0.000 {all}
          2    0.000    0.000    0.000    0.000 protocol.py:241(_box)
         24    0.000    0.000    0.000    0.000 {method 'get' of 'dict' objects}
          2    0.000    0.000    0.000    0.000 {method 'join' of 'str' objects}
          2    0.000    0.000    0.000    0.000 brine.py:173(_dump_long)
          2    0.000    0.000    0.000    0.000 {method 'acquire' of 'thread.lock' objects}
          2    0.000    0.000    0.000    0.000 {next}
          4    0.000    0.000    0.000    0.000 compat.py:17(BYTES_LITERAL)
          2    0.000    0.000    0.000    0.000 {method 'release' of 'thread.lock' objects}
          1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

I am trying to makes sense of this to see where it is getting slowed down. The only difference that I really see is that the first call for the function has a different totime.
Does anyone have a better code analyzer that I could use?
Let me know if there is anything else you might need.

A: You might wanna try building a look up table of "tab strings".
Instead of:
output_string += ('\t' * indent_number)

Try:
output_string += indent_string[ident_number]

Obviously this needs some logic to only prepopulate the array up to a certain level and keep dynamically building if it goes beyond. But quick hack should give you an idea if this is your problem.


text:
Q: Dataframe not recognized for GINI function (package reldist) I want to calculate the Gini coefficient using the library reldist.
This is my code :
library(reldist)

year_return <- read.csv("year_return.csv")
year_return[3:19] <- lapply(year_return[3:19], function(x)
  as.numeric(as.character(x)))
year_return[[2]] <- as.Date(year_return[[2]])
str(year_return)

gini(year_return[3:19],w)

This is the error I get :

Error in `[.data.frame`(x, ox) : undefined columns selected

This is w :
     [,1]       [,2]       [,3]       [,4]       [,5]       [,6]       [,7]       [,8]       [,9]
     0.04591712 0.04078667 0.04126135 0.05131896 0.04349168 0.04834431 0.04694083 0.03904389 0.04117694
  [,10]      [,11]      [,12]      [,13]      [,14]     [,15]      [,16]      [,17]     [,18]
     0.04537461 0.04692524 0.04045692 0.04696848 0.05087293 0.1713231 0.08499888 0.04396601 0.0708321

This is what I get for str(year_return) :
X       Date  .SXQR  .SXTR  .SXNR  .SXMR  .SXAR  .SX3R  .SX6R  .SXFR  .SXOR  .SXDR  .SX4R  .SXRR  .SXER
1 1 2000-01-03 364.94 223.93 489.04 586.38 306.56 246.81 385.36 403.82 283.78 455.39 427.43 498.08 457.57
2 2 2000-01-04 345.04 218.90 474.05 566.15 301.13 239.24 374.64 390.41 275.93 434.92 414.10 476.17 435.72
3 3 2000-01-05 338.22 215.88 464.20 542.29 298.22 239.55 373.26 383.48 272.54 430.05 406.33 466.19 436.23
4 4 2000-01-06 343.13 218.18 470.82 529.33 300.69 249.75 377.26 383.48 272.47 434.15 417.91 464.59 438.26
5 5 2000-01-07 349.46 220.10 478.87 531.65 306.50 255.17 381.19 390.23 273.76 447.02 428.54 474.40 445.40
6 6 2000-01-10 356.20 223.01 484.07 581.82 310.84 252.75 387.74 393.75 278.76 453.80 431.81 473.14 440.15
    .SXKR  .SX7R   .SX8R  .SXIR  .SXPR
1 1016.39 489.65 1070.72 466.36 368.62
2  971.51 471.23 1015.13 450.38 365.89
3  924.57 464.75  949.91 446.67 363.78
4  887.88 461.62  935.48 448.10 370.22
5  918.33 465.41  970.17 456.69 376.62
6  944.22 467.89 1002.93 460.26 373.81

Here you can find the dataset I am using (year_return.csv)


text:
Q: make jquery slidy slider width 100% i am using this slider - > http://writerservices.us/slidy/ for your information.
I need to make slider width 100%, so in every resolution it stays 100%.

This is the html js code, there is variable width, bet when i write width: "100%" it doesn`t do what i want.
and html slider code looks like that

A: According to slidy's own documentation, the "width" option is to always be provided in pixels and never percentages (https://github.com/wbotelhos/slidy).
I would recommend using a different slider that supports percentage widths.

A:
Use width:"100% !important"

        </div

A: try this fiddle
    $('#menu').slidy({
        animation: 'slide',
        children: 'a',
        menu: true,
        pause: true,
        speed: 1100,
        time: 400001111111111111,
        width: $(document).width(),
        height: $(document).height()
    });


text:
Q: Separable ODE's I came across this question in my tutorial sheet for my ODE class, and got a bit stuck.
The differential equation $x y^\prime =y ( \ln (x)- \ln (y))$ is neither separable, nor linear. By making the substitution $y(x) = xv(x)$, show that the new equation for $v(x)$ is a separable equation.
My working:
substitute $y(x) = x v(x)$ so,
$x y^\prime = x v( \ln(x)- \ln(y))$
$y^\prime =v(\ln(x)-\ln(y))$
Now, the part Im confused about is how to actually show that this equation is separable. Any help would be much appreciated, thanks in advance.

A: We have
$$y = v x \implies y' = v + v' x$$
Substituting (notice you did not substitute $y'$ in order to reduce it to a Separable Equation).
$$x y' = x (v + v' x) = y(\ln(x) - \ln(y)) = v x(\ln(x) - \ln(vx))$$
Can you continue now?
Hint: Start by solving for $v'$ and then see what you have.


text:
Q: how to join two tables into a new table for display in c#? I have two tables (Flights details) , (Dates of flights)
Flights
id  |    callsign   |    type
1   |     BAW240    |    A370
2   |     AAL767    |    B777
3   |     JTE201    |    A320

Dates
ID  |       date
1   |     10/10/2016
1   |     10/12/2016
1   |     10/14/2016
1   |     10/15/2016
2   |     11/25/2016
2   |     11/29/2016
3   |     10/20/2016
3   |     10/21/2016
3   |     10/22/2016

I want to join two tables like this
id  |    callsign   |    type   | dates
1   |     BAW240    |    A370   | 10/10/2016 , 10/12/2016 , 10/14/2016 , 10/15/2016
2   |     AAL767    |    B777   | 11/25/2016 , 11/29/2016
3   |     JTE201    |    A320   | 10/20/2016 , 10/21/2016 , 10/22/2016

this final table is just for preview , and letting the user see a summary of dates.
how can i achieve this?

A: I used many times this technique in order to list multiple invoices associated to a receipt.
USE AdventureWorks2008R2
SELECT CAT.id, CAT.callsign, CAT.type,
            STUFF((SELECT ',' + SUB.dates AS [text()]
                        — Add a comma (,) before each value
                        FROM Dates SUB
                        WHERE
                        SUB.flightid= CAT.id
                        FOR XML PATH('') — Select it as XML
                        ), 1, 1, '' )
                        — This is done to remove the first character (,)
                        — from the result
            AS dates
FROM  Flights CAT

Source:
https://sqlandme.com/2011/04/27/tsql-concatenate-rows-using-for-xml-path/

A: Select A.*
      ,Dates=B.Dates
 From  Flights A
 Cross Apply (Select Dates=Stuff((Select Distinct ',' + cast(Date as varchar(25))
               From  Dates
               Where ID=A.ID
                For XML Path ('')),1,1,'')
               ) B

Returns
id  callsign    type    Dates
1   BAW240      A370    2016-10-10,2016-10-12,2016-10-14,2016-10-15
2   AAL767      B777    2016-11-25,2016-11-29
3   JTE201      A320    2016-10-20,2016-10-21,2016-10-22


text:
Q: jQuery AJAX calls getting fired multiple times within click handler I'm currently developing a PHP web app, and I'm making use of the datatables jQuery plugin, and jQuery AJAX calls to create a dynamic table that can have elements edited, deleted and added. This (seems to be) working fine, however, I've observed that within some of my click handlers, AJAX calls are being fired multiple times - and I'm not quite sure why.
Here is the page at the moment so you have an idea of where I'm coming from:

As you can see, I have basic data on users, and actions to the left. Each row in the table looks like this in the HTML:

    <?= $userAccount['firstName'] ?>
    <?= $userAccount['lastName'] ?>
    <?= $userAccount['email'] ?>
    <?= $userAccount['jobTitle'] ?>

        <i data-userId="<?= $userAccount['id'] ?>" class="fas fa-user-edit enrolr-standard-icon mr-2 event-user-edit">
        <i data-userId="<?= $userAccount['id'] ?>" class="fas fa-user-times enrolr-danger-icon mr-2 event-user-delete-staff">

Since (after the initial page load/render) these table rows are being removed/added dynamically, I decided to therefore listen for events at the document level for clicks on the .event-user-delete-staff class, like so:
$(document).on('click', '.event-user-delete-staff', function () {
    // Storing some details for later use by handlers
    const userEmail = $(this).closest('tr').find('td').eq(2).html();
    const $button = $(this);

    // Shows confirm dialog, only performs deletion when "yes" is clicked, which causes the third function parameter to run
    confirmDialog(`Are you sure you want to delete ${userEmail}? This action cannot be undone.`, 'Confirm Deletion', function () {
        const $parentToRemove = $button.closest('tr');

        // Make post to remove user.
        $.ajax({
            type: 'POST',
            url: '../php/account/_deleteUser.php',
            data: {
                id: $button.attr('data-userId')
            },
            dataType: 'json',
            success: function (response) {
                // Handle response.
                if (response.success == true) {
                    displaySuccessToast(response.message);
                    // Fade out row then update datatable.
                    $parentToRemove.fadeOut(500, () => {
                        staffTable.row($parentToRemove).remove().draw();
                    });
                } else {
                    displayErrorToastStandard(response.message);
                }
            },
            error: function () {
                // Show error on failure.
                displayErrorToastStandard('Something went wrong while handling this request');
            }
        });
    });
});

Now, the reason I noticed the AJAX calls are being made multiple times is because I noticed multiple toast messages are being displayed for each delete event (The displaySuccessToast method, all this does is clone a toast template and display it). The following basically happens:

*

*First deletion from table - works fine, row is removed and success message displays.

*Second deletion from table - This is where things start to get funky. Correct row is deleted from table, however, two toasts show and two AJAX calls are made.

*Third deletion from table - Trend continues, now 3 toasts get displayed and 3 AJAX calls are made.

Having added some console logs and stepping through the code, I can tell this isn't because the $(document).on('click', '.event-user-delete-staff', function () event listener is firing multiple times. It only fires once per deletion, as it should.
I think the suspect is the confirmDialog() method, as I've observed via some console logs, it is in here that it is firing multiple times.
This method looks like this:
window.confirmDialog = function (message, title, yesCallback) {
    // Sets some details in the confirm dialog
    $('#confirmMessage').html(message);
    $('#confirmTitle').html(title);

    // Shows the modal
    $('#confirmModal').modal('show');

    // On the "yes" button within the dialog being clicked, hides modal and calls the yesCallback function.
    $('#confirmBtnYes').on('click', function () {
        $('#confirmModal').modal('hide');
        yesCallback();
    });

    // On "no" just hides the modal.
    $('#confirmBtnNo').on('click', function () {
        $('#confirmModal').modal('hide');
    });
}

However, I suspect it's not really the fault of this method; but is some kind of misunderstanding of mine as to how function callbacks like this work, and using variables from the parent scope within them?
As I've said; I don't think this is because the event listener itself is firing multiple times, on the second deletion (and beyond...), the event still only logs being called once, it is within the confirmDialog function callback method where it logs twice.
Can someone please advise what I'm doing wrong here, and what could be causing this behaviour?
Edit - For posterity, and anyone else who stumbles across this and wants to know what I changed...
The problem in this case, is that each time the confirmDialog method was being called, it would add another listener to the yes button. This means, when the yes button in that dialog was clicked, it would fire the most recent event... and all the other ones attached before. I simply changed the confirm button yes dialog to look like so:
$('#confirmBtnYes').off().on('click', function () {
    $('#confirmModal').modal('hide');
    yesCallback();
});

Using off() first ensures no other event listeners are lingering around on that yes button. Probably not the best or cleanest solution, but hey, it works.
A thank you to Nick with his answer below, who pointed out where I was going wrong

A: You're adding a new event handler to the Yes button in the confirm dialog every time you call confirmDialog:
$('#confirmBtnYes').on('click', function () {
    $('#confirmModal').modal('hide');
    yesCallback();
});

This means that the first time you click the yes button, yesCallback will get called once, the second time yesCallback will get called twice, etc. etc.
You're also doing the same for the No button, but since that just hides the modal it doesn't really affect the operation of the page.


text:
Q: Im trying to find if a number is a prime or not and an error throws "The operator && is undefined for the argument type int int" public class prime {

    public static void main(String[] args) {

        int a=2;

        if (a/=2  && a/=1)
            System.out.println(a + "is a prime number");
        else
            System.out.println(a +"is not a prime number");

    }

}

P.S- this is my 3rd code that Im writing all on my own.!!
not sure if conceptually I am on the right path to find the answer.. some help will be really appreciated

A: The operator && (logical and) is a short-circuit logical boolean operator. You need boolean expressions to use it. /= is a shorthand for division and assigning. a /= 2 is a = a / 2. This is not a boolean expression, so you can't use an && operator.
It's worth looking at the documentation here and here for a summary of assignment operators like /= and logical operators like &&.

A: *

*You will need "%" to check if number is divide completely. "%" is remainder operator and number is divide completely if remainder is equal to 0.

*Probably you misunderstood the task. You need to check if number does not divide completely. The number can be divide completely only by them self and by 1. So you need to check if number is divide completely by all smaller positive numbers (for n it will be n-1, ..., 2, if you will consider 2, then you start from 2 - 1, so you start from 1, and 1 < 2, so you don't check any number). If you found at lest one such nuber that divide completely your number, then your number is not prime. If you don't find, then your number is prime.
E.g when n is 7, you need to chekc if 7 is divide completely by 6, 5, 4, 3, 2. It will be 7%6 == 1, 7%5 == 2, 7%4 == 3, ... (you will don't get 7 % X == 0, there is no such X, so 7 is prime)
When n is 8, you need to check 7, 6, 5, 4, 3, 2.
And it will be 8 % 7 == 1, 8 % 6 == 2, 8 % 5 == 3, 8 % 4 == 0 (you found 8 % X == 0, it will be for 4 and for 2, to 8 is not a prime)
if(n % 2 == 0) {
    System.out.println(n + "is divide completely by 2");
} else {
    System.out.println(n + "is not divide completely by 2");
}

int x = 7;
int y = 5;
System.out.println("remainder of dividing x by y is "+(x % y));


text:
Q: Div Set to Viewport Height, Even When Screen Resized I am looking to make a div called nav (featured at the very top) take up the entire screen height, even when the screen is resized. This is the script that Ive included in my index file, but it does not work. (I tried working with height: 100vh, but that didn't work for me either.)

A: No need for jScript here. I think what you're looking for is the css flexbox-model:
html, body {
  height: 100%;
}
body {
  display: flex;
}

#nav {
  flex: 1;
}

Havent tried it here, but that one should work for you. Simply add height: 100%; display: flex to the parent and flex: 1 on the child element.
Referring to https://css-tricks.com/snippets/css/a-guide-to-flexbox/

A: Using Jquery you can go with this
CSS
    body {
        padding:0;
        margin: 0;
    }
    #nav {
        width:100%;
        background-color:#abc;
        text-align:center;
    }

    #height {
        font-size:20px;
    }

HTML

Script
    $(window).on("resize", function(){
        var height = $(window).height();
        $("#nav").css({ "height": height });
        $("span#height").html("the height is " + height);
    }).resize();

This should work both on load and resize thanks to the use of the ".resize()" in the last section of the function.
Keep in mind that "$(window).height()" return the height of the window WITH the horizontal scrollbar, if rendered.
VH is not fully supported on all the browsers so avoid it for now.


text:
Q: A question about a property of spectral density $f(\lambda)$, i.e. $f(\lambda) \geq 0$. I'm reading Time Series analysis from the book Introduction to time series and forecasting by Peter J. Brockwell and Richard A. Davis. I'm going through the chapter of Spectral Analysis.
Where spectral density defined as
$$
f(\lambda) = \frac{1}{2\pi} \sum_{|h| < \infty} \exp{(-ih\lambda)} \gamma(h)
$$
Here $\{\gamma(h)\}_{|h|<\infty}$ is is auto covariance function of time series $\{X_t\}_{|t|<\infty}$.
I'm basically stuck in the proof of $f(\lambda)\geq 0 $. there is a step
$$
\frac{1}{2\pi N}\sum_{|r|<N}\sum_{|s|<N} \exp{(i\lambda(r-s))}\gamma(r-s)
$$
$$
= \frac{1}{2\pi}\sum_{|h|<N}\bigg(1 - \frac{|h|}{N}\bigg) \exp{(i\lambda h)}\gamma(h)
$$
How to derive the second line from the first line?

A: I think this is just a counting argument, but somehow I don't get the result you get in your question, so I'll leave my argument here so maybe it is useful to you or someone can correct it (or you can find a flaw in your book). The summand in the double summation only depends on $r-s$, and when $|r|,|s| < N$, the difference $r-s$ also satisfies $|r-s| < N$. So set $h \overset{def}{=} r-s$ and count the number of pairs $(r,s)$ satisfying $|r| < N$, $|s| < N$ and $r-s = h$.
One easily found such pair is $r=h$ and $s=0$. Since we want $|r-s| = h$ and $|r|$, $|s| < N$, the pairs look like this for say $h > 0$:
$$
(-N+1+h, -N+1)), \cdots, (0, -h), \cdots, (h, 0), \cdots, (N-1, N-1-h)
$$
Of course, the case $h < 0$ will have the same count, so the answer depends only on $|h|$. You see that the answers $(0,-h), (1,-h+1), \cdots, (h-1,1),(h,0)$ account for $|h|+1$ answers, and for $r < 0$ you have $N-(|h|+1)$ answers, and similarly for the answers with $s > 0$. This gives you a total of $2(N-(|h|+1)) + |h|+1 = 2N-(|h|+1)$ such pairs. So you can re-write your sum as
$$
\frac 1{2\pi N} \sum_{|r|,|s| < N} \mathrm{exp}(i\lambda(r-s)) \gamma(r-s)
$$
by putting together the terms involving $(r,s)$ with $|r|,|s| < N$ and $r-s = h$ and just put your count in front of the term, which gives
$$
\frac 1{2\pi N} \sum_{|h| < N} (2N-(h+1)) \mathrm{exp}(i\lambda h) \gamma(h)
$$
By bringing the factor $\frac 1N$ in the summation, you get
$$
\frac 1{2\pi} \sum_{|h| < N} \left( 2-\frac{|h|+1}N \right) \mathrm{exp}(i\lambda h) \gamma(h)
$$
One possible reason that I see for the discrepancy in our counts is if you're really summing over $0 \le r,s < N$ instead of $|r|,|s| < N$, because then the count becomes $N-|h|$ instead of $2N-(|h|+1)$, and you get the correct factor. That may explain your mistake (or the author's).
Hope that helps,


text:
Q: Indexing across a mount point in windows I have a new windows 7 computer. The first thing I did was in stall a 2nd hard drive and mount it at C:/Users/me this seems to work just fine, except one issue.
Search does not find and file there, and the indexing service will not index it.
I think the latter is the cause of the former. Is there a to tell the indexer to look past the mount point?

A: After much searching, I found this: http://support.microsoft.com/kb/260207
It explains that drives mounted to folders are not indexed BY DESIGN.
It does not explain what kind of brain dead design this is, or what the reasons are.

A: They explain  a bit more about this "issue" here:

Monitoring the USN change journal is
  new to WS 3.0. The benefit is that we
  can use the journal change log to
  determine file changes without
  rescanning the files on the drive,
  even if the search service is not
  running.

In the thread, they give a link to a Windows Search add-in which may work with Windows 7, but only for the 32-bit versioon so I cannot confirm it.

*

*Supported Operating Systems: Windows Server 2003; Windows Server 2003 Service Pack 1; Windows Vista; Windows XP Service Pack 2
Note x64 bit installations are not supported

*

*Windows Desktop Search 03.00.0000.XXXX or later versions

*Windows Search 04.00.6001.XXXXX

I'm not sure which version of Windows Search is included in Windows 7 though. The Indexer Gadget returns "Windows Search version 6.1.7600.16385" but that's the version of Windows 7. Maybe Windows Search doesn't have a separate version number anymore?

A: I have a similar issue on Windows 7 64bit. What I found is that if you (through Explorer) go to the folder to which the drive is mounted to, and then go into a subfolder, and the type something in the search textbox in the upper right corner, you will get a popup asking you whether you want to index this "unindexed" folder. If you click yes, the indexing service will index the folder.
Now I have no idea how to remove this location from the index as it doesn't show up in the "Indexed locations" window. But the files are indexed, no doubt! EDIT: It seems that after the folder is deleted or unmounted, one can see the paths in "Indexed locations" window as unavailable.
One could tweak the registry and add mountpoints manually: see here
I also find thet my mount point is correctly registered here:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows Search\UsnNotifier\Windows\Volumes

A: Have you check in "Indexing options", "Modify"? From there you can select drives to be indexed.

A: I had a similar problem and was recommended to install Windows Desktop Search Addin for Networks, - works well for me now.
 http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=f7e981d9-5a3b-4872-a07e-220761e27283


text:
Q: Prerequisites for understanding algebraic geometry of "algebraic gerbes" I am trying to learn about algebraic geometry of gerbes.
I am familiar with set up of gerbes in the case of differential geometry. Though there is some similarity between differentiable gerbes and gerbes as mentioned above, they are not quite same.
So, what are the prerequisites to learn about gerbes in the algebraic geometry set up? I am familiar with notion of stacks. What other Grothendieck topologies and stacks over categories with that Grothendieck topologies should I be comfortable with to understand and use the notion of gerbe mentioned above.


text:
Q: Why can't curl retrieve the SSH host key (key: ) I've been using curl (by means of git-ftp) for a while, and passing only username and an sftp URL.
Authentication would always work implicitely through publickey.
Suddenly curl will not connect through SSH anymore – apparently because it does not get a host key and therefore rejects the connection:
Trying {IP}...
* Connected to host.example.com ({IP}) port 22 (#0)
* SSH MD5 fingerprint: {Fingerprint}
* SSH host check: 2, key: <none>
* Closing connection 0
Why can't curl get the key?
Connections with ssh -v work and do give me 2 host keys, also curl --insecure will work.

A: libssh2 does not support some later keys like ecdsa-sha2-nistp256 and ssh-ed25519.
So if you already have one of these keys in your .ssh/known_hosts, libssh2 will fail. But you can add another key that libssh2 supports, like RSA:
To fix it, retrieve the RSA public key from the remote host and add it to your known_hosts file:
ssh-keyscan hostname.example.com >> ~/.ssh/known_hosts
The exact format and file location might vary by system.

A: I fixed the problem by replacing the ipv6 address with the domain, inside of the known_hosts file.
It happened to already exist in a file named known_hosts2 in the same directory, but I guess this file is not actually read by ssh/curl.


text:
Q: RDF4J List of Valid Triple Indexes is there a list of valid triple indexes to initialize a nativestore?
I searched in the github repo rdf4j-storage but couldn't find an enumeration or something similar.

A: Triple stores use indexes based on subject, object, predicate and context. The index structure is given by the order of the first letter of each of these words, so, for example spoc, posc (these are the most common).
Any 4-letter permutation of these is accepted by RDF4J native store.
See for example https://github.com/eclipse/rdf4j-storage/blob/master/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/TripleStore.java, method parseIndexSpecList.


text:
Q: PostgresQL for each row, generate new rows and merge I have a table called example that looks as follows:
ID | MIN | MAX |
1  | 1   |  5  |
2  | 34  | 38  |

I need to take each ID and loop from it's min to max, incrementing by 2 and thus get the following WITHOUT using INSERT statements, thus in a SELECT:
ID | INDEX | VALUE
1  |  1    |   1
1  |  2    |   3
1  |  3    |   5
2  |  1    |   34
2  |  2    |   36
2  |  3    |   38

Any ideas of how to do this?

A: The set-returning function generate_series does exactly that:
SELECT
  id,
  generate_series(1, (max-min)/2+1) AS index,
  generate_series(min, max, 2) AS value
FROM
  example;

(online demo)
The index can alternatively be generated with RANK() (example, see also @a_horse_with_no_name's answer) if you don't want to rely on the parallel sets.

A: Use generate_series() to generate the numbers and a window function to calculate the index:
select e.id,
       row_number() over (partition by e.id order by g.value) as index,
       g.value
from example e
  cross join generate_series(e.min, e.max, 2) as g(value);


text:
Q: bind method from Bluebird saves context(this) between calls After this docs http://bluebirdjs.com/docs/api/promise.bind.html I expect
that life of binded context will ends with end of call. But apparently it is not.
Following code:
const Promise = require('bluebird');

const chain = (callNumber) => {
    console.log('call:', callNumber, '============');
    return asyncFunction()
        .bind({})
        .then(() => {
            console.log('this', callNumber, this);
            this.t = 1
        })
        .then(() => {
            this.t2 = 2
        })
        .then(() => {
            console.log('this', callNumber, this);
        })
};

const asyncFunction = () => new Promise((resolve) => {
    return Promise.delay(100)
        .then(resolve);
});

chain(1).then(() => chain(2));

produces this result:
call: 1 ============
this 1 {}
this 1 { t: 1, t2: 2 }
call: 2 ============
this 2 { t: 1, t2: 2 }
this 2 { t: 1, t2: 2 }

Expected result:
call: 1 ============
this 1 {}
this 1 { t: 1, t2: 2 }
call: 2 ============
this 2 {}
this 2 { t: 1, t2: 2 }

Is this correct behaviour or I made mistake somewhere?

A: Bluebird Promise.bind is misused. It's supposed to be used with dynamic this:

Without arrow functions that provide lexical this, the correspondence between async and sync code breaks down when writing object-oriented code. .bind alleviates this.

E.g.:
promise.bind({})
.then(function () {
    console.log('this', callNumber, this);
    this.t = 1
})

With arrow functions, this is lexical and refers to Node module, module.exports. It stays the same between chain calls.


text:
Q: SQL matching column with another in same table, IN statement not working I'm trying to make an SQL query. I'm still new to SQL, maybe someone could give me some direction, or let me know if this is even possible.
Please note I have read up on IN, ALL, INNER JOIN etc and I still cannot get the proper query. I have tried to find the solution for hours.
These are my table columns:
+-----------+---------------+------+-----+---------+-------+
| Field     | Type          | Null | Key | Default | Extra |
+-----------+---------------+------+-----+---------+-------+
| route     | varchar(100)  | NO   | PRI | NULL    |       |
| stopID    | varchar(5)    | NO   | PRI | NULL    |       |
| stopName  | varchar(100)  | NO   |     | NULL    |       |
| Latitude  | float(10,6)   | YES  |     | NULL    |       |
| Longitude | float(10,6)   | YES  |     | NULL    |       |
| timeList  | varchar(1000) | NO   |     | NULL    |       |
| day       | varchar(5)    | NO   | PRI | NULL    |       |
+-----------+---------------+------+-----+---------+-------+

I need the stopId's and stopNames where the stopName matches another stopName with a different stopID AND the day='Week' (Otherwise a total of 3 results will come back since there are Week, Sat, Sun days.).
| 16    | 1639   | MYUNIQUESTOPNAME  |   43.514000 |  -80.199600 | (a really long list of times) | Week  |
| 5     | 0530   | MYUNIQUESTOPNAME  |   43.514000 |  -80.199600 | (a really long list of times) | Week  |

SELECT stopID,stopName FROM Routes WHERE stopName='MYUNIQUESTOPNAME' AND day='Week';
+--------+---------------------------+
| stopID | stopName                  |
+--------+---------------------------+
| 1612   | MYUNIQUESTOPNAME          |
| 1639   | MYUNIQUESTOPNAME          |
| 0530   | MYUNIQUESTOPNAME          |
+--------+---------------------------+

Gives me what I want, but that's only for one stop, and doing it this way, I would have to do it manually. There's a lot of stops.
Secondly, I would then want all the id's and names that have NO matches (are unique to the bus route).
SELECT stopID,stopName FROM Routes WHERE stopName IN (SELECT stopName FROM Routes WHERE day='Week') AND day='Week';

The above DOES NOT GIVE ME WHAT I WANT. All my searching implies that it is though... What am I doing incorrectly...?
mysql version is 5.5.41-0+wheezy1

A: With the query you are running you will return all stops as the nested query will always contain the stop from the outer query.
Use the following to stop this from happening.
SELECT stopID,stopName AS s1
FROM Routes
WHERE stopName IN (SELECT stopName AS s2
                   FROM Routes
                   WHERE day='Week'
                   AND s1.stopID <> s2.stopID)
AND day='Week';

A: If you want a list of stops where the list is small ad you can use IN:
SELECT stopID,stopName
FROM Routes
WHERE stopName IN ('MYUNIQUESTOPNAME', 'ANOTHERNAME', 'AThirdNAME') AND day='Week';

To get a list of stops where the stopName exists more than once for a week day:
SELECT stopID,stopName
FROM Routes
WHERE stopName IN
  (SELECT DISTINCT stopName
   FROM Routes
   WHERE day = 'Week'
   GROUP BY stopName
   HAVING COUNT(stopName) > 1)
AND day='Week';

A: Do a self join on the table (routes) on the column (stopName) and then get all the results where day=week and stopIds are not same. This would give you the answer to the first query
Select unq.stopId, unq.stopName from Routes unq join Routes other on other.stopName=unq.stopName where unq.stopId!= other.stopId and unq.day = 'Week'

For the second one where you want only those which are unique, do a group by on stop name and pick the records where grouping results in only one record
Select unq.stopId, unq.stopName from Routes unq group by unq.stopName having count(*) = 1


text: Q: Download files from fileshare I'm creating a inno installer/updater. Now I need a way to download my files from a fileshare. I found already some solutions for downloading over ftp/http but non over a smb file share. Is it possible to download/copy a file from a smb file share using inno setup? And how to do it if it is possible?


text:
Q: Spring Cassandra store a List with custom object's I like to store a object like:
@Table(value = "my_table")
public class MyTableDto {
  @PrimaryKeyColumn(name = "uid", type = PrimaryKeyType.PARTITIONED)
  @CassandraType(type = DataType.Name.UUID)
  private UUID uid;

  @Column(value = "child_ids")
  private List<ChildIdDto> childIds;
}

Then I get the exception:
Caused by: org.springframework.dao.InvalidDataAccessApiUsageException: Only primitive types are allowed inside Collections for property [childIds] of type ['interface java.util.List'] in entity [de.myapplication.repository.dto.MyTableDto]

I do understand the exception, but is there another way to persist custom objects?
EDIT:

*

*When I comment out this attribute, everything works

A: ! Never say never, I got the solution.
To give a good example, I will list all according classes.
ParentClass.java
@Table(value = "my_table") //OPT
public class MyTableDto {
  @PrimaryKeyColumn(name = "uid", type = PrimaryKeyType.PARTITIONED)
  @CassandraType(type = DataType.Name.UUID)
  private UUID uid;

  @Column(value = "child_ids") //OPT
  private List<ChildDto> childIds;
}

ChildDto.java
@UserDefinedType // THE SOLUTION
public class ChildDto {
  @Column(value = "child") //OPT
  @CassandraType(type = DataType.Name.TEXT) //OPT
  private String groupId;

  @Column(value = "description") //OPT
  @CassandraType(type = Name.TEXT) //OPT
  private String description;
}

The @UserDefinedType is the solution.
For more information see here.
NOTE: Each annotation with "OPT" is NOT required


text:
Q: Can Laravel Dusk Run in a CLI Application? This question technically had two parts:

*

*is the chrome driver of Dusk functional in a CLI app?

*would Laravel Zero be able to work with Dusk?
I would like to create a command line app that runs some personal banking automation. I know Dusk can be used with external sites, but I don't have experience in Dusk with CLI apps and I've not yet used Laravel Zero.

A: Yes to both questions. Laravel Dusk accepts a --headless option for running a headless version of chrome.
Within the DuskTestCase class, you can supply the arguements needed like:
$options = (new ChromeOptions)->addArguments([
   '--disable-gpu',
   '--headless',
   '--no-sandbox',
]);