get current page/url in attribute selector

Question: I am trying to style some text menu in my css, when the link of that menu equals the current url. But doesn't seem to work. This is the sentence:
#pages.tabs ul li a[href$=location]{color:blue !important;}

, where #pages.tabs ul li is the menu list where are located those links. I guessed the location thing contained the current url in css. But i don't even know if this can be achieved only with css.
Many thanks in advance,
Comment: You can't do that with only CSS. You need server side script or JavaScript to do this.
Answer: This can not be done with css only you need to use javascript too. Give a class to current url li and give styling from css. like
Html

Home

Useful Sites

Software

The Workbench

Contact

Css
.currentpage {
   color: #640200;
   background-color: #000000;
}

Comment: Can I embeed a javascript function inside css template (using
Comment: you can use script tag.
Answer: Only use addClass or removeClass from JQuery.
Css code:
.liactive{background-color:#3C6EC9;}

Jquery code:
$(document).ready(function(){

$('ul li').click(function(){
  var items=$('ul li').get();
  for(var i=0;i<items.length;i++)
  $(items[i]).removeClass('liactive');
  $(this).addClass('liactive');
 });

});

I made this code for you. Have fun ^^
Here is your example --------> Knee's JSFiddle
Comment: thank you very much, sorry for late reply. I don't know if I can insert this code in my web, because it is a blogger site with 'dynamic view' template enabled. Because of this, I was trying to do it only via css.
Comment: Slightly simpler, more readable JQ solution (1) 2 lines of code in the event handler (removeClass & addClass), (2) cut out extra html ( are superfluous bloat here) - http://jsfiddle.net/bhilleli/e0cu3kb2/14/


Distinct random variables in sampling

Question:
Let $X_1,X_2,\dots$ be i.i.d. random variables with $X_1 \sim U[0,1]$.
  Throwing out a null set all the variables are distinct.

Can anyone explain this second sentence? What does he mean with "throwing out a null set"?
Comment: It means that the sets $\{ X_i = X_j \}$ have measure zero.
Answer: It means, "with probability $1$, the $X_i$ are distinct", or "the event that the $X_i$ are not distinct is a null set".

Distinct random variables in sampling


error in mongo DB query - $cond operator

Question: This is BSON document. I want only those entries whose attribute length is greater than zero
/* 1 */
    {
        "_id" : "http://exhentai.org",
        "length" : 0,
        "value" : ""
    }

    /* 2 */
    {
        "_id" : "http://vuclip.com",
        "length" : 77,
        "value" : "vuclip scroll learn official weve launched close news team pressroom linkedin"
    }

    /* 3 */
    {
        "_id" : "http://hbogo.com",
        "length" : 174,
        "value" : "hbo hbo anywhere hbo enjoy instant unlimited access every episode every season best hbo shows movies comedy sports documentaries hbo free subscription participating providers"
    }

So output should be
       /* 2 */
        {
            "_id" : "http://vuclip.com",
            "length" : 77,
            "value" : "vuclip scroll learn official weve launched close news team pressroom linkedin"
        }

        /* 3 */
        {
            "_id" : "http://hbogo.com",
            "length" : 174,
            "value" : "hbo hbo anywhere hbo enjoy instant unlimited access every episode every season best hbo shows movies comedy sports documentaries hbo free subscription participating providers"
        }

What I tried
db.coll.aggregate([
    {$project: {
       Text:
               {
                 $cond: { if: { $gte: [ "$length", 20 ] }, then: "$value" }
               }
       _id : 0
     }}
])

Answer: This can be simply done using $gt Operator
db.collection.find({'length':{ $gt:0 }})


get relative paths to files in ruby

Question: I have a folder structure as follows:
.
└── FolderA
    ├── a.cpp
    ├── b.cpp
    ├── c.cpp
    ├── FolderB
    │   ├── trial.cpp
    │   └── trial1.cpp
    └── FolderC
        └── srcFolder
            └── anothercppfile.cpp

I wanted to store the names of all .cpp files which are present in FolderA in an array. I have to ensure that I preserve the relative paths of the files which are present in folders inside FolderA.
I can use:
require 'find'
cpp_file_paths = []
Find.find('path/to/search') do |path|
  cpp_file_paths << path if path =~ /.*\.cpp$/
end

But I do not get the relative paths. I am unsure on how to proceed. The final array must be:
["a.cpp",
 "b.cpp",
 "c.cpp",
 "/FolderB/trial.cpp",
 "/FolderB/trial1.cpp",
 "/FolderC/srcFolder/anothercppfile.cpp"]

Comment: Your question is still not much clear.. Could you draw a FS Tree and tell us the exact output? That will help us to help you confidently ?
Answer: You can use Dir.glob:
Starting with Ruby 2.5 there's a base argument:
cpp_file_paths = Dir.glob('**/*.cpp', base: 'FolderA')
#=> ["a.cpp", "b.cpp", "c.cpp", "FolderB/trial.cpp", "FolderB/trial1.cpp", "FolderC/srcFolder/anothercppfile.cpp"]

For older Rubies, you can chdir into the base directory:
Dir.chdir('FolderA') do
  cpp_file_paths = Dir.glob('**/*.cpp') #=> ["a.cpp", "b.cpp", "c.cpp", "FolderB/trial.cpp", "FolderB/trial1.cpp", "FolderC/srcFolder/anothercppfile.cpp"]
end

Note that the paths are relative, i.e. they don't start with a /. Passing a block to chdir ensures that the current directory is restored afterwards (thanks Arup Rakshit).
Comment: Nice answer! You can *pass* the block with `::chdir` method.

get relative paths to files in ruby


How is the approximation justified and how to improve it?

Question: In an attempt to find the solution to the equation

$Mx=e^x$ with $M$ being a large real number and the solution $w \gt 1$

I was asked to justify why $\ln M$ is a reasonable approximation to $w$.
I was also asked to improve the approximation by writing $w=\ln M +y$. I need to find an approximation for $y$ hence improve the approximation $\ln M$.
I vaguely know that $\ln M$ is reasonable because $M$ is large, but feel a bit uncertain, and I do not quiet understand the second part of the question. Could somebody help me please?
Answer: $\ln M$ is a rough approximation because it turns the dominant term, $e^x$, into $M$; so we are off by a factor of $\ln M$ "only": $M\ln M\ne e^{\ln M}$.
What could be a good choice of $y$ to make $w=\ln M+y$ a better appoximation? Just as the first approximation dealt with the factor $M$ on the left, we may want choose $y$ so that it deals with the (now) secdond factor $\ln M$; that is, we let $y=\ln\ln M$.This we we find $M\ln w=M\ln M+M\ln\ln M$ and $e^w=e^{\ln M+\ln\ln M}=M\ln M$.
Another way to put this and at the same time to see how to continue to a full sequence of improving approximations: Apply $\ln$ to both sids of the original equation to get
$$x=f(x)=\ln M+\ln x. $$
Now we are looking for a fixed point of $f$ and - at least in the range we are interested in - we have $|f'(x)|=\frac1x\approx \frac1{\ln M}\ll 1$. Therefore the sequence defined by $x_1=\ln M$, $x_{n+1}=f(x_n)$ converges quite nicely to a limit $w$ that solves the original equation. Actually, it doesn't even matter a lot what we pick as first approximation $x_1$ (for example, we get the very same sequence with just one additional term if we start with the very different starting point $x_0=1$).


CopyToDataTable is not a member of system.array

Question: I have a function in a VB.Net script file, but it produces the error 'CopyToDataTable' is not a member of 'system.array'. Any ideas?
Public Function CollectionFromTable(tableName As String, sql As String, sortOrder As String) As DataTable
    Dim foundRows() As DataRow
    foundRows = ds.Tables(tableName).Select(sql, sortOrder)

    Return foundRows.CopyToDataTable
End Function

Note: I have the following imports at the top but still get the error.
Imports System
Imports System.Data
Imports System.Windows.Forms
Imports System.Math
Imports Microsoft.VisualBasic
Imports System.Collections.Generic
Imports System.Data.DataRow
Imports System.Linq
Imports System.Drawing
Imports System.Xml
Imports System.Collections

Answer: It's an extension method in the DataTableExtensions class. You need to have a reference to the System.Data.DataSetExtensions.dll. (You've already got an import for the right namespace.)
Answer: If you're looking for this method (CopyToDataTable from DataTableExtensions), it's in System.Data.DataSetExtensions. Do you have that assembly referenced in your project?
Answer: I had the same issue in VS2010 and now it is solved by adding the above reference. To add the ref. in VS2010 menu go to >Project >> Properties >> from right tab select Reference >> click Add button >> click .NET tab >> select the System.Data.DataSetExtensions reference >> done!
Thank you Jon Skeet.


Reverse while loop

Question:     while($data=$SQL->fetch(PDO::FETCH_ASSOC)){
       echo $data=['message'];
   }

is that possible to reverse while loop?
I have a page echo out messages and I need put in reverse
SQL- DESC LIMIT 20
fetch last 20 messages
but my chat box is print in reverse
message 1 (oldest message)
message 2
message 3 (newest message)

Comment: Why not just order your SQL query?
Comment: @HenkJansen Adjusting the query should be preferred especially for large datasets, as it can become a performance problem there.
Comment: You can also put the result in an array first, and then reverse the array, but i think it's better if you use @BenFortune's solution.
Comment: possible duplicate of [MYSQL select last 3 rows, order by ASC](http://stackoverflow.com/questions/8891060/mysql-select-last-3-rows-order-by-asc). Have a look at the accepted answer.
Answer: You should define the order of the data set in your original SQL query.
See documentation for the ORDER BY clause.

Update

It seems that the OP wants the 20 newest messages, but ordered in reverse. Then you need to perform a subquery like this:
SELECT `message`
FROM (SELECT * FROM `table`
      ORDER BY `id` DESC
      LIMIT 20) AS `i`
ORDER BY `i`.`id` ASC;

Comment: the problem is, i fetch DESC last 20 messages, but my chat box is reverse
Comment: when query desc, it put newest message on top, but i need it at bottom
Answer: After fetching records You can just reverse your returned array
https://www.php.net/array_reverse
Comment: a query does not return an array.
Answer: If you really want to reverse the data in PHP, you can use array_reverse:
// Fetch all records
$data = $SQL->fetchAll(PDO::FETCH_ASSOC);

// Reverse them
$data = array_reverse($data);

foreach ($data as $record) {
    echo $record['message'];
}

Although I would recommend ordering in SQL, as it will be faster.

Reverse while loop


why # is not printing in dialer in the given code, I just want to print # in the dialer

Question: In this I want to print the number *555# in the dialer, but only " * * *555**" is printing not with"#"
Comment: Can you please share whatever code you already have so that we can see where you are stuck.
Answer: It looks like you're parsing a tel: URI here.
In a URI a hash/pound/# is a special character so you'll need to url encode it. # url encoded is %23.
So changing the string to be "tel:*555%23" should do it.
Answer: You can replace the # with %23
i.e.
"*555%23"


PowerBI Web app Dashboard Sample error AADSTS50011

Question: I download the integrate-dashboard-web-app and enter the ClientSecret and the ClientID values in the cloud.config file. But when I run the project I am getting this error "AADSTS50011: The reply address 'http://localhost:13526/Redirect' does not match the reply addresses". Is there some additaional setting I need to add to the Azure Active Directory? I dont see anything that related to the application for power BI in Azure
Answer: I got the same error. Below is how I fixed it:

Ensure that the Redirect URL set on the Power BI App (registered) is http://localhost:13526/Redirect
In the sample app, ensure the Cloud.config RedirectUrl setting has the value http://localhost:13526/Redirect
In the sample app, in the Page_Load method in redirect.aspx.cs, change the line:
string redirectUri = String.Format("{0}Redirect", Properties.Settings.Default.RedirectUrl);
to:
string redirectUri = String.Format("{0}", Properties.Settings.Default.RedirectUrl);


How to increase mouse sensitivity in Skyrim?

Question: How can i increase mouse sensitivity in Skyrim?

on the main menu the mouse cursor is sluggish
in-game mouse sensitivity is too low

Things i've tried:

increasing Look Sensitivity in-game:

In my SkyrimPrefs.ini file:

Increasing [Controls]\fMouseHeadingSensitivity from 0.0125 to 1.0500
Adding [Controls]\fMouseHeadingXScale = 1.0500
Adding [Controls]\fMouseHeadingYScale = 1.0500
Turning off mouse acceleration: Changing [Controls]\bMouseAcceleration from 1 to 0
Turning off v-sync: Adding [Display]\iPresentInterval = 0

Changing Detail in the launcher to Low from auto-detected Ultra

Running in Windowed mode

Turning off Steam's Overlay UI:

Increasing my mouse pointer speed in Windows

Note: My question is different from How can I sync vertical/horizontal mouse sensitivities?, which looks to make the poor mouse sensitivity equal in both directions. i want not poor mouse sensitivity.
Note: "C:\Program Files (x86)\Steam\steamapps\common\skyrim\Skyrim\SkyrimPrefs.ini"
Note: And restarting Skyrim after each change.
Note: Including details of what i've tried are only presented to shut people up who bitch about a "lack of research effort". i should be able to ask my question with explanation, justification, or research. Also people love screenshots - it draws them in like moths.
See also

FoV and sensitivity.
How do I even out the mouse sensitivity?
Tweaks to make Skyrim that much better (self.skyrim)
Comment: I need to know the opposite myself. When in the menu, the mouse is too sensitive and I've tried adjusting mouse sensitivity via control panel.
Comment: did you try to increase cursor speed in you (OS) config panel?
Comment: This question is relevant to my interests. I did all of this, as well as turning off mouse acceleration. The DPI on my G500 is maxed out at 2500 right now, and it still requires a ton of arm movement and lifting up the mouse just to turn around. :( Have you tried capping the framerate at 30fps? I've heard that worked for some people. I'm trying to find the method and I'll update this post when I do.
Comment: Heads-up: [Disabling Vsync is HIGHLY UNRECOMMENDED. It introduces bugs with physics, time-scaling, graphics and controls](http://gaming.stackexchange.com/a/103571/4797)
Answer: The suggested SkyrimPrefs.ini i was using was the wrong one.
Using Process Monitor i was able to figure out that the correct one is:
%USERPROFILE%\Documents\My Games\Skyrim\SkyrimPrefs.ini

e.g.
C:\Users\Ian\Documents\My Games\Skyrim\SkyrimPrefs.ini

Changing [Controls]\fMouseHeadingSensitivity to
fMouseHeadingSensitivity=0.1250  (new)
fMouseHeadingSensitivity=0.0125  (old)

did the trick.
Comment: @aediaλ In the SkyrimPrefs.ini file, under [Interface] there is the line: `fMouseCursorSpeed=1.0000` Change that value to whatever you want, and ta da! Your mouse should be faster in the menus!
Comment: I was having this issue and thought I was going crazy when after a day of playing I'd tried most of the things documented in your question, even changed my wireless mouse batteries, and nothing worked. My existing value was `fMouseHeadingSensitivity=0.0500`, I think, but the new value you suggest still worked well for me. Thank you so much for the clear writeup. (I found the post from Google when I wasn't logged in while gaming, and it was a huge help.)
Comment: Perfect information!!
Comment: This worked great for me in game. In the main menu the mouse is still TERRIBLY slow. Any ideas on how I might fix it?
Comment: @dborba There i cannot help you; i feel your pain.


Attaching Suspended Ceiling Angle to Drywall Only?

Question: I'm finishing my basement, and made a mistake.
The wall in some portions was only framed in up to 84". I'm matching the height of my suspended ceiling to the bottom of a steel I-beam the crosses the whole basement at a height of - you guessed it - 85".
I've already insulated, drywalled, primed and painted.
I'm looking for a way to affix the angle to the drywall. It'll be 100ish inches long on the offending wall, bearing half the weight of four-ish half-tiles, so not terribly much. I'm wondering if drywall anchors should be stout enough.
I know the proper answer is to frame up behind the drywall, but I'm not gonna. There are reasons.
Answer: If I'm understanding correctly, the drywall extends 1" past the top of the framing, and that's where you want to attach the angle for the suspended ceiling?

I would normally suggest screw-in type anchors for this (much stronger than the push-in kind), but I'd be worried that installing one will cause damage the top edge of the drywall, and make the anchor useless. If you want to go that way, try it in a piece of scrap first.
Given that it's not a lot of weight, you'd probably be okay with push-in anchors (where you drill a hole then push them in). Just be careful during drilling and don't hammer them too hard. The tiles aren't heavy nor are they subject to dynamic loads. I'd put an anchor in every 16 or maybe 24".
A better bet would be a "Toggler": they push in through a hole (minimizing potential to damage the drywall) but flatten out and have much more strength than the typical push-in anchors.

You'll have to hold the angle up, mark the holes, then pre-drill and install the anchors before you can actually mount it, of course. Bit of a pain but not as much as taking down and then refinishing drywall.
Comment: Gregmac, that is exactly the situation, your illustration is perfect. I did a little research on different types of drywall fasteners after posting this and found that they make little molly bolts designed for 1/2" drywall. I think I'll get my hands on some of those and try them out. One point of clarification though: I need to install my angle about 1" higher than the framing stops, but my drywall is another 5" or 6" higher than that, so I'm not too worried about damaging fragile drywall edge.
Comment: @JimStewart I did mention those and while I think they're great my concern is that because they compress the gypsum, installing them too close to the edge like this could result in the gypsum coming out and both visually damaging the drywall but more importantly having no holding strength. If it's the edge with paper folded over it, *maybe* it would work, but I'd still be skeptical.
Comment: Stay away from the plastic zip ties with a metal backing plate, they are awful, the plastic breaks and the metal falls behind your drywall.  Stick to the product gregmac has in his pic, they are far superior, i used after i broke a few of the zip tie ones.
Comment: @gregmac the OP added in a comment that the drywall goes 5" or 6" above the location of the anchors. A really superior drywall anchor is sold for use with elfa shelving systems, but these might be overkill for this application. https://www.containerstore.com/s/elfa/components/installation-hardware-tools/elfa-drywall-plaster-anchors/123d?productId=10031759&country=US&currency=USD&utm_source=tcscompshop&utm_medium=feed&utm_campaign=google&cid=cse:PLA
Comment: Thanks all for the help! It seems I have plenty of solid options. I generally have little faith in drywall for structure, so that was the driving concern behind my question. I'll probably opt for whichever solution will allow me to suck the angle flat against the drywall, so I don't have a little gap caused by the 'lip' found on most push-in types.


How to insert update & delete the data from the database in powerbuilder

Question: Can any one please help me how to Insert the data into database from window form. How to fetch the data to show on window form & same to update the data from database. I am looking for the  code that contain sql query with in the code not from the quick select data window. I am very new in powerbuilder.I want to write a code fetch update data from the code any where & show anywhere.
Thanks
Answer: I'm not quite sure about your question. Try going to this website http://powerbuilder.hyderabad-colleges.com.
Look for Datawindow control and Datawndow object topics.
There are other ways to manipulate data in Powerbuilder like using Embeded SQL (stored procedure and cursors).
I hope this will help you.
Comment: This documentation is very outdated in some points (like the support for mac & unix and the requirement to have a 486 or a "fast" 28.8 modem...) but the basics of using a datawindow are unchanged. It could help a beginner provided that he manages to find the GUI equivalents of PB5/6 into a recent PB. Also, the parts talking about creating C++ classes with Watcom C++ are irrelevant nowadays.
Comment: Just because Java is difficult to use doesn't mean you have make PowerBuilder difficult to use.
Comment: Like in JAVA we can give the Query with in the code. Retrive the data from Object.
 PreparedStatement st = con.prepareStatement("select * from task4Table ");
    ResultSet r1=st.executeQuery();

So same like how can we fetch,update the data  from the code not from the Data window.
Comment: The equivalent is what's called Embedded SQL in the documentation (as the responder suggests). However, using a DataWindow object will be better performing, more maintainable, reusable, etc.... Not only should the phrase "When in Rome, do as the Romans do" apply, but you should also ask why the Romans like doing it that way.
Comment: Stick with Java might be better idea I think too dangerous to use a tool with this much power.
Answer: The whole point of the Datawindow is that it does all that work for you.
Retrieve data:
dw_1.Retrieve(arguments)
Update the database:
dw_1.Update()
Answer: I'm not understanding the question entirely you must be having trouble with a multi-table update they can be challenging for a new developer.
This will do an update into two tables I did it in a hurry so might be a syntax error or two.
<code>// insert a row
li_row = dw_1.insertrow(0)
dw_1.setitem(li_row, 'col1', 'try reading')
dw_1.setitem(li_row, 'col2', 'the PowerBuilder')
dw_1.setitem(li_row, 'col3', 'manual next time')

// do accept text left out for purposes of brevity

// Update first table and dont bother with another accepttext
// since weve already done one and dont set the updateflags
// so second half of update creates correct sql statement
li_rtn = dw_1.Update(false, false)
if li_rtn = 1 then
  dw_1.modify('tbl1_col1.Update = No')
  dw_1.modify('tbl1_col2.Update = No')
  dw_1.modify('tbl1_col3.Update = No')
  dw_1.modify('tbl1_id.Key = No')
  dw_1.modify("Datawindow.Table.updateable = 'tbl2'")
  dw_1.modify('tbl2_col1.Update = Yes')
  dw_1.modify('tbl2_col2_id.Key = Yes')
  li_rtn = dw_1.update(false, true)
  if li_rtn = 1 then
    commit using sqlca;
  else
    rollback using sqlca;
  end if
end if
// cleanup the temp recs
li_rowcount = dw_1.rowcount()
for li_row = li_rowcount to 1 step -1
   dw_1.deleterow(li_row)
next
dw_1.Update()
</code>


Size of Image after watermarking

Question: I'm curios what happens to the size of the host image after an invisible watermark has been inserted. I'm guessing the size will increase but by how much?
For example, the cover image to be inserted is 1kb and the host image is 2kb. Since your adding additional information the size will be 3kb after the embedding process?
Comment: Depends on the compression algorithm.
Answer: I think it depends on the algorithm used for inserting the watermark. If the watermark is inserted without any quality loss, it is likely that the file would increase by at least 2KB.
Comment: I'm using DCT and will embed the watermark in the middle band coefficient. The watermark that will be inserted is a gray scale with the size of 123 x 123.

Size of Image after watermarking


What is the correct order of transformations scale, rotate and translate and why?

Question: This is a rather primitive question coming from an electronic engineer. When applying rotate (about origin), scale (in which we shall translate towards origin and then back) and translate, does it matter in what order we do it? Why?
Basically in my case I have an image in coordinate space that goes from -2 to +2 in x and -1.5 to +1.5 in y to get ration of 4:3. This range comes from how the original mandelbrot set is plotted. I need to scale and translate this to fit into an axes (of pixels) in bitmap that goes from 0 to 800 in x axis and 0 to 600 in y axis. I am trying to understand what matrix to use to scale and translate the points from my mandelbrot set into the bitmap image.
Answer: Usually you scale first, then rotate and finally translate. The reason is because usually you want the scaling to happen along the axis of the object and rotation about the center of the object.
In your case you don't really need to worry about this generic solution though, but you only need to map range [0, 800] $\rightarrow$ [-2, 2] for x-coordinate and [0, 600] $\rightarrow$ [-1.5, 1.5] for y-coordinate, in order to map screen coordinates to real/imaginary components for Mandelbrot calculation. So this is simply done by:
$$real=4*(x+0.5)/800-2$$
$$imag=3*(y+0.5)/600-1.5$$
Note that you need to calculate Mandelbrot coordinates from screen coordinates and not the other way around. This is to ensure that you evaluate the Manderbrot equation for each pixel exactly once and are not left with holes in the image or do double evaluation per pixel.
Comment: Yeah, but that's not correct. You need to do the inverse to evaluate the Mandelbrot equation for each pixel in your image exactly once. I should have probably emphasized that in my answer.
Comment: @quantum231 unless you get a coordinate in the [0, 600][0, 800] space and need to know what it was in the [-1.5, 1.5][-2, 2] space to sample it.
Comment: errrr I assign range from [-2,+2] to [0, 800] and [-1.5, 1.5] to [0, 600] and not the other way around. I thought this was clear from my question.
Comment: Hi, did you derive that equation?


Is there a way of downloading a file (such as PDF) and storing it on the device with Capacitor?

Question: Is it possible to download and store files (accessing the file system) with Capacitor? I've only been able to find Cordova plugins, but would like to keep the app pure using Ionic and Capacitor.
Answer: You should simply use download() method like this:
this.pdfObj.download();

Here you can find more info: https://forum.ionicframework.com/t/do-you-know-how-to-save-and-open-a-pdf-using-capacitor-and-ionic-4/158634/3
Answer: You can use Filesystem plugin for Capacitor to handel file-system and you can write your file inside directory
You can find reference for plugin here.
downloadFile(options: DownloadFileOptions) => Promise<DownloadFileResult>


Using App Engine Datastore Low Level API with Java

Question: How to find the total number of entries in an entity type in App Engine Datastore using Low Level API?
I there a function or filter to query for this purpose?
I am using Java to implement this.
Comment: possible duplicate of [what is the GQL count query](http://stackoverflow.com/questions/27177513/what-is-the-gql-count-query)
Comment: @Patrice That link in that answer redirects to Python docs not Java.
Comment: Fair enough, but the logic would be the same. You can either use user87049's answer, or do a generic "get all entities of kind" and run a "count()" on the returned object.
Answer: App Engine has an API for getting datastore statistics programmatically:
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Entity globalStat = datastore.prepare(new Query("__Stat_Total__")).asSingleEntity();
Long totalBytes = (Long) globalStat.getProperty("bytes");
Long totalEntities = (Long) globalStat.getProperty("count")

See the documentation: https://cloud.google.com/appengine/docs/java/datastore/stats
You can get entities of a kind using __Stat_Kind__
Comment: "__Stat_Total__" and "__Stat_Kind__" doesn't work in local development server. Only works in App Engine Server.


How to install .deb file from within preinst script?

Question: I have my own application packaged using dpkg. The application depends on several .deb files which I'm trying to install from within the preinst script of my application. The preinst script checks if a dependent deb file is installed, if not it goes to install it using the dpkg -i command. This is repeated for all the dependent deb files needed by the main application.
When I try to install the main application using dpkg -i, the commands returns failure when trying to execute the preinst script. Below is that error message:
dpkg: error: dpkg status database is locked by another process

I deleted /var/lib/dpkg/lock file and retried to install the application. But to no avail. If I run the preinst script separately like any other shell script, it runs without any issue. All the deb files will be installed properly. So, the issue is only when this preinst script is being run automatically by the dpkg -i command.
I'm lost trying to determine the root cause. If anyone can shed some light on what the real issue might be, their help will be greatly appreciated.

Thank you, ObsessiveSS0F for your quick response.
I understand the point you are making but that will not help my situation. Let me tell you why.

My main application (let's say mainapp.deb) depends on five other .deb files
(let's say 1.deb, 2.deb and so on).
The dependent .deb files are my own private packages/libraries. So these are not
downloadable from the web. So, I cannot use apt-get to install these automatically.
I would make the "Depends" field in the control file to point to 1.deb, 2.deb..etc,
but as you know dpkg -i will not automatically install the dependencies.
I can execute dpkg -i, followed by apt-get -f install, but for apt-get to work, I
have to edit the /etc/apt/sources.list file to add a reference to the local directory
on the system where the dependent .deb files are stored.
Well, #4 seems to work but is not an option for me because this application will be
installed on many servers and the installation program has to be fully automated.

I continued to investigate the reason why preinst was failing to install the .deb files and I think I have found out why.

When I run dpkg -i mainapp.deb,the dpkg process is creating the /var/lib/dpkg/lock
and some files under /var/lib/dkpg/updates directory.
Now, the preinst script has a series of dpkg -i commands to install the dependent
.deb files. So, as soon as the first dpkg -i command in the preinst script is
executed, it fails because of the locks created by the earlier dpkg command.
It seems that two dpkg commands cannot be executed in parallel because of the locks.

I modified the preinst script to backup the locks created by the dpkg process to a temporary location and deleted the original locks. (the lsof command did report that the
locks were deleted). Now that the locks were gone, the dpkg -i commands within the preinst script executed without any issues. I restored the locks back before exiting the preinst script so that the primary dpkg -i command could continue. It worked but I have a feeling that this is not the right approach.
I'm still trying to figure out alternate ways for installing a .deb file along with it's dependencies.
Comment: Could you share the preinst script?, I'm in a similar situation and would like to read the solution instead of figure it out by myself =)
Comment: Nevermind, I figure it out, https://gist.github.com/chilicuil/74fddda2a31bba09b973
Answer: It is not needed to use a preinst script to install .deb files. You can simply add dependencies and then package using an archive, and any dependencies and pre-depends will be automatically installed.
Answer: The thought of shuffling lock files makes me uncomfortable.  If it's guaranteed not to mess with the application install then it doesn't seem like there should be a problem however I believe that the pre-install script is more for things like stopping services that will be affected by the installation.
It seems the root cause of the problem is that the pre-install script is being shelled from the dpkg operation after the lock file has been set. It seems likely that the correct way of doing it is to either separate the installation of the dependencies altogether, or to re-package the application so that it works with a local ppa and installs the dependencies correctly.
I am wondering if it might not be better to set up the dependencies with --set-selection and process them with dpkg either before or after installing the application.  The dependencies can be loaded with:
sudo dpkg --set-selections < dependency_files
Where the dependency_files is in the format, for example:
samba                   install
samba-common            install
samba-common-bin        install
samba-ldb-tools         install
samba4                  install
samba4-common-bin       install

I believe the files can then be installed with
dpkg --selected-only

It might even be possible that your pre-install script can be used for the --set-selections part of the operation at least.
As for re-packaging, I can't be of any help there, but there seems to be a community of package maintainers the would be able to help:
http://www.debian.org/devel/join/newmaint
http://www.debian.org/support


How to exclude only two symbols in a regex with \S+

Question: I have this regex
(?<=^|\s|\w[;'])(@(\S+))

to take only the usernames. I used \S because in the website there are also a lot of asian with asian nicknames (and if I use \w i have problems).
But now I have to exclude symbols like , or . added at the end of the word. How to edit it?
Live version:
https://regex101.com/r/NEz05o/2
Comment: You could exclude it `(?<=^|\s|\w[;'])(@([^\s.,]+))` https://regex101.com/r/eUXM0A/1 and you can omit the second group if you only want the value without the @ `(?<=^|\s|\w[;'])@([^\s.,]+)`
Comment: @WiktorStribiżew this looks an interesting solution... what are the characters excluded by \b?
Comment: @J.Luca All non-word chars (non-letters, non-digits, non-underscores).
Comment: @WiktorStribiżew what is the difference between \b and \W ?
Comment: Sorry, it seems I overlooked one of the examples, you do not need `\b` here. `\b` is a word boundary and `\W` matches any non-word char.
Answer: You can exclude the . and , from the match using a negated character class using [^\s.,]+ This will give you 2 capturing groups.
(?<=^|\s|\w[;'])(@([^\s.,]+))

Regex demo
If you only want the value after the @, you can use a single capturing group
(?<=^|\s|\w[;'])@([^\s.,]+)

Regex demo
Comment: @WiktorStribiżew In the example link the is an entry with `It should take only "bongo" -> @bongo.caro` that is why I exluded the dot and the comma.
Comment: thanks! I need 2 groups, so I will use (?<=^|\s|\w[;'])(@([^\s.,]+))! Just the last tip. I noted that i can not take mike if i have ".@mike". Do you know how to fix?
Comment: @J.Luca In that case you can add the `\s` and the `.` to a character class `(?<=^|[\s.]|\w[;'])(@([^\s.,]+))` See https://regex101.com/r/RZY6wi/1


using statset for changing the properties in matlab

Question: Trying to change the optimopts properties of the factoran function, namely, TolX and TolFun in Matlab but apparently the values are still remaining as the default:
 optionsFactoran = statset('TolX',1e-4,'TolFun',1e-4)

and then using the factor analysis function:
[lambda,psi,T,stats,F] = factoran(MyMatrix,10,'optimopts',optionsFactoran);

as can be seen here, the values are still the default:
>> statset('factoran')

ans =

      Display: 'off'
  MaxFunEvals: 400
      MaxIter: 100
       TolBnd: []
       TolFun: 1.0000e-08
   TolTypeFun: []
         TolX: 1.0000e-08
     TolTypeX: []
      GradObj: []
     Jacobian: []
    DerivStep: []
  FunValCheck: []
       Robust: []
 RobustWgtFun: []
       WgtFun: []
         Tune: []
  UseParallel: []
UseSubstreams: []
      Streams: {}
    OutputFcn: []

any ideas are appreciated.
Answer: Calling statset with an output argument (as you do at the start of your question) gives you a structure of Statistics Toolbox options that you can pass in to functions such as factoran. If you display the structure, you'll see that it always contains a field for each of the Statistics Toolbox options, and each has an empty value, other than the ones you specified as inputs.
You haven't "set" anything permanently (there are no global "settings" to set), you've just created a structure containing some options. You can run statset again with different inputs, and it will just give you another options structure - again, nothing global has been set.
Calling statset with no output arguments (as you do at the end of your question) and with a function name such as factoran as input just shows you the defaults for a particular function. In other words, these are the values that would be used if you didn't pass in an options structure to specify other values.
Those are always the defaults for that function - you can't change them. If you want to use something different, you create an options structure and pass it in.
Comment: thanks for the answer. I actually did change them locally (as you mentioned not globally) but since one of the `psi` values were still smaller than `0.005` I was receiving the same warning message and that was why I thought It wasn't working. Changing `TolFun` to bigger value solved the issue.


Many to many relationship with Room resulting in Error: Entities and Pojos must have a usable public constructor

Question: I am encountering the issue stated in the title. I have the following entities:
@Entity(tableName = "Person")
data class Person(@PrimaryKey var id: Int,
              var firstName: String,
              var surname: String,
              var age: Int,
              var numberOfHobbies: Int) {
    @Ignore
    constructor() : this(0, "", "", 0, 0)
}

@Entity(tableName = "Skill")
data class Skill(@PrimaryKey var id: Int,
             var skillName: String) {
    @Ignore
    constructor() : this(0, "")
}

@Entity(tableName = "PersonSkill")
data class PersonSkill(var personId: Int,
                   var skillId: Int) {
    @Ignore
    constructor() : this(0, 0)

    @field:PrimaryKey(autoGenerate = true)
    var id: Int = 0
}

And the following relationships:
data class SkillWithPersons(
    @Embedded var skill: Skill = Skill(0, "UNKNOWN"),
    @Relation(
            parentColumn = "id",
            entityColumn = "skillId",
            entity = PersonSkill::class,
            projection = arrayOf("personId")
    ) var personIds: List<Int> = emptyList()
) {
      constructor() : this(Skill(0, "UNKNOWN"), emptyList())
 }

data class PersonWithSkills(
    @Embedded var person: Person = Person(0, "UNKNOWN", "UNKNOWN", 0, 0),
    @Relation(
            parentColumn = "id",
            entityColumn = "personId",
            entity = PersonSkill::class,
            projection = arrayOf("skillId")
    ) var skillIds: List<Int> = emptyList()
) {
      constructor(): this(Person(0, "UNKNOWN", "UNKNOWN", 0, 0), emptyList())
}

And I have tried everything, and yet it does not work. I keep getting the following error with kotlin-kapt:
e: error: Entities and Pojos must have a usable public constructor. You can have an empty constructor or a constructor whose parameters match the fields (by name and type).
e:

e:   Tried the following constructors but they failed to match:
e:   Integer(int) : [value : null]
e:   Integer(java.lang.String) : [s : null]
e: error: Entities and Pojos must have a usable public constructor. You can have an empty constructor or a constructor whose parameters match the fields (by name and type).
e:

e: java.lang.IllegalStateException:

I am using the following versions:
Android Studio 3.0 with Gradle 4,
Room: 1.0.0-alpha9-1,
Build tools: 26.0.2,
Kotlin: 1.1.51
It seems there's a bug with the use of @Relation as kotin-kapt seems to no handle it. Has anyone encountered this situation before? I have even tried to remove the projection from the @Relation but even that does not seem to make a difference.
Comment: Have you tried the same Room schema in Java and annotation processor instead of kapt?
Comment: Removing the `@Ignore` from default constructors got rid of the error for me.
Comment: @Virusman that doesn't work for me
Answer: @Relation Tag in Room right now only support one to Many relation ship as mentioned by "Florina Muntenescu" in her blog post
Also for the above question make changes in your data classes as mentioned below
@Entity(tableName = "Person")
data class Person(@PrimaryKey
                  var id: Int = 0,
                  var firstName: String = "",
                  var surname: String = "",
                  var age: Int = 0,
                  var numberOfHobbies: Int = 0)

@Entity(tableName = "Skill")
data class Skill(@PrimaryKey
                 var id: Int = 0,
                 var skillName: String = "")

@Entity(tableName = "PersonSkill")
data class PersonSkill(@PrimaryKey
                       var id: Int = 0
                       var personId: Int = 0,
                       var skillId: Int = 0)

data class SkillWithPersons(
    @Embedded
    var skill: Skill? = null
    @Relation(
            parentColumn = "id",
            entityColumn = "skillId",
            entity = PersonSkill::class,
            projection = arrayOf("personId"))
            var personIds: List<Int> = ArrayList()
            )

data class PersonWithSkills(
    @Embedded
    var person: Person? = null
    @Relation(
            parentColumn = "id",
            entityColumn = "personId",
            entity = PersonSkill::class,
            projection = arrayOf("skillId"))
            var skillIds: List<Int> = ArrayList()
)

This way you can get rid of errors.


Will I visit all the explorable zones if I follow the personal storyline to the end?

Question: The next mission is going to take place in a new zone, and I'm split between completing a nearby zone now, where no mission has taken place so far and I just happened to wander in, or coming back later if the personal storyline is going to take me there eventually.
My race is Sylvari, if that makes a difference.
Comment: I havn't completed the story yet, but I doubt the story takes you to all zones. since the story quests go up in level each time, the chances of them going back to low level zones is small.
Answer: No, you will not receive missions for each zone with your personal storyline. Which zones you travel through will depend on your race and the decisions made during character creation and during your storyline.
I recently completed the personal storyline, and found roughly half a dozen zones that I had never been to.
Comment: Do bear in mind that some POI's can only be reached through the story missions. Such as the 'Trahearne Speech' area in Fort Trinity.
Comment: @DavidYell That is no longer true, btw.


BDH formula not taking an external variable

Question: I want to use an external date variable to be used in the bdh formula of the pdblp package. But for some reason .format() is not working in this case.

startdate = '20130101'

df1 = con.bdh(['FV1 Comdty',  'TY1 Comdty'], 'FUT_EQV_DUR_NOTL', '{}', '20190630').format(startdate)

It gives me the following error
InvalidArgumentException: Choice sub-element not found for name 'securityData'. (0x00020002)
Answer: Why don't you just do?
df1 = con.bdh(['FV1 Comdty',  'TY1 Comdty'], 'FUT_EQV_DUR_NOTL', startdate, '20190630')

Comment: Well that worked. I feel stupid now. I had tried the same thing yesterday but it had not worked. Maybe just carelessness. Anyway thank you for the help
Comment: Happens all the time. Cheers


SQL % of data contains a value

Question: I have a Microsoft SQL table with an organization column and an mi_status column, both of which are strings.  I want to find out for each (grouped by) organization how many of the records have an mi_status of 'In Stock', how many total records there are, and then what % of the records are In Stock.
I can easily get the In Stock part via something like this:
SELECT organization, count(*)
FROM table
WHERE mi_status = 'In Stock'
GROUP BY organiztion

but I don't know how to also get the total rows in that same select since I've got the 'where' clause there.
Answer: Use conditional aggregation:
SELECT organization, count(*) as total,
       SUM(CASE WHEN mi_status = 'In Stock' THEN 1 ELSE 0 END) as total_instock,
       AVG(CASE WHEN mi_status = 'In Stock' THEN 1.0 ELSE 0 END) as proportion_instock
FROM table
GROUP BY organization;

Comment: Nice thinking with the `AVERAGE`, but you should change it to `AVG`
Comment: @Lamak Isn't that GREAT?  Gordon demonstrated this earlier this morning.  Makes me wonder how long that has been in back pocket
Answer: Use a CASE expression:
SELECT  organization,
        SUM(CASE WHEN mi_status = 'In Stock' THEN 1 ELSE 0 END) In_Stock,
        COUNT(*) Total,
        SUM(CASE WHEN mi_status = 'In Stock' THEN 1 ELSE 0 END)*100.0/COUNT(*) Percentage
FROM dbo.YourTable
GROUP BY organization;

Answer: SELECT
    organization,
    count(*),
    (SELECT COUNT(*) FROM table) as total
FROM
    table
WHERE
    mi_status = 'In Stock'
GROUP BY
    organization

SQL % of data contains a value


Postgres Alter Column Integer to Boolean

Question: I've a field that is INTEGER NOT NULL DEFAULT 0 and I need to change that to bool.
This is what I am using:
ALTER TABLE mytabe
ALTER mycolumn TYPE bool
USING
    CASE
        WHEN 0 THEN FALSE
        ELSE TRUE
    END;

But I am getting:
ERROR:  argument of CASE/WHEN must be type boolean, not type integer

********** Error **********

ERROR: argument of CASE/WHEN must be type boolean, not type integer
SQL state: 42804

Any idea?
Thanks.
Answer: Try this:
ALTER TABLE mytabe ALTER COLUMN mycolumn DROP DEFAULT;
ALTER TABLE mytabe ALTER mycolumn TYPE bool USING CASE WHEN mycolumn=0 THEN FALSE ELSE TRUE END;
ALTER TABLE mytabe ALTER COLUMN mycolumn SET DEFAULT FALSE;

You need to remove the constraint first (as its not a boolean), and secondly your CASE statement was syntactically wrong.
Answer: Postgres can automatically cast integer to boolean. The key phrase is
using some_col_name::boolean
-- here some_col_name is the column you want to do type change

Above Answer is correct that helped me Just one modification instead of case I used type casting
ALTER TABLE mytabe ALTER COLUMN mycolumn DROP DEFAULT;
ALTER TABLE mytabe ALTER mycolumn TYPE bool USING mycolumn::boolean;
ALTER TABLE mytabe ALTER COLUMN mycolumn SET DEFAULT FALSE;

Comment: @BenJohnson try `USING mycolumn::text::boolean;`
Comment: The Accepted answer is better because it does *not* rely on type-casting. This method fails with `cannot cast type smallint to boolean`, for example.
Answer: Also check that you don't have any CHECK constraint on you column like:
[...] CONSTRAINT blabla CHECK ((field = ANY (ARRAY[0, 1])))
otherwise you alter command will error with a cannot convert to boolean type


LED T8 tubes overheating?

Question: Last fall (around mid-October), I installed two LED tube lights in a fluorescent fixture--since there were three lights total, it had two LEDs and one fluorescent bulb. A few days ago, I started running into an issue where all three lights in the fixture (not just the LEDs) would suddenly turn off and not turn back on for several hours. I've tried switching around the bulbs and tried running it with just the two LEDs, but with no luck. When I have just the one fluorescent tube in the fixture, though, it works fine.
LED tubes are Philips UniversalFit; fluorescent tube is 32W/48 T8, and the fixture says "use only T8 32W MAX lamps." Ballast is Class P electronic. Based on a cursory Google search it appears that the LED bulbs may be causing the ballast to overheat and disconnect--but if this is the case, I'm not sure why it would take several months to appear.
I live in an apartment, going ballast-free isn't really an option; I'm limited to plug-and-play LEDs. Any suggestions or insights as to what may be going on would be most welcome!
Comment: Nice job on your first post! Including the brand/model of the bulbs & ballast is something few think to do on their first post. If you could [edit] to include info on the fixture itself, that would probably also be very helpful. While you're waiting for an answer, take the [tour] and read through the [help] so you can learn how to make the most of the site.
Comment: The mis match of wattages May have finished off the ballast, hopefully you have universal led tubes that can be direct wired, direct wire also saves power and you don't have to worry about the ballast any longer.
Comment: Have you talked with your apartment's maintenance folks about the situation? They might be willing to entertain going to direct-fit if plug-and-play isn't playing nicely with your ballast...
Comment: Thanks all! I'm still having issues with the fluorescent tubes only, so I think the ballast may be the issue. Let's see if they'll simply remove it and go for direct wire...
Answer: I agree; it sounds like a blown ballast to me. As Ed Beal suggests, if the ballast is rapid-start (2 wires per tube end) the imbalance of some LEDs some real fluorescent may have caused it undue stress.  Or perhaps the ballast was starting to get marginal on its own, and using LEDs forestalled the problem until it deteriorated more.
I'd roll it back to real fluorescent and see if that takes care of it; if it does, happy dappy.  Today's real fluorescents are superb in color quality, and electronic ballasts take care of the rest of the undesirable qualities of "That 70's Fluorescent".  So no need to go LED if it works at that point.
Note that T8 real fluorescent tubes will not work on T12 ballasts or vice versa. They may "half-work" with bad side effects, and will stress out the ballast.

LED T8 tubes overheating?


Android Volley : ImageRequest deprecated

Question: I'm on Android Studio version 1.4. I'm using the Android Volley library (I use the mcxiaoke mirror here). But the ImageRequest is deprecated. The code still works but deprecated. Has anyone found an alternative for this?
I've search for this issue in Google but didn't find any solution.
Answer: I think the class is not deprecated but the constructor that you are using is deprecated.
use this constructor instead of this one
Usage example :
ImageRequest request = new ImageRequest(
                             url, myResponseListener, maxWidth,
                             maxHeight, scaleType, Config.RGB_565, myErrorListener);

Comment: thank you very much for pointing that out. Sorry for my noobness, very new to android.
Answer:  button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            final ImageRequest imageRequest=new ImageRequest (url, new Response.Listener<Bitmap>() {
                @Override
                public void onResponse(Bitmap response) {
                    imageView.setImageBitmap(response);

                }
            },0,0, ImageView.ScaleType.CENTER_CROP,null, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(MainActivity.this,"Some Thing Goes Wrong",Toast.LENGTH_SHORT).show();
                    error.printStackTrace();

                }
            });emphasized text

Answer: I've used Square's Picaso library as an alternative. It works well; you can check it out at http://square.github.io/picasso/.
Comment: Thank you for your answer. It looks interesting, sure i will try it later.
Comment: Although picasso is great, i suggest to just use volley for everything, stringrequest, jsonrequest, imagerequest. So you can benefit from lower app weight by using less libraries.


Arduino Serial monitor writes data twice

Question: I have a sketch written in Arduino IDE which monitors on 2 RXs pins signal data and writes it to Serial Monitor. I have a problem that it from 1 RX the data are always written twice, but another RX (response) is OK, what could be the problem?
So I don't think it is problem in program of MCU.
Comment: What's connected?  What's sending?  What's being sent?   Which one double prints and which one is OK?  Man, you've given almost no information to go on here.  What do you expect anyone to be able to do?
Comment: Are you maybe doing local echo and remote echo?
Comment: I attached image of communication.
I have a board with MCU(AVR) and GSM module SIM800L, I connected this arduino to Rx and Tx of MCU so I can see the whole communication. Commands from MCU (AT Commands) are doubled in Arduino Serial Monitor and response from GSM is printed normally. In MCU I use for sending simple functions (I will edit my topic and put it there)
Answer: Your SIM800L module may have Command Echo enabled. You can send the following commands to change it:
<code>ATE0        // Disable echo temporarily; After SIM800 reset, saved setting will be used.
ATE1        // Enable echo temporarily; After SIM800 reset, saved value will be used.

ATE0&W      // Disable echo and save setting
ATE1&W      // Enable echo and save setting
</code>
Reference: SIM800_Series_AT_Command_Manual (page 35, page 355 end)
Comment: It helped! Thank you very much.
Comment: Glad that it helped. And welcome to Stack Overflow! Please see [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers)


Can storing a set of pointers lead to undefined behaviour?

Question: Consider the following code:
#include <iostream>

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

  std::set<int*> ints;

  for (int i = 0; i < 10; i ++) {
    int * k = new int(i);
    ints.insert(k);
  }

  for (auto i : ints) {
    // some order-sensitive operations, for example:
    std::cout << (*i) << " ";
  }

  return 0;
}

Where the second loop is sensitive to the order in which elements are taken from the set. Is it possible that the result of execution of such program will be different in different runs of the program?
As far as I know, std::set sorts elements internally. Since allocations in memory not necessarily have increasing addresses, it is possible (though unlikely), that the output of this program will not be 0 1 2 3 4 5 6 7 8 9?
Comment: I'd say that even if the order may not be deterministic, it's still not undefined behaviour in the usual sense (http://en.wikipedia.org/wiki/Undefined_behavior).
Comment: @Pukku Yeah, I used the wrong term. Its closer to "unspecified" behaviour.
Answer: Yes, they may be different, but it will not be because of UB.
There are two things that are implementation defined here:

the way std::less<int*> does the ordering (although on most implementations you will see a "natural" ordering)
The addresses that are returned by operator new may or may not be the same every time. This will most likely vary on the allocator your implementation use, and both ways (deterministic and seemingly random) have been seen in the wild. (Note that when you run the program through e.g. valgrind the order may still be always the same, but different than when run natively).

So do not rely on this being in any particular order you are interested in.
Answer: It's not "undefined behavior" in the standard's sense (that anything can happen).
However, it is definitely unspecified what pointer addresses you will get when allocating memory. The standard says nothing about how the free store is organized, or the order of addresses for different allocations.
Answer: Use the manual, Luke.
std::set documentation in MSDN

An STL set is:
(...)
Sorted, because its elements are ordered by key values within the container in accordance with a specified comparison function.

The pointers are simply ints, so these variables will be sorted by their addresses. Memory manager can allocate these variables in very different places, so you have no guarantee, that their order (in terms of their values) will be kept.
However, it seems, that you can provide your own comparison function:
std::set::set() documentation on MSDN
You then may sort the elements of set in a way, which fits you best.
Comment: For the described Microsoft implementation, it is true that pointers are almost ints - except on Win64, where they're not. On other architectures, pointers can be even less int-like. The most famous exception is classical x86, where they're weird 20 bits beasts.


Why should you not use CONCAT() for static string literals?

Question: So you have
$sql = "SELECT * FROM `table` WHERE `some_text_field` LIKE CONCAT('%', ?, '%')";
$stmt = $dbh->prepare($sql);
$stmt->execute(array($_POST['badies_code']));

And looking at another question i found that this causes a security concern, but why?
I found this question, a downvoted answer and an upvoted comment that is why i ask
The comment said

This is not the correct way to do this. You should not use CONCAT() for three static string literals, as it opens you up to a specific type of SQL injection (i forget the name). –  Theodore R. Smith

PHP PDO prepared statement -- mysql LIKE query
Answer: It would be quite a complex task to remember the name of injection that doesn't exist.
There is nothing wrong in using concat() with prepared statement.
Comment: @Victory Without a statement from @TheodoreR.Smith we can't do anything more than just (educated) guesses. I can't imagine a situation either in which using `CONCAT` can be dangerous except from building SQL statements dynamically within stored procedures. And the *Lateral SQL Injection* technique shows that one may be vulnerable even though there is no explicit parameter involved. However, prepared statements is *the* mitigation technique that should be used whenever parameters are involved.
Comment: Can you expand on what you mean when using the terms "intentional" and "strict". Thank you
Comment: strict means strict, when you need exact value to match the given one. intentionally means intentionaly partial match. Anyway, it's only my speculations trying to explain that idea of non-existent "injection"
Comment: What do you think about Gumbo's response?
Comment: inapplicable for mysql
Answer: I think what @TheodoreR.Smith may have meant is the so called Lateral SQL Injection in Oracle Database[1][2].
It works by changing environment variables holding format information such as NLS_DATE_FORMAT, or NLS_NUMERIC_CHARACTERS, which are then used in a stored procedure that builds and executes a statement dynamically (this is where string concatenation is used, denoted by the || operators):
CREATE OR REPLACE PROCEDURE date_proc IS
    stmt VARCHAR2(200);
    v_date DATE := SYSDATE;
BEGIN
    stmt := 'select object_name from all_objects where created = ''' || v_date || '''';
    EXECUTE IMMEDIATE stmt;
END;

Here SYSDATE returns the current date in the format specified in NLS_DATE_FORMAT. Although the procedure has no parameter, changing the date format to something like ' or 1=1--:
ALTER SESSION SET NLS_DATE_FORMAT = ''' or 1=1--'

The resulting statement is:
select object_name from all_objects where created = '' or 1=1--'

This environment variable manipulation is specific to Oracle Database. And again, it can be mitigated using prepared statements:
CREATE OR REPLACE PROCEDURE date_proc IS
    stmt VARCHAR2(200);
    v_date DATE := SYSDATE;
BEGIN
    stmt := 'select object_name from all_objects where created = :date';
    EXEC SQL PREPARE prepared_stmt FROM :stmt;
    EXEC SQL EXECUTE prepared_stmt USING :v_date;
end;

I'm not aware that MySQL is prone to this kind of environment variable manipulation.
However, building statements dynamically without proper processing is prone to SQL injections, no matter whether it happens in the application or in the database. So using prepared statements in stored procedures is mandatory as well.


MouseListener is not firing fast enough

Question: I have a Class extending JFrame that is watching for a mouse click anywhere:
<code>addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e){
        System.out.println("mouse was clicked");
    }
});
</code>
I usually have to wait nearly a second between clicks to trigger the event. If I make 2 or 3 clicks in a second, only one event fires. How do you watch for fast click events?
This is my first time using Java and I'm using NetBeans.
Comment: I see no latency; something else is slowing it down.
Answer: Try using mousePressed instead of mouseClicked.  mouseClicked looks for multiple button clicks, so it will coalesce some events.
Comment: Just to clarify, the `MouseEvent` received by `mouseClicked()` reports the click count supplied by the host's native driver. The latter may or may not take user preferences into account, as discussed in comments following @aperkins' answer.
Comment: You are my hero.
Answer: Hopefully this helps 3.5 years later for anyone searching for answers to the same problem :)
When you click on the mouse you will fire the following events.

MousePressed
MouseDragged (if you pressed hard enough to move the
cursor slightly)
MouseReleased
MouseClicked

I ran into this very problem making the events the lazy way in Netbeans using their Forms utility.
I found the accidental dragging of my mouse between Press and Release is what killed the click event.
Working as intended or a minor failing of the JVM and Netbeans?  I don't know.

The work-around I used was to register a MousePressed and MouseReleased event to simulate the clicking.
If the Press and Release do not happen on the same Object, MouseReleased will do nothing.
If the Press and Release happen on the same Object, I call my method with appropriate parameters to consume the event.
Note that since I'm handling clicks on the JFrame, so it IS the only swing object, so I'm passing a Point object of the mouse coords and comparing both, ensuring they fall within the specified rectangle.
Answer: To expand a little on what @Ricky Clarkson said: MousePressed will fire every time a mouse button is pressed; MouseReleased will fire every time a mouse button is released, and MouseClicked events will fire every time the OS feels that the user is done clicking (i.e. they have clicked enough to overflow the click count or there was enough time from their last click for it to count as the finished click). the user presses and releases the mouse event.
If you want information on a mouse press, then use the MousePressed event.  Otherwise, you will get the event of a MouseClicked whenever the OS wants to give it to Java, which can depend greatly on the settings of the system (i.e. how long of a delay is set in the System options - like the Control Panel - to allow for double clicks).
Hope this helps clarify.

Edit: Removed my statements related to the OS information - it seems I was mistaken in my recollection of how this worked.  My apologies.
Comment: I thought that if you 'double-clicked' you would get two mouse-clicked events, one with a click-count of 1 and one with a click-count of 2?
Comment: @camickr: I get your result on Mac OS and Windows. In addition, adjusting the host's double-click speed changes the interval between which repeated clicks serve to increment the result of `getClickCount()` versus returning to a count of one. For example, a long double-click interval allows me to see an incrementing `getClickCount()` by clicking at a leisurely pace (as you observe), while a short interval requires rapid clicking to see anything but one. On Ubuntu, the host preference appears to be ignored; but, like Mac OS and Windows, events are reported promptly.
Comment: Really think this answer should be down voted, but I can only test on windows. The system settings have nothing to do with how many mouseClicked events are generated. A mouseClicked event is generated for every pressed/released event at the same mouse coordinate. The system settings only control the "click count". If you click slowly the count will always be 1. If you click fast (within the system settings) the click count keeps increasing. Try the tutorial demo: http://download.oracle.com/javase/tutorial/uiswing/events/mouselistener.html
Comment: @camickr: Using `MouseEventDemo` on Mac OS X, I see a distinct change in the behavior of `getClickCount()` when I adjust the host's double-click speed; but I see no delay in reporting events, as suggested by @aperkins. I am unable to explain how the accepted answer impacts the latency asserted in the question.
Comment: @trashgod, what is the distinct change? I always get 3 events in the same order (pressed/released/clicked). The difference is the click count. When I click slowly (ie. every second) the click count is always 1. When I click more rapidly the click count keeps increasing (1, 2, 3, 4, 5, 6...). There are not lost events and the events are generated immediately.
Comment: @aperkins: I have voted your answer down, as I believe the second paragraph is unclear. The host OS may adapt the reported click count based on user preference, but events are reported promptly. If I am mistaken, I'd welcome a counter-example. In either case, I can't undo the vote unless the answer is edited.
Comment: Apologies to all if I was misleading - my memory of the event structure was slightly different than reality it seems, and I have not needed to tell the difference between double or single clicks in my recent work.  I have edited the answer appropriately.

MouseListener is not firing fast enough


How to reinstall gnome-terminal?

Question: I dont know exactly what happened. When I open my terminal window, it completely cracked. I dont anything editing this window. How to i reinstall gnome-terminal ?
I have tried the below post's solutions,
How to reinstall Terminal?
But, it didn't solve my problem.

It would be great, if give any solutions.
Thanks.
Comment: The question you linked to seems to be about reinstalling gnome-terminal *when it's been removed*: to reinstall it when it's currently installed but screwed up, you probably need to add the flag `--reinstall` to the command i.e. `sudo apt-get install --reinstall gnome-terminal`
Comment: I have tried with your command. But, that problem has not solved.
Comment: In that case, the problem is likely not with any of the files in the `gnome-terminal` package - perhaps it is something in your local (user) configuration? Do you see the same behaviour if logged in to a different account / guest account?
Comment: @steeldriver I have tried different users too .... Still, blank window only opened. I have tried to execute exit command in this window. It works. But, content has not displayed.
Answer: Read the next paragraph to its end before doing anything!
Switch to a TTY by pressing Ctrl + Alt + F1. It also works for F2 to F6. If something is running on TTY1 (used F1), use the next one. Log in and enter sudo apt-get purge gnome-terminal. To get back to the graphical session, press Ctrl + Alt + F7.
You might want to remove the profile files before reinstalling gnome-terminal (by typing in sudo apt-get install gnome-terminal). To do so, delete ~/.gconf/apps/gnome-terminal, if it exist on your system. I have no idea where it is on Ubuntu 15.04, so maybe google this one.
Edit: I figured out the path on Ubuntu 15.04: /usr/share/glib-2.0/schemas/org.gnome.Terminal.gschema.xml.
Comment: thanks for your reply. I have execute above solutions. Problem has not solved :-( . My OS- ubuntu14.04
Comment: I've never had something like this and have no idea how to solve it. However, you can try to install a new terminal. Mate Terminal is pretty much the same thing. `sudo apt-get install mate-terminal`
Comment: Did you delete the files mentioned in my answer?
Comment: sorry.... small mistake.. It works well... Thank you very much.
Answer: Most likely you ran into this problem after upgrading python2.7 to python3.5, anyway the solution is rather easy:
Just open xterm and type the following:
sudo apt-get -f install gnome-terminal

or
sudo apt-get remove gnome-terminal && sudo apt-get install gnome-terminal

if it didn't work either ways though, run sudo apt-get remove python3 first and repeat the steps.
Comment: It worked like a charm. Thank you so much. :)
Answer: open xterm or a tty terminal, and run the following command:
sudo apt-get remove gnome-terminal && sudo apt-get install gnome-terminal

Answer: Uninstalling and reinstalling the application (terminal or xterm) doesn't work because it doesn't create the ~/.bashrc file. The solution is to create/edit this file with appropriate logic. :-) You can find some modified version of these files in extenstion.gnome.org

How to reinstall gnome-terminal?


Syntax error when creating directory with spaces, parentheses, apostrophe, and question mark

Question: I know that this probably has something to do with escaping characters, and that there might be similar questions asked already, but this is a tricky combination that I can't figure out.
On my Plex media server I create a directory for each album. The mkdir command for one of the albums does not work for me:
mkdir 'Oasis (2) - (What's The Story) Morning Glory?'
I get an error:
bash: syntax error near unexpected token `)'
I've tried different combinations of escaping characters and removing some of them to find which ones are problematic, but I still can't figure out how I could properly create a directory with this exact name.
Comment: You may find this site helpful https://www.mtu.edu/umc/services/websites/writing/characters-avoid/
Answer: Use " and not '.
$ mkdir "Oasis (2) - (What's The Story) Morning Glory"
$
$ rm Oasis\ \(2\)\ -\ \(What\'s\ The\ Story\)\ Morning\ Glory/ -rf
$

You have a ' in your text so that does not match with the ''s around it. You can also use:
$ mkdir Oasis\ \(2\)\ -\ \(What\'s\ The\ Story\)\ Morning\ Glory/

Escape by adding a \ in front of each of these: {space} ( ) ' for this specific directory.
When it comes to filenames try to avoid characters that are NOT used on different platforms. Windows has different rules than Linux etc.

Windows filenames: anything except ASCII's control characters and \/:*?"<>|
Linux, OS-X: anything except null or /

Systems might warn about it but some do also remove the invalid character or replace it by a code and when you copy the file back suddenly have 2 versions.
Comment: What do you mean by characters that are not used on different platforms?
Comment: see the alteration.


Best compression library/format for compressing on the fly and binary search?

Question: I'm looking for a compression library/format with the following abilities:

Can compress my data as I write it.
Will let me efficiently binary search through the file.
Will let me efficiently traverse the file in reverse.

Context: I'm writing a C++ app that listens for incoming data, normalizes it, and then needs to persist the normalized output to disk. The data already compresses pretty well when I run gzip on the files by hand. However, the amount of incoming data is potentially massive, and I'd like to do the compression on the fly. Each entry in the file has a timestamp associated with it and I may be only interested in the chunk of data between time X and time Y, so to quickly find that chunk I'd like to be able to binary search. And even iterate in reverse if possible. Do any particular compression libraries/formats stick out as being particularly good for my project? I've found libraries that satisfy #1, but often whether #2 or #3 will work is undocumented.
Comment: I suppose you mean, without managing the chunks yourself :) ? I know that protobuf provides lazy decoding, which allow efficient searching, but you need to actually encode the data in binary format yourself, so may not be as efficient in compression :/
Answer: You can just compress a few chunks at a time so that you can decompress them separately, then keep an (uncompressed but small) index to the beginning of each block of chunks in the compressed data.  That will allow almost random access to the chunks and still keep them in order by timestamp.  The limit case to this is to compress each chunk individually, although that might hurt your compression ratio.


insulating exterior walls

Question: I have an old house with no insulation. The walls are 2x4 with plaster and lath. The outside is aluminum siding, in good shape. I would like to blow cellulose insulation inside the wall cavities from the inside, then hang paneling over the plaster.
Do I really need to worry about moisture if I'm actually keeping the warm air from inside reaching the cold air that would come into the cavity once filled?
All this talk about moisture problems is confusing me. And one step further would be to wrap the room with foil radiant insulation then install furring strips then hang paneling or drywall. What are your thoughts on this aside from loosing inside space?
Comment: Where do you live?
Answer: Any recommendation depends on your location - I wouldn't provide the same answer for Yuma, AZ as I might for Edmonton, AB.
When water vapor diffuses through a wall and reaches the exterior sheathing, if that sheathing temperature is below the dew point the vapor will condense. Depending on the amount of water vapor and the rate at which the wall cavity is able to dry out, this may lead to moisture problems.
Installing insulation in the wall cavity will help reduce heating costs, but won't address the problem of sheathing temperature. As a result, some builders are specifying 2" to 4" or more foil faced polyiso panels be installed outside of the sheathing to raise the temperature above the dew point. In these designs, some don't even advocate using cavity insulation. Vapor will still diffuse into the cavity, but it will not condense on the sheathing surface.
Installing foil faced polyiso on the interior of the wall, properly air sealed and with taped joints, forms an effective vapor barrier which will reduce the problem of moisture diffusing through the walls. However it may not solve all of the problems with vapor diffusion so it's quite possible to still have problems.
Additionally, while most people look to insulation as a primary solution for energy savings, often older homes would find greater benefit from air sealing. There is almost no way you can make an older house with plaster walls "too tight." In fact, the idea of houses being "too tight" is something of a myth. Your goal should be to have "managed ventilation" rather than the unmanaged ventilation common in older homes.
In my 1870's New England house as an "inside" solution I removed the plaster, installed fiberglass batt insulation in the cavities, applied 2" foil faced polyiso over the studs (for a thermal break and vapor barrier), with 1x3 furring strips and gypsum on top.

insulating exterior walls


Compile GCC To Run On Android with NDK Standalone Toolchain

Question: I'm running the Android NDK standalone toolchain installed on CentOS and built with the make-standalone-toolchain.sh script using android-14 and ARM GCC 4.7 compiler.
I'd like to build GCC to run in the KBOX environment on my NookHD which has CM installed, using the Android standalone toolchain.  I'd like to use make with the configure scripts instead of Android's ndk-build if possible, because I've put effort into using them, but I'm open to switching to ndk-build.
I've tried several methods, all of which have failed, mostly because I'm working with instructions/recommendations I've pieced together from various threads and articles I've found.
My question(s):

Is what I'm trying to do possible?
If yes, is there a set of instructions/help files...even a rough outline...of how to accomplish this?

NOTE:  I am aware that there are IDE apps in Google Play.  I also know that KBOX has a downloadable Debian package of GCC. I'd still like to build GCC for my environment for various reasons.
Answer: Kevin Boone's kbox2 has now got a gcc .deb package. BTW i am also trying to set up a full blown development tool chain on the android phone itself. Got both gcc and make from the kbox2 website. But still not sure if they produce binaries which work with bionic. basic hello world app works though.
Comment: Sorry it took so long to respond.  From my original post:  _I also know that KBOX has a downloadable Debian package of GCC. I'd still like to build GCC for my environment for various reasons_.  Keep me updated on your progress for the development toolchain...I'll let you know if I get anything up and running.


How can i update data in c#

Question:
I'm working in Visual Studio 2019 In c
I have problem with updating data to database
I use local Visual Studio SQL database

private void button1_Click(object sender, EventArgs e)
{
String source = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Szabolcs\Documents\Adatbázis Kezelés2.mdf;Integrated Security=True;Connect Timeout=30";
SqlConnection con = new SqlConnection(source);
con.Open();
        String sqlSelectQuery = "SELECT * FROM [Table] WHERE ID = "+ int.Parse(textBox1.Text);
        SqlCommand cmd = new SqlCommand(sqlSelectQuery, con);
        SqlDataReader dr = cmd.ExecuteReader();

        if (dr.Read())
        {
            textBox2.Text = (dr["Name"].ToString());
            textBox3.Text = (dr["Kor"].ToString());
            label4.Text = (dr["Kor"].ToString());
            label5.Text = (dr["Kor"].ToString());

            int s = 11;
            string y = (dr["Kor"].ToString());

            label4.Text = (dr["Kor"].ToString());
            x = Int32.Parse(label4.Text);
            x = x + 0;

            label6.Text = (x.ToString());

        }
    }

    private void button2_Click(object sender, EventArgs e)
    {
        String source = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Szabolcs\Documents\Adatbázis Kezelés2.mdf;Integrated Security=True;Connect Timeout=30";
        SqlConnection con = new SqlConnection(source);
        con.Open();
        x = x + 1;
        label6.Text = (x.ToString());
        String st = "UPDATE supplier SET Kor = " + label6.Text + " WHERE Id = " + textBox1.Text;
    }

Comment: [SQL Injection alert](http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx) - you should **not** concatenate together your SQL statements - use **parametrized queries** instead to avoid SQL injection - check out [Little Bobby Tables](http://bobby-tables.com/)
Comment: What's the issue?
Comment: Almost the same as you did in button1 except typically you use `ExecuteNonQuery()` for an UPDATE. Though if my guess is correct, you will have a sql syntax error because you have not quoted `label6.Text`.
Comment: The problem is that SQL is not "Uppdating" the data. Edit: Program is working just not uppdate the data
Answer: Add these lines
SqlCommand cmd = new SqlCommand(st, con);
int result = cmd.ExecuteNonQuery();

Please put a breakpoint and check the value of st, is it generating the valid query.
I would suggest to use parameterized query to avoid sql injection.
Also, please avoid using Select *, please use columns.
Comment: There is have error: System.Data.SqlClient.SqlException: 'Invalid object name 'supplier'.'
Comment: Do you have supplier table? Or check your connection string, are you pointing to the right database?
Comment: I have "supplier" here: `String st = "UPDATE supplier SET Kor = " + label6.Text + " WHERE Id = " + textBox1.Text;`
Comment: So is supplier table present in database?
Comment: Here have a picture [link](https://imgur.com/a1ieLQq)
Comment: @Szabolcs that table is literally named "Table", not supplier.
Comment: Ohh... Its working. Thank you for help. Have a nice day

How can i update data in c#


Could power fluctuations have killed my refrigerator?

Question: Bought a house (built in 1937) recently.
When the clothes washer runs (particularly, when it agitates), lights in the house flicker.
I've read in numerous places online that this is possibly due to a loose neutral somewhere.
Would that kind of power flicker kill my fridge?  The freezer keeps cold, but not the fridge, and I'm almost certain it's due to the control board dying.  My impression is that poor power stability can kill control boards in appliances (I'm pretty sure it happened in our previous house, to a fridge).
I'm asking because I want to know if I need to get the flickering fixed before I get the fridge fixed.
Answer: That kind of flicker can kill your house. I'd get it fixed before proceeding with anything else. Loose connections and undersized wire = potential fire.
Comment: Hard to say, but my accountant lost her house to a fire caused by a bad wire connection in an outlet so I get a little paranoid when people start mentioning potential loose connections. So I'd say, especially since it's a multiple circuit issue that it needs immediate attention.
Comment: The outlet the washer is plugged into is odd---they have a 6-outlet thing screwed onto what looks like an outlook or junction box.  I was thinking maybe that's the problem, not something more systemic.  While I'm waiting for an electrician to come, could I plug the washer into a different outlet using a thick extension cord and see if it has the same effect on the house, or is that a terrible idea?  And beyond the general fire hazard issue, is that kind of flicker hard on equipment (TV, cable modem, FIOS box, etc etc)?
Comment: You could try, briefly, but one bad outlet or multitap is unlikely to be the source of a whole house flickering. And voltage spikes are bad for electronic equipment. That's why they invented surge protectors.
Comment: There is no use for a 6-plug tap on a washing machine socket. The washing machine outlet is normally dedicated to only that purpose, wired direct to a breaker with it being the only socket on that circuit. (though this is a 1937 residence, built before such became common practice.) If you're familiar with doing such stuff, I'd go get a faceplate, pull the tap off (may be secured by the center screw) and plug direct into the socket. And flickering is not only a safety hazard, but can kill other equipment, especially motors if it's a brownout/low voltage situation.
Comment: Thanks for the comments.  How urgent is this to fix?  I've contacted a couple electricians, but it seems like most electricians are single man or small shops and they don't return calls that quickly.  Is this something that can wait a couple days (time to contact plus inevitable delay due to not scheduling right away), or is this an emergency that needs to be looked at in the next 24 hours?
Comment: An electrician came by yesterday.  Voltmeter said that one leg coming into the house is 125V, the other is 112V.  Electrician claimed that's too far from 120/120 to be tolerable.  True?  Said it starts above the main breaker; told me to call POCO (which I've done).
Comment: Yes, low power can burn out motors. If the voltage is only at 112V, it's probably dropping to 100v or less under full circuit load as evidenced by the symptoms. Good news, it's external so the fire hazard issue goes away. More good news, it's the power company's to deal with.
Comment: The flickering is gone; I'm not 100% sure, but I think it's because the electrician I mentioned above tightened up some loose connections on the panel.  Between the power company coming out and looking at the box housing the meter, and the electrician replacing that box and some other stuff on the outside, the voltages readings are now good.
Comment: Glad to hear! Stable power is nice!
Answer: Get the flicker fixed as Fiasco Labs recommends.  But I doubt the circuit board on your fridge failed.  Those are usually an all or nothing failure.  Instead look at the valve that controls the airflow from the freezer to fridge.  That is a common source of fridge too cold/hot issues.
Comment: diceless is right, your freezer is what keeps your fridge cold. Will your freezer keep ice cream frozen hard? If not, you may have a fridge problem in addition to electrical issues. Note: its not uncommon, especially in older homes, for the inductive load induced at initial start-up of electric motors to dim the lights very briefly.
Comment: I had to switch out a fridge at an apartment complex because of this. ( to be seen doing something ) I then hot glued the controls so that wouldn't happen again. ( both fridges are still being used as far as I know )
Comment: Appliance tech came and fixed the fridge today.  Said the board went bad.
Comment: Glad you got it fixed.


Rainlabs Blog Plugin paging

Question: Working in octoberCMS, followed a few video and got the blog plugin up and running no problem. The only area that not really talked about that I just wanted to ask was how to get the paging feature working with the Rain labs blog plugin.
http://students.cnawebdev.org/DG309/2170/successwithtess/index
Sandbox for playing with October, but if you scroll down to the bottom you can see if the pager which isn't working. So any advice would be great for anyone that used the CMS or plugin before.
Comment: It's common for people who are new to the site to ask questions and then never accept an answer. As a result, their newer questions tend to be ignored. Reputation points are the currency of this site, and accepting an answer is like tipping a waiter/waitress :-) please valid my anwser if it was resolving your question
Answer: Usually on an home page, you don't have pagination. You can show the last 4 post with a link to the Blog page
Use the blogPosts component to display a list of latest blog posts on a page.
see documantation here : https://octobercms.com/plugin/rainlab-blog
title = "Accueil"
url = "/"
layout = "default"
is_hidden = 0

[blogPosts]
pageNumber = "{{ :page }}"
postsPerPage = 4
noPostsMessage = "No posts found"
sortOrder = "published_at desc"
categoryPage = "actualite"
postPage = "blog-detail"

==
{% set posts = blogPosts.posts %}

{% for post in posts %}

{{ post.title }}

                                {{ post.published_at|date('d.m.Y') }}

            {% endfor %}
All blog posts

I hope this can help you

Rainlabs Blog Plugin paging


Shouldn't this character be infected in The Last of Us II?

Question: In The Last of Us Part II there are two separated fights between the two main characters:

 Abby and Ellie.

During the first fight, there's a cut scene where

 Ellie bites Abby in the arm.

From what I understand, Ellie is technically infected, as shown by the scanner in the beginning of part I. She only doesn't turn because of the mutation in her brain, but the infection is there. If this is right, then...

 Shouldn't Abby become infected after Ellie bit her in their first fight?
Answer: We don't really know how Ellie's immunity works. However, she does mention:

I can't... get you infected, if that's what you're worried about... I can't make you immune either.

So she somehow knows that she can't infect other people.
Comment: I somehow missed this scene in the game. +1
Comment: I don't know how lesbian relationships work as I'm a white heterosexual male in my late 30s, but...is there a lot of biting involved? Both Abby and Ellie drew blood in their bites, and we know the infection is spread through bites from infected. This is an ok answer, though...
Comment: @tilley31 I don't think that being white or in your 30s disqualifies you from understanding how relationships work!  But the general idea is that the infection is spread through bodily fluids. Whether those fluids need to be saliva and/or blood is unclear, but if so, then most kinds of romantic relationships would include activities that involve the exchange of those fluids. (Think about kissing somebody who has a small cut somewhere in their mouth.) Note that this is already true, even before the zombie apocalypse.
Comment: I was talking about LESBIAN relationships, not all relationships, in a kind of tongue in cheek way :P. Guess the real answer would be wether Ellie qualifies as "infected" or not. As I understand it, she has the infection, but she doesn't turn because of her mutation, which the Fireflies intended to use for a vaccine. If it's not like that, and she just hast the anti-bodies for it, then it's ok.
Comment: @tilley31 I don't think there's a big difference between lesbian relationships and any other kind of relationship when it comes to the issue of whether one partner can infect another with a fungus-based zombie plague. But you're right that we just don't know the details of exactly how the infection works, so we have to take Ellie's word for it that she knows she can't infect other people.


Is $f^n(A)$ eventually constant if $f\colon A \to A$ is a ring-endomorphism of the commutative Artinian ring $A$?

Question: Let $A$ be a commutative Artinian ring and suppose that $f \colon A \to A$ is a ring-morphism. Observe that $f(A) \supseteq f^2(A) \supseteq f^3(A) \supseteq \dots$
Is it true that there exists $n_0 \in \mathbb{N}$ such that $f^{n_0}(A) = f^n(A)$ for every $n \geq n_0$?
I would say that the answer is no. I have the following counterexample, but I am not sure of its correctness. Let $F$ be a field and $A \colon\!= F(\{x_n : n\in\mathbb{N}\})$ be the set of rational functions  (i.e. formal quotients of polynomials) over the set of countable many variables $\{x_n : n\in\mathbb{N}\}$.
In this context, $A$ is Artinian (in fact, a field) and the map $T\colon \{x_k : n\in\mathbb{N}\} \to A$ defined by $x_k \to x_{k+1}$ extends to a ring-morphism $T\colon A \to A$ (not sure about these two things). Then, $T^n(A) = F(\{x_k : k\geq n\})$, so the sequence of images $T^n(A)$ never stabilizes.
Maybe I should also mention that when $A$ is an Artinian module and $f$ a module endomorphism, then my question has an affirmative answer.
Answer: Your counterexample is correct.
That fields are Artinian is clear as there are only two ideals in any fields and fields of rational functions are fields nonetheless. You could argue that the map you propose is induced by universal properties if that makes you feel safer regarding their existence. This can be done by combining the universal property of the polynomial ring in countable many variables and the universal property of the quotient field. This should do the job of formally extending the shifting map to a ring endomorphism as desired.
The reason why this fails is that the image of an ideal along a ring homomorphism is not necessarily an ideal. Hence non of the ring-theoretic properties apply to the chain $A\supseteq f(A)\supseteq f^2(A)\supseteq\cdots$ of subsets. On the other hand, it does work  in the case of Artinian modules because the image of a submodule along a homomorphism of modules is again a submodule.


Skylake L2 cache enhanced by reducing associativity?

Question: In Intel's optimization guide, section 2.1.3, they list a number of enhancements to the caches and memory subsystem in Skylake (emphasis mine):

The cache hierarchy of the Skylake microarchitecture has the following
  enhancements:

Higher Cache bandwidth compared to previous generations.
Simultaneous handling of more loads and  stores enabled by enlarged buffers.
Processor can do two page walks in parallel compared  to one in Haswell microarchitecture and earlier  generations.
Page split load penalty down from 100 cycles in previous generation to 5 cycles.
L3 write bandwidth increased from 4 cycles pe r line in previous generation to 2 per line.
Support for the CLFLUSHOPT instruction to flush ca che lines and manage memory ordering of flushed  data using SFENCE.
Reduced performance penalty for a software prefetch that specifies a NULL pointer.
L2 associativity changed from 8 ways to 4 ways.

The final one caught my eye. In what way is a reduction in the number of ways an enhancement? By itself, it seems that fewer ways is strictly worse than more ways. Of course, I get that there might be valid engineering reasons why a reduction in the number of ways could be a tradeoff that enables other enhancements, but here it is positioned, by itself, as an enhancement.
What am I missing?
Answer: It's strictly worse for performance of the L2 cache.
According to this AnandTech writeup of SKL-SP (aka skylake-avx512 or SKL-X), Intel has stated that "the main reason [for reducing associativity] was to make the design more modular".  Skylake-AVX512 has 1MiB of L2 cache with 16-way associativity.
Presumably the drop to 4-way associativity doesn't hurt too badly in the dual and quad-core laptop and desktop parts (SKL-S), since there's lots of bandwidth to L3 cache.  I think if Intel's simulations and testing had found that it hurt a lot, they would have put in the extra design time to keep the 8-way 256k cache on non-AVX512 Skylake.

The upside of lower associativity is power budget.  It could indirectly help performance by allowing more turbo headroom,  but mostly they did it to improve efficiency, NOT to improve speed.  Freeing up some room in the power budget allows them to spend it elsewhere.  Or not to spend all of it, and just use less power.
Mobile and many-core-server CPUs care a lot about power budget, much more than high-end quad-core desktop CPUs.
The heading on the list should more accurately read "changes", not "enhancements", but I'm sure the marketing department wouldn't let them write anything that didn't sound positive.  :P  At least Intel documents things accurately and in detail, including the ways new CPUs are worse than older designs.

Anandtech's SKL writeup suggests that dropping the associativity freed up the power budget to increase L2 bandwidth, which (in the big picture) compensates for the increased miss rate.
IIRC, Intel has a policy that any proposed design change must have a 2:1 ratio of perf gain to power cost, or something like that.  So presumably if they lost 1% performance but save 3% power with this L2 change, they do it.  The 2:1 number might be correct, if I'm remembering this correctly, but the 1% and 3% example are totally made up.
There was some discussion of this change in one of the podcast interviews David Kanter did right after details were released at IDF.  IDK if this is the right link.
Comment: Here's [another interesting theory](http://www.agner.org/optimize/blog/read.php?i=415#867): that the Skylake-S (i.e., original Skylake) had several architectural modifications in anticipation of AVX-512 support in the later Skylake-X and Skylake Xeon lines, even though Skylake-S didn't support it. In particular: _[SKL reducing associativity to 4] was preparation to increasing cache size - SKL-S cache is just a quarter of SKL-X cache with the same organization, and reduced associativity allowed to reduce transistor budget of massive 1MB cache._. Just speculation but interesting nonetheless!
Comment: @BeeOnRope: yeah, I had the same thought after reading [AnandTech's SKL-X writeup](http://www.anandtech.com/show/11550/the-intel-skylakex-review-core-i9-7900x-i7-7820x-and-i7-7800x-tested/4), where they make the same claim: reduced L2 associativity was at least partly to make it more modular.  So the assumption that SKL-S gets an overall speedup from spending the power budget elsewhere may not be correct.  (It doesn't rule it out, though.  It may still be an overall good or neutral change for SKL-S.  And Intel wouldn't have done it if they think it's too bad.)


Local and global minima of the cost function in logistic regression

Question: I'm misunderstanding the idea behind the minima in the derivation of the logistic regression formula.
The idea is to increase the hypothesis as much as possible (i.e correct prediction probability close to 1 as possible), which in turn requires minimising the cost function $J(\theta)$ as much as possible.
Now I've been told that for this all to work, the cost function must be convex. My understanding of convexity requires there to be no maximums, and therefore there can only be one minimum, the global minimum. Is this really the case? If it's not, please explain why not. Also, if it's not the case, then that implies the possibility of multiple minima in the cost function, implying multiple sets of parameters yielding higher and higher probabilities. Is this possible? Or can I be certain the returned parameters refer to the global minima and hence highest probability/ prediction?
Comment: (1) The Logistic regression problem is convex (2) Because it's convex, local-minimum = global-minimum 3) Regulization is a very important approach within this task; e.g. adding some costs to penalize the weights (4) L2-based regulization has only one solution (5) L1-based regulization might have multiple solutions of the same objective; still convex (6) There are algorithms not guaranteeing convergence to the optimum like SGD-based approaches. They are still important in large-scale opt
Comment: Could you please elaborate or give some reference for L1 and L2 part , how they change solution ? How can L! have multiple solutions and still be convex ? Also does doing gradient updates in mini batch style or using some optimizer for learning rate changes the convexity of the method or solution ?
Answer: The fact that we use convex cost function does not guarantee a convex problem.
There is a distinction between a convex cost function and a convex method.
The typical cost functions you encounter (cross entropy, absolute loss, least squares) are designed to be convex.
However, the convexity of the problem depends also on the type of ML algorithm you use.
Linear algorithms (linear regression, logistic regression etc) will give you convex solutions, that is they will converge. When using neural nets with hidden layers however, you are no longer guaranteed a convex solution.
Thus, convexity is a measure of describing your method not only your cost function!
LR is a linear classification method so you should get a convex optimization problem each time you use it! However, if the data is not linearly separable, it might not give a solution and it definitely won't give you a good solution in that case.
Answer: Yes, Logistic Regression and Linear Regression aims to find weights and biases which improve the accuracy of the model (or say work well with higher probability on the test data, or real world data). To achieve that, we try to find weights and biases such a way that it has least deviations (say cost) between prediction and real out-comes. So, if we plot cost function and find its minima, that would achieve the same purpose. Hence we use a model such a way that its cost function would have one local minima (i.e. model should be convex)